@hogsend/engine 0.35.1 → 0.36.1

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.
@@ -0,0 +1,203 @@
1
+ import { contacts, type Database } from "@hogsend/db";
2
+ import { and, eq, isNull, or } from "drizzle-orm";
3
+ import type { Context } from "hono";
4
+ import type { AppEnv } from "../../app.js";
5
+ import {
6
+ contactKey,
7
+ normalizeEmail,
8
+ resolveContact,
9
+ } from "../../lib/contacts.js";
10
+ import {
11
+ InvalidUserTokenError,
12
+ verifyUserToken,
13
+ } from "../../lib/user-token.js";
14
+
15
+ export type FeedRecipient =
16
+ | { ok: true; recipientKey: string; contactId?: string }
17
+ | { ok: false; status: 400 | 403; error: string };
18
+
19
+ export interface FeedRecipientParams {
20
+ userId?: string;
21
+ email?: string;
22
+ anonymousId?: string;
23
+ userToken?: string;
24
+ }
25
+
26
+ /**
27
+ * THE SECURITY CORE. Derive the SERVER-TRUSTED `recipientKey` for a feed request.
28
+ * NEVER reads `recipientKey` (or any key it returns) from the request body/query
29
+ * directly — every value is either token-verified or a self-addressing anon id.
30
+ *
31
+ * - `userToken` present (works for publishable AND secret callers): verify the
32
+ * HMAC (`BETTER_AUTH_SECRET`); recipientKey = canonical key for the token's
33
+ * `userId`. A forged/expired token → 403.
34
+ * - SECRET key (`!publishable`) with `userId`/`email`: server-trusted, resolve
35
+ * its canonical key directly.
36
+ * - PUBLISHABLE + `anonymousId` (no token): recipientKey = the RAW anon id. It
37
+ * is NOT passed through the contact resolver — the resolver can fold an anon
38
+ * id into an identified survivor's canonical key, and returning that would let
39
+ * an anon caller (who only knows its own browser anon id) read an identified
40
+ * person's feed. The raw anon id can only ever match feed rows `sendFeedItem`
41
+ * wrote under that same anon id — UNLESS the supplied value is some identified
42
+ * contact's canonical key (`external_id`/`email`). `sendFeedItem` stores an
43
+ * identified recipient's rows under `external_id ?? anonymous_id ?? id`, so a
44
+ * token-less pk_ caller passing `anonymousId=<victim external_id|email>` would
45
+ * otherwise read/mutate that victim's feed. Mirroring the events route's
46
+ * `PublishableAnonymousMergeError` invariant, we reject a publishable
47
+ * `anonymousId` that collides with an identified contact's key → 403.
48
+ * - else (publishable, no identity) → 400 fail-closed.
49
+ *
50
+ * There is no path where a caller's request-supplied recipientKey is honored.
51
+ */
52
+ export async function resolveFeedRecipient(
53
+ c: Context<AppEnv>,
54
+ params: FeedRecipientParams,
55
+ ): Promise<FeedRecipient> {
56
+ const { db, env } = c.get("container");
57
+ const publishable = c.get("publishable") === true;
58
+
59
+ // 1. Token path — the ONLY thing that authorizes a concrete userId for a
60
+ // publishable caller (and accepted from a secret caller too).
61
+ if (params.userToken) {
62
+ let userId: string;
63
+ try {
64
+ userId = verifyUserToken({
65
+ token: params.userToken,
66
+ secret: env.BETTER_AUTH_SECRET,
67
+ }).userId;
68
+ } catch (err) {
69
+ if (err instanceof InvalidUserTokenError) {
70
+ return { ok: false, status: 403, error: "Invalid userToken" };
71
+ }
72
+ throw err;
73
+ }
74
+ const ck = await canonicalKey(db, { userId });
75
+ return { ok: true, recipientKey: ck.recipientKey, contactId: ck.contactId };
76
+ }
77
+
78
+ // 2. Secret key: trust userId/email directly.
79
+ if (!publishable && (params.userId || params.email)) {
80
+ const ck = await canonicalKey(db, {
81
+ userId: params.userId,
82
+ email: params.email,
83
+ });
84
+ return { ok: true, recipientKey: ck.recipientKey, contactId: ck.contactId };
85
+ }
86
+
87
+ // 3. Publishable anon: its raw anon id IS its recipientKey (no resolver — see
88
+ // the doc comment's fold hazard). But a token-less publishable caller may
89
+ // only address its OWN browser anon id — NEVER an identified contact's
90
+ // canonical key. `sendFeedItem` stores an identified recipient's feed rows
91
+ // under `external_id ?? email`-derived key, so reject any `anonymousId` that
92
+ // collides with an identified contact's key (mirrors the events route's
93
+ // `restrictToAnonymous` / `PublishableAnonymousMergeError` invariant).
94
+ if (params.anonymousId) {
95
+ if (publishable && (await collidesWithIdentified(db, params.anonymousId))) {
96
+ return {
97
+ ok: false,
98
+ status: 403,
99
+ error: "anonymousId is not addressable",
100
+ };
101
+ }
102
+ // Surface the anon contact's row id (when it exists) as engine-internal
103
+ // provenance. The feed's OWN mark/clear re-ingests (emitMarkEvents,
104
+ // inapp.feed_cleared) re-ingest keyed `userId: recipientKey` = this raw anon
105
+ // id; threading the row id makes them fold into THIS contact by id instead of
106
+ // minting a phantom `external_id=<anonId>` twin — the twin that then trips
107
+ // collidesWithIdentified and 403-locks the visitor out of their own feed.
108
+ const anonRow = await db
109
+ .select({ id: contacts.id })
110
+ .from(contacts)
111
+ .where(
112
+ and(
113
+ eq(contacts.anonymousId, params.anonymousId),
114
+ isNull(contacts.deletedAt),
115
+ ),
116
+ )
117
+ .limit(1);
118
+ return {
119
+ ok: true,
120
+ recipientKey: params.anonymousId,
121
+ contactId: anonRow[0]?.id,
122
+ };
123
+ }
124
+
125
+ // 4. No identity → fail-closed.
126
+ return {
127
+ ok: false,
128
+ status: 400,
129
+ error: "anonymousId, userId, email, or userToken is required",
130
+ };
131
+ }
132
+
133
+ /**
134
+ * True when `value` is the canonical key of an IDENTIFIED contact — i.e. a live
135
+ * contact's `external_id`, or its `email` when that is its canonical key (no
136
+ * `external_id`). Such a value names an identified person's feed rows, so a
137
+ * token-less publishable caller must NOT be allowed to claim it as an "anon id".
138
+ *
139
+ * A genuine browser anon id only ever matches a contact via `anonymous_id` whose
140
+ * canonical key is that same anon id (the contact has no `external_id`) — that is
141
+ * the caller's OWN anon contact and is allowed (returns false).
142
+ */
143
+ async function collidesWithIdentified(
144
+ db: Database,
145
+ value: string,
146
+ ): Promise<boolean> {
147
+ const rows = await db
148
+ .select({
149
+ externalId: contacts.externalId,
150
+ email: contacts.email,
151
+ anonymousId: contacts.anonymousId,
152
+ })
153
+ .from(contacts)
154
+ .where(
155
+ and(
156
+ or(
157
+ eq(contacts.externalId, value),
158
+ eq(contacts.email, value),
159
+ eq(contacts.anonymousId, value),
160
+ ),
161
+ isNull(contacts.deletedAt),
162
+ ),
163
+ );
164
+ for (const row of rows) {
165
+ // The supplied value is this contact's `external_id` → its rows are keyed on
166
+ // it (identified). Reject.
167
+ if (row.externalId === value) return true;
168
+ // The supplied value is this contact's `email` AND that email is its
169
+ // canonical key (no external_id) → identified rows are keyed on it. Reject.
170
+ if (row.email === value && !row.externalId) return true;
171
+ }
172
+ return false;
173
+ }
174
+
175
+ /**
176
+ * Canonical key (`external_id ?? anonymous_id ?? id`) for a known contact. Prefer
177
+ * an `email` match (most specific send target), then `userId` (external id or
178
+ * uuid via `resolveContact`). When no contact exists yet, key on the asserted
179
+ * identifier — a future `sendFeedItem({ recipient: { userId/email } })` resolves
180
+ * to a contact whose canonical key is that same value, so the two agree.
181
+ */
182
+ async function canonicalKey(
183
+ db: Database,
184
+ ident: { userId?: string; email?: string },
185
+ ): Promise<{ recipientKey: string; contactId?: string }> {
186
+ if (ident.email) {
187
+ const email = normalizeEmail(ident.email);
188
+ const rows = await db
189
+ .select()
190
+ .from(contacts)
191
+ .where(and(eq(contacts.email, email), isNull(contacts.deletedAt)))
192
+ .limit(1);
193
+ if (rows[0])
194
+ return { recipientKey: contactKey(rows[0]), contactId: rows[0].id };
195
+ return { recipientKey: email };
196
+ }
197
+ if (ident.userId) {
198
+ const row = await resolveContact({ db, id: ident.userId });
199
+ if (row) return { recipientKey: contactKey(row), contactId: row.id };
200
+ return { recipientKey: ident.userId };
201
+ }
202
+ return { recipientKey: "" };
203
+ }
@@ -2,6 +2,7 @@ import { OpenAPIHono } from "@hono/zod-openapi";
2
2
  import type { AppEnv } from "../app.js";
3
3
  import type { HogsendClient } from "../container.js";
4
4
  import { requireApiKey, requireScope } from "../middleware/api-key.js";
5
+ import { requirePublishableOrIngest } from "../middleware/publishable-key.js";
5
6
  import { createRateLimit } from "../middleware/rate-limit.js";
6
7
  import { adminRouter } from "./admin/index.js";
7
8
  import { campaignsRouter } from "./campaigns/index.js";
@@ -10,6 +11,7 @@ import { contactsRouter } from "./contacts/index.js";
10
11
  import { emailRouter } from "./email/index.js";
11
12
  import { emailsRouter } from "./emails/index.js";
12
13
  import { eventsRouter } from "./events/index.js";
14
+ import { feedRouter } from "./feed/index.js";
13
15
  import { healthRouter } from "./health.js";
14
16
  import { listsRouter } from "./lists/index.js";
15
17
  import { trackingRouter } from "./tracking/index.js";
@@ -52,16 +54,71 @@ export function registerRoutes(
52
54
  prefix: "ratelimit:emails",
53
55
  max: EMAIL_RATE_LIMIT_MAX,
54
56
  });
55
- for (const base of [
56
- "/contacts",
57
- "/events",
58
- "/emails",
59
- "/lists",
60
- "/campaigns",
61
- ]) {
57
+
58
+ // ---- Browser-reachable subset (publishable OR secret-ingest) ----
59
+ // Registered BEFORE the secret-only prefix loop so these specific patterns
60
+ // win Hono's match order. `requirePublishableOrIngest` accepts EITHER a
61
+ // secret ingest-scoped key (unchanged) OR a pk_/ingest-public key (Origin-
62
+ // allowlisted, fail-closed). Everything NOT listed here stays secret-only.
63
+ //
64
+ // `/events` has no subtree (only `POST /`), so the bare pattern is complete.
65
+ v1.use("/events", requirePublishableOrIngest);
66
+ // `/lists` catalog + the new static `/preferences` read + subscribe/unsub.
67
+ v1.use("/lists", requirePublishableOrIngest);
68
+ v1.use("/lists/preferences", requirePublishableOrIngest);
69
+ v1.use("/lists/:id/subscribe", requirePublishableOrIngest);
70
+ v1.use("/lists/:id/unsubscribe", requirePublishableOrIngest);
71
+ // Feed: `GET /feed` list/stream + `POST /feed/mark`/`mark-all` — publishable OR
72
+ // secret. Both the bare `/feed` (GET list) and the `/feed/*` subtree
73
+ // (mark/mark-all/stream) are covered (Hono treats them as distinct patterns).
74
+ // Recipient scoping is enforced server-side in `resolveFeedRecipient`, never
75
+ // from the request.
76
+ v1.use("/feed", requirePublishableOrIngest);
77
+ v1.use("/feed/*", requirePublishableOrIngest);
78
+ // Bare `/contacts` is dual-purpose: PUT/POST = the publishable upsert;
79
+ // DELETE = secret-only. Hono runs ALL matching `use`s, so a single guard must
80
+ // branch by method rather than stacking two guards (which would 403 a valid
81
+ // pk_ upsert via the secret guard). Any OTHER `/contacts/*` (incl. /find)
82
+ // stays secret-only below.
83
+ const contactsDeleteGuard = requireScope("ingest");
84
+ v1.use("/contacts", async (c, next) => {
85
+ if (c.req.method !== "DELETE") {
86
+ return requirePublishableOrIngest(c, next);
87
+ }
88
+ // DELETE is secret-only: chain `requireApiKey` then `requireScope("ingest")`
89
+ // exactly as the secret prefix loop does. `requireApiKey` only runs its
90
+ // `next` on a successful auth (else it returns 401/expired), so use a flag
91
+ // to detect that and surface its short-circuit response; otherwise hand off
92
+ // to the scope guard (which itself returns its 403 or calls `next`).
93
+ let authed = false;
94
+ const res = await requireApiKey(c, async () => {
95
+ authed = true;
96
+ });
97
+ if (!authed) return res;
98
+ return contactsDeleteGuard(c, next);
99
+ });
100
+
101
+ // ---- Secret-only prefixes (unchanged behavior) ----
102
+ // `/emails`, `/campaigns`: bare + subtree. A pk_ key hitting these fails
103
+ // `requireScope("ingest")` (its `["ingest-public"]` scope is neither `ingest`
104
+ // nor `full-admin`) → 403, no escalation.
105
+ //
106
+ // NOTE: deliberately NO `/lists/*` OR `/contacts/*` secret catch-all. Hono
107
+ // runs ALL matching `use`s, AND a `/<prefix>/*` `use` ALSO matches the bare
108
+ // `/<prefix>` path — so a `/contacts/*` guard would re-run on the bare
109
+ // `/contacts` upsert and 403 a valid pk_ key AFTER the method-branch
110
+ // publishable guard above already accepted it (the exact `/lists/*` collision
111
+ // we avoid the same way). The only secret-only `/contacts` subtree route is
112
+ // `GET /contacts/find`, so guard it EXPLICITLY; the bare-`/contacts`
113
+ // method-branch guard above is the sole authority on the bare path (DELETE is
114
+ // secret-only there, PUT/POST publishable). Any FUTURE secret-only
115
+ // `/contacts/<x>` or `/lists/<x>` route must mount its own
116
+ // `requireApiKey + requireScope("ingest")` (fail-closed by construction).
117
+ for (const base of ["/emails", "/campaigns"]) {
62
118
  v1.use(base, requireApiKey, requireScope("ingest"));
63
119
  v1.use(`${base}/*`, requireApiKey, requireScope("ingest"));
64
120
  }
121
+ v1.use("/contacts/find", requireApiKey, requireScope("ingest"));
65
122
  // Register the email rate-limit ONCE. The wildcard pattern `/emails/*` matches
66
123
  // BOTH the bare `POST /v1/emails` and any subtree, so a single registration
67
124
  // covers the whole emails surface. Registering both bare AND wildcard with the
@@ -71,6 +128,7 @@ export function registerRoutes(
71
128
 
72
129
  v1.route("/contacts", contactsRouter);
73
130
  v1.route("/events", eventsRouter);
131
+ v1.route("/feed", feedRouter);
74
132
  v1.route("/emails", emailsRouter);
75
133
  v1.route("/lists", listsRouter);
76
134
  v1.route("/campaigns", campaignsRouter);
@@ -1,18 +1,25 @@
1
1
  import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
- import type { Database } from "@hogsend/db";
2
+ import { type Database, emailPreferences } from "@hogsend/db";
3
3
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
4
+ import { and, eq } from "drizzle-orm";
4
5
  import type { AppEnv } from "../../app.js";
5
6
  import {
6
7
  resolveContact,
7
8
  resolveOrCreateContact,
9
+ resolveRecipient,
8
10
  serializeContact,
11
+ serializePrefs,
9
12
  } from "../../lib/contacts.js";
10
13
  import type { Logger } from "../../lib/logger.js";
11
14
  import { emitOutbound } from "../../lib/outbound.js";
12
15
  import { applyListMembership } from "../../lib/preferences.js";
13
16
  import { errorSchema } from "../../lib/schemas.js";
14
17
  import { getListRegistry } from "../../lists/registry-singleton.js";
15
- import { listMembershipError } from "../_shared.js";
18
+ import {
19
+ gatePublishableIdentity,
20
+ listMembershipError,
21
+ requireIdentity,
22
+ } from "../_shared.js";
16
23
 
17
24
  const listSummarySchema = z.object({
18
25
  id: z.string(),
@@ -24,6 +31,8 @@ const listSummarySchema = z.object({
24
31
  const bodySchema = z.object({
25
32
  email: z.string().optional(),
26
33
  userId: z.string().optional(),
34
+ // Publishable-key identity assertion (§Phase 1). Ignored on the secret path.
35
+ userToken: z.string().optional(),
27
36
  });
28
37
 
29
38
  const listRoute = createRoute({
@@ -45,6 +54,44 @@ const listRoute = createRoute({
45
54
  },
46
55
  });
47
56
 
57
+ // STATIC `/preferences` read. MUST be registered before any `/:id` GET so the
58
+ // literal path wins matching (there is no `/:id` GET today, so order is safe
59
+ // regardless — but keep it adjacent to `GET /` to preserve that invariant).
60
+ const prefsQuerySchema = z.object({
61
+ userId: z.string().optional(),
62
+ email: z.string().optional(),
63
+ anonymousId: z.string().optional(),
64
+ });
65
+
66
+ const prefsResponseSchema = z.object({
67
+ categories: z.record(z.string(), z.boolean()),
68
+ unsubscribedAll: z.boolean(),
69
+ });
70
+
71
+ const preferencesRoute = createRoute({
72
+ method: "get",
73
+ path: "/preferences",
74
+ tags: ["Lists"],
75
+ summary: "Read a contact's list/email preferences",
76
+ description:
77
+ "Returns `{ categories, unsubscribedAll }` for the resolved contact. Behind the publishable gate: a pk_ key may read anon-only (anonymousId) — a concrete `email`/`userId` read requires a verified userToken (v3).",
78
+ request: { query: prefsQuerySchema },
79
+ responses: {
80
+ 200: {
81
+ content: { "application/json": { schema: prefsResponseSchema } },
82
+ description: "The contact's list/email preferences",
83
+ },
84
+ 400: {
85
+ content: { "application/json": { schema: errorSchema } },
86
+ description: "Missing identity",
87
+ },
88
+ 403: {
89
+ content: { "application/json": { schema: errorSchema } },
90
+ description: "Publishable key may not read a concrete identity",
91
+ },
92
+ },
93
+ });
94
+
48
95
  const subscribeRoute = createRoute({
49
96
  method: "post",
50
97
  path: "/{id}/subscribe",
@@ -72,6 +119,11 @@ const subscribeRoute = createRoute({
72
119
  content: { "application/json": { schema: errorSchema } },
73
120
  description: "Missing recipient or no resolvable email",
74
121
  },
122
+ 403: {
123
+ content: { "application/json": { schema: errorSchema } },
124
+ description:
125
+ "Publishable key attempted to act on another identity without a verified userToken",
126
+ },
75
127
  404: {
76
128
  content: { "application/json": { schema: errorSchema } },
77
129
  description: "Unknown list id",
@@ -106,6 +158,11 @@ const unsubscribeRoute = createRoute({
106
158
  content: { "application/json": { schema: errorSchema } },
107
159
  description: "Missing recipient or no resolvable email",
108
160
  },
161
+ 403: {
162
+ content: { "application/json": { schema: errorSchema } },
163
+ description:
164
+ "Publishable key attempted to act on another identity without a verified userToken",
165
+ },
109
166
  404: {
110
167
  content: { "application/json": { schema: errorSchema } },
111
168
  description: "Unknown list id",
@@ -206,10 +263,66 @@ export const listsRouter = new OpenAPIHono<AppEnv>()
206
263
 
207
264
  return c.json({ lists }, 200);
208
265
  })
266
+ .openapi(preferencesRoute, async (c) => {
267
+ const { db } = c.get("container");
268
+ const { userId, email } = c.req.valid("query");
269
+
270
+ // Identity gate (publishable-aware). A secret key needs email/userId via
271
+ // `requireIdentity`. A publishable key may read anon-only — but a concrete
272
+ // `email`/`userId` read would leak another person's prefs, so it is rejected
273
+ // unless v3's userToken arm is added. (`anonymousId` is accepted for a
274
+ // publishable read; it never resolves to another identity's prefs here.)
275
+ if (!c.get("publishable")) {
276
+ const guard = requireIdentity(c, { email, userId });
277
+ if (guard) return guard;
278
+ } else if (email || userId) {
279
+ return c.json(
280
+ {
281
+ error:
282
+ "publishable preference reads are anon-only without a userToken",
283
+ },
284
+ 403,
285
+ );
286
+ }
287
+
288
+ const recipient = await resolveRecipient({ db, userId, email });
289
+ if (!recipient) {
290
+ return c.json({ categories: {}, unsubscribedAll: false }, 200);
291
+ }
292
+ // `email_preferences.user_id` is keyed on `external_id ?? contact.id`
293
+ // (risk 10) — mirror `resolveRecipient`'s contactId fallback.
294
+ const extId = recipient.externalId ?? recipient.contactId;
295
+ const rows = await db
296
+ .select()
297
+ .from(emailPreferences)
298
+ .where(
299
+ and(
300
+ eq(emailPreferences.userId, extId),
301
+ eq(emailPreferences.email, recipient.email),
302
+ ),
303
+ )
304
+ .limit(1);
305
+ const row = rows[0];
306
+ if (!row) {
307
+ return c.json({ categories: {}, unsubscribedAll: false }, 200);
308
+ }
309
+ const prefs = serializePrefs(row);
310
+ return c.json(
311
+ { categories: prefs.categories, unsubscribedAll: prefs.unsubscribedAll },
312
+ 200,
313
+ );
314
+ })
209
315
  .openapi(subscribeRoute, async (c) => {
210
- const { db, hatchet, logger } = c.get("container");
316
+ const { db, hatchet, logger, env } = c.get("container");
211
317
  const { id } = c.req.valid("param");
212
- const { email, userId } = c.req.valid("json");
318
+ const { email, userId, userToken } = c.req.valid("json");
319
+
320
+ const guard = gatePublishableIdentity(
321
+ c,
322
+ { email, userId, userToken },
323
+ env.BETTER_AUTH_SECRET,
324
+ );
325
+ if (guard) return guard;
213
326
 
214
327
  const result = await applyListSubscription({
215
328
  db,
@@ -232,9 +345,16 @@ export const listsRouter = new OpenAPIHono<AppEnv>()
232
345
  return c.json({ list: id, subscribed: true as const }, 200);
233
346
  })
234
347
  .openapi(unsubscribeRoute, async (c) => {
235
- const { db, hatchet, logger } = c.get("container");
348
+ const { db, hatchet, logger, env } = c.get("container");
236
349
  const { id } = c.req.valid("param");
237
- const { email, userId } = c.req.valid("json");
350
+ const { email, userId, userToken } = c.req.valid("json");
351
+
352
+ const guard = gatePublishableIdentity(
353
+ c,
354
+ { email, userId, userToken },
355
+ env.BETTER_AUTH_SECRET,
356
+ );
357
+ if (guard) return guard;
238
358
 
239
359
  const result = await applyListSubscription({
240
360
  db,
package/src/worker.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  sendCampaignTask,
32
32
  } from "./workflows/send-campaign.js";
33
33
  import { sendEmailTask } from "./workflows/send-email.js";
34
+ import { sendFeedTask } from "./workflows/send-feed.js";
34
35
 
35
36
  export interface CreateWorkerOptions {
36
37
  container: HogsendClient;
@@ -89,6 +90,7 @@ export function createWorker(opts: CreateWorkerOptions): Worker {
89
90
 
90
91
  const baseWorkflows = [
91
92
  sendEmailTask,
93
+ sendFeedTask,
92
94
  importContactsTask,
93
95
  sendCampaignTask,
94
96
  reapStuckCampaignsTask,
@@ -0,0 +1,44 @@
1
+ import type { JsonValue } from "@hatchet-dev/typescript-sdk/v1/types.js";
2
+ import type { FeedBlock } from "@hogsend/db";
3
+ import { type SendFeedItemOptions, sendFeedItem } from "../lib/feed.js";
4
+ import { hatchet } from "../lib/hatchet.js";
5
+
6
+ /**
7
+ * JSON-serializable input for the `send-feed` task. Mirrors the journey task
8
+ * convention (explicit fields + a `[key: string]: JsonValue` index signature) so
9
+ * Hatchet's `JsonObject` constraint is satisfied; the fn re-narrows it to the
10
+ * structured {@link SendFeedItemOptions} at the boundary.
11
+ */
12
+ interface SendFeedTaskInput {
13
+ recipient: { userId?: string; email?: string; anonymousId?: string };
14
+ type: string;
15
+ title?: string;
16
+ body?: string;
17
+ blocks?: FeedBlock[];
18
+ actionUrl?: string;
19
+ metadata?: Record<string, JsonValue>;
20
+ category?: string;
21
+ templateKey?: string;
22
+ journeyStateId?: string;
23
+ idempotencyKey?: string;
24
+ [key: string]: JsonValue | undefined;
25
+ }
26
+
27
+ /**
28
+ * Durable wrapper around {@link sendFeedItem} — the in-app-feed sibling of the
29
+ * `send-email` task. `sendFeedItem` owns recipient resolution, `in_app`
30
+ * suppression, the replay-safe idempotency key, and the Redis publish.
31
+ */
32
+ export const sendFeedTask = hatchet.task({
33
+ name: "send-feed",
34
+ retries: 1,
35
+ executionTimeout: "30s",
36
+ backoff: { factor: 2, maxSeconds: 30 },
37
+ fn: async (input: SendFeedTaskInput) => {
38
+ const result = await sendFeedItem(input as SendFeedItemOptions);
39
+ return {
40
+ feedItemId: result.feedItemId,
41
+ suppressed: result.suppressed,
42
+ };
43
+ },
44
+ });