notifkit 0.1.14 → 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.
- package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
- package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/{bootstrap-m107TukN.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
- package/dist/{bulk-xAd_biYV.mjs → bulk-CJ5QXiPa.mjs} +1 -1
- package/dist/index.d.mts +71 -27
- package/dist/index.mjs +2 -2
- package/dist/{main-CWIBUEc7.mjs → main-6_bXQBDH.mjs} +21 -41
- package/dist/{main-WkxXwP5q.mjs → main-8nP3qmCT.mjs} +29 -49
- package/dist/{main-HT5c6jyf.mjs → main-B82bsFoy.mjs} +183 -334
- package/dist/{main-C87TSAqM.mjs → main-CpaHF1Zw.mjs} +13 -15
- package/dist/{main-DRHL2bst.mjs → main-DULD8-th.mjs} +8 -6
- package/dist/{main-D_62f9fH.mjs → main-ZW5RaiOK.mjs} +77 -64
- package/dist/{main-5kVwbbnW.mjs → main-g1KEcXXp.mjs} +676 -582
- package/dist/{main-C0MjK1Au.mjs → main-mGIT8jv4.mjs} +4 -4
- package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
- package/dist/{src-DYqdD694.mjs → src-BE_EUpZ6.mjs} +93 -93
- package/package.json +1 -1
- package/scripts/create-admin.mjs +0 -0
- package/scripts/create-project.mjs +6 -2
- package/scripts/migrate.mjs +0 -0
- package/scripts/notifkit.mjs +0 -0
- package/src/client.ts +3 -3
- package/src/config/index.ts +1 -0
- package/src/contracts/common.ts +2 -0
- package/src/contracts/envelope.ts +1 -1
- package/src/contracts/events/notification-created.ts +2 -0
- package/src/contracts/events/notification-delivered.ts +1 -1
- package/src/contracts/events/notification-failed.ts +1 -1
- package/src/contracts/events/notification-requested.ts +3 -2
- package/src/contracts/helpers.ts +1 -2
- package/src/contracts/index.ts +1 -0
- package/src/contracts/registry.ts +1 -0
- package/src/contracts/sdk.ts +8 -37
- package/src/db/schema.ts +8 -13
- package/src/idempotency/index.ts +6 -8
- package/src/metrics/index.ts +2 -0
- package/src/rate-limiter/api-rate-limiter.ts +208 -0
- package/src/rate-limiter/index.ts +3 -411
- package/src/rate-limiter/project-settings-cache.ts +99 -0
- package/src/rate-limiter/user-throttle.ts +100 -0
- package/src/redis/index.ts +10 -3
- package/src/repositories/admin-user.ts +83 -0
- package/src/repositories/contact.ts +359 -0
- package/src/repositories/index.ts +9 -1416
- package/src/repositories/preference.ts +35 -0
- package/src/repositories/project.ts +110 -0
- package/src/repositories/segment.ts +16 -0
- package/src/repositories/template.ts +72 -0
- package/src/repositories/types.ts +49 -0
- package/src/repositories/user.ts +644 -0
- package/src/repositories/workflow.ts +64 -0
- package/src/services/ai/main.ts +29 -71
- package/src/services/api/admin-static.ts +4 -1
- package/src/services/api/handlers/auth.ts +109 -0
- package/src/services/api/handlers/campaigns.ts +191 -0
- package/src/services/api/handlers/events.ts +99 -0
- package/src/services/api/handlers/notifications.ts +356 -0
- package/src/services/api/handlers/projects.ts +116 -0
- package/src/services/api/handlers/shared.ts +262 -0
- package/src/services/api/handlers/suppressions.ts +95 -0
- package/src/services/api/handlers/system.ts +314 -0
- package/src/services/api/handlers/templates.ts +97 -0
- package/src/services/api/handlers/unsubscribe.ts +215 -0
- package/src/services/api/handlers/users.ts +262 -0
- package/src/services/api/handlers/workflows.ts +150 -0
- package/src/services/api/handlers.ts +25 -2190
- package/src/services/api/health.ts +133 -0
- package/src/services/api/http.ts +12 -0
- package/src/services/api/main.ts +32 -322
- package/src/services/api/router.ts +1 -1
- package/src/services/api/webhooks.ts +172 -0
- package/src/services/delivery/main.ts +256 -498
- package/src/services/engine/main.ts +31 -235
- package/src/services/engine/quiet-hours.ts +151 -0
- package/src/services/engine/schedule-or-dispatch.ts +104 -0
- package/src/services/enricher/main.ts +9 -21
- package/src/services/events/main.ts +2 -2
- package/src/services/scheduler/main.ts +16 -25
- package/src/services/workflow/duration.ts +24 -0
- package/src/services/workflow/main.ts +6 -164
- package/src/services/workflow/timers.ts +157 -0
- package/src/shared/events.ts +3 -2
- package/src/templates/render.ts +1 -0
- package/src/workers/index.ts +7 -4
- package/src/workflows/sdk.ts +1 -0
- package/dashboard/README.md +0 -29
- package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
- package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { RedisClient } from "@/redis/index.js";
|
|
3
|
+
import { getAdminSession } from "@/services/auth/index.js";
|
|
4
|
+
import { getMetricsRegistry } from "@/metrics/index.js";
|
|
5
|
+
import { sendJson, extractAuthToken } from "./http.js";
|
|
6
|
+
|
|
7
|
+
export interface HealthDeps {
|
|
8
|
+
redis: RedisClient;
|
|
9
|
+
sql: any;
|
|
10
|
+
isAdminApiKey: (token: string) => boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** GET /health, /metrics, /live and /ready. */
|
|
14
|
+
export function createHealthHandlers({ redis, sql, isAdminApiKey }: HealthDeps) {
|
|
15
|
+
let cachedHealth: { response: any; statusCode: number; expiresAt: number } | null = null;
|
|
16
|
+
|
|
17
|
+
async function handleHealth(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
18
|
+
if (cachedHealth && cachedHealth.expiresAt > Date.now()) {
|
|
19
|
+
sendJson(res, cachedHealth.statusCode, cachedHealth.response);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const [redisOk, dbOk] = await Promise.all([redis.healthCheck(), dbHealthCheck()]);
|
|
24
|
+
|
|
25
|
+
const workers: Record<string, any> = {};
|
|
26
|
+
let overallOk = redisOk && dbOk;
|
|
27
|
+
|
|
28
|
+
if (redisOk) {
|
|
29
|
+
const keys = ["enricher", "engine", "scheduler", "delivery", "ai", "workflow", "events"];
|
|
30
|
+
try {
|
|
31
|
+
const vals = await redis.native.mget(keys.map((k) => `notif:health:${k}`));
|
|
32
|
+
for (let i = 0; i < keys.length; i++) {
|
|
33
|
+
const key = keys[i] as string;
|
|
34
|
+
const val = vals[i];
|
|
35
|
+
if (val) {
|
|
36
|
+
const parsed = JSON.parse(val);
|
|
37
|
+
workers[key] = parsed;
|
|
38
|
+
if (parsed.redis === false || parsed.state === "error") {
|
|
39
|
+
overallOk = false;
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
workers[key] = { status: "unknown", message: "No report received from worker" };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} catch (err) {
|
|
46
|
+
for (const key of keys) {
|
|
47
|
+
workers[key] = {
|
|
48
|
+
status: "error",
|
|
49
|
+
error: err instanceof Error ? err.message : String(err),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const statusCode = overallOk ? 200 : 503;
|
|
56
|
+
const response = {
|
|
57
|
+
service: "api",
|
|
58
|
+
status: overallOk ? "ok" : "degraded",
|
|
59
|
+
redis: redisOk,
|
|
60
|
+
database: dbOk,
|
|
61
|
+
workers,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
cachedHealth = {
|
|
65
|
+
response,
|
|
66
|
+
statusCode,
|
|
67
|
+
expiresAt: Date.now() + 1000,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
sendJson(res, statusCode, response);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function handleMetrics(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
74
|
+
const remoteIp = req.socket.remoteAddress ?? "";
|
|
75
|
+
const isLoopback =
|
|
76
|
+
remoteIp === "127.0.0.1" ||
|
|
77
|
+
remoteIp === "::1" ||
|
|
78
|
+
remoteIp === "::ffff:127.0.0.1" ||
|
|
79
|
+
remoteIp === "localhost";
|
|
80
|
+
|
|
81
|
+
let authorized = isLoopback;
|
|
82
|
+
if (!authorized) {
|
|
83
|
+
const token = extractAuthToken(req);
|
|
84
|
+
if (token) {
|
|
85
|
+
if (token.startsWith("nk_sess_") && redis?.native) {
|
|
86
|
+
const session = await getAdminSession(redis.native, token);
|
|
87
|
+
if (session) authorized = true;
|
|
88
|
+
} else if (isAdminApiKey(token)) {
|
|
89
|
+
authorized = true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!authorized) {
|
|
95
|
+
sendJson(res, 401, {
|
|
96
|
+
error: "unauthorized",
|
|
97
|
+
message: "Metrics endpoint requires admin credentials",
|
|
98
|
+
});
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const registry = getMetricsRegistry();
|
|
103
|
+
res.writeHead(200, { "Content-Type": registry.contentType });
|
|
104
|
+
res.end(await registry.metrics());
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function handleLive(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
108
|
+
sendJson(res, 200, { status: "ok" });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function handleReady(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
112
|
+
if (cachedHealth && cachedHealth.expiresAt > Date.now()) {
|
|
113
|
+
sendJson(res, cachedHealth.statusCode === 200 ? 200 : 503, {
|
|
114
|
+
status: cachedHealth.statusCode === 200 ? "ready" : "unready",
|
|
115
|
+
});
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const [redisOk, dbOk] = await Promise.all([redis.healthCheck(), dbHealthCheck()]);
|
|
119
|
+
const isReady = redisOk && dbOk;
|
|
120
|
+
sendJson(res, isReady ? 200 : 503, { status: isReady ? "ready" : "unready" });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function dbHealthCheck(): Promise<boolean> {
|
|
124
|
+
try {
|
|
125
|
+
await sql`SELECT 1`;
|
|
126
|
+
return true;
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return { handleHealth, handleMetrics, handleLive, handleReady };
|
|
133
|
+
}
|
package/src/services/api/http.ts
CHANGED
|
@@ -61,6 +61,18 @@ export async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
|
|
61
61
|
});
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
export function extractAuthToken(req: Pick<IncomingMessage, "headers">): string | undefined {
|
|
65
|
+
const authHeader = req.headers["authorization"];
|
|
66
|
+
if (typeof authHeader === "string" && authHeader.toLowerCase().startsWith("bearer ")) {
|
|
67
|
+
return authHeader.slice(7).trim();
|
|
68
|
+
}
|
|
69
|
+
const apiKeyHeader = req.headers["x-api-key"];
|
|
70
|
+
if (typeof apiKeyHeader === "string") {
|
|
71
|
+
return apiKeyHeader.trim();
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
64
76
|
export function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
|
65
77
|
const payload = JSON.stringify(body);
|
|
66
78
|
res.writeHead(status, {
|
package/src/services/api/main.ts
CHANGED
|
@@ -14,22 +14,25 @@ import {
|
|
|
14
14
|
AdminUserRepository,
|
|
15
15
|
} from "@/repositories/index.js";
|
|
16
16
|
import { STREAMS } from "@/contracts/index.js";
|
|
17
|
-
import { readJsonBody,
|
|
17
|
+
import { readJsonBody, sendJson, HttpError, extractAuthToken } from "./http.js";
|
|
18
18
|
import { Router } from "./router.js";
|
|
19
19
|
import { createHandlers } from "./handlers.js";
|
|
20
20
|
import { handleAdminRequest } from "./admin-static.js";
|
|
21
21
|
import { RedisLiveDeliveryEvents } from "./live-events.js";
|
|
22
|
+
import { createHealthHandlers } from "./health.js";
|
|
23
|
+
import { createWebhookHandler } from "./webhooks.js";
|
|
22
24
|
import { getAdminSession, hashPassword } from "@/services/auth/index.js";
|
|
23
|
-
import { projects,
|
|
24
|
-
import { eq
|
|
25
|
+
import { projects, projectApiKeys } from "@/db/schema.js";
|
|
26
|
+
import { eq } from "drizzle-orm";
|
|
25
27
|
import { randomBytes, timingSafeEqual, createHash } from "node:crypto";
|
|
26
|
-
import { LRUCache
|
|
28
|
+
import { LRUCache } from "@/shared/index.js";
|
|
27
29
|
import { transportRegistry } from "@/transport/index.js";
|
|
28
30
|
import type { Redis } from "@/redis/index.js";
|
|
29
31
|
import { z } from "zod";
|
|
30
|
-
import { getMetricsRegistry } from "@/metrics/index.js";
|
|
31
32
|
import { ApiRateLimiter } from "@/rate-limiter/index.js";
|
|
32
33
|
|
|
34
|
+
export { extractAuthToken };
|
|
35
|
+
|
|
33
36
|
/** Pub/sub channel used to drop a cached API key across every API process. */
|
|
34
37
|
export const API_KEY_INVALIDATION_CHANNEL = "apikey.invalidated";
|
|
35
38
|
|
|
@@ -65,16 +68,15 @@ let router: Router;
|
|
|
65
68
|
let liveEvents: RedisLiveDeliveryEvents | null = null;
|
|
66
69
|
let apiRateLimiter: ApiRateLimiter;
|
|
67
70
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
return undefined;
|
|
71
|
+
/** Whether `token` is ADMIN_API_KEY, compared in constant time. */
|
|
72
|
+
function isAdminApiKey(token: string): boolean {
|
|
73
|
+
if (!config.ADMIN_API_KEY) return false;
|
|
74
|
+
const expectedBuffer = Buffer.from(config.ADMIN_API_KEY);
|
|
75
|
+
const providedBuffer = Buffer.from(token);
|
|
76
|
+
return (
|
|
77
|
+
expectedBuffer.length === providedBuffer.length &&
|
|
78
|
+
timingSafeEqual(expectedBuffer, providedBuffer)
|
|
79
|
+
);
|
|
78
80
|
}
|
|
79
81
|
|
|
80
82
|
/**
|
|
@@ -122,127 +124,6 @@ async function handleCreateProject(req: IncomingMessage, res: ServerResponse): P
|
|
|
122
124
|
sendJson(res, 201, { id: projectId, apiKey });
|
|
123
125
|
}
|
|
124
126
|
|
|
125
|
-
let cachedHealth: { response: any; statusCode: number; expiresAt: number } | null = null;
|
|
126
|
-
|
|
127
|
-
async function handleHealth(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
128
|
-
if (cachedHealth && cachedHealth.expiresAt > Date.now()) {
|
|
129
|
-
sendJson(res, cachedHealth.statusCode, cachedHealth.response);
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const [redisOk, dbOk] = await Promise.all([redis.healthCheck(), dbHealthCheck()]);
|
|
134
|
-
|
|
135
|
-
const workers: Record<string, any> = {};
|
|
136
|
-
let overallOk = redisOk && dbOk;
|
|
137
|
-
|
|
138
|
-
if (redisOk) {
|
|
139
|
-
const keys = ["enricher", "engine", "scheduler", "delivery", "ai", "workflow", "events"];
|
|
140
|
-
try {
|
|
141
|
-
const vals = await redis.native.mget(keys.map((k) => `notif:health:${k}`));
|
|
142
|
-
for (let i = 0; i < keys.length; i++) {
|
|
143
|
-
const key = keys[i] as string;
|
|
144
|
-
const val = vals[i];
|
|
145
|
-
if (val) {
|
|
146
|
-
const parsed = JSON.parse(val);
|
|
147
|
-
workers[key] = parsed;
|
|
148
|
-
if (parsed.redis === false || parsed.state === "error") {
|
|
149
|
-
overallOk = false;
|
|
150
|
-
}
|
|
151
|
-
} else {
|
|
152
|
-
workers[key] = { status: "unknown", message: "No report received from worker" };
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
} catch (err) {
|
|
156
|
-
for (const key of keys) {
|
|
157
|
-
workers[key] = { status: "error", error: err instanceof Error ? err.message : String(err) };
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const statusCode = overallOk ? 200 : 503;
|
|
163
|
-
const response = {
|
|
164
|
-
service: "api",
|
|
165
|
-
status: overallOk ? "ok" : "degraded",
|
|
166
|
-
redis: redisOk,
|
|
167
|
-
database: dbOk,
|
|
168
|
-
workers,
|
|
169
|
-
};
|
|
170
|
-
|
|
171
|
-
cachedHealth = {
|
|
172
|
-
response,
|
|
173
|
-
statusCode,
|
|
174
|
-
expiresAt: Date.now() + 1000,
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
sendJson(res, statusCode, response);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
async function handleMetrics(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
181
|
-
const remoteIp = req.socket.remoteAddress ?? "";
|
|
182
|
-
const isLoopback =
|
|
183
|
-
remoteIp === "127.0.0.1" ||
|
|
184
|
-
remoteIp === "::1" ||
|
|
185
|
-
remoteIp === "::ffff:127.0.0.1" ||
|
|
186
|
-
remoteIp === "localhost";
|
|
187
|
-
|
|
188
|
-
let authorized = isLoopback;
|
|
189
|
-
if (!authorized) {
|
|
190
|
-
const token = extractAuthToken(req);
|
|
191
|
-
if (token) {
|
|
192
|
-
if (token.startsWith("nk_sess_") && redis?.native) {
|
|
193
|
-
const session = await getAdminSession(redis.native, token);
|
|
194
|
-
if (session) authorized = true;
|
|
195
|
-
} else if (config.ADMIN_API_KEY) {
|
|
196
|
-
const expectedBuffer = Buffer.from(config.ADMIN_API_KEY);
|
|
197
|
-
const providedBuffer = Buffer.from(token);
|
|
198
|
-
if (
|
|
199
|
-
expectedBuffer.length === providedBuffer.length &&
|
|
200
|
-
timingSafeEqual(expectedBuffer, providedBuffer)
|
|
201
|
-
) {
|
|
202
|
-
authorized = true;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
if (!authorized) {
|
|
209
|
-
sendJson(res, 401, {
|
|
210
|
-
error: "unauthorized",
|
|
211
|
-
message: "Metrics endpoint requires admin credentials",
|
|
212
|
-
});
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const registry = getMetricsRegistry();
|
|
217
|
-
res.writeHead(200, { "Content-Type": registry.contentType });
|
|
218
|
-
res.end(await registry.metrics());
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async function handleLive(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
222
|
-
sendJson(res, 200, { status: "ok" });
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async function handleReady(_req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
226
|
-
if (cachedHealth && cachedHealth.expiresAt > Date.now()) {
|
|
227
|
-
sendJson(res, cachedHealth.statusCode === 200 ? 200 : 503, {
|
|
228
|
-
status: cachedHealth.statusCode === 200 ? "ready" : "unready",
|
|
229
|
-
});
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
const [redisOk, dbOk] = await Promise.all([redis.healthCheck(), dbHealthCheck()]);
|
|
233
|
-
const isReady = redisOk && dbOk;
|
|
234
|
-
sendJson(res, isReady ? 200 : 503, { status: isReady ? "ready" : "unready" });
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
async function dbHealthCheck(): Promise<boolean> {
|
|
238
|
-
try {
|
|
239
|
-
await sql`SELECT 1`;
|
|
240
|
-
return true;
|
|
241
|
-
} catch {
|
|
242
|
-
return false;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
127
|
// ─── HTTP server ────────────────────────────────────────────────────────────
|
|
247
128
|
|
|
248
129
|
let server: ReturnType<typeof createServer>;
|
|
@@ -312,6 +193,12 @@ export async function startApiServer() {
|
|
|
312
193
|
db,
|
|
313
194
|
};
|
|
314
195
|
h = createHandlers(deps);
|
|
196
|
+
// Created per start, so a restart in the same process starts with no cached health.
|
|
197
|
+
const { handleHealth, handleMetrics, handleLive, handleReady } = createHealthHandlers({
|
|
198
|
+
redis,
|
|
199
|
+
sql,
|
|
200
|
+
isAdminApiKey,
|
|
201
|
+
});
|
|
315
202
|
|
|
316
203
|
router = new Router();
|
|
317
204
|
router
|
|
@@ -466,15 +353,8 @@ export async function startApiServer() {
|
|
|
466
353
|
isAdminToken = true;
|
|
467
354
|
keyRole = sessionKeyRole(session.role);
|
|
468
355
|
}
|
|
469
|
-
} else if (
|
|
470
|
-
|
|
471
|
-
const providedBuffer = Buffer.from(token);
|
|
472
|
-
if (
|
|
473
|
-
expectedBuffer.length === providedBuffer.length &&
|
|
474
|
-
timingSafeEqual(expectedBuffer, providedBuffer)
|
|
475
|
-
) {
|
|
476
|
-
isAdminToken = true;
|
|
477
|
-
}
|
|
356
|
+
} else if (isAdminApiKey(token)) {
|
|
357
|
+
isAdminToken = true;
|
|
478
358
|
}
|
|
479
359
|
|
|
480
360
|
if (isAdminToken) {
|
|
@@ -532,7 +412,10 @@ export async function startApiServer() {
|
|
|
532
412
|
});
|
|
533
413
|
tokenHashToToken.set(tokenHash, token);
|
|
534
414
|
if (tokenHashToToken.size > 2000) {
|
|
415
|
+
// A cached token must stay findable by its hash, or revoking it
|
|
416
|
+
// cannot evict it, so the two are dropped together.
|
|
535
417
|
tokenHashToToken.clear();
|
|
418
|
+
authCache.clear();
|
|
536
419
|
}
|
|
537
420
|
}
|
|
538
421
|
}
|
|
@@ -547,14 +430,6 @@ export async function startApiServer() {
|
|
|
547
430
|
}
|
|
548
431
|
|
|
549
432
|
// Project rate limit - In-Memory Token Leasing with Redis Sliding Window
|
|
550
|
-
if (!apiRateLimiter && redis?.native) {
|
|
551
|
-
apiRateLimiter = new ApiRateLimiter({
|
|
552
|
-
redis: redis.native,
|
|
553
|
-
windowMs: API_RATE_LIMIT_WINDOW_MS,
|
|
554
|
-
logger,
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
|
|
558
433
|
const allowed = apiRateLimiter
|
|
559
434
|
? await apiRateLimiter.check(projectId || "global", projectRateLimitRpm)
|
|
560
435
|
: true;
|
|
@@ -589,15 +464,8 @@ export async function startApiServer() {
|
|
|
589
464
|
}
|
|
590
465
|
authorized = true;
|
|
591
466
|
}
|
|
592
|
-
} else if (
|
|
593
|
-
|
|
594
|
-
const providedBuffer = Buffer.from(token);
|
|
595
|
-
if (
|
|
596
|
-
expectedBuffer.length === providedBuffer.length &&
|
|
597
|
-
timingSafeEqual(expectedBuffer, providedBuffer)
|
|
598
|
-
) {
|
|
599
|
-
authorized = true;
|
|
600
|
-
}
|
|
467
|
+
} else if (isAdminApiKey(token)) {
|
|
468
|
+
authorized = true;
|
|
601
469
|
}
|
|
602
470
|
|
|
603
471
|
if (!authorized) {
|
|
@@ -720,164 +588,7 @@ export async function startApiServer() {
|
|
|
720
588
|
}
|
|
721
589
|
|
|
722
590
|
if (transport.parseWebhook) {
|
|
723
|
-
router.post(transport.webhookPath,
|
|
724
|
-
let deadline: NodeJS.Timeout | undefined;
|
|
725
|
-
try {
|
|
726
|
-
await Promise.race([
|
|
727
|
-
(async () => {
|
|
728
|
-
const rawBody = await readRawBody(req);
|
|
729
|
-
if (!transport.verifyWebhook) {
|
|
730
|
-
if (!res.headersSent)
|
|
731
|
-
sendJson(res, 501, {
|
|
732
|
-
error: "not_implemented",
|
|
733
|
-
message: "Webhook signature verification is not implemented for this provider",
|
|
734
|
-
});
|
|
735
|
-
return;
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
const isValid = await transport.verifyWebhook(rawBody, req.headers);
|
|
739
|
-
if (!isValid) {
|
|
740
|
-
if (!res.headersSent)
|
|
741
|
-
sendJson(res, 401, {
|
|
742
|
-
error: "unauthorized",
|
|
743
|
-
message: "Invalid webhook signature",
|
|
744
|
-
});
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
let body;
|
|
748
|
-
try {
|
|
749
|
-
body = rawBody ? JSON.parse(rawBody) : {};
|
|
750
|
-
} catch {
|
|
751
|
-
body = {};
|
|
752
|
-
}
|
|
753
|
-
const events = await transport.parseWebhook!(body, rawBody, req.headers);
|
|
754
|
-
|
|
755
|
-
if (events.length > 0) {
|
|
756
|
-
const providerIds = events
|
|
757
|
-
.map((e) => e.providerMessageId)
|
|
758
|
-
.filter(Boolean) as string[];
|
|
759
|
-
const logsToProject = new Map<string, string>();
|
|
760
|
-
const logsToTask = new Map<string, string>();
|
|
761
|
-
const logsToCampaign = new Map<string, string | null>();
|
|
762
|
-
if (providerIds.length > 0) {
|
|
763
|
-
const existing = await db
|
|
764
|
-
.select({
|
|
765
|
-
providerMessageId: messageLogs.providerMessageId,
|
|
766
|
-
projectId: messageLogs.projectId,
|
|
767
|
-
taskId: messageLogs.taskId,
|
|
768
|
-
campaignId: messageLogs.campaignId,
|
|
769
|
-
})
|
|
770
|
-
.from(messageLogs)
|
|
771
|
-
.where(inArray(messageLogs.providerMessageId, providerIds));
|
|
772
|
-
for (const row of existing) {
|
|
773
|
-
if (row.providerMessageId) {
|
|
774
|
-
logsToProject.set(row.providerMessageId, row.projectId);
|
|
775
|
-
logsToTask.set(row.providerMessageId, row.taskId);
|
|
776
|
-
// Inherit the campaign from the delivery this event is
|
|
777
|
-
// about, or an open never counts toward the send that
|
|
778
|
-
// earned it.
|
|
779
|
-
logsToCampaign.set(row.providerMessageId, row.campaignId);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
// Only record events we can attribute to a real message. An
|
|
785
|
-
// unresolvable providerMessageId used to be written against a
|
|
786
|
-
// zero-UUID project, which is unjoinable and leaks across tenants.
|
|
787
|
-
const attributable = events.filter(
|
|
788
|
-
(e) => e.providerMessageId && logsToProject.has(e.providerMessageId),
|
|
789
|
-
);
|
|
790
|
-
|
|
791
|
-
const rows = attributable.map((e) => ({
|
|
792
|
-
projectId: logsToProject.get(e.providerMessageId)!,
|
|
793
|
-
taskId: logsToTask.get(e.providerMessageId)!,
|
|
794
|
-
providerMessageId: e.providerMessageId,
|
|
795
|
-
channel: transport.channel,
|
|
796
|
-
// Engagement events are not delivery attempts.
|
|
797
|
-
attempt: 0,
|
|
798
|
-
kind: e.status,
|
|
799
|
-
status: e.status,
|
|
800
|
-
campaignId: logsToCampaign.get(e.providerMessageId) ?? null,
|
|
801
|
-
metadata: e.metadata ?? null,
|
|
802
|
-
}));
|
|
803
|
-
|
|
804
|
-
const skipped = events.length - rows.length;
|
|
805
|
-
if (skipped > 0) {
|
|
806
|
-
logger.warn(
|
|
807
|
-
{ channel, skipped },
|
|
808
|
-
"webhook events skipped: unknown providerMessageId",
|
|
809
|
-
);
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
if (rows.length > 0) {
|
|
813
|
-
// Providers retry on any non-2xx, so redelivery of an event we have
|
|
814
|
-
// already recorded must be a no-op rather than a constraint error.
|
|
815
|
-
await db.insert(messageLogs).values(rows).onConflictDoNothing();
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
// An unsubscribe, a spam complaint, or a permanently dead
|
|
819
|
-
// address must stop future sends — logging it is not enough.
|
|
820
|
-
// Soft bounces are excluded: the address is still good.
|
|
821
|
-
const suppressionRows = attributable
|
|
822
|
-
.filter(
|
|
823
|
-
(e) =>
|
|
824
|
-
e.recipient &&
|
|
825
|
-
(e.status === "unsubscribed" ||
|
|
826
|
-
e.status === "complained" ||
|
|
827
|
-
(e.status === "bounced" && e.bounceType === "hard")),
|
|
828
|
-
)
|
|
829
|
-
.map((e) => ({
|
|
830
|
-
projectId: logsToProject.get(e.providerMessageId)!,
|
|
831
|
-
channel: transport.channel,
|
|
832
|
-
target: normaliseTarget(e.recipient!),
|
|
833
|
-
reason: e.status,
|
|
834
|
-
source: channel,
|
|
835
|
-
taskId: logsToTask.get(e.providerMessageId)!,
|
|
836
|
-
}));
|
|
837
|
-
|
|
838
|
-
if (suppressionRows.length > 0) {
|
|
839
|
-
// First reason wins: a later bounce should not overwrite the
|
|
840
|
-
// record that the person actively unsubscribed.
|
|
841
|
-
await db.insert(suppressions).values(suppressionRows).onConflictDoNothing();
|
|
842
|
-
logger.info(
|
|
843
|
-
{ channel, count: suppressionRows.length },
|
|
844
|
-
"addresses suppressed from provider webhook",
|
|
845
|
-
);
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
const unsuppressable = attributable.filter(
|
|
849
|
-
(e) =>
|
|
850
|
-
!e.recipient &&
|
|
851
|
-
(e.status === "unsubscribed" ||
|
|
852
|
-
e.status === "complained" ||
|
|
853
|
-
e.status === "bounced"),
|
|
854
|
-
).length;
|
|
855
|
-
if (unsuppressable > 0) {
|
|
856
|
-
// Worth shouting about: the event arrived, we logged it, and
|
|
857
|
-
// we still cannot stop mailing the person.
|
|
858
|
-
logger.warn(
|
|
859
|
-
{ channel, count: unsuppressable },
|
|
860
|
-
"suppression events carried no recipient address — transport must set WebhookEvent.recipient",
|
|
861
|
-
);
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
if (!res.headersSent) sendJson(res, 200, { success: true });
|
|
865
|
-
})(),
|
|
866
|
-
new Promise((_, reject) => {
|
|
867
|
-
deadline = setTimeout(() => reject(new Error("Webhook processing timeout")), 15000);
|
|
868
|
-
}),
|
|
869
|
-
]);
|
|
870
|
-
} catch (err) {
|
|
871
|
-
// The detail is ours to log, not the provider's: providers keep
|
|
872
|
-
// response bodies in their delivery logs.
|
|
873
|
-
logger.error({ err, channel }, "webhook processing error or timeout");
|
|
874
|
-
if (!res.headersSent) {
|
|
875
|
-
sendJson(res, 500, { error: "internal_error" });
|
|
876
|
-
}
|
|
877
|
-
} finally {
|
|
878
|
-
clearTimeout(deadline);
|
|
879
|
-
}
|
|
880
|
-
});
|
|
591
|
+
router.post(transport.webhookPath, createWebhookHandler(transport, channel, { db, logger }));
|
|
881
592
|
logger.info(`Mounted webhook for ${channel} at ${transport.webhookPath}`);
|
|
882
593
|
}
|
|
883
594
|
}
|
|
@@ -908,10 +619,9 @@ export async function stopApiServer(): Promise<void> {
|
|
|
908
619
|
await liveEvents?.close();
|
|
909
620
|
liveEvents = null;
|
|
910
621
|
// These are module-scoped, so a restart in the same process must not inherit
|
|
911
|
-
// the previous instance's cached auth
|
|
622
|
+
// the previous instance's cached auth.
|
|
912
623
|
authCache = new LRUCache<string, CachedAuthKey>(1000, AUTH_CACHE_TTL_MS);
|
|
913
624
|
tokenHashToToken.clear();
|
|
914
|
-
cachedHealth = null;
|
|
915
625
|
if (sql) await sql.end();
|
|
916
626
|
if (redis) await redis.disconnect();
|
|
917
627
|
logger?.info("api stopped");
|
|
@@ -28,7 +28,7 @@ interface Route {
|
|
|
28
28
|
*
|
|
29
29
|
* Routes are indexed by `"METHOD:segmentCount"` so `match()` only inspects the
|
|
30
30
|
* small bucket of routes that share the same method and path depth, instead of
|
|
31
|
-
* scanning
|
|
31
|
+
* scanning every registered route on every request.
|
|
32
32
|
*/
|
|
33
33
|
export class Router {
|
|
34
34
|
/** Indexed buckets: key is `"METHOD:segmentCount"`. */
|