@hogsend/engine 0.35.0 → 0.36.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.
- package/package.json +7 -7
- package/src/app.ts +22 -1
- package/src/index.ts +48 -0
- package/src/lib/api-key-hash.ts +7 -2
- package/src/lib/banner.ts +71 -0
- package/src/lib/contacts.ts +57 -0
- package/src/lib/feed.ts +233 -0
- package/src/lib/ingestion.ts +10 -0
- package/src/lib/user-token.ts +100 -0
- package/src/middleware/api-key.ts +4 -0
- package/src/middleware/publishable-key.ts +119 -0
- package/src/middleware/require-admin.ts +18 -2
- package/src/routes/_shared.ts +61 -0
- package/src/routes/admin/api-keys.ts +46 -10
- package/src/routes/contacts/index.ts +38 -12
- package/src/routes/events/index.ts +70 -30
- package/src/routes/feed/index.ts +503 -0
- package/src/routes/feed/recipient.ts +183 -0
- package/src/routes/index.ts +65 -7
- package/src/routes/lists/index.ts +126 -6
- package/src/worker.ts +2 -0
- package/src/workflows/send-feed.ts +44 -0
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
import { feedItems } from "@hogsend/db";
|
|
2
|
+
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
|
+
import { and, count, desc, eq, gt, inArray, lt, sql } from "drizzle-orm";
|
|
4
|
+
import { streamSSE } from "hono/streaming";
|
|
5
|
+
import type { AppEnv } from "../../app.js";
|
|
6
|
+
import { ingestEvent } from "../../lib/ingestion.js";
|
|
7
|
+
import { getRedis } from "../../lib/redis.js";
|
|
8
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
9
|
+
import { resolveFeedRecipient } from "./recipient.js";
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Serialization
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
type FeedItemRow = typeof feedItems.$inferSelect;
|
|
16
|
+
|
|
17
|
+
const feedItemSchema = z.object({
|
|
18
|
+
id: z.string(),
|
|
19
|
+
type: z.string(),
|
|
20
|
+
title: z.string().nullable(),
|
|
21
|
+
body: z.string().nullable(),
|
|
22
|
+
blocks: z.array(z.record(z.string(), z.unknown())).nullable(),
|
|
23
|
+
actionUrl: z.string().nullable(),
|
|
24
|
+
metadata: z.record(z.string(), z.unknown()).nullable(),
|
|
25
|
+
category: z.string(),
|
|
26
|
+
status: z.enum(["unseen", "seen", "read", "archived"]),
|
|
27
|
+
seenAt: z.string().nullable(),
|
|
28
|
+
readAt: z.string().nullable(),
|
|
29
|
+
archivedAt: z.string().nullable(),
|
|
30
|
+
createdAt: z.string(),
|
|
31
|
+
updatedAt: z.string(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
/** Deps the per-item `inapp.*` emit needs from the container. */
|
|
35
|
+
type IngestDeps = Pick<
|
|
36
|
+
Parameters<typeof ingestEvent>[0],
|
|
37
|
+
"db" | "registry" | "hatchet" | "logger" | "analytics"
|
|
38
|
+
>;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Emit one server-side `inapp.*` event per updated feed item id (shared by
|
|
42
|
+
* `/mark` and `/mark-all`'s per-item branch). The idempotency key matches the
|
|
43
|
+
* SDK's optimistic client capture so the journey fires once.
|
|
44
|
+
*/
|
|
45
|
+
function emitMarkEvents(
|
|
46
|
+
deps: IngestDeps,
|
|
47
|
+
args: {
|
|
48
|
+
ids: { id: string }[];
|
|
49
|
+
eventType: string;
|
|
50
|
+
feedId: string;
|
|
51
|
+
recipientKey: string;
|
|
52
|
+
},
|
|
53
|
+
): Promise<unknown> {
|
|
54
|
+
return Promise.allSettled(
|
|
55
|
+
args.ids.map((r) =>
|
|
56
|
+
ingestEvent({
|
|
57
|
+
...deps,
|
|
58
|
+
event: {
|
|
59
|
+
event: args.eventType,
|
|
60
|
+
// recipientKey IS the canonical contact key — pass it as userId so
|
|
61
|
+
// the resolver lands on the SAME contact.
|
|
62
|
+
userId: args.recipientKey,
|
|
63
|
+
eventProperties: { feedItemId: r.id, feedId: args.feedId },
|
|
64
|
+
idempotencyKey: `inapp:${args.feedId}:${r.id}:${args.eventType}`,
|
|
65
|
+
source: "inapp",
|
|
66
|
+
},
|
|
67
|
+
}),
|
|
68
|
+
),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function serializeFeedItem(row: FeedItemRow) {
|
|
73
|
+
return {
|
|
74
|
+
id: row.id,
|
|
75
|
+
type: row.type,
|
|
76
|
+
title: row.title ?? null,
|
|
77
|
+
body: row.body ?? null,
|
|
78
|
+
blocks: (row.blocks ?? null) as Record<string, unknown>[] | null,
|
|
79
|
+
actionUrl: row.actionUrl ?? null,
|
|
80
|
+
metadata: (row.metadata ?? null) as Record<string, unknown> | null,
|
|
81
|
+
category: row.category,
|
|
82
|
+
status: row.status,
|
|
83
|
+
seenAt: row.seenAt?.toISOString() ?? null,
|
|
84
|
+
readAt: row.readAt?.toISOString() ?? null,
|
|
85
|
+
archivedAt: row.archivedAt?.toISOString() ?? null,
|
|
86
|
+
createdAt: row.createdAt.toISOString(),
|
|
87
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
// Mark-state model
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
const markState = z.enum(["seen", "read", "archived", "unseen", "unread"]);
|
|
96
|
+
type MarkState = z.infer<typeof markState>;
|
|
97
|
+
|
|
98
|
+
type FeedUpdateSet = Partial<{
|
|
99
|
+
status: "unseen" | "seen" | "read" | "archived";
|
|
100
|
+
seenAt: Date | null;
|
|
101
|
+
readAt: Date | null;
|
|
102
|
+
archivedAt: Date | null;
|
|
103
|
+
updatedAt: Date;
|
|
104
|
+
}>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Map a requested mark `state` to (a) the row UPDATE patch and (b) the server-
|
|
108
|
+
* side `inapp.*` event name. The DB enum is `[unseen, seen, read, archived]`;
|
|
109
|
+
* `unread` is a virtual state meaning "seen-but-not-read" (status `seen`, clear
|
|
110
|
+
* `readAt`).
|
|
111
|
+
*/
|
|
112
|
+
function markStateToUpdate(state: MarkState): {
|
|
113
|
+
set: FeedUpdateSet;
|
|
114
|
+
eventType: string;
|
|
115
|
+
} {
|
|
116
|
+
const now = new Date();
|
|
117
|
+
switch (state) {
|
|
118
|
+
case "seen":
|
|
119
|
+
return {
|
|
120
|
+
set: { status: "seen", seenAt: now, updatedAt: now },
|
|
121
|
+
eventType: "inapp.item_seen",
|
|
122
|
+
};
|
|
123
|
+
case "read":
|
|
124
|
+
return {
|
|
125
|
+
// `seenAt` is only set here when null is desired; we always stamp it so a
|
|
126
|
+
// read implies seen.
|
|
127
|
+
set: { status: "read", readAt: now, seenAt: now, updatedAt: now },
|
|
128
|
+
eventType: "inapp.item_read",
|
|
129
|
+
};
|
|
130
|
+
case "archived":
|
|
131
|
+
return {
|
|
132
|
+
set: { status: "archived", archivedAt: now, updatedAt: now },
|
|
133
|
+
eventType: "inapp.item_archived",
|
|
134
|
+
};
|
|
135
|
+
case "unseen":
|
|
136
|
+
return {
|
|
137
|
+
set: { status: "unseen", seenAt: null, readAt: null, updatedAt: now },
|
|
138
|
+
eventType: "inapp.item_unseen",
|
|
139
|
+
};
|
|
140
|
+
case "unread":
|
|
141
|
+
return {
|
|
142
|
+
set: { status: "seen", readAt: null, updatedAt: now },
|
|
143
|
+
eventType: "inapp.item_unread",
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
// Schemas
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
const listQuerySchema = z.object({
|
|
153
|
+
feedId: z.string().optional(),
|
|
154
|
+
status: z.enum(["unseen", "seen", "read", "archived", "all"]).optional(),
|
|
155
|
+
before: z.string().optional(),
|
|
156
|
+
after: z.string().optional(),
|
|
157
|
+
pageSize: z.coerce.number().int().positive().max(100).optional(),
|
|
158
|
+
// Recipient resolution (server-side; never trusted as recipientKey directly).
|
|
159
|
+
userToken: z.string().optional(),
|
|
160
|
+
anonymousId: z.string().optional(),
|
|
161
|
+
userId: z.string().optional(),
|
|
162
|
+
email: z.string().optional(),
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const listResponseSchema = z.object({
|
|
166
|
+
items: z.array(feedItemSchema),
|
|
167
|
+
pageInfo: z.object({
|
|
168
|
+
before: z.string().nullable(),
|
|
169
|
+
after: z.string().nullable(),
|
|
170
|
+
hasNextPage: z.boolean(),
|
|
171
|
+
}),
|
|
172
|
+
metadata: z.object({
|
|
173
|
+
total_count: z.number(),
|
|
174
|
+
unseen_count: z.number(),
|
|
175
|
+
unread_count: z.number(),
|
|
176
|
+
}),
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const markBodySchema = z.object({
|
|
180
|
+
ids: z.array(z.string()).min(1),
|
|
181
|
+
state: markState,
|
|
182
|
+
feedId: z.string().optional(),
|
|
183
|
+
userToken: z.string().optional(),
|
|
184
|
+
anonymousId: z.string().optional(),
|
|
185
|
+
userId: z.string().optional(),
|
|
186
|
+
email: z.string().optional(),
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const markAllBodySchema = z.object({
|
|
190
|
+
state: markState,
|
|
191
|
+
feedId: z.string().optional(),
|
|
192
|
+
userToken: z.string().optional(),
|
|
193
|
+
anonymousId: z.string().optional(),
|
|
194
|
+
userId: z.string().optional(),
|
|
195
|
+
email: z.string().optional(),
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
const streamQuerySchema = z.object({
|
|
199
|
+
feedId: z.string().optional(),
|
|
200
|
+
userToken: z.string().optional(),
|
|
201
|
+
anonymousId: z.string().optional(),
|
|
202
|
+
userId: z.string().optional(),
|
|
203
|
+
email: z.string().optional(),
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
const listRoute = createRoute({
|
|
207
|
+
method: "get",
|
|
208
|
+
path: "/",
|
|
209
|
+
tags: ["Feed"],
|
|
210
|
+
summary: "List in-app feed items for the resolved recipient",
|
|
211
|
+
description:
|
|
212
|
+
"Recipient-scoped server-side. A publishable key reads its own anon feed (anonymousId) or a token-verified userId; a secret key may pass userId/email directly. NEVER reads recipientKey from the request.",
|
|
213
|
+
request: { query: listQuerySchema },
|
|
214
|
+
responses: {
|
|
215
|
+
200: {
|
|
216
|
+
content: { "application/json": { schema: listResponseSchema } },
|
|
217
|
+
description: "The recipient's feed page + counts",
|
|
218
|
+
},
|
|
219
|
+
400: {
|
|
220
|
+
content: { "application/json": { schema: errorSchema } },
|
|
221
|
+
description: "Missing identity",
|
|
222
|
+
},
|
|
223
|
+
403: {
|
|
224
|
+
content: { "application/json": { schema: errorSchema } },
|
|
225
|
+
description: "Invalid userToken",
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const markRoute = createRoute({
|
|
231
|
+
method: "post",
|
|
232
|
+
path: "/mark",
|
|
233
|
+
tags: ["Feed"],
|
|
234
|
+
summary: "Mark specific feed items",
|
|
235
|
+
description:
|
|
236
|
+
"Updates the given item ids INTERSECTED with the recipient's own rows (a pk_ caller can never read or mutate another recipient's items, even by guessing ids), then emits an `inapp.*` event server-side (deduped against the client's optimistic capture by a shared idempotency key).",
|
|
237
|
+
request: {
|
|
238
|
+
body: { content: { "application/json": { schema: markBodySchema } } },
|
|
239
|
+
},
|
|
240
|
+
responses: {
|
|
241
|
+
200: {
|
|
242
|
+
content: {
|
|
243
|
+
"application/json": {
|
|
244
|
+
schema: z.object({ updated: z.number() }),
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
description: "Items updated",
|
|
248
|
+
},
|
|
249
|
+
400: {
|
|
250
|
+
content: { "application/json": { schema: errorSchema } },
|
|
251
|
+
description: "Missing identity",
|
|
252
|
+
},
|
|
253
|
+
403: {
|
|
254
|
+
content: { "application/json": { schema: errorSchema } },
|
|
255
|
+
description: "Invalid userToken",
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const markAllRoute = createRoute({
|
|
261
|
+
method: "post",
|
|
262
|
+
path: "/mark-all",
|
|
263
|
+
tags: ["Feed"],
|
|
264
|
+
summary: "Mark all of the recipient's feed items",
|
|
265
|
+
request: {
|
|
266
|
+
body: { content: { "application/json": { schema: markAllBodySchema } } },
|
|
267
|
+
},
|
|
268
|
+
responses: {
|
|
269
|
+
200: {
|
|
270
|
+
content: {
|
|
271
|
+
"application/json": {
|
|
272
|
+
schema: z.object({ updated: z.number() }),
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
description: "Items updated",
|
|
276
|
+
},
|
|
277
|
+
400: {
|
|
278
|
+
content: { "application/json": { schema: errorSchema } },
|
|
279
|
+
description: "Missing identity",
|
|
280
|
+
},
|
|
281
|
+
403: {
|
|
282
|
+
content: { "application/json": { schema: errorSchema } },
|
|
283
|
+
description: "Invalid userToken",
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
const streamRoute = createRoute({
|
|
289
|
+
method: "get",
|
|
290
|
+
path: "/stream",
|
|
291
|
+
tags: ["Feed"],
|
|
292
|
+
summary: "SSE stream of realtime feed events for the resolved recipient",
|
|
293
|
+
description:
|
|
294
|
+
"Server-Sent Events over `feed:<recipientKey>` (Redis pub/sub via a DEDICATED subscriber connection). Closes the subscriber on disconnect.",
|
|
295
|
+
request: { query: streamQuerySchema },
|
|
296
|
+
responses: {
|
|
297
|
+
200: { description: "SSE stream" },
|
|
298
|
+
400: {
|
|
299
|
+
content: { "application/json": { schema: errorSchema } },
|
|
300
|
+
description: "Missing identity",
|
|
301
|
+
},
|
|
302
|
+
403: {
|
|
303
|
+
content: { "application/json": { schema: errorSchema } },
|
|
304
|
+
description: "Invalid userToken",
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// The feed router does NOT re-apply auth internally — the data-plane prefix gate
|
|
310
|
+
// in `routes/index.ts` (`requirePublishableOrIngest`) runs before requests reach
|
|
311
|
+
// here. The routes still fail-closed on identity via `resolveFeedRecipient`.
|
|
312
|
+
export const feedRouter = new OpenAPIHono<AppEnv>()
|
|
313
|
+
.openapi(listRoute, async (c) => {
|
|
314
|
+
const { db } = c.get("container");
|
|
315
|
+
const q = c.req.valid("query");
|
|
316
|
+
|
|
317
|
+
const rec = await resolveFeedRecipient(c, q);
|
|
318
|
+
if (!rec.ok) return c.json({ error: rec.error }, rec.status);
|
|
319
|
+
|
|
320
|
+
// EVERY query is scoped WHERE recipient_key = <server-derived key>.
|
|
321
|
+
const where = [eq(feedItems.recipientKey, rec.recipientKey)];
|
|
322
|
+
if (q.feedId) where.push(eq(feedItems.category, q.feedId));
|
|
323
|
+
if (q.status && q.status !== "all") {
|
|
324
|
+
where.push(eq(feedItems.status, q.status));
|
|
325
|
+
}
|
|
326
|
+
// Guard against an unparseable cursor: `new Date("garbage")` is `Invalid
|
|
327
|
+
// Date`, which drizzle would bind as an invalid timestamp (Postgres 22007 →
|
|
328
|
+
// 500). Skip the bound rather than error; the recipient scope still holds.
|
|
329
|
+
if (q.before) {
|
|
330
|
+
const d = new Date(q.before);
|
|
331
|
+
if (!Number.isNaN(d.getTime())) where.push(lt(feedItems.createdAt, d));
|
|
332
|
+
}
|
|
333
|
+
if (q.after) {
|
|
334
|
+
const d = new Date(q.after);
|
|
335
|
+
if (!Number.isNaN(d.getTime())) where.push(gt(feedItems.createdAt, d));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// `pageSize` is already capped at 100 by the query schema (`.max(100)`).
|
|
339
|
+
const pageSize = q.pageSize ?? 20;
|
|
340
|
+
const rows = await db
|
|
341
|
+
.select()
|
|
342
|
+
.from(feedItems)
|
|
343
|
+
.where(and(...where))
|
|
344
|
+
.orderBy(desc(feedItems.createdAt))
|
|
345
|
+
.limit(pageSize + 1);
|
|
346
|
+
|
|
347
|
+
const hasNextPage = rows.length > pageSize;
|
|
348
|
+
const page = rows.slice(0, pageSize);
|
|
349
|
+
|
|
350
|
+
// Recipient-scoped metadata counts (independent of the page filters, except
|
|
351
|
+
// the same recipient scope).
|
|
352
|
+
const metaRows = await db
|
|
353
|
+
.select({
|
|
354
|
+
total: count(),
|
|
355
|
+
unseen: count(sql`CASE WHEN ${feedItems.status} = 'unseen' THEN 1 END`),
|
|
356
|
+
unread: count(
|
|
357
|
+
sql`CASE WHEN ${feedItems.status} IN ('unseen', 'seen') THEN 1 END`,
|
|
358
|
+
),
|
|
359
|
+
})
|
|
360
|
+
.from(feedItems)
|
|
361
|
+
.where(eq(feedItems.recipientKey, rec.recipientKey));
|
|
362
|
+
const m = metaRows[0] ?? { total: 0, unseen: 0, unread: 0 };
|
|
363
|
+
|
|
364
|
+
return c.json(
|
|
365
|
+
{
|
|
366
|
+
items: page.map(serializeFeedItem),
|
|
367
|
+
pageInfo: {
|
|
368
|
+
before: page.at(-1)?.createdAt.toISOString() ?? null,
|
|
369
|
+
after: page[0]?.createdAt.toISOString() ?? null,
|
|
370
|
+
hasNextPage,
|
|
371
|
+
},
|
|
372
|
+
metadata: {
|
|
373
|
+
total_count: m.total,
|
|
374
|
+
unseen_count: m.unseen,
|
|
375
|
+
unread_count: m.unread,
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
200,
|
|
379
|
+
);
|
|
380
|
+
})
|
|
381
|
+
.openapi(markRoute, async (c) => {
|
|
382
|
+
const { db, registry, hatchet, logger, analytics } = c.get("container");
|
|
383
|
+
const body = c.req.valid("json");
|
|
384
|
+
|
|
385
|
+
const rec = await resolveFeedRecipient(c, body);
|
|
386
|
+
if (!rec.ok) return c.json({ error: rec.error }, rec.status);
|
|
387
|
+
|
|
388
|
+
const { set, eventType } = markStateToUpdate(body.state);
|
|
389
|
+
const feedId = body.feedId ?? "in_app";
|
|
390
|
+
|
|
391
|
+
// INTERSECT the requested ids with the recipient's OWN rows — fail-closed
|
|
392
|
+
// scoping. `recipientKey` is server-derived, NOT from the body, so a pk_
|
|
393
|
+
// caller can never mutate another recipient's items even by guessing ids.
|
|
394
|
+
const updated = await db
|
|
395
|
+
.update(feedItems)
|
|
396
|
+
.set(set)
|
|
397
|
+
.where(
|
|
398
|
+
and(
|
|
399
|
+
eq(feedItems.recipientKey, rec.recipientKey),
|
|
400
|
+
inArray(feedItems.id, body.ids),
|
|
401
|
+
),
|
|
402
|
+
)
|
|
403
|
+
.returning({ id: feedItems.id });
|
|
404
|
+
|
|
405
|
+
// Emit `inapp.*` server-side per updated id. Shared idempotency key dedups
|
|
406
|
+
// against the SDK's optimistic client capture (whichever lands second is
|
|
407
|
+
// absorbed by `user_events.idempotencyKey`), so the journey fires once.
|
|
408
|
+
await emitMarkEvents(
|
|
409
|
+
{ db, registry, hatchet, logger, analytics },
|
|
410
|
+
{ ids: updated, eventType, feedId, recipientKey: rec.recipientKey },
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
return c.json({ updated: updated.length }, 200);
|
|
414
|
+
})
|
|
415
|
+
.openapi(markAllRoute, async (c) => {
|
|
416
|
+
const { db, registry, hatchet, logger, analytics } = c.get("container");
|
|
417
|
+
const body = c.req.valid("json");
|
|
418
|
+
|
|
419
|
+
const rec = await resolveFeedRecipient(c, body);
|
|
420
|
+
if (!rec.ok) return c.json({ error: rec.error }, rec.status);
|
|
421
|
+
|
|
422
|
+
const { set, eventType } = markStateToUpdate(body.state);
|
|
423
|
+
const feedId = body.feedId ?? "in_app";
|
|
424
|
+
|
|
425
|
+
const where = [eq(feedItems.recipientKey, rec.recipientKey)];
|
|
426
|
+
if (body.feedId) where.push(eq(feedItems.category, body.feedId));
|
|
427
|
+
|
|
428
|
+
const updated = await db
|
|
429
|
+
.update(feedItems)
|
|
430
|
+
.set(set)
|
|
431
|
+
.where(and(...where))
|
|
432
|
+
.returning({ id: feedItems.id });
|
|
433
|
+
|
|
434
|
+
// Mark-all-read emits a single `inapp.feed_cleared` (not per-item); other
|
|
435
|
+
// states emit per-item `inapp.*`, sharing the dedup key with the client.
|
|
436
|
+
if (body.state === "read") {
|
|
437
|
+
await ingestEvent({
|
|
438
|
+
db,
|
|
439
|
+
registry,
|
|
440
|
+
hatchet,
|
|
441
|
+
logger,
|
|
442
|
+
analytics,
|
|
443
|
+
event: {
|
|
444
|
+
event: "inapp.feed_cleared",
|
|
445
|
+
userId: rec.recipientKey,
|
|
446
|
+
eventProperties: { feedId },
|
|
447
|
+
idempotencyKey: `inapp:${feedId}:all:inapp.feed_cleared`,
|
|
448
|
+
source: "inapp",
|
|
449
|
+
},
|
|
450
|
+
}).catch(() => {});
|
|
451
|
+
} else {
|
|
452
|
+
await emitMarkEvents(
|
|
453
|
+
{ db, registry, hatchet, logger, analytics },
|
|
454
|
+
{ ids: updated, eventType, feedId, recipientKey: rec.recipientKey },
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return c.json({ updated: updated.length }, 200);
|
|
459
|
+
})
|
|
460
|
+
.openapi(streamRoute, async (c) => {
|
|
461
|
+
const rec = await resolveFeedRecipient(c, c.req.valid("query"));
|
|
462
|
+
if (!rec.ok) return c.json({ error: rec.error }, rec.status);
|
|
463
|
+
const channel = `feed:${rec.recipientKey}`;
|
|
464
|
+
|
|
465
|
+
return streamSSE(c, async (stream) => {
|
|
466
|
+
// DEDICATED subscriber connection — NEVER `.subscribe()` on the shared
|
|
467
|
+
// getRedis() singleton (it would poison the rate-limiter/auth/cache).
|
|
468
|
+
const sub = getRedis().duplicate();
|
|
469
|
+
let closed = false;
|
|
470
|
+
const teardown = async () => {
|
|
471
|
+
if (closed) return;
|
|
472
|
+
closed = true;
|
|
473
|
+
try {
|
|
474
|
+
await sub.unsubscribe(channel);
|
|
475
|
+
} catch {
|
|
476
|
+
// best-effort
|
|
477
|
+
}
|
|
478
|
+
// Close the duplicate; no leak.
|
|
479
|
+
sub.disconnect();
|
|
480
|
+
};
|
|
481
|
+
stream.onAbort(() => {
|
|
482
|
+
void teardown();
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
sub.on("message", (_ch, msg) => {
|
|
486
|
+
// writeSSE rejects after close — swallow.
|
|
487
|
+
void stream.writeSSE({ event: "feed", data: msg }).catch(() => {});
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
try {
|
|
491
|
+
await sub.subscribe(channel);
|
|
492
|
+
await stream.writeSSE({ event: "ready", data: "{}" });
|
|
493
|
+
// Keep-alive heartbeat until aborted.
|
|
494
|
+
while (!stream.aborted && !closed) {
|
|
495
|
+
await stream.sleep(25_000);
|
|
496
|
+
if (stream.aborted || closed) break;
|
|
497
|
+
await stream.writeSSE({ event: "ping", data: "{}" }).catch(() => {});
|
|
498
|
+
}
|
|
499
|
+
} finally {
|
|
500
|
+
await teardown();
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
});
|
|
@@ -0,0 +1,183 @@
|
|
|
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 }
|
|
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
|
+
return { ok: true, recipientKey: await canonicalKey(db, { userId }) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 2. Secret key: trust userId/email directly.
|
|
78
|
+
if (!publishable && (params.userId || params.email)) {
|
|
79
|
+
return {
|
|
80
|
+
ok: true,
|
|
81
|
+
recipientKey: await canonicalKey(db, {
|
|
82
|
+
userId: params.userId,
|
|
83
|
+
email: params.email,
|
|
84
|
+
}),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 3. Publishable anon: its raw anon id IS its recipientKey (no resolver — see
|
|
89
|
+
// the doc comment's fold hazard). But a token-less publishable caller may
|
|
90
|
+
// only address its OWN browser anon id — NEVER an identified contact's
|
|
91
|
+
// canonical key. `sendFeedItem` stores an identified recipient's feed rows
|
|
92
|
+
// under `external_id ?? email`-derived key, so reject any `anonymousId` that
|
|
93
|
+
// collides with an identified contact's key (mirrors the events route's
|
|
94
|
+
// `restrictToAnonymous` / `PublishableAnonymousMergeError` invariant).
|
|
95
|
+
if (params.anonymousId) {
|
|
96
|
+
if (publishable && (await collidesWithIdentified(db, params.anonymousId))) {
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
status: 403,
|
|
100
|
+
error: "anonymousId is not addressable",
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return { ok: true, recipientKey: params.anonymousId };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 4. No identity → fail-closed.
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
status: 400,
|
|
110
|
+
error: "anonymousId, userId, email, or userToken is required",
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* True when `value` is the canonical key of an IDENTIFIED contact — i.e. a live
|
|
116
|
+
* contact's `external_id`, or its `email` when that is its canonical key (no
|
|
117
|
+
* `external_id`). Such a value names an identified person's feed rows, so a
|
|
118
|
+
* token-less publishable caller must NOT be allowed to claim it as an "anon id".
|
|
119
|
+
*
|
|
120
|
+
* A genuine browser anon id only ever matches a contact via `anonymous_id` whose
|
|
121
|
+
* canonical key is that same anon id (the contact has no `external_id`) — that is
|
|
122
|
+
* the caller's OWN anon contact and is allowed (returns false).
|
|
123
|
+
*/
|
|
124
|
+
async function collidesWithIdentified(
|
|
125
|
+
db: Database,
|
|
126
|
+
value: string,
|
|
127
|
+
): Promise<boolean> {
|
|
128
|
+
const rows = await db
|
|
129
|
+
.select({
|
|
130
|
+
externalId: contacts.externalId,
|
|
131
|
+
email: contacts.email,
|
|
132
|
+
anonymousId: contacts.anonymousId,
|
|
133
|
+
})
|
|
134
|
+
.from(contacts)
|
|
135
|
+
.where(
|
|
136
|
+
and(
|
|
137
|
+
or(
|
|
138
|
+
eq(contacts.externalId, value),
|
|
139
|
+
eq(contacts.email, value),
|
|
140
|
+
eq(contacts.anonymousId, value),
|
|
141
|
+
),
|
|
142
|
+
isNull(contacts.deletedAt),
|
|
143
|
+
),
|
|
144
|
+
);
|
|
145
|
+
for (const row of rows) {
|
|
146
|
+
// The supplied value is this contact's `external_id` → its rows are keyed on
|
|
147
|
+
// it (identified). Reject.
|
|
148
|
+
if (row.externalId === value) return true;
|
|
149
|
+
// The supplied value is this contact's `email` AND that email is its
|
|
150
|
+
// canonical key (no external_id) → identified rows are keyed on it. Reject.
|
|
151
|
+
if (row.email === value && !row.externalId) return true;
|
|
152
|
+
}
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Canonical key (`external_id ?? anonymous_id ?? id`) for a known contact. Prefer
|
|
158
|
+
* an `email` match (most specific send target), then `userId` (external id or
|
|
159
|
+
* uuid via `resolveContact`). When no contact exists yet, key on the asserted
|
|
160
|
+
* identifier — a future `sendFeedItem({ recipient: { userId/email } })` resolves
|
|
161
|
+
* to a contact whose canonical key is that same value, so the two agree.
|
|
162
|
+
*/
|
|
163
|
+
async function canonicalKey(
|
|
164
|
+
db: Database,
|
|
165
|
+
ident: { userId?: string; email?: string },
|
|
166
|
+
): Promise<string> {
|
|
167
|
+
if (ident.email) {
|
|
168
|
+
const email = normalizeEmail(ident.email);
|
|
169
|
+
const rows = await db
|
|
170
|
+
.select()
|
|
171
|
+
.from(contacts)
|
|
172
|
+
.where(and(eq(contacts.email, email), isNull(contacts.deletedAt)))
|
|
173
|
+
.limit(1);
|
|
174
|
+
if (rows[0]) return contactKey(rows[0]);
|
|
175
|
+
return email;
|
|
176
|
+
}
|
|
177
|
+
if (ident.userId) {
|
|
178
|
+
const row = await resolveContact({ db, id: ident.userId });
|
|
179
|
+
if (row) return contactKey(row);
|
|
180
|
+
return ident.userId;
|
|
181
|
+
}
|
|
182
|
+
return "";
|
|
183
|
+
}
|