notifkit 0.1.15 → 0.1.16

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 (85) hide show
  1. package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
  2. package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
  3. package/dashboard/dist/index.html +2 -2
  4. package/dist/{bootstrap-BOmT69OH.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
  5. package/dist/{bulk-ZPiOJRx-.mjs → bulk-CJ5QXiPa.mjs} +1 -1
  6. package/dist/index.d.mts +71 -27
  7. package/dist/index.mjs +2 -2
  8. package/dist/{main-CCqcFDDe.mjs → main-6_bXQBDH.mjs} +21 -41
  9. package/dist/{main-BdZvBgV7.mjs → main-8nP3qmCT.mjs} +22 -48
  10. package/dist/{main-C0m9-Eos.mjs → main-B82bsFoy.mjs} +183 -334
  11. package/dist/{main-CTjaZ7ZD.mjs → main-CpaHF1Zw.mjs} +13 -15
  12. package/dist/{main-JEXBLP2A.mjs → main-DULD8-th.mjs} +8 -6
  13. package/dist/{main-C6S3EsJ3.mjs → main-ZW5RaiOK.mjs} +77 -64
  14. package/dist/{main-g33jpia4.mjs → main-g1KEcXXp.mjs} +676 -582
  15. package/dist/{main-24J4U8yP.mjs → main-mGIT8jv4.mjs} +4 -4
  16. package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
  17. package/dist/{src-9LXITcNi.mjs → src-BE_EUpZ6.mjs} +93 -93
  18. package/package.json +1 -1
  19. package/scripts/create-project.mjs +6 -2
  20. package/src/client.ts +3 -3
  21. package/src/config/index.ts +1 -0
  22. package/src/contracts/common.ts +2 -0
  23. package/src/contracts/envelope.ts +1 -1
  24. package/src/contracts/events/notification-created.ts +2 -0
  25. package/src/contracts/events/notification-delivered.ts +1 -1
  26. package/src/contracts/events/notification-failed.ts +1 -1
  27. package/src/contracts/events/notification-requested.ts +3 -2
  28. package/src/contracts/helpers.ts +1 -2
  29. package/src/contracts/index.ts +1 -0
  30. package/src/contracts/registry.ts +1 -0
  31. package/src/contracts/sdk.ts +8 -37
  32. package/src/db/schema.ts +8 -13
  33. package/src/idempotency/index.ts +6 -8
  34. package/src/metrics/index.ts +2 -0
  35. package/src/rate-limiter/api-rate-limiter.ts +208 -0
  36. package/src/rate-limiter/index.ts +3 -411
  37. package/src/rate-limiter/project-settings-cache.ts +99 -0
  38. package/src/rate-limiter/user-throttle.ts +100 -0
  39. package/src/redis/index.ts +10 -3
  40. package/src/repositories/admin-user.ts +83 -0
  41. package/src/repositories/contact.ts +359 -0
  42. package/src/repositories/index.ts +9 -1416
  43. package/src/repositories/preference.ts +35 -0
  44. package/src/repositories/project.ts +110 -0
  45. package/src/repositories/segment.ts +16 -0
  46. package/src/repositories/template.ts +72 -0
  47. package/src/repositories/types.ts +49 -0
  48. package/src/repositories/user.ts +644 -0
  49. package/src/repositories/workflow.ts +64 -0
  50. package/src/services/ai/main.ts +29 -71
  51. package/src/services/api/admin-static.ts +4 -1
  52. package/src/services/api/handlers/auth.ts +109 -0
  53. package/src/services/api/handlers/campaigns.ts +191 -0
  54. package/src/services/api/handlers/events.ts +99 -0
  55. package/src/services/api/handlers/notifications.ts +356 -0
  56. package/src/services/api/handlers/projects.ts +116 -0
  57. package/src/services/api/handlers/shared.ts +262 -0
  58. package/src/services/api/handlers/suppressions.ts +95 -0
  59. package/src/services/api/handlers/system.ts +314 -0
  60. package/src/services/api/handlers/templates.ts +97 -0
  61. package/src/services/api/handlers/unsubscribe.ts +215 -0
  62. package/src/services/api/handlers/users.ts +262 -0
  63. package/src/services/api/handlers/workflows.ts +150 -0
  64. package/src/services/api/handlers.ts +25 -2190
  65. package/src/services/api/health.ts +133 -0
  66. package/src/services/api/http.ts +12 -0
  67. package/src/services/api/main.ts +32 -322
  68. package/src/services/api/router.ts +1 -1
  69. package/src/services/api/webhooks.ts +172 -0
  70. package/src/services/delivery/main.ts +256 -498
  71. package/src/services/engine/main.ts +31 -247
  72. package/src/services/engine/quiet-hours.ts +151 -0
  73. package/src/services/engine/schedule-or-dispatch.ts +104 -0
  74. package/src/services/enricher/main.ts +9 -21
  75. package/src/services/events/main.ts +2 -2
  76. package/src/services/scheduler/main.ts +16 -25
  77. package/src/services/workflow/duration.ts +24 -0
  78. package/src/services/workflow/main.ts +6 -164
  79. package/src/services/workflow/timers.ts +157 -0
  80. package/src/shared/events.ts +3 -2
  81. package/src/templates/render.ts +1 -0
  82. package/src/workers/index.ts +7 -4
  83. package/src/workflows/sdk.ts +1 -0
  84. package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
  85. package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
@@ -1,2195 +1,30 @@
1
- import { randomUUID, randomBytes, createHash } from "node:crypto";
2
- import type { IncomingMessage, ServerResponse } from "node:http";
3
- import type { Logger } from "@/logger/index.js";
4
- import type { RedisClient } from "@/redis/index.js";
5
- import type { StreamProducer } from "@/queue/index.js";
6
- import type {
7
- UserRepository,
8
- ContactRepository,
9
- TemplateRepository,
10
- ProjectRepository,
11
- WorkflowRepository,
12
- SegmentRepository,
13
- AdminUserRepository,
14
- } from "@/repositories/index.js";
15
- import {
16
- verifyPassword,
17
- createAdminSession,
18
- revokeAdminSession,
19
- getAdminSession,
20
- DUMMY_PASSWORD_HASH,
21
- } from "@/services/auth/index.js";
22
- import type { Preferences } from "@/contracts/index.js";
23
- import {
24
- AddUserSchema,
25
- UpdateUserSchema,
26
- BatchAddContactsSchema,
27
- type UserContactInput,
28
- SyncTemplatesSchema,
29
- NotifyRequestSchema,
30
- ContactChannelSchema,
31
- type ContactChannel,
32
- PreferencesSchema,
33
- type NotificationRequestedPayload,
34
- type NotificationTarget,
35
- buildStreamEvent,
36
- CreateWorkflowSchema,
37
- TriggerWorkflowSchema,
38
- STREAMS,
39
- CONSUMER_GROUPS,
40
- PUBSUB_CHANNELS,
41
- } from "@/contracts/index.js";
42
- import { readJsonBody, sendJson, sendNoContent, sendValidationError } from "./http.js";
43
- import type { RouteContext } from "./router.js";
44
- import type { LiveDeliveryEvents } from "./live-events.js";
45
- import { globalEmitter, getPriorityBucket, normaliseTarget } from "@/shared/index.js";
46
- import { metrics } from "@/metrics/index.js";
47
- import { eq, desc, and, lte, gte, sql, like, or, isNotNull, inArray } from "drizzle-orm";
48
- import {
49
- messageLogs,
50
- workflowDefinitions,
51
- scheduledPayloads,
52
- suppressions,
53
- users as dbUsers,
54
- userTopicPreferences,
55
- deliveryOutbox,
56
- } from "@/db/schema.js";
57
- import { readBaseConfig } from "@/config/index.js";
58
- import { verifyUnsubscribeToken } from "@/unsubscribe/index.js";
59
- import type { Db } from "@/db/index.js";
60
- import { z } from "zod";
61
-
62
- const IngestEventSchema = z.object({
63
- name: z.string().min(1),
64
- properties: z.record(z.string(), z.unknown()),
65
- });
66
-
67
- export interface Deps {
68
- logger: Logger;
69
- redis: RedisClient;
70
- producers: Record<string, StreamProducer>;
71
- userRepo: UserRepository;
72
- contactRepo: ContactRepository;
73
- templateRepo: TemplateRepository;
74
- projectRepo: ProjectRepository;
75
- workflowRepo: WorkflowRepository;
76
- segmentRepo: SegmentRepository;
77
- adminUserRepo?: AdminUserRepository;
78
- db: Db;
79
- /** Delivery outcomes for GET /v1/events/stream. */
80
- liveEvents: LiveDeliveryEvents;
81
- }
82
-
83
- // Inline user shape (email/phone/pushToken already normalised to string[] by Zod).
84
- interface InlineUserLike {
85
- id: string;
86
- language?: string;
87
- timezone?: string;
88
- contacts?: UserContactInput[];
89
- email?: string[];
90
- phone?: string[];
91
- pushToken?: string[];
92
- segments?: string[];
93
- preferences?: Preferences;
94
- }
95
-
96
- interface ResolvedContact {
97
- channel: ContactChannel;
98
- target: string;
99
- label?: string;
100
- isPrimary?: boolean;
101
- enabled?: boolean;
102
- preferences?: Preferences;
103
- }
104
-
105
- /** Map an inline or user input's contacts and legacy arrays into resolved contact records. */
106
- function contactsOf(user: InlineUserLike): ResolvedContact[] {
107
- const list: ResolvedContact[] = [];
108
-
109
- if (user.contacts && Array.isArray(user.contacts)) {
110
- for (const c of user.contacts) {
111
- list.push({
112
- channel: c.channel,
113
- target: c.target,
114
- label: c.label,
115
- isPrimary: c.isPrimary,
116
- enabled: c.enabled,
117
- preferences: c.preferences,
118
- });
119
- }
120
- }
121
-
122
- if (user.email) {
123
- for (const target of user.email) {
124
- list.push({ channel: "email", target });
125
- }
126
- }
127
- if (user.phone) {
128
- for (const target of user.phone) {
129
- list.push({ channel: "sms", target });
130
- }
131
- }
132
- if (user.pushToken) {
133
- for (const target of user.pushToken) {
134
- list.push({ channel: "push", target });
135
- }
136
- }
137
-
138
- return list;
139
- }
140
-
141
- /** Persist user records + their contacts in bulk. Shared by addUser and inline notify. */
142
- async function persistUsers(deps: Deps, users: InlineUserLike[], projectId: string): Promise<void> {
143
- const usersList = users.map((u) => {
144
- const primaryEmail = u.email?.[0] ?? u.contacts?.find((c) => c.channel === "email")?.target;
145
-
146
- // Omitted fields stay omitted: the upsert merges what is given into the
147
- // stored profile, so an inline `{ id, phone }` on notify must not reset the
148
- // user's timezone, language or email. Defaults are applied when read.
149
- return {
150
- userId: u.id,
151
- language: u.language,
152
- timezone: u.timezone,
153
- email: primaryEmail,
154
- segments: u.segments ?? [],
155
- preferences: u.preferences ?? {},
156
- };
157
- });
158
-
159
- const contactsList: any[] = [];
160
- for (const u of users) {
161
- for (const c of contactsOf(u)) {
162
- contactsList.push({
163
- userId: u.id,
164
- channel: c.channel,
165
- target: c.target,
166
- preferences: c.preferences ?? {},
167
- });
168
- }
169
- }
170
-
171
- await deps.db.transaction(async (tx) => {
172
- const txUserRepo =
173
- deps.userRepo.constructor.name === "Object"
174
- ? deps.userRepo
175
- : new (deps.userRepo.constructor as any)(tx);
176
- const txContactRepo =
177
- deps.contactRepo.constructor.name === "Object"
178
- ? deps.contactRepo
179
- : new (deps.contactRepo.constructor as any)(tx);
180
- await txUserRepo.upsertManyFull(projectId, usersList);
181
- await txContactRepo.upsertMany(projectId, contactsList);
182
- });
183
- }
184
-
185
- /**
186
- * A dead-letter entry, read the way StreamConsumer writes it: the original
187
- * event JSON under `data`, carrying a `dlq` block that records which stream it
188
- * failed on. Flat `payload`/`eventType` fields are accepted for entries written
189
- * by hand or by older versions.
190
- */
191
- interface DlqEntry {
192
- id: string;
193
- eventType: string;
194
- payload: any;
195
- projectId?: string;
196
- error: string;
197
- timestamp: string;
198
- /** The event as it was published, without its `dlq` block. */
199
- event: Record<string, any> | null;
200
- originalStream?: string;
201
- fields: Record<string, string>;
202
- }
203
-
204
- function parseDlqEntry(id: string, rawFields: string[]): DlqEntry {
205
- const fields: Record<string, string> = {};
206
- for (let i = 0; i < rawFields.length; i += 2) {
207
- fields[rawFields[i]!] = rawFields[i + 1]!;
208
- }
209
-
210
- let parsed: Record<string, any> | null = null;
211
- if (fields.data) {
212
- try {
213
- parsed = JSON.parse(fields.data);
214
- } catch {
215
- parsed = null;
216
- }
217
- }
218
- const { dlq, ...event } = parsed ?? {};
219
-
220
- let payload: any = fields;
221
- if (parsed) {
222
- payload = event.payload;
223
- } else if (fields.payload) {
224
- try {
225
- payload = JSON.parse(fields.payload);
226
- } catch {
227
- payload = fields.payload;
228
- }
229
- }
230
-
231
- const ms = Number(id.split("-")[0]);
232
- return {
233
- id,
234
- eventType: event.type ?? fields.eventType ?? fields.event_type ?? "unknown",
235
- payload,
236
- projectId: payload?.projectId ?? payload?.project_id ?? fields.projectId,
237
- error: dlq?.reason ?? fields.error ?? fields.reason ?? "Dead letter payload",
238
- timestamp:
239
- dlq?.ackedAt ??
240
- fields.timestamp ??
241
- (Number.isFinite(ms) ? new Date(ms).toISOString() : new Date().toISOString()),
242
- event: parsed ? event : null,
243
- originalStream: dlq?.originalStream,
244
- fields,
245
- };
246
- }
247
-
248
- /**
249
- * Ids that live in uuid columns. Anything else can match no row, and passing it
250
- * to Postgres fails the query outright — a 500 for what is simply not found.
251
- */
252
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
253
- const isUuid = (v: string | undefined): v is string => typeof v === "string" && UUID_RE.test(v);
254
-
255
- /** Opaque position in the delivery log: a row's full-precision timestamp and id. */
256
- function encodeLogCursor(ts: string, id: string): string {
257
- return Buffer.from(JSON.stringify([ts, id])).toString("base64url");
258
- }
259
-
260
- function decodeLogCursor(cursor: string | null | undefined): { ts: string; id: string } | null {
261
- if (!cursor) return null;
262
- // Cursors handed out before this format were a millisecond timestamp.
263
- if (/^\d+$/.test(cursor)) {
264
- return {
265
- ts: new Date(Number(cursor)).toISOString(),
266
- id: "ffffffff-ffff-ffff-ffff-ffffffffffff",
267
- };
268
- }
269
- try {
270
- const [ts, id] = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
271
- if (
272
- typeof ts === "string" &&
273
- typeof id === "string" &&
274
- !Number.isNaN(Date.parse(ts)) &&
275
- /^[0-9a-f-]{36}$/i.test(id)
276
- ) {
277
- return { ts, id };
278
- }
279
- } catch {
280
- // fall through
281
- }
282
- return null;
283
- }
284
-
285
- /**
286
- * A LIKE pattern matching `term` anywhere, with the term's own `%`, `_` and
287
- * `\` taken literally rather than as wildcards.
288
- */
289
- function contains(term: string): string {
290
- return `%${term.replace(/[\\%_]/g, "\\$&")}%`;
291
- }
292
-
293
- function getQueryParam(ctx: RouteContext, key: string): string | undefined {
294
- if (!ctx.query) return undefined;
295
- if (typeof ctx.query.get === "function") {
296
- return ctx.query.get(key) ?? undefined;
297
- }
298
- return (ctx.query as any)[key] ?? undefined;
299
- }
300
-
301
- /**
302
- * Page size from `?limit=`, clamped to [1, max]. Missing or non-numeric
303
- * values fall back to `fallback`; `undefined` there means "no limit".
304
- */
305
- function parseLimit<F extends number | undefined>(
306
- ctx: RouteContext,
307
- fallback: F,
308
- max = 100,
309
- ): number | F {
310
- const n = parseInt(getQueryParam(ctx, "limit") ?? "", 10);
311
- return Number.isNaN(n) ? fallback : Math.min(Math.max(n, 1), max);
312
- }
1
+ import { createTemplatesHandlers } from "./handlers/templates.js";
2
+ import { createUsersHandlers } from "./handlers/users.js";
3
+ import { createNotificationsHandlers } from "./handlers/notifications.js";
4
+ import { createWorkflowsHandlers } from "./handlers/workflows.js";
5
+ import { createEventsHandlers } from "./handlers/events.js";
6
+ import { createProjectsHandlers } from "./handlers/projects.js";
7
+ import { createSystemHandlers } from "./handlers/system.js";
8
+ import { createUnsubscribeHandlers } from "./handlers/unsubscribe.js";
9
+ import { createCampaignsHandlers } from "./handlers/campaigns.js";
10
+ import { createSuppressionsHandlers } from "./handlers/suppressions.js";
11
+ import { createAuthHandlers } from "./handlers/auth.js";
12
+ import type { Deps } from "./handlers/shared.js";
13
+
14
+ export type { Deps };
313
15
 
314
16
  export function createHandlers(deps: Deps) {
315
- const { logger } = deps;
316
-
317
- // ── PUT /v1/templates — initializeApp({ templates }) ──────────────────────
318
- async function syncTemplates(
319
- req: IncomingMessage,
320
- res: ServerResponse,
321
- ctx: RouteContext,
322
- ): Promise<void> {
323
- const parsed = SyncTemplatesSchema.safeParse(await readJsonBody(req));
324
- if (!parsed.success) return sendValidationError(res, parsed.error);
325
-
326
- const synced = await deps.templateRepo.upsertMany(
327
- ctx.projectId!,
328
- parsed.data.templates.map((t) => ({
329
- id: t.id,
330
- channel: t.channel,
331
- topics: t.topic ?? [],
332
- content: t.content,
333
- aiPrompts: (t as any).aiPrompts,
334
- })),
335
- );
336
-
337
- // Invalidate caches
338
- for (const t of parsed.data.templates) {
339
- await deps.redis.native.publish("template.invalidated", `${ctx.projectId}:${t.id}`);
340
- }
341
-
342
- logger.info({ synced }, "templates synced");
343
- sendJson(res, 200, { synced });
344
- }
345
-
346
- // ── POST /v1/users — addUser ──────────────────────────────────────────────
347
- async function addUser(
348
- req: IncomingMessage,
349
- res: ServerResponse,
350
- ctx: RouteContext,
351
- ): Promise<void> {
352
- const parsed = AddUserSchema.safeParse(await readJsonBody(req));
353
- if (!parsed.success) return sendValidationError(res, parsed.error);
354
-
355
- await persistUsers(deps, [parsed.data], ctx.projectId!);
356
- logger.info({ userId: parsed.data.id }, "user upserted");
357
- sendJson(res, 201, { id: parsed.data.id });
358
- }
359
-
360
- // ── PATCH /v1/users/:id — updateUser ──────────────────────────────────────
361
- async function updateUser(
362
- req: IncomingMessage,
363
- res: ServerResponse,
364
- ctx: RouteContext,
365
- ): Promise<void> {
366
- const userId = ctx.params.id!;
367
- const parsed = UpdateUserSchema.safeParse(await readJsonBody(req));
368
- if (!parsed.success) return sendValidationError(res, parsed.error);
369
- const patch = parsed.data;
370
-
371
- const updated = await deps.userRepo.updatePartial(ctx.projectId!, userId, {
372
- language: patch.language,
373
- timezone: patch.timezone,
374
- email: patch.email?.[0] ?? patch.contacts?.find((c) => c.channel === "email")?.target,
375
- segments: patch.segments,
376
- preferences: patch.preferences,
377
- });
378
- if (!updated) return sendJson(res, 404, { error: "user_not_found", id: userId });
379
-
380
- // New contact values in the patch are added (existing ones are kept).
381
- for (const c of contactsOf({ id: userId, ...patch })) {
382
- if (c.preferences) {
383
- await deps.contactRepo.upsert(ctx.projectId!, userId, c.channel, c.target, c.preferences);
384
- } else {
385
- await deps.contactRepo.upsert(ctx.projectId!, userId, c.channel, c.target);
386
- }
387
- }
388
- logger.info({ userId }, "user updated");
389
- sendJson(res, 200, { id: userId });
390
- }
391
-
392
- // ── DELETE /v1/users/:id — deleteUser ─────────────────────────────────────
393
- async function deleteUser(
394
- _req: IncomingMessage,
395
- res: ServerResponse,
396
- ctx: RouteContext,
397
- ): Promise<void> {
398
- const userId = ctx.params.id!;
399
- const deleted = await deps.userRepo.delete(ctx.projectId!, userId);
400
- if (!deleted) return sendJson(res, 404, { error: "user_not_found", id: userId });
401
- logger.info({ userId }, "user deleted");
402
- sendNoContent(res);
403
- }
404
-
405
- // ── POST /v1/users/:id/contacts — addUserContact / batch contacts ─────────
406
- async function addContact(
407
- req: IncomingMessage,
408
- res: ServerResponse,
409
- ctx: RouteContext,
410
- ): Promise<void> {
411
- const userId = ctx.params.id!;
412
- const body = await readJsonBody(req);
413
- const parsed = BatchAddContactsSchema.safeParse(body);
414
- if (!parsed.success) return sendValidationError(res, parsed.error);
415
-
416
- const user = await deps.userRepo.findById(ctx.projectId!, userId);
417
- if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
418
-
419
- if (Array.isArray(parsed.data)) {
420
- const contactsList = parsed.data.map((c) => ({
421
- userId,
422
- channel: c.channel,
423
- target: c.target,
424
- preferences: c.preferences ?? {},
425
- }));
426
- await deps.contactRepo.upsertMany(ctx.projectId!, contactsList);
427
- logger.info({ userId, count: contactsList.length }, "contacts batch added");
428
- sendJson(res, 201, {
429
- userId,
430
- contacts: contactsList.map((c) => ({ channel: c.channel, target: c.target })),
431
- });
432
- } else {
433
- await deps.contactRepo.upsert(
434
- ctx.projectId!,
435
- userId,
436
- parsed.data.channel,
437
- parsed.data.target,
438
- parsed.data.preferences ?? {},
439
- );
440
- logger.info({ userId, channel: parsed.data.channel }, "contact added");
441
- sendJson(res, 201, { userId, channel: parsed.data.channel, target: parsed.data.target });
442
- }
443
- }
444
-
445
- // ── DELETE /v1/users/:id/contacts/:channel/:target — deleteUserContact ────
446
- async function deleteContact(
447
- _req: IncomingMessage,
448
- res: ServerResponse,
449
- ctx: RouteContext,
450
- ): Promise<void> {
451
- const userId = ctx.params.id!;
452
- const channelResult = ContactChannelSchema.safeParse(ctx.params.channel);
453
- if (!channelResult.success)
454
- return sendJson(res, 400, { error: "invalid_channel", channel: ctx.params.channel });
455
-
456
- const deleted = await deps.contactRepo.delete(
457
- ctx.projectId!,
458
- userId,
459
- channelResult.data,
460
- ctx.params.target!,
461
- );
462
- if (!deleted) return sendJson(res, 404, { error: "contact_not_found" });
463
- logger.info({ userId, channel: channelResult.data }, "contact deleted");
464
- sendNoContent(res);
465
- }
466
-
467
- // ── POST /v1/notify — notify ──────────────────────────────────────────────
468
- async function notify(
469
- req: IncomingMessage,
470
- res: ServerResponse,
471
- ctx: RouteContext,
472
- ): Promise<void> {
473
- const rawBody = await readJsonBody(req);
474
- const parsed = NotifyRequestSchema.safeParse(rawBody);
475
-
476
- if (!parsed.success) return sendValidationError(res, parsed.error);
477
- const body = parsed.data;
478
-
479
- // Resolve the (unresolved) target. Inline users are synced first.
480
- let targets: NotificationTarget[] = [];
481
- const inlineUsersToSync: InlineUserLike[] = [];
482
- if (body.user !== undefined) {
483
- const users = Array.isArray(body.user) ? body.user : [body.user];
484
- for (const u of users) {
485
- if (typeof u === "string") {
486
- targets.push({ type: "user", userId: u });
487
- } else {
488
- inlineUsersToSync.push(u);
489
- targets.push({ type: "user", userId: u.id });
490
- }
491
- }
492
-
493
- if (inlineUsersToSync.length > 0) {
494
- try {
495
- await persistUsers(deps, inlineUsersToSync, ctx.projectId!);
496
- } catch (err) {
497
- deps.logger.error({ err }, "inline user bulk sync failed");
498
- }
499
- }
500
- } else if (body.segment !== undefined) {
501
- targets.push({ type: "segment", segment: body.segment });
502
- } else {
503
- targets.push({ type: "topic", topic: body.topic! });
504
- }
505
-
506
- const baseNotificationId = (req.headers["x-idempotency-key"] as string) || randomUUID();
507
-
508
- const priority = body.priority ?? "normal";
509
- const p = getPriorityBucket(priority);
510
- const producer = deps.producers[p] ?? deps.producers.normal!;
511
-
512
- const messageIds: string[] = [];
513
- let lastNotificationId = "";
514
-
515
- const CHUNK_SIZE = 1000;
516
- for (let chunkStart = 0; chunkStart < targets.length; chunkStart += CHUNK_SIZE) {
517
- const chunk = targets.slice(chunkStart, chunkStart + CHUNK_SIZE);
518
-
519
- const events = chunk.map((target, idx) => {
520
- const i = chunkStart + idx;
521
- const notificationId =
522
- targets.length > 1 ? `${baseNotificationId}-${i}` : baseNotificationId;
523
- lastNotificationId = notificationId;
524
-
525
- const payload: NotificationRequestedPayload = {
526
- projectId: ctx.projectId!,
527
- target,
528
- templateId: body.template,
529
- priority,
530
- channels: body.channels,
531
- data: body.data ?? {},
532
- aiPrompts: body.aiPrompts,
533
- fallback: body.fallback ?? false,
534
- scheduledAt: body.sendAt,
535
- // Only a caller's own key: the enricher keeps those for the full
536
- // 24-hour window, and dedupes everything else on the event id.
537
- ...(req.headers["x-idempotency-key"] ? { idempotencyKey: notificationId } : {}),
538
- campaignId: body.campaign,
539
- };
540
-
541
- return buildStreamEvent(
542
- "notification.requested",
543
- payload as Record<string, unknown>,
544
- "api",
545
- notificationId,
546
- );
547
- });
548
-
549
- const { messageIds: chunkMessageIds } = await producer.publishBatch(events);
550
- messageIds.push(...chunkMessageIds);
551
- }
552
-
553
- logger.debug({ count: targets.length, priority: p }, "notification requested");
554
- metrics.messagesPublished.inc({ channel: "api", priority: p }, targets.length);
555
-
556
- if (targets.length === 1) {
557
- sendJson(res, 202, {
558
- messageId: messageIds[0],
559
- notificationId: lastNotificationId,
560
- target: targets[0],
561
- ...(body.campaign ? { campaign: body.campaign } : {}),
562
- });
563
- } else {
564
- sendJson(res, 202, {
565
- messageIds,
566
- notificationIdsBase: baseNotificationId,
567
- batchSize: targets.length,
568
- ...(body.campaign ? { campaign: body.campaign } : {}),
569
- });
570
- }
571
- }
572
-
573
- // ── DELETE /v1/notifications/:taskId — cancelNotification ─────────────────
574
- async function cancelNotification(
575
- req: IncomingMessage,
576
- res: ServerResponse,
577
- ctx: RouteContext,
578
- ): Promise<void> {
579
- const { taskId } = ctx.params;
580
- if (!taskId) return sendJson(res, 400, { error: "missing_task_id" });
581
-
582
- const rows = await deps.db
583
- .select({ payload: scheduledPayloads.payload })
584
- .from(scheduledPayloads)
585
- .where(eq(scheduledPayloads.taskId, taskId))
586
- .limit(1);
587
-
588
- if (rows.length === 0) {
589
- return sendJson(res, 404, {
590
- error: "not_found",
591
- message: "Task not found or already processed",
592
- });
593
- }
594
-
595
- const payload = rows[0]!.payload as any;
596
- if (payload.projectId !== ctx.projectId) {
597
- return sendJson(res, 404, {
598
- error: "not_found",
599
- message: "Task not found or already processed",
600
- });
601
- }
602
-
603
- const deletedRows = await deps.db
604
- .delete(scheduledPayloads)
605
- .where(eq(scheduledPayloads.taskId, taskId))
606
- .returning({ taskId: scheduledPayloads.taskId });
607
-
608
- if (deletedRows.length > 0) {
609
- globalEmitter.emit("notification:canceled", { projectId: ctx.projectId, taskId });
610
- sendJson(res, 200, { success: true });
611
- } else {
612
- sendJson(res, 404, { error: "not_found", message: "Task not found or already processed" });
613
- }
614
- }
615
-
616
- // ── POST /v1/workflows/trigger — triggerWorkflow ──────────────────────────
617
- async function triggerWorkflow(
618
- req: IncomingMessage,
619
- res: ServerResponse,
620
- ctx: RouteContext,
621
- ): Promise<void> {
622
- const parsed = TriggerWorkflowSchema.safeParse(await readJsonBody(req));
623
- if (!parsed.success) return sendValidationError(res, parsed.error);
624
-
625
- const input: Record<string, unknown> = { ...(parsed.data.input ?? {}) };
626
- if (parsed.data.user) {
627
- if (typeof parsed.data.user === "string") {
628
- input.user = {
629
- id: parsed.data.user,
630
- ...(typeof input.user === "object" && input.user
631
- ? (input.user as Record<string, unknown>)
632
- : {}),
633
- };
634
- } else {
635
- try {
636
- await persistUsers(deps, [parsed.data.user], ctx.projectId!);
637
- } catch (err) {
638
- deps.logger.error({ err }, "inline user sync for workflow failed");
639
- }
640
- input.user = {
641
- id: parsed.data.user.id,
642
- ...(typeof input.user === "object" && input.user
643
- ? (input.user as Record<string, unknown>)
644
- : {}),
645
- };
646
- }
647
- }
648
-
649
- const instanceId = randomUUID();
650
- const messageId = await deps.producers.workflow!.publish(
651
- buildStreamEvent(
652
- "workflow.triggered",
653
- {
654
- projectId: ctx.projectId!,
655
- instanceId,
656
- name: parsed.data.name,
657
- input,
658
- },
659
- "api",
660
- instanceId,
661
- ),
662
- );
663
- logger.info({ messageId, instanceId, workflowName: parsed.data.name }, "workflow triggered");
664
- sendJson(res, 202, { messageId, instanceId });
665
- }
666
-
667
- // ── POST /v1/events — ingestEvent ─────────────────────────────────────────
668
- async function ingestEvent(
669
- req: IncomingMessage,
670
- res: ServerResponse,
671
- ctx: RouteContext,
672
- ): Promise<void> {
673
- const tsStr = req.headers["x-timestamp"];
674
- const expiryStr = req.headers["x-expiry"];
675
-
676
- if (tsStr && expiryStr) {
677
- const now = Date.now();
678
- const eventTime = new Date(tsStr as string).getTime();
679
- const expMs = parseInt(expiryStr as string, 10) * 1000;
680
-
681
- // An unreadable timestamp or expiry made every comparison false, which
682
- // let the event through unchecked.
683
- if (Number.isNaN(eventTime) || Number.isNaN(expMs)) {
684
- sendJson(res, 400, {
685
- error: "invalid_timestamp",
686
- message: "x-timestamp and x-expiry must be a date and a number of seconds",
687
- });
688
- return;
689
- }
690
- if (now > eventTime + expMs) {
691
- sendJson(res, 400, { error: "event_expired", message: "Webhook event is expired" });
692
- return;
693
- }
694
- }
695
-
696
- const parsed = IngestEventSchema.safeParse(await readJsonBody(req));
697
- if (!parsed.success) return sendValidationError(res, parsed.error);
698
-
699
- const eventId = randomUUID();
700
- const messageId = await deps.producers.events!.publish(
701
- buildStreamEvent(
702
- "event.received",
703
- {
704
- projectId: ctx.projectId!,
705
- eventName: parsed.data.name,
706
- payload: parsed.data.properties,
707
- },
708
- "api",
709
- eventId,
710
- ),
711
- );
712
- logger.info({ messageId, eventId, eventName: parsed.data.name }, "event received");
713
- sendJson(res, 202, { messageId, eventId });
714
- }
715
- // ── GET /v1/events/stream — getEventsStream ──────────────────────────────────
716
- async function getEventsStream(
717
- req: IncomingMessage,
718
- res: ServerResponse,
719
- ctx: RouteContext,
720
- ): Promise<void> {
721
- let open = true;
722
- let stop: (() => void) | undefined;
723
- req.on("close", () => {
724
- open = false;
725
- stop?.();
726
- });
727
-
728
- const unlisten = await deps.liveEvents.listen((e) => {
729
- // Only events that name this project. One naming none belongs to no
730
- // tenant, so it goes to nobody rather than to everybody.
731
- if (!ctx.projectId || e.projectId !== ctx.projectId) return;
732
- res.write(`event: ${e.event}\n`);
733
- const data =
734
- e.event === "delivery:delivered"
735
- ? { taskId: e.taskId, providerMessageId: e.providerMessageId, channel: e.channel }
736
- : { taskId: e.taskId, error: e.error, channel: e.channel };
737
- res.write(`data: ${JSON.stringify(data)}\n\n`);
738
- });
739
- if (!open) return unlisten();
740
- stop = unlisten;
741
-
742
- // Only once subscribed: a client that has the headers is already listening,
743
- // so whatever it triggers next cannot be missed.
744
- res.writeHead(200, {
745
- "Content-Type": "text/event-stream",
746
- "Cache-Control": "no-cache",
747
- Connection: "keep-alive",
748
- });
749
- res.write("retry: 10000\n\n");
750
- }
751
-
752
- // ── GET /v1/notifications/logs — getNotificationLogs ────────────────────
753
- async function getNotificationLogs(
754
- req: IncomingMessage,
755
- res: ServerResponse,
756
- ctx: RouteContext,
757
- ): Promise<void> {
758
- const limit = parseLimit(ctx, 50);
759
- const cursor = ctx.query.get("cursor");
760
-
761
- const templateId = getQueryParam(ctx, "templateId");
762
- const workflowInstanceId = getQueryParam(ctx, "workflowInstanceId");
763
- const channel = getQueryParam(ctx, "channel");
764
- const status = getQueryParam(ctx, "status");
765
- const taskId = getQueryParam(ctx, "taskId");
766
- const campaign = getQueryParam(ctx, "campaign") || getQueryParam(ctx, "campaignId");
767
- const search = getQueryParam(ctx, "search");
768
-
769
- const conditions = [eq(messageLogs.projectId, ctx.projectId!)];
770
- if (templateId) conditions.push(eq(messageLogs.templateId, templateId));
771
- if (workflowInstanceId) conditions.push(eq(messageLogs.workflowInstanceId, workflowInstanceId));
772
- if (channel) conditions.push(eq(messageLogs.channel, channel as any));
773
- if (status) conditions.push(eq(messageLogs.status, status as any));
774
- if (taskId) conditions.push(eq(messageLogs.taskId, taskId));
775
- if (campaign) conditions.push(eq(messageLogs.campaignId, campaign));
776
- if (search) {
777
- conditions.push(
778
- or(
779
- like(messageLogs.taskId, contains(search)),
780
- like(messageLogs.templateId, contains(search)),
781
- like(messageLogs.providerMessageId, contains(search)),
782
- like(messageLogs.campaignId, contains(search)),
783
- )!,
784
- );
785
- }
786
-
787
- // One entry per task, newest activity first. Rows are scanned in
788
- // (timestamp, id) order — a batch of deliveries shares one timestamp, so
789
- // the timestamp alone cannot mark a place — and a task is listed at its
790
- // newest row. The cursor is that row for the first task of the next page,
791
- // and any task with a row newer than the cursor was listed on an earlier
792
- // page. Paging on a millisecond timestamp over `limit * 2` rows skipped
793
- // tasks that shared a timestamp and dropped any that did not fit the slice.
794
- const start = decodeLogCursor(cursor);
795
- const tsText = sql<string>`${messageLogs.timestamp}::text`;
796
- const position = (ts: string, id: string) => sql`(${ts}::timestamptz, ${id}::uuid)`;
797
- const rowKey = sql`(${messageLogs.timestamp}, ${messageLogs.id})`;
798
-
799
- const order: string[] = [];
800
- const rowsByTask = new Map<string, (typeof messageLogs.$inferSelect)[]>();
801
- let nextCursor: string | null = null;
802
- let scanFrom = start;
803
- let inclusive = true;
804
- const batchSize = Math.max(limit * 4, 50);
805
-
806
- for (let round = 0; round < 50 && nextCursor === null; round++) {
807
- const batch = await deps.db
808
- .select({ row: messageLogs, ts: tsText })
809
- .from(messageLogs)
810
- .where(
811
- and(
812
- ...conditions,
813
- scanFrom
814
- ? sql`${rowKey} ${inclusive ? sql`<=` : sql`<`} ${position(scanFrom.ts, scanFrom.id)}`
815
- : undefined,
816
- ),
817
- )
818
- .orderBy(desc(messageLogs.timestamp), desc(messageLogs.id))
819
- .limit(batchSize);
820
-
821
- const fresh = [...new Set(batch.map((b) => b.row.taskId))].filter((t) => !rowsByTask.has(t));
822
- const listedEarlier = new Set<string>();
823
- if (start && fresh.length > 0) {
824
- const newer = await deps.db
825
- .selectDistinct({ taskId: messageLogs.taskId })
826
- .from(messageLogs)
827
- .where(
828
- and(
829
- ...conditions,
830
- inArray(messageLogs.taskId, fresh),
831
- sql`${rowKey} > ${position(start.ts, start.id)}`,
832
- ),
833
- );
834
- for (const r of newer) listedEarlier.add(r.taskId);
835
- }
836
-
837
- for (const { row, ts } of batch) {
838
- if (listedEarlier.has(row.taskId)) continue;
839
- let rows = rowsByTask.get(row.taskId);
840
- if (!rows) {
841
- if (order.length === limit) {
842
- nextCursor = encodeLogCursor(ts, row.id);
843
- break;
844
- }
845
- rows = [];
846
- order.push(row.taskId);
847
- rowsByTask.set(row.taskId, rows);
848
- }
849
- rows.push(row);
850
- }
851
-
852
- if (batch.length < batchSize) break;
853
- const last = batch[batch.length - 1]!;
854
- scanFrom = { ts: last.ts, id: last.row.id };
855
- inclusive = false;
856
- }
857
-
858
- // The latest outcome, rather than the dispatch that preceded it.
859
- const deduplicatedLogs = order.map((taskId) => {
860
- const rows = rowsByTask.get(taskId)!;
861
- return rows.find((r) => r.status !== "dispatched") ?? rows[0]!;
862
- });
863
-
864
- sendJson(res, 200, { logs: deduplicatedLogs, nextCursor });
865
- }
866
-
867
- // ── GET /v1/notifications/:taskId — getNotificationStatus ───────────────
868
- async function getNotificationStatus(
869
- req: IncomingMessage,
870
- res: ServerResponse,
871
- ctx: RouteContext,
872
- ): Promise<void> {
873
- const { taskId } = ctx.params;
874
- if (!taskId) return sendJson(res, 400, { error: "missing_task_id" });
875
-
876
- const logs = await deps.db
877
- .select()
878
- .from(messageLogs)
879
- .where(and(eq(messageLogs.taskId, taskId), eq(messageLogs.projectId, ctx.projectId!)))
880
- .orderBy(desc(messageLogs.timestamp));
881
-
882
- if (logs.length === 0) {
883
- // It might still be pending in Redis or scheduled
884
- return sendJson(res, 404, {
885
- error: "not_found",
886
- message: "Task not found or not processed yet",
887
- });
888
- }
889
-
890
- // Newest first, so `status` is the latest known state rather than whichever
891
- // row Postgres happened to return first.
892
- sendJson(res, 200, { status: logs[0]?.status, logs });
893
- }
894
-
895
- // ── GET /v1/users/:id — getUser ───────────────────────────────────────────
896
- async function getUser(
897
- req: IncomingMessage,
898
- res: ServerResponse,
899
- ctx: RouteContext,
900
- ): Promise<void> {
901
- const userId = ctx.params.id!;
902
- const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
903
- if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
904
-
905
- const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
906
- sendJson(res, 200, { ...user, contacts });
907
- }
908
-
909
- // ── GET /v1/users/:id/preferences — getUserPreferences ────────────────────
910
- async function getUserPreferences(
911
- req: IncomingMessage,
912
- res: ServerResponse,
913
- ctx: RouteContext,
914
- ): Promise<void> {
915
- const userId = ctx.params.id!;
916
- const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
917
- if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
918
-
919
- sendJson(res, 200, user.preferences);
920
- }
921
-
922
- // ── PATCH /v1/users/:id/preferences — updateUserPreferences ───────────────
923
- async function updateUserPreferences(
924
- req: IncomingMessage,
925
- res: ServerResponse,
926
- ctx: RouteContext,
927
- ): Promise<void> {
928
- const userId = ctx.params.id!;
929
- const parsed = PreferencesSchema.safeParse(await readJsonBody(req));
930
- if (!parsed.success) return sendValidationError(res, parsed.error);
931
-
932
- const updated = await deps.userRepo.updatePartial(ctx.projectId!, userId, {
933
- preferences: parsed.data,
934
- });
935
- if (!updated) return sendJson(res, 404, { error: "user_not_found", id: userId });
936
-
937
- logger.info({ userId }, "user preferences updated");
938
- sendJson(res, 200, { id: userId, preferences: parsed.data });
939
- }
940
-
941
- // ── POST /v1/workflows — createWorkflow ───────────────────────────────────
942
- async function createWorkflow(
943
- req: IncomingMessage,
944
- res: ServerResponse,
945
- ctx: RouteContext,
946
- ): Promise<void> {
947
- const body = await readJsonBody(req);
948
- const parsed = CreateWorkflowSchema.safeParse(body);
949
- if (!parsed.success) return sendValidationError(res, parsed.error);
950
- const input = parsed.data;
951
-
952
- try {
953
- await deps.db
954
- .insert(workflowDefinitions)
955
- .values({
956
- projectId: ctx.projectId!,
957
- name: input.name,
958
- steps: input.steps,
959
- })
960
- .onConflictDoUpdate({
961
- target: [workflowDefinitions.projectId, workflowDefinitions.name],
962
- set: {
963
- steps: input.steps,
964
- },
965
- });
966
- sendJson(res, 201, { name: input.name });
967
- } catch (error: any) {
968
- // Logged, not returned: driver errors name tables, constraints and values.
969
- deps.logger.error({ err: error }, "Failed to create workflow definition");
970
- sendJson(res, 500, { error: "internal_error" });
971
- }
972
- }
973
-
974
- // ── GET /v1/templates — listTemplates ─────────────────────────────────────
975
- async function listTemplates(
976
- req: IncomingMessage,
977
- res: ServerResponse,
978
- ctx: RouteContext,
979
- ): Promise<void> {
980
- const limit = parseLimit(ctx, undefined);
981
- const channel = getQueryParam(ctx, "channel");
982
- const topic = getQueryParam(ctx, "topic");
983
- let templates = await deps.templateRepo.list(ctx.projectId!);
984
- if (channel) {
985
- templates = templates.filter((t: any) => t.channel === channel);
986
- }
987
- if (topic) {
988
- templates = templates.filter((t: any) => t.topics?.includes(topic));
989
- }
990
- if (limit) {
991
- templates = templates.slice(0, limit);
992
- }
993
- sendJson(res, 200, { templates });
994
- }
995
-
996
- // ── GET /v1/templates/:id — getTemplate ───────────────────────────────────
997
- async function getTemplate(
998
- req: IncomingMessage,
999
- res: ServerResponse,
1000
- ctx: RouteContext,
1001
- ): Promise<void> {
1002
- const templateId = ctx.params.id!;
1003
- const template = await deps.templateRepo.findById(ctx.projectId!, templateId);
1004
- if (!template) return sendJson(res, 404, { error: "template_not_found", id: templateId });
1005
-
1006
- sendJson(res, 200, template);
1007
- }
1008
-
1009
- // ── DELETE /v1/templates/:id — deleteTemplate ───────────────────────────
1010
- async function deleteTemplate(
1011
- req: IncomingMessage,
1012
- res: ServerResponse,
1013
- ctx: RouteContext,
1014
- ): Promise<void> {
1015
- const templateId = ctx.params.id!;
1016
- const deleted = await deps.templateRepo.delete(ctx.projectId!, templateId);
1017
- if (!deleted) return sendJson(res, 404, { error: "template_not_found", id: templateId });
1018
-
1019
- await deps.redis.native.publish("template.invalidated", `${ctx.projectId}:${templateId}`);
1020
- logger.info({ templateId }, "template deleted");
1021
- sendNoContent(res);
1022
- }
1023
-
1024
- // ── GET /v1/workflows — listWorkflows ─────────────────────────────────────
1025
- async function listWorkflows(
1026
- req: IncomingMessage,
1027
- res: ServerResponse,
1028
- ctx: RouteContext,
1029
- ): Promise<void> {
1030
- const limit = parseLimit(ctx, undefined);
1031
- const search = getQueryParam(ctx, "search")?.trim().toLowerCase();
1032
- let workflows = await deps.workflowRepo.listDefinitions(ctx.projectId!);
1033
- if (search) {
1034
- workflows = workflows.filter((w: any) => w.name?.toLowerCase().includes(search));
1035
- }
1036
- if (limit) {
1037
- workflows = workflows.slice(0, limit);
1038
- }
1039
- sendJson(res, 200, { workflows });
1040
- }
1041
-
1042
- // ── GET /v1/workflows/instances/:id — getWorkflow ─────────────────────────
1043
- async function getWorkflow(
1044
- req: IncomingMessage,
1045
- res: ServerResponse,
1046
- ctx: RouteContext,
1047
- ): Promise<void> {
1048
- const instanceId = ctx.params.id!;
1049
- const workflow = isUuid(instanceId)
1050
- ? await deps.workflowRepo.getInstance(ctx.projectId!, instanceId)
1051
- : null;
1052
- if (!workflow) return sendJson(res, 404, { error: "workflow_not_found", id: instanceId });
1053
-
1054
- sendJson(res, 200, workflow);
1055
- }
1056
-
1057
- // ── DELETE /v1/workflows/instances/:id — cancelWorkflow ───────────────────
1058
- async function cancelWorkflow(
1059
- req: IncomingMessage,
1060
- res: ServerResponse,
1061
- ctx: RouteContext,
1062
- ): Promise<void> {
1063
- const instanceId = ctx.params.id!;
1064
- const canceled =
1065
- isUuid(instanceId) && (await deps.workflowRepo.cancelInstance(ctx.projectId!, instanceId));
1066
- if (!canceled) return sendJson(res, 400, { error: "workflow_not_cancelable", id: instanceId });
1067
-
1068
- logger.info({ instanceId }, "workflow canceled");
1069
- sendNoContent(res);
1070
- }
1071
-
1072
- // ── GET /v1/users — listUsers ─────────────────────────────────────────────
1073
- async function listUsers(
1074
- req: IncomingMessage,
1075
- res: ServerResponse,
1076
- ctx: RouteContext,
1077
- ): Promise<void> {
1078
- const limit = parseLimit(ctx, 50);
1079
- const cursor = getQueryParam(ctx, "cursor");
1080
- const search = getQueryParam(ctx, "search");
1081
- const segment = getQueryParam(ctx, "segment");
1082
- const language = getQueryParam(ctx, "language");
1083
- const timezone = getQueryParam(ctx, "timezone");
1084
- const channel = getQueryParam(ctx, "channel");
1085
-
1086
- const filters =
1087
- search || segment || language || timezone || channel
1088
- ? { search, segment, language, timezone, channel }
1089
- : undefined;
1090
-
1091
- const result = await deps.userRepo.list(ctx.projectId!, limit, cursor, filters);
1092
- sendJson(res, 200, result);
1093
- }
1094
-
1095
- // ── GET /v1/users/:id/contacts — getUserContacts ──────────────────────────
1096
- async function getUserContacts(
1097
- req: IncomingMessage,
1098
- res: ServerResponse,
1099
- ctx: RouteContext,
1100
- ): Promise<void> {
1101
- const userId = ctx.params.id!;
1102
- const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
1103
- sendJson(res, 200, { contacts });
1104
- }
1105
-
1106
- // ── GET /v1/segments — listSegments ───────────────────────────────────────
1107
- async function listSegments(
1108
- req: IncomingMessage,
1109
- res: ServerResponse,
1110
- ctx: RouteContext,
1111
- ): Promise<void> {
1112
- const segments = await deps.segmentRepo.listSegments(ctx.projectId!);
1113
- sendJson(res, 200, { segments });
1114
- }
1115
-
1116
- // ── GET /v1/projects — listProjects ───────────────────────────────────────
1117
- async function listProjects(
1118
- req: IncomingMessage,
1119
- res: ServerResponse,
1120
- _ctx: RouteContext,
1121
- ): Promise<void> {
1122
- const projects = await deps.projectRepo.list();
1123
- sendJson(res, 200, { projects });
1124
- }
1125
-
1126
- // ── DELETE /v1/projects/:id — deleteProject ───────────────────────────────
1127
- async function deleteProject(
1128
- req: IncomingMessage,
1129
- res: ServerResponse,
1130
- ctx: RouteContext,
1131
- ): Promise<void> {
1132
- const id = ctx.params.id!;
1133
- const deleted = isUuid(id) && (await deps.projectRepo.delete(id));
1134
- if (!deleted) return sendJson(res, 404, { error: "project_not_found" });
1135
-
1136
- sendNoContent(res);
1137
- }
1138
-
1139
- // ── PATCH /v1/projects/:id — updateProject ────────────────────────────────
1140
- async function updateProject(
1141
- req: IncomingMessage,
1142
- res: ServerResponse,
1143
- ctx: RouteContext,
1144
- ): Promise<void> {
1145
- const id = ctx.params.id!;
1146
- const parsed = z
1147
- .object({
1148
- rateLimitRpm: z.number().nullable().optional(),
1149
- throttleLimit: z.number().nullable().optional(),
1150
- throttleWindowHours: z.number().nullable().optional(),
1151
- })
1152
- .safeParse(await readJsonBody(req));
1153
-
1154
- if (!parsed.success) return sendValidationError(res, parsed.error);
1155
-
1156
- const updated = isUuid(id) && (await deps.projectRepo.updateSettings(id, parsed.data));
1157
- if (!updated) return sendJson(res, 404, { error: "project_not_found" });
1158
-
1159
- // Drop the engine's cached throttle overrides so the change applies to the
1160
- // next notification instead of waiting out the cache TTL.
1161
- await deps.redis.native.publish(PUBSUB_CHANNELS.PROJECT_INVALIDATED, id);
1162
-
1163
- // rateLimitRpm is read through the API's auth cache, which is keyed by token
1164
- // hash rather than project — dropping the whole cache is the only way to
1165
- // pick up a new limit promptly. Project updates are rare admin operations.
1166
- if (parsed.data.rateLimitRpm !== undefined) {
1167
- await deps.redis.native.publish(PUBSUB_CHANNELS.API_KEY_INVALIDATED, "*");
1168
- }
1169
-
1170
- logger.info({ projectId: id }, "project settings updated");
1171
- sendJson(res, 200, { id });
1172
- }
1173
-
1174
- // ── POST /v1/projects/:id/keys — createProjectKey ───────────────────
1175
- async function createProjectKey(
1176
- req: IncomingMessage,
1177
- res: ServerResponse,
1178
- ctx: RouteContext,
1179
- ): Promise<void> {
1180
- const id = ctx.params.id!;
1181
- const parsed = z
1182
- .object({ role: z.enum(["admin", "read_only"]).default("admin") })
1183
- .safeParse(await readJsonBody(req));
1184
- const role = parsed.success ? parsed.data.role : "admin";
1185
-
1186
- // A key for a project that does not exist would fail the foreign key.
1187
- if (!isUuid(id) || !(await deps.projectRepo.findThrottleSettings(id))) {
1188
- return sendJson(res, 404, { error: "project_not_found" });
1189
- }
1190
-
1191
- const apiKey = `nk_live_${randomBytes(32).toString("hex")}`;
1192
- const apiKeyHash = createHash("sha256").update(apiKey).digest("hex");
1193
-
1194
- const key = await deps.projectRepo.createApiKey(id, apiKeyHash, role);
1195
- sendJson(res, 201, { id: key.id, apiKey, role });
1196
- }
1197
-
1198
- // ── GET /v1/projects/:id/keys — listProjectKeys ─────────────────────
1199
- async function listProjectKeys(
1200
- req: IncomingMessage,
1201
- res: ServerResponse,
1202
- ctx: RouteContext,
1203
- ): Promise<void> {
1204
- const id = ctx.params.id!;
1205
- if (!isUuid(id)) return sendJson(res, 404, { error: "project_not_found" });
1206
- const keys = await deps.projectRepo.listApiKeys(id);
1207
- sendJson(res, 200, { keys });
1208
- }
1209
-
1210
- // ── DELETE /v1/projects/:id/keys/:keyId — deleteProjectKey ──────────
1211
- async function deleteProjectKey(
1212
- req: IncomingMessage,
1213
- res: ServerResponse,
1214
- ctx: RouteContext,
1215
- ): Promise<void> {
1216
- const { id, keyId } = ctx.params;
1217
- const deleted = isUuid(id) && isUuid(keyId) && (await deps.projectRepo.deleteApiKey(id, keyId));
1218
- if (!deleted) return sendJson(res, 404, { error: "key_not_found" });
1219
-
1220
- await deps.redis.native.publish("apikey.invalidated", "*");
1221
- sendNoContent(res);
1222
- }
1223
-
1224
- // ── GET /v1/system/health — getSystemHealth ──────────────────────────────
1225
- async function getSystemHealth(
1226
- _req: IncomingMessage,
1227
- res: ServerResponse,
1228
- _ctx: RouteContext,
1229
- ): Promise<void> {
1230
- const keys = ["enricher", "engine", "scheduler", "delivery", "ai", "workflow", "events"];
1231
- const workers: Record<string, any> = {};
1232
- let redisOk = false;
1233
- let dbOk = false;
1234
- let redisLatency = 0;
1235
- let dbLatency = 0;
1236
-
1237
- const startRedis = Date.now();
1238
- try {
1239
- await deps.redis.native.ping();
1240
- redisOk = true;
1241
- redisLatency = Date.now() - startRedis;
1242
- } catch {
1243
- redisOk = false;
1244
- }
1245
-
1246
- const startDb = Date.now();
1247
- try {
1248
- await deps.db.execute(sql`SELECT 1`);
1249
- dbOk = true;
1250
- dbLatency = Date.now() - startDb;
1251
- } catch {
1252
- dbOk = false;
1253
- }
1254
-
1255
- if (redisOk) {
1256
- try {
1257
- const vals = await deps.redis.native.mget(keys.map((k) => `notif:health:${k}`));
1258
- for (let i = 0; i < keys.length; i++) {
1259
- const key = keys[i] as string;
1260
- const val = vals[i];
1261
- if (val) {
1262
- workers[key] = JSON.parse(val);
1263
- } else {
1264
- workers[key] = { status: "unknown", message: "No heartbeat" };
1265
- }
1266
- }
1267
- } catch (err: any) {
1268
- for (const key of keys) {
1269
- workers[key] = { status: "error", error: err.message };
1270
- }
1271
- }
1272
- }
1273
-
1274
- sendJson(res, 200, {
1275
- status: redisOk && dbOk ? "healthy" : "degraded",
1276
- redis: { ok: redisOk, latencyMs: redisLatency },
1277
- db: { ok: dbOk, latencyMs: dbLatency },
1278
- workers,
1279
- });
1280
- }
1281
-
1282
- // Helper to resolve true unconsumed backlog (consumer group lag + pending entries)
1283
- async function getStreamBacklog(
1284
- redis: any,
1285
- streamKey: string,
1286
- targetGroup?: string,
1287
- ): Promise<number> {
1288
- if (!targetGroup) {
1289
- return await redis.xlen(streamKey);
1290
- }
1291
-
1292
- if (typeof redis.xinfo === "function") {
1293
- try {
1294
- const groups = await redis.xinfo("GROUPS", streamKey);
1295
- if (Array.isArray(groups) && groups.length > 0) {
1296
- for (const item of groups) {
1297
- const groupData: Record<string, any> = {};
1298
- if (Array.isArray(item)) {
1299
- for (let i = 0; i < item.length; i += 2) {
1300
- groupData[String(item[i])] = item[i + 1];
1301
- }
1302
- } else if (item && typeof item === "object") {
1303
- Object.assign(groupData, item);
1304
- }
1305
-
1306
- if (groupData.name === targetGroup) {
1307
- const pending = typeof groupData.pending === "number" ? groupData.pending : 0;
1308
- if (typeof groupData.lag === "number") {
1309
- return groupData.lag + pending;
1310
- }
1311
- if (groupData["last-delivered-id"] === "0-0") {
1312
- const totalLen = await redis.xlen(streamKey);
1313
- return totalLen + pending;
1314
- }
1315
- return pending;
1316
- }
1317
- }
1318
- }
1319
- } catch {
1320
- // Group or stream may not exist yet, fallback to xlen
1321
- }
1322
- }
1323
-
1324
- return await redis.xlen(streamKey);
1325
- }
1326
-
1327
- // ── GET /v1/system/metrics — getSystemMetrics ────────────────────────────
1328
- async function getSystemMetrics(
1329
- _req: IncomingMessage,
1330
- res: ServerResponse,
1331
- ctx: RouteContext,
1332
- ): Promise<void> {
1333
- const streamMap: Record<string, { key: string; group?: string }> = {
1334
- INBOUND_CRITICAL: { key: STREAMS.INBOUND_CRITICAL, group: CONSUMER_GROUPS.ENRICHER },
1335
- INBOUND_NORMAL: { key: STREAMS.INBOUND_NORMAL, group: CONSUMER_GROUPS.ENRICHER },
1336
- INBOUND_LOW: { key: STREAMS.INBOUND_LOW, group: CONSUMER_GROUPS.ENRICHER },
1337
- ENRICHED_NORMAL: { key: STREAMS.ENRICHED_NORMAL, group: CONSUMER_GROUPS.ENGINE },
1338
- OUTBOUND_CRITICAL: { key: STREAMS.OUTBOUND_CRITICAL, group: CONSUMER_GROUPS.DELIVERY },
1339
- OUTBOUND_NORMAL: { key: STREAMS.OUTBOUND_NORMAL, group: CONSUMER_GROUPS.DELIVERY },
1340
- OUTBOUND_LOW: { key: STREAMS.OUTBOUND_LOW, group: CONSUMER_GROUPS.DELIVERY },
1341
- WORKFLOW_INBOUND: { key: STREAMS.WORKFLOW_INBOUND, group: CONSUMER_GROUPS.WORKFLOW },
1342
- EVENTS_INBOUND: { key: STREAMS.EVENTS_INBOUND, group: CONSUMER_GROUPS.EVENTS },
1343
- DEAD_LETTER: { key: STREAMS.DEAD_LETTER },
1344
- };
1345
-
1346
- const streamDepths: Record<string, number> = {};
1347
- if (ctx.isAdmin !== false) {
1348
- for (const [key, { key: realRedisKey, group }] of Object.entries(streamMap)) {
1349
- try {
1350
- const depth = await getStreamBacklog(deps.redis.native, realRedisKey, group);
1351
- streamDepths[key] = depth;
1352
- } catch {
1353
- streamDepths[key] = 0;
1354
- }
1355
- }
1356
- }
1357
-
1358
- // Scoped to the caller's project if provided, otherwise aggregate across all projects
1359
- let total = 0;
1360
- let delivered = 0;
1361
-
1362
- if (ctx.projectId) {
1363
- const totalTasksRes = await deps.db
1364
- .select({ count: sql<number>`count(distinct ${messageLogs.taskId})` })
1365
- .from(messageLogs)
1366
- .where(eq(messageLogs.projectId, ctx.projectId));
1367
- const deliveredTasksRes = await deps.db
1368
- .select({ count: sql<number>`count(distinct ${messageLogs.taskId})` })
1369
- .from(messageLogs)
1370
- .where(and(eq(messageLogs.projectId, ctx.projectId), eq(messageLogs.status, "delivered")));
1371
-
1372
- total = Number(totalTasksRes[0]?.count ?? 0);
1373
- delivered = Number(deliveredTasksRes[0]?.count ?? 0);
1374
- } else {
1375
- const totalTasksRes = await deps.db
1376
- .select({ count: sql<number>`count(distinct ${messageLogs.taskId})` })
1377
- .from(messageLogs);
1378
- const deliveredTasksRes = await deps.db
1379
- .select({ count: sql<number>`count(distinct ${messageLogs.taskId})` })
1380
- .from(messageLogs)
1381
- .where(eq(messageLogs.status, "delivered"));
1382
-
1383
- total = Number(totalTasksRes[0]?.count ?? 0);
1384
- delivered = Number(deliveredTasksRes[0]?.count ?? 0);
1385
- }
1386
-
1387
- // Project-scoped calls compute failure against their own task count;
1388
- // cluster-wide administrative calls read the global dead letter queue length.
1389
- const failed = ctx.projectId ? Math.max(0, total - delivered) : streamDepths.DEAD_LETTER || 0;
1390
- const successRate = total > 0 ? Number(((delivered / total) * 100).toFixed(2)) : 100;
1391
-
1392
- sendJson(res, 200, {
1393
- streams: streamDepths,
1394
- deliveryStats: {
1395
- total,
1396
- delivered,
1397
- failed,
1398
- successRate,
1399
- },
1400
- });
1401
- }
1402
-
1403
- // ── GET /v1/dlq — getDLQMessages ─────────────────────────────────────────
1404
- async function getDLQMessages(
1405
- _req: IncomingMessage,
1406
- res: ServerResponse,
1407
- ctx: RouteContext,
1408
- ): Promise<void> {
1409
- try {
1410
- const rawEntries = await deps.redis.native.xrevrange(
1411
- STREAMS.DEAD_LETTER,
1412
- "+",
1413
- "-",
1414
- "COUNT",
1415
- "100",
1416
- );
1417
- const allMessages = (rawEntries || []).map(([id, fields]: [string, string[]]) =>
1418
- parseDlqEntry(id, fields),
1419
- );
1420
-
1421
- const messages = ctx.projectId
1422
- ? allMessages.filter((m) => m.projectId === ctx.projectId)
1423
- : allMessages;
1424
-
1425
- sendJson(res, 200, {
1426
- messages: messages.slice(0, 50).map((m) => ({
1427
- id: m.id,
1428
- eventType: m.eventType,
1429
- payload: m.payload,
1430
- error: m.error,
1431
- timestamp: m.timestamp,
1432
- originalStream: m.originalStream,
1433
- })),
1434
- });
1435
- } catch {
1436
- sendJson(res, 200, { messages: [] });
1437
- }
1438
- }
1439
-
1440
- /** The entry, or null when it does not exist or belongs to another project. */
1441
- async function findDlqEntry(ctx: RouteContext, messageId: string): Promise<DlqEntry | null> {
1442
- // Redis rejects a malformed stream id rather than matching nothing.
1443
- if (!/^\d+-\d+$/.test(messageId)) return null;
1444
- const rawEntries = await deps.redis.native.xrange(STREAMS.DEAD_LETTER, messageId, messageId);
1445
- if (!rawEntries || rawEntries.length === 0 || !rawEntries[0]) return null;
1446
- const entry = parseDlqEntry(rawEntries[0][0], rawEntries[0][1]);
1447
- if (ctx.projectId && entry.projectId !== ctx.projectId) return null;
1448
- return entry;
1449
- }
1450
-
1451
- // ── POST /v1/dlq/replay — replayDLQMessage ────────────────────────────────
1452
- async function replayDLQMessage(
1453
- req: IncomingMessage,
1454
- res: ServerResponse,
1455
- ctx: RouteContext,
1456
- ): Promise<void> {
1457
- const body = (await readJsonBody(req).catch(() => ({}))) as any;
1458
- const messageId = body?.id;
1459
-
1460
- if (!messageId) {
1461
- sendJson(res, 400, { error: "missing_message_id" });
1462
- return;
1463
- }
1464
-
1465
- try {
1466
- const entry = await findDlqEntry(ctx, messageId);
1467
- if (!entry) {
1468
- sendJson(res, 404, { error: "dlq_message_not_found" });
1469
- return;
1470
- }
1471
-
1472
- // Back onto the stream it failed on: a failed send belongs with delivery,
1473
- // not at the start of the pipeline, where its payload does not parse.
1474
- const replayable = new Set<string>(Object.values(STREAMS));
1475
- replayable.delete(STREAMS.DEAD_LETTER);
1476
- const inbound =
1477
- STREAMS[
1478
- `INBOUND_${getPriorityBucket(entry.payload?.priority ?? entry.fields.priority).toUpperCase()}` as keyof typeof STREAMS
1479
- ] ?? STREAMS.INBOUND_NORMAL;
1480
- const targetStream =
1481
- entry.originalStream && replayable.has(entry.originalStream)
1482
- ? entry.originalStream
1483
- : inbound;
1484
-
1485
- const xaddArgs: string[] = [];
1486
- if (entry.event) {
1487
- xaddArgs.push("data", JSON.stringify(entry.event));
1488
- } else {
1489
- for (const [k, v] of Object.entries(entry.fields)) xaddArgs.push(k, v);
1490
- }
1491
- await deps.redis.native.xadd(targetStream, "*", ...xaddArgs);
1492
- await deps.redis.native.xdel(STREAMS.DEAD_LETTER, messageId);
1493
-
1494
- sendJson(res, 200, { success: true, replayedId: messageId, stream: targetStream });
1495
- } catch (err) {
1496
- logger.error({ err, messageId }, "DLQ replay failed");
1497
- sendJson(res, 500, { error: "replay_failed" });
1498
- }
1499
- }
1500
-
1501
- // ── DELETE /v1/dlq/:id — deleteDLQMessage ────────────────────────────────
1502
- async function deleteDLQMessage(
1503
- _req: IncomingMessage,
1504
- res: ServerResponse,
1505
- ctx: RouteContext,
1506
- ): Promise<void> {
1507
- const messageId = ctx.params.id;
1508
- if (!messageId) return sendJson(res, 400, { error: "missing_id" });
1509
-
1510
- try {
1511
- if (!(await findDlqEntry(ctx, messageId))) {
1512
- sendJson(res, 404, { error: "dlq_message_not_found" });
1513
- return;
1514
- }
1515
- await deps.redis.native.xdel(STREAMS.DEAD_LETTER, messageId);
1516
- sendJson(res, 200, { success: true });
1517
- } catch (err) {
1518
- logger.error({ err, messageId }, "DLQ delete failed");
1519
- sendJson(res, 500, { error: "delete_failed" });
1520
- }
1521
- }
1522
-
1523
- // ── GET /v1/notifications/scheduled — getScheduledMessages ──────────────
1524
- async function getScheduledMessages(
1525
- _req: IncomingMessage,
1526
- res: ServerResponse,
1527
- ctx: RouteContext,
1528
- ): Promise<void> {
1529
- const limit = parseLimit(ctx, 50);
1530
- const cursor = getQueryParam(ctx, "cursor");
1531
- const channel = getQueryParam(ctx, "channel");
1532
-
1533
- const conditions = [sql`(payload->>'projectId') = ${ctx.projectId!}`];
1534
- if (cursor) {
1535
- conditions.push(sql`task_id > ${cursor}`);
1536
- }
1537
- if (channel) {
1538
- conditions.push(sql`(payload->>'channel') = ${channel}`);
1539
- }
1540
-
1541
- const rows = await deps.db
1542
- .select()
1543
- .from(scheduledPayloads)
1544
- .where(and(...conditions))
1545
- .orderBy(scheduledPayloads.taskId)
1546
- .limit(limit + 1);
1547
-
1548
- const hasNext = rows.length > limit;
1549
- const scheduled = hasNext ? rows.slice(0, limit) : rows;
1550
- const nextCursor =
1551
- hasNext && scheduled.length > 0 ? scheduled[scheduled.length - 1]!.taskId : null;
1552
-
1553
- sendJson(res, 200, { scheduled, nextCursor });
1554
- }
1555
-
1556
- // ── GET /v1/users/:id/details — getUserDetails ────────────────────────────
1557
- async function getUserDetails(
1558
- _req: IncomingMessage,
1559
- res: ServerResponse,
1560
- ctx: RouteContext,
1561
- ): Promise<void> {
1562
- const userId = ctx.params.id!;
1563
- const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
1564
- if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
1565
-
1566
- const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
1567
- const contactTargets = contacts.map((c) => c.target);
1568
- let logs: any[] = [];
1569
- if (contactTargets.length > 0) {
1570
- // One statement: fetching every task id the addresses were ever sent and
1571
- // passing them back as parameters failed outright past 65,535 sends.
1572
- const sentTo = deps.db
1573
- .select({ taskId: deliveryOutbox.taskId })
1574
- .from(deliveryOutbox)
1575
- .where(inArray(deliveryOutbox.destination, contactTargets));
1576
- logs = await deps.db
1577
- .select()
1578
- .from(messageLogs)
1579
- .where(and(eq(messageLogs.projectId, ctx.projectId!), inArray(messageLogs.taskId, sentTo)))
1580
- .orderBy(desc(messageLogs.timestamp))
1581
- .limit(50);
1582
- }
1583
-
1584
- sendJson(res, 200, { ...user, contacts, logs });
1585
- }
1586
-
1587
- // ── Unsubscribe ───────────────────────────────────────────────────────────
1588
- //
1589
- // Both routes are unauthenticated: they are reached from a mail client, which
1590
- // has no API key. The signed token in the URL is the credential and it
1591
- // authorises exactly one thing for one address.
1592
-
1593
- function sendHtml(res: ServerResponse, status: number, body: string): void {
1594
- res.writeHead(status, {
1595
- "Content-Type": "text/html; charset=utf-8",
1596
- // Nothing here should be cached by an inbox proxy or shared cache.
1597
- "Cache-Control": "no-store",
1598
- "X-Content-Type-Options": "nosniff",
1599
- "Referrer-Policy": "no-referrer",
1600
- });
1601
- res.end(body);
1602
- }
1603
-
1604
- function escapeHtml(value: string): string {
1605
- return value
1606
- .replace(/&/g, "&amp;")
1607
- .replace(/</g, "&lt;")
1608
- .replace(/>/g, "&gt;")
1609
- .replace(/"/g, "&quot;");
1610
- }
1611
-
1612
- function page(title: string, message: string): string {
1613
- return `<!doctype html><html lang="en"><head><meta charset="utf-8">
1614
- <meta name="viewport" content="width=device-width,initial-scale=1">
1615
- <title>${escapeHtml(title)}</title>
1616
- <style>body{font:16px/1.6 system-ui,sans-serif;max-width:34rem;margin:12vh auto;padding:0 1.5rem;color:#111}
1617
- h1{font-size:1.4rem;margin:0 0 .75rem}p{margin:0 0 1rem;color:#444}
1618
- button{font:inherit;padding:.6rem 1.2rem;border:0;border-radius:6px;background:#111;color:#fff;cursor:pointer}
1619
- code{background:#f4f4f5;padding:.1rem .35rem;border-radius:4px}</style>
1620
- </head><body><h1>${escapeHtml(title)}</h1>${message}</body></html>`;
1621
- }
1622
-
1623
- /**
1624
- * GET — the page a human lands on after clicking the link in the mail body.
1625
- *
1626
- * Deliberately does not unsubscribe anything. Corporate mail scanners and
1627
- * link prescanners issue a GET against every URL in a message; performing the
1628
- * opt-out here would unsubscribe people who never clicked. The mutation lives
1629
- * behind the POST.
1630
- */
1631
- async function unsubscribePage(
1632
- _req: IncomingMessage,
1633
- res: ServerResponse,
1634
- ctx: RouteContext,
1635
- ): Promise<void> {
1636
- const cfg = readBaseConfig();
1637
- const token = ctx.query.get("token") ?? "";
1638
- if (!cfg.UNSUBSCRIBE_SECRET) {
1639
- deps.logger.warn(
1640
- "UNSUBSCRIBE_SECRET is not configured — unable to verify unsubscribe tokens",
1641
- );
1642
- }
1643
- const claim = cfg.UNSUBSCRIBE_SECRET
1644
- ? verifyUnsubscribeToken(token, cfg.UNSUBSCRIBE_SECRET)
1645
- : null;
1646
-
1647
- if (!claim) {
1648
- return sendHtml(
1649
- res,
1650
- 400,
1651
- page(
1652
- "This link is not valid",
1653
- "<p>It may have been altered in transit, or this server may have been reconfigured since the message was sent. Replying to the message and asking to be removed will still work.</p>",
1654
- ),
1655
- );
1656
- }
1657
-
1658
- const what =
1659
- claim.topics.length > 0
1660
- ? `<code>${claim.topics.map(escapeHtml).join("</code>, <code>")}</code> messages`
1661
- : "all messages";
1662
-
1663
- sendHtml(
1664
- res,
1665
- 200,
1666
- page(
1667
- "Unsubscribe",
1668
- `<p>Stop sending ${what} to <code>${escapeHtml(claim.target)}</code>?</p>
1669
- <form method="post" action="/v1/unsubscribe?token=${encodeURIComponent(token)}">
1670
- <button type="submit">Unsubscribe</button></form>`,
1671
- ),
1672
- );
1673
- }
1674
-
1675
- /**
1676
- * POST — the real opt-out.
1677
- *
1678
- * Serves two callers with one handler: a mail client doing RFC 8058 one-click
1679
- * (body `List-Unsubscribe=One-Click`, token in the query string, no
1680
- * confirmation possible), and the form on the page above. Neither can carry a
1681
- * CSRF token, and the one-click spec forbids an interstitial, so the signed
1682
- * token is the whole of the authorisation.
1683
- */
1684
- async function unsubscribe(
1685
- req: IncomingMessage,
1686
- res: ServerResponse,
1687
- ctx: RouteContext,
1688
- ): Promise<void> {
1689
- // The one-click POST carries `List-Unsubscribe=One-Click` as its body and
1690
- // the token in the query string, so there is nothing here worth reading —
1691
- // but an unread body leaves bytes on a keep-alive socket. Discard it.
1692
- req.resume();
1693
-
1694
- const cfg = readBaseConfig();
1695
- const token = ctx.query.get("token") ?? "";
1696
- if (!cfg.UNSUBSCRIBE_SECRET) {
1697
- deps.logger.warn(
1698
- "UNSUBSCRIBE_SECRET is not configured — unable to verify unsubscribe tokens",
1699
- );
1700
- }
1701
- const claim = cfg.UNSUBSCRIBE_SECRET
1702
- ? verifyUnsubscribeToken(token, cfg.UNSUBSCRIBE_SECRET)
1703
- : null;
1704
-
1705
- if (!claim) {
1706
- return sendHtml(
1707
- res,
1708
- 400,
1709
- page(
1710
- "This link is not valid",
1711
- "<p>It may have been altered in transit, or this server may have been reconfigured since the message was sent.</p>",
1712
- ),
1713
- );
1714
- }
1715
-
1716
- const target = normaliseTarget(claim.target);
1717
-
1718
- try {
1719
- const userRows = await deps.db
1720
- .select({ id: dbUsers.id })
1721
- .from(dbUsers)
1722
- .where(and(eq(dbUsers.projectId, claim.projectId), eq(dbUsers.externalId, claim.userId)))
1723
- .limit(1);
1724
- const internalId = userRows[0]?.id;
1725
-
1726
- if (claim.topics.length > 0 && internalId) {
1727
- // Scoped opt-out: silence this kind of mail and leave the rest,
1728
- // including anything transactional, working.
1729
- await deps.db
1730
- .insert(userTopicPreferences)
1731
- .values(claim.topics.map((topic) => ({ userId: internalId, topic, enabled: false })))
1732
- .onConflictDoUpdate({
1733
- target: [userTopicPreferences.userId, userTopicPreferences.topic],
1734
- set: { enabled: sql`excluded.enabled` },
1735
- });
1736
- } else {
1737
- // No topic to scope to, or the user record is gone. Either way the
1738
- // request has to be honoured, so fall back to suppressing the address
1739
- // outright — over-honouring an unsubscribe is the safe direction.
1740
- await deps.db
1741
- .insert(suppressions)
1742
- .values({
1743
- projectId: claim.projectId,
1744
- channel: claim.channel as any,
1745
- target,
1746
- reason: "unsubscribed",
1747
- source: "unsubscribe-link",
1748
- })
1749
- .onConflictDoNothing();
1750
- }
1751
-
1752
- logger.info(
1753
- {
1754
- projectId: claim.projectId,
1755
- channel: claim.channel,
1756
- topics: claim.topics,
1757
- scoped: claim.topics.length > 0 && Boolean(internalId),
1758
- },
1759
- "unsubscribe honoured",
1760
- );
1761
- } catch (err) {
1762
- // A 5xx here means the mail client reports failure and, worse, the person
1763
- // believes they have opted out when they have not.
1764
- logger.error({ err, projectId: claim.projectId }, "unsubscribe failed to apply");
1765
- return sendHtml(
1766
- res,
1767
- 500,
1768
- page(
1769
- "Something went wrong",
1770
- "<p>We could not record that just now. Please try again in a moment.</p>",
1771
- ),
1772
- );
1773
- }
1774
-
1775
- sendHtml(
1776
- res,
1777
- 200,
1778
- page(
1779
- "You're unsubscribed",
1780
- `<p>We've stopped sending ${
1781
- claim.topics.length > 0 ? "these messages" : "messages"
1782
- } to <code>${escapeHtml(claim.target)}</code>. It may take a few minutes to take effect for mail already on its way.</p>`,
1783
- ),
1784
- );
1785
- }
1786
-
1787
- // ── GET /v1/campaigns — listCampaigns ─────────────────────────────────────
1788
- //
1789
- // One row per campaign label, newest activity first, with support for filtering
1790
- // by search keyword, channel, date range, and minimum message counts.
1791
- async function listCampaigns(
1792
- _req: IncomingMessage,
1793
- res: ServerResponse,
1794
- ctx: RouteContext,
1795
- ): Promise<void> {
1796
- const limit = parseLimit(ctx, 20);
1797
- const search = getQueryParam(ctx, "search")?.trim();
1798
- const channel = getQueryParam(ctx, "channel")?.trim();
1799
- const since = getQueryParam(ctx, "since")?.trim();
1800
- const until = getQueryParam(ctx, "until")?.trim();
1801
- const minMessagesParam = parseInt(getQueryParam(ctx, "minMessages") || "", 10);
1802
- const minMessages = isNaN(minMessagesParam) ? undefined : Math.max(minMessagesParam, 1);
1803
-
1804
- const conditions = [
1805
- eq(messageLogs.projectId, ctx.projectId!),
1806
- isNotNull(messageLogs.campaignId),
1807
- ];
1808
-
1809
- if (search) {
1810
- conditions.push(like(messageLogs.campaignId, contains(search)));
1811
- }
1812
- if (channel) {
1813
- conditions.push(eq(messageLogs.channel, channel as any));
1814
- }
1815
- if (since) {
1816
- const sinceDate = new Date(since);
1817
- if (!isNaN(sinceDate.getTime())) {
1818
- conditions.push(gte(messageLogs.timestamp, sinceDate));
1819
- }
1820
- }
1821
- if (until) {
1822
- const untilDate = new Date(until);
1823
- if (!isNaN(untilDate.getTime())) {
1824
- conditions.push(lte(messageLogs.timestamp, untilDate));
1825
- }
1826
- }
1827
-
1828
- let query = deps.db
1829
- .select({
1830
- campaign: messageLogs.campaignId,
1831
- messages: sql<number>`count(distinct ${messageLogs.taskId})`,
1832
- firstSentAt: sql<string>`min(${messageLogs.timestamp})`,
1833
- lastActivityAt: sql<string>`max(${messageLogs.timestamp})`,
1834
- })
1835
- .from(messageLogs)
1836
- .where(and(...conditions))
1837
- .groupBy(messageLogs.campaignId)
1838
- .orderBy(desc(sql`max(${messageLogs.timestamp})`))
1839
- .limit(limit);
1840
-
1841
- if (minMessages !== undefined) {
1842
- query = query.having(gte(sql`count(distinct ${messageLogs.taskId})`, minMessages)) as any;
1843
- }
1844
-
1845
- const rows = await query;
1846
-
1847
- sendJson(res, 200, {
1848
- campaigns: rows.map((r: any) => ({
1849
- campaign: r.campaign,
1850
- messages: Number(r.messages ?? 0),
1851
- firstSentAt: r.firstSentAt,
1852
- lastActivityAt: r.lastActivityAt,
1853
- })),
1854
- });
1855
- }
1856
-
1857
- // ── GET /v1/campaigns/:campaign/stats — getCampaignStats ──────────────────
1858
- //
1859
- // The delivery funnel for one campaign, in a single grouped scan.
1860
- //
1861
- // Every figure counts *distinct tasks*, not rows: a task accumulates a
1862
- // dispatch row, an attempt row, and any number of engagement rows, so
1863
- // counting rows would inflate every number by a different factor. Opening the
1864
- // same email twice is one person who opened it.
1865
- async function getCampaignStats(
1866
- _req: IncomingMessage,
1867
- res: ServerResponse,
1868
- ctx: RouteContext,
1869
- ): Promise<void> {
1870
- const campaign = ctx.params.campaign;
1871
- if (!campaign) return sendJson(res, 400, { error: "missing_campaign" });
1872
-
1873
- const rows = await deps.db
1874
- .select({
1875
- channel: messageLogs.channel,
1876
- kind: messageLogs.kind,
1877
- status: messageLogs.status,
1878
- tasks: sql<number>`count(distinct ${messageLogs.taskId})`,
1879
- })
1880
- .from(messageLogs)
1881
- .where(and(eq(messageLogs.projectId, ctx.projectId!), eq(messageLogs.campaignId, campaign)))
1882
- .groupBy(messageLogs.channel, messageLogs.kind, messageLogs.status);
1883
-
1884
- if (rows.length === 0) {
1885
- return sendJson(res, 404, {
1886
- error: "not_found",
1887
- message: `No messages recorded for campaign '${campaign}'`,
1888
- });
1889
- }
1890
-
1891
- const ENGAGEMENT = ["opened", "clicked", "bounced", "complained", "unsubscribed"] as const;
1892
- type Engagement = (typeof ENGAGEMENT)[number];
1893
-
1894
- const blank = () => ({
1895
- sent: 0,
1896
- delivered: 0,
1897
- failed: 0,
1898
- opened: 0,
1899
- clicked: 0,
1900
- bounced: 0,
1901
- complained: 0,
1902
- unsubscribed: 0,
1903
- });
1904
-
1905
- const byChannel = new Map<string, ReturnType<typeof blank>>();
1906
- for (const row of rows as any[]) {
1907
- const bucket = byChannel.get(row.channel) ?? blank();
1908
- const n = Number(row.tasks ?? 0);
1909
-
1910
- if (ENGAGEMENT.includes(row.kind as Engagement)) {
1911
- bucket[row.kind as Engagement] += n;
1912
- } else if (row.kind === "dispatched") {
1913
- // `sent` is every task that reached a provider at all, which is the
1914
- // denominator a bounce rate is measured against. Each attempt logs a
1915
- // dispatched row besides its outcome row, and the two are grouped
1916
- // separately, so counting both counted every message twice.
1917
- bucket.sent += n;
1918
- } else {
1919
- if (row.status === "delivered") bucket.delivered += n;
1920
- if (row.status === "failed") bucket.failed += n;
1921
- }
1922
- byChannel.set(row.channel, bucket);
1923
- }
1924
-
1925
- const total = blank();
1926
- for (const bucket of byChannel.values()) {
1927
- for (const key of Object.keys(total) as (keyof ReturnType<typeof blank>)[]) {
1928
- total[key] += bucket[key];
1929
- }
1930
- }
1931
-
1932
- const pct = (n: number, d: number) => (d > 0 ? Number(((n / d) * 100).toFixed(2)) : null);
1933
-
1934
- // Engagement only exists where a provider reports it back. Saying "0% open
1935
- // rate" for an SMS blast, or for email with no webhook wired, reads as a
1936
- // failed campaign rather than an untracked one.
1937
- const channels = [...byChannel.keys()];
1938
- const engagementCapable = channels.some((c) => c === "email");
1939
- const sawEngagement = ENGAGEMENT.some((k) => total[k] > 0);
1940
-
1941
- const warnings: string[] = [];
1942
- if (!engagementCapable) {
1943
- warnings.push(
1944
- `Opens and clicks are not reported on ${channels.join(", ")} — those figures are not tracked, not zero.`,
1945
- );
1946
- } else if (!sawEngagement && total.delivered > 0) {
1947
- warnings.push(
1948
- "No engagement events recorded. If the provider webhook is not configured, opens and clicks cannot be tracked and will stay at zero.",
1949
- );
1950
- }
1951
-
1952
- sendJson(res, 200, {
1953
- campaign,
1954
- totals: {
1955
- ...total,
1956
- deliveryRate: pct(total.delivered, total.sent),
1957
- openRate: pct(total.opened, total.delivered),
1958
- clickRate: pct(total.clicked, total.delivered),
1959
- bounceRate: pct(total.bounced, total.sent),
1960
- complaintRate: pct(total.complained, total.delivered),
1961
- unsubscribeRate: pct(total.unsubscribed, total.delivered),
1962
- },
1963
- byChannel: Object.fromEntries(byChannel),
1964
- engagementTracked: engagementCapable && sawEngagement,
1965
- warnings,
1966
- });
1967
- }
1968
-
1969
- // ── GET /v1/suppressions — listSuppressions ───────────────────────────────
1970
- async function listSuppressions(
1971
- _req: IncomingMessage,
1972
- res: ServerResponse,
1973
- ctx: RouteContext,
1974
- ): Promise<void> {
1975
- const limit = parseLimit(ctx, 100, 500);
1976
- const channel = getQueryParam(ctx, "channel");
1977
- const reason = getQueryParam(ctx, "reason");
1978
- const target = getQueryParam(ctx, "target");
1979
-
1980
- const conditions = [eq(suppressions.projectId, ctx.projectId!)];
1981
- if (channel) conditions.push(eq(suppressions.channel, channel as any));
1982
- if (reason) conditions.push(eq(suppressions.reason, reason));
1983
- if (target) conditions.push(like(suppressions.target, contains(target.toLowerCase().trim())));
1984
-
1985
- const rows = await deps.db
1986
- .select()
1987
- .from(suppressions)
1988
- .where(and(...conditions))
1989
- .orderBy(desc(suppressions.createdAt))
1990
- .limit(limit);
1991
-
1992
- sendJson(res, 200, { suppressions: rows });
1993
- }
1994
-
1995
- // ── POST /v1/suppressions — createSuppression ─────────────────────────────
1996
- async function createSuppression(
1997
- req: IncomingMessage,
1998
- res: ServerResponse,
1999
- ctx: RouteContext,
2000
- ): Promise<void> {
2001
- const parsed = z
2002
- .object({
2003
- channel: ContactChannelSchema,
2004
- target: z.string().min(1),
2005
- reason: z.enum(["unsubscribed", "complained", "bounced", "manual"]).default("manual"),
2006
- })
2007
- .safeParse(await readJsonBody(req));
2008
- if (!parsed.success) return sendValidationError(res, parsed.error);
2009
-
2010
- const { channel, target, reason } = parsed.data;
2011
- await deps.db
2012
- .insert(suppressions)
2013
- .values({
2014
- projectId: ctx.projectId!,
2015
- channel,
2016
- target: normaliseTarget(target),
2017
- reason,
2018
- source: "api",
2019
- })
2020
- .onConflictDoNothing();
2021
-
2022
- sendJson(res, 201, { channel, target: normaliseTarget(target), reason });
2023
- }
2024
-
2025
- // ── DELETE /v1/suppressions/:channel/:target — deleteSuppression ──────────
2026
- //
2027
- // Re-enables sending to an address. Intentionally manual: a suppression
2028
- // records that somebody asked not to be contacted, and undoing that should be
2029
- // a decision rather than a retry.
2030
- async function deleteSuppression(
2031
- _req: IncomingMessage,
2032
- res: ServerResponse,
2033
- ctx: RouteContext,
2034
- ): Promise<void> {
2035
- const { channel, target } = ctx.params;
2036
- if (!channel || !target) return sendJson(res, 400, { error: "missing_channel_or_target" });
2037
-
2038
- await deps.db
2039
- .delete(suppressions)
2040
- .where(
2041
- and(
2042
- eq(suppressions.projectId, ctx.projectId!),
2043
- eq(suppressions.channel, channel as any),
2044
- eq(suppressions.target, normaliseTarget(target)),
2045
- ),
2046
- );
2047
-
2048
- sendNoContent(res);
2049
- }
2050
-
2051
- // ── POST /v1/auth/login — login ───────────────────────────────────────────
2052
- async function login(req: IncomingMessage, res: ServerResponse): Promise<void> {
2053
- if (!deps.adminUserRepo) {
2054
- sendJson(res, 500, {
2055
- error: "internal_error",
2056
- message: "Admin user repository not initialized",
2057
- });
2058
- return;
2059
- }
2060
-
2061
- const body = await readJsonBody(req);
2062
- const parsed = z
2063
- .object({
2064
- identifier: z.string().min(1, "Identifier (email or username) is required"),
2065
- password: z.string().min(1, "Password is required"),
2066
- })
2067
- .safeParse(body);
2068
-
2069
- if (!parsed.success) {
2070
- sendValidationError(res, parsed.error);
2071
- return;
2072
- }
2073
-
2074
- const { identifier, password } = parsed.data;
2075
- const user = await deps.adminUserRepo.findByEmailOrUsername(identifier);
2076
- const targetHash = user ? user.passwordHash : DUMMY_PASSWORD_HASH;
2077
- let isValid = await verifyPassword(password, targetHash);
2078
- // The startup admin's ADMIN_PASSWORD is stored trimmed (a Windows `set`
2079
- // leaves a trailing space in it), so one configured with spaces at either
2080
- // end would otherwise never match what is typed. Only a failed attempt
2081
- // with such spaces pays the second check.
2082
- if (!isValid && password.trim() !== password && password.trim()) {
2083
- isValid = await verifyPassword(password.trim(), targetHash);
2084
- }
2085
- if (!user || !isValid) {
2086
- sendJson(res, 401, { error: "unauthorized", message: "Invalid credentials" });
2087
- return;
2088
- }
2089
-
2090
- const session = await createAdminSession(deps.redis.native, user);
2091
- sendJson(res, 200, {
2092
- token: session.token,
2093
- user: {
2094
- id: user.id,
2095
- email: user.email,
2096
- username: user.username,
2097
- role: user.role,
2098
- },
2099
- expiresAt: session.expiresAt,
2100
- });
2101
- }
2102
-
2103
- // ── POST /v1/auth/logout — logout ─────────────────────────────────────────
2104
- async function logout(req: IncomingMessage, res: ServerResponse): Promise<void> {
2105
- const authHeader = req.headers["authorization"];
2106
- let token: string | undefined;
2107
- if (typeof authHeader === "string" && authHeader.toLowerCase().startsWith("bearer ")) {
2108
- token = authHeader.slice(7).trim();
2109
- }
2110
- if (token) {
2111
- await revokeAdminSession(deps.redis.native, token);
2112
- }
2113
- sendJson(res, 200, { message: "Logged out successfully" });
2114
- }
2115
-
2116
- // ── GET /v1/auth/me — getMe ───────────────────────────────────────────────
2117
- async function getMe(req: IncomingMessage, res: ServerResponse): Promise<void> {
2118
- const authHeader = req.headers["authorization"];
2119
- let token: string | undefined;
2120
- if (typeof authHeader === "string" && authHeader.toLowerCase().startsWith("bearer ")) {
2121
- token = authHeader.slice(7).trim();
2122
- }
2123
- if (!token) {
2124
- sendJson(res, 401, { error: "unauthorized", message: "Missing token" });
2125
- return;
2126
- }
2127
-
2128
- const session = await getAdminSession(deps.redis.native, token);
2129
- if (!session) {
2130
- sendJson(res, 401, { error: "unauthorized", message: "Invalid or expired session" });
2131
- return;
2132
- }
2133
-
2134
- sendJson(res, 200, {
2135
- user: {
2136
- id: session.adminId,
2137
- email: session.email,
2138
- username: session.username,
2139
- role: session.role,
2140
- },
2141
- });
2142
- }
2143
-
2144
17
  return {
2145
- login,
2146
- logout,
2147
- getMe,
2148
- syncTemplates,
2149
- addUser,
2150
- updateUser,
2151
- deleteUser,
2152
- addContact,
2153
- deleteContact,
2154
- notify,
2155
- cancelNotification,
2156
- triggerWorkflow,
2157
- ingestEvent,
2158
- getEventsStream,
2159
- getNotificationLogs,
2160
- getNotificationStatus,
2161
- getUser,
2162
- getUserDetails,
2163
- unsubscribePage,
2164
- unsubscribe,
2165
- listCampaigns,
2166
- getCampaignStats,
2167
- listSuppressions,
2168
- createSuppression,
2169
- deleteSuppression,
2170
- getUserPreferences,
2171
- updateUserPreferences,
2172
- listTemplates,
2173
- getTemplate,
2174
- deleteTemplate,
2175
- createWorkflow,
2176
- listWorkflows,
2177
- getWorkflow,
2178
- cancelWorkflow,
2179
- listUsers,
2180
- getUserContacts,
2181
- listSegments,
2182
- listProjects,
2183
- deleteProject,
2184
- updateProject,
2185
- createProjectKey,
2186
- listProjectKeys,
2187
- deleteProjectKey,
2188
- getSystemHealth,
2189
- getSystemMetrics,
2190
- getDLQMessages,
2191
- replayDLQMessage,
2192
- deleteDLQMessage,
2193
- getScheduledMessages,
18
+ ...createTemplatesHandlers(deps),
19
+ ...createUsersHandlers(deps),
20
+ ...createNotificationsHandlers(deps),
21
+ ...createWorkflowsHandlers(deps),
22
+ ...createEventsHandlers(deps),
23
+ ...createProjectsHandlers(deps),
24
+ ...createSystemHandlers(deps),
25
+ ...createUnsubscribeHandlers(deps),
26
+ ...createCampaignsHandlers(deps),
27
+ ...createSuppressionsHandlers(deps),
28
+ ...createAuthHandlers(deps),
2194
29
  };
2195
30
  }