@hogsend/engine 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +93 -0
  2. package/README.md +18 -0
  3. package/package.json +58 -0
  4. package/src/app.ts +102 -0
  5. package/src/container.ts +172 -0
  6. package/src/env.ts +56 -0
  7. package/src/index.ts +114 -0
  8. package/src/journeys/define-journey.ts +188 -0
  9. package/src/journeys/journey-context.ts +179 -0
  10. package/src/journeys/registry-singleton.ts +21 -0
  11. package/src/journeys/registry.ts +53 -0
  12. package/src/lib/alerting.ts +205 -0
  13. package/src/lib/api-key-hash.ts +19 -0
  14. package/src/lib/auth.ts +39 -0
  15. package/src/lib/backfill.ts +84 -0
  16. package/src/lib/contacts.ts +68 -0
  17. package/src/lib/db.ts +13 -0
  18. package/src/lib/email-service-types.ts +115 -0
  19. package/src/lib/email-stats.ts +33 -0
  20. package/src/lib/email.ts +94 -0
  21. package/src/lib/enrollment-guards.ts +56 -0
  22. package/src/lib/hatchet.ts +20 -0
  23. package/src/lib/html.ts +25 -0
  24. package/src/lib/ingestion.ts +162 -0
  25. package/src/lib/logger.ts +32 -0
  26. package/src/lib/mailer.ts +266 -0
  27. package/src/lib/notifications.ts +61 -0
  28. package/src/lib/posthog.ts +19 -0
  29. package/src/lib/redis.ts +30 -0
  30. package/src/lib/schemas.ts +8 -0
  31. package/src/lib/tracked.ts +175 -0
  32. package/src/lib/tracking-event-names.ts +5 -0
  33. package/src/lib/tracking-events.ts +84 -0
  34. package/src/lib/tracking.ts +78 -0
  35. package/src/middleware/api-key.ts +129 -0
  36. package/src/middleware/audit.ts +47 -0
  37. package/src/middleware/auth.ts +24 -0
  38. package/src/middleware/error-handler.ts +22 -0
  39. package/src/middleware/rate-limit.ts +65 -0
  40. package/src/middleware/request-logger.ts +19 -0
  41. package/src/routes/admin/alerts.ts +347 -0
  42. package/src/routes/admin/api-keys.ts +211 -0
  43. package/src/routes/admin/audit-logs.ts +102 -0
  44. package/src/routes/admin/bulk.ts +503 -0
  45. package/src/routes/admin/contacts.ts +342 -0
  46. package/src/routes/admin/dlq.ts +202 -0
  47. package/src/routes/admin/emails.ts +269 -0
  48. package/src/routes/admin/events.ts +132 -0
  49. package/src/routes/admin/index.ts +36 -0
  50. package/src/routes/admin/journey-logs.ts +117 -0
  51. package/src/routes/admin/journeys.ts +677 -0
  52. package/src/routes/admin/metrics.ts +559 -0
  53. package/src/routes/admin/preferences.ts +165 -0
  54. package/src/routes/admin/timeline.ts +221 -0
  55. package/src/routes/email/index.ts +8 -0
  56. package/src/routes/email/preferences.ts +144 -0
  57. package/src/routes/email/unsubscribe.ts +161 -0
  58. package/src/routes/health.ts +131 -0
  59. package/src/routes/index.ts +32 -0
  60. package/src/routes/ingest.ts +71 -0
  61. package/src/routes/tracking/click.ts +103 -0
  62. package/src/routes/tracking/index.ts +9 -0
  63. package/src/routes/tracking/open.ts +71 -0
  64. package/src/routes/webhooks/index.ts +17 -0
  65. package/src/routes/webhooks/resend.ts +68 -0
  66. package/src/routes/webhooks/sources.ts +97 -0
  67. package/src/webhook-sources/define-webhook-source.ts +34 -0
  68. package/src/worker.ts +64 -0
  69. package/src/workflows/check-alerts.ts +24 -0
  70. package/src/workflows/import-contacts.ts +134 -0
  71. package/src/workflows/send-email.ts +54 -0
@@ -0,0 +1,347 @@
1
+ import { alertHistory, alertRules } from "@hogsend/db";
2
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
+ import { and, count, desc, eq, gte, lte } from "drizzle-orm";
4
+ import type { AppEnv } from "../../app.js";
5
+ import { errorSchema } from "../../lib/schemas.js";
6
+
7
+ const alertRuleSchema = z.object({
8
+ id: z.string(),
9
+ name: z.string(),
10
+ type: z.string(),
11
+ threshold: z.record(z.string(), z.number()),
12
+ channel: z.string(),
13
+ channelConfig: z.record(z.string(), z.string()),
14
+ enabled: z.boolean(),
15
+ cooldownMinutes: z.number(),
16
+ lastFiredAt: z.string().nullable(),
17
+ createdAt: z.string(),
18
+ updatedAt: z.string(),
19
+ });
20
+
21
+ const alertHistorySchema = z.object({
22
+ id: z.string(),
23
+ alertRuleId: z.string(),
24
+ payload: z.record(z.string(), z.unknown()).nullable(),
25
+ deliveryStatus: z.string(),
26
+ error: z.string().nullable(),
27
+ createdAt: z.string(),
28
+ });
29
+
30
+ const listRulesRoute = createRoute({
31
+ method: "get",
32
+ path: "/rules",
33
+ tags: ["Admin — Alerts"],
34
+ summary: "List alert rules",
35
+ request: {
36
+ query: z.object({
37
+ limit: z.coerce.number().min(1).max(100).default(50),
38
+ offset: z.coerce.number().min(0).default(0),
39
+ }),
40
+ },
41
+ responses: {
42
+ 200: {
43
+ content: {
44
+ "application/json": {
45
+ schema: z.object({
46
+ rules: z.array(alertRuleSchema),
47
+ total: z.number(),
48
+ limit: z.number(),
49
+ offset: z.number(),
50
+ }),
51
+ },
52
+ },
53
+ description: "Paginated alert rules list",
54
+ },
55
+ },
56
+ });
57
+
58
+ const createRuleRoute = createRoute({
59
+ method: "post",
60
+ path: "/rules",
61
+ tags: ["Admin — Alerts"],
62
+ summary: "Create an alert rule",
63
+ request: {
64
+ body: {
65
+ content: {
66
+ "application/json": {
67
+ schema: z.object({
68
+ name: z.string().min(1),
69
+ type: z.enum([
70
+ "bounce_rate_exceeded",
71
+ "journey_failure_spike",
72
+ "delivery_issue",
73
+ "high_complaint_rate",
74
+ ]),
75
+ threshold: z.record(z.string(), z.number()),
76
+ channel: z.enum(["webhook", "slack", "email"]),
77
+ channelConfig: z.record(z.string(), z.string()),
78
+ cooldownMinutes: z.number().min(1).default(60),
79
+ }),
80
+ },
81
+ },
82
+ },
83
+ },
84
+ responses: {
85
+ 201: {
86
+ content: {
87
+ "application/json": {
88
+ schema: z.object({ rule: alertRuleSchema }),
89
+ },
90
+ },
91
+ description: "Alert rule created",
92
+ },
93
+ },
94
+ });
95
+
96
+ const updateRuleRoute = createRoute({
97
+ method: "patch",
98
+ path: "/rules/{id}",
99
+ tags: ["Admin — Alerts"],
100
+ summary: "Update an alert rule",
101
+ request: {
102
+ params: z.object({ id: z.string().uuid() }),
103
+ body: {
104
+ content: {
105
+ "application/json": {
106
+ schema: z.object({
107
+ name: z.string().optional(),
108
+ threshold: z.record(z.string(), z.number()).optional(),
109
+ channelConfig: z.record(z.string(), z.string()).optional(),
110
+ enabled: z.boolean().optional(),
111
+ cooldownMinutes: z.number().min(1).optional(),
112
+ }),
113
+ },
114
+ },
115
+ },
116
+ },
117
+ responses: {
118
+ 200: {
119
+ content: {
120
+ "application/json": {
121
+ schema: z.object({ rule: alertRuleSchema }),
122
+ },
123
+ },
124
+ description: "Alert rule updated",
125
+ },
126
+ 404: {
127
+ content: { "application/json": { schema: errorSchema } },
128
+ description: "Alert rule not found",
129
+ },
130
+ },
131
+ });
132
+
133
+ const deleteRuleRoute = createRoute({
134
+ method: "delete",
135
+ path: "/rules/{id}",
136
+ tags: ["Admin — Alerts"],
137
+ summary: "Delete an alert rule",
138
+ request: {
139
+ params: z.object({ id: z.string().uuid() }),
140
+ },
141
+ responses: {
142
+ 200: {
143
+ content: {
144
+ "application/json": {
145
+ schema: z.object({ deleted: z.boolean() }),
146
+ },
147
+ },
148
+ description: "Alert rule deleted",
149
+ },
150
+ 404: {
151
+ content: { "application/json": { schema: errorSchema } },
152
+ description: "Alert rule not found",
153
+ },
154
+ },
155
+ });
156
+
157
+ const listHistoryRoute = createRoute({
158
+ method: "get",
159
+ path: "/history",
160
+ tags: ["Admin — Alerts"],
161
+ summary: "List alert history",
162
+ request: {
163
+ query: z.object({
164
+ limit: z.coerce.number().min(1).max(100).default(50),
165
+ offset: z.coerce.number().min(0).default(0),
166
+ ruleId: z.string().uuid().optional(),
167
+ from: z.string().datetime().optional(),
168
+ to: z.string().datetime().optional(),
169
+ }),
170
+ },
171
+ responses: {
172
+ 200: {
173
+ content: {
174
+ "application/json": {
175
+ schema: z.object({
176
+ history: z.array(alertHistorySchema),
177
+ total: z.number(),
178
+ limit: z.number(),
179
+ offset: z.number(),
180
+ }),
181
+ },
182
+ },
183
+ description: "Paginated alert history",
184
+ },
185
+ },
186
+ });
187
+
188
+ function serializeRule(row: typeof alertRules.$inferSelect) {
189
+ return {
190
+ id: row.id,
191
+ name: row.name,
192
+ type: row.type,
193
+ threshold: row.threshold as Record<string, number>,
194
+ channel: row.channel,
195
+ channelConfig: row.channelConfig as Record<string, string>,
196
+ enabled: row.enabled,
197
+ cooldownMinutes: row.cooldownMinutes,
198
+ lastFiredAt: row.lastFiredAt?.toISOString() ?? null,
199
+ createdAt: row.createdAt.toISOString(),
200
+ updatedAt: row.updatedAt.toISOString(),
201
+ };
202
+ }
203
+
204
+ export const alertsRouter = new OpenAPIHono<AppEnv>()
205
+ .openapi(listRulesRoute, async (c) => {
206
+ const { db } = c.get("container");
207
+ const { limit, offset } = c.req.valid("query");
208
+
209
+ const [rows, totalRows] = await Promise.all([
210
+ db
211
+ .select()
212
+ .from(alertRules)
213
+ .orderBy(desc(alertRules.createdAt))
214
+ .limit(limit)
215
+ .offset(offset),
216
+ db.select({ count: count() }).from(alertRules),
217
+ ]);
218
+
219
+ return c.json(
220
+ {
221
+ rules: rows.map(serializeRule),
222
+ total: totalRows[0]?.count ?? 0,
223
+ limit,
224
+ offset,
225
+ },
226
+ 200,
227
+ );
228
+ })
229
+ .openapi(createRuleRoute, async (c) => {
230
+ const { db } = c.get("container");
231
+ const body = c.req.valid("json");
232
+
233
+ const [created] = await db
234
+ .insert(alertRules)
235
+ .values({
236
+ name: body.name,
237
+ type: body.type,
238
+ threshold: body.threshold,
239
+ channel: body.channel,
240
+ channelConfig: body.channelConfig,
241
+ cooldownMinutes: body.cooldownMinutes,
242
+ })
243
+ .returning();
244
+
245
+ if (!created) throw new Error("Failed to create alert rule");
246
+
247
+ return c.json({ rule: serializeRule(created) }, 201);
248
+ })
249
+ .openapi(updateRuleRoute, async (c) => {
250
+ const { db } = c.get("container");
251
+ const { id } = c.req.valid("param");
252
+ const body = c.req.valid("json");
253
+
254
+ const rows = await db
255
+ .select()
256
+ .from(alertRules)
257
+ .where(eq(alertRules.id, id))
258
+ .limit(1);
259
+
260
+ if (!rows[0]) {
261
+ return c.json({ error: "Alert rule not found" }, 404);
262
+ }
263
+
264
+ const [updated] = await db
265
+ .update(alertRules)
266
+ .set({
267
+ ...(body.name !== undefined ? { name: body.name } : {}),
268
+ ...(body.threshold !== undefined ? { threshold: body.threshold } : {}),
269
+ ...(body.channelConfig !== undefined
270
+ ? { channelConfig: body.channelConfig }
271
+ : {}),
272
+ ...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
273
+ ...(body.cooldownMinutes !== undefined
274
+ ? { cooldownMinutes: body.cooldownMinutes }
275
+ : {}),
276
+ updatedAt: new Date(),
277
+ })
278
+ .where(eq(alertRules.id, id))
279
+ .returning();
280
+
281
+ if (!updated) throw new Error("Failed to update alert rule");
282
+
283
+ return c.json({ rule: serializeRule(updated) }, 200);
284
+ })
285
+ .openapi(deleteRuleRoute, async (c) => {
286
+ const { db } = c.get("container");
287
+ const { id } = c.req.valid("param");
288
+
289
+ const rows = await db
290
+ .select()
291
+ .from(alertRules)
292
+ .where(eq(alertRules.id, id))
293
+ .limit(1);
294
+
295
+ if (!rows[0]) {
296
+ return c.json({ error: "Alert rule not found" }, 404);
297
+ }
298
+
299
+ await db.delete(alertRules).where(eq(alertRules.id, id));
300
+
301
+ return c.json({ deleted: true }, 200);
302
+ })
303
+ .openapi(listHistoryRoute, async (c) => {
304
+ const { db } = c.get("container");
305
+ const { limit, offset, ruleId, from, to } = c.req.valid("query");
306
+
307
+ const conditions = [];
308
+ if (ruleId) {
309
+ conditions.push(eq(alertHistory.alertRuleId, ruleId));
310
+ }
311
+ if (from) {
312
+ conditions.push(gte(alertHistory.createdAt, new Date(from)));
313
+ }
314
+ if (to) {
315
+ conditions.push(lte(alertHistory.createdAt, new Date(to)));
316
+ }
317
+
318
+ const where = conditions.length > 0 ? and(...conditions) : undefined;
319
+
320
+ const [rows, totalRows] = await Promise.all([
321
+ db
322
+ .select()
323
+ .from(alertHistory)
324
+ .where(where)
325
+ .orderBy(desc(alertHistory.createdAt))
326
+ .limit(limit)
327
+ .offset(offset),
328
+ db.select({ count: count() }).from(alertHistory).where(where),
329
+ ]);
330
+
331
+ return c.json(
332
+ {
333
+ history: rows.map((row) => ({
334
+ id: row.id,
335
+ alertRuleId: row.alertRuleId,
336
+ payload: (row.payload ?? null) as Record<string, unknown> | null,
337
+ deliveryStatus: row.deliveryStatus,
338
+ error: row.error,
339
+ createdAt: row.createdAt.toISOString(),
340
+ })),
341
+ total: totalRows[0]?.count ?? 0,
342
+ limit,
343
+ offset,
344
+ },
345
+ 200,
346
+ );
347
+ });
@@ -0,0 +1,211 @@
1
+ import { apiKeys } from "@hogsend/db";
2
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
+ import { and, count, desc, eq, isNull } from "drizzle-orm";
4
+ import type { AppEnv } from "../../app.js";
5
+ import { generateApiKey } from "../../lib/api-key-hash.js";
6
+ import { errorSchema } from "../../lib/schemas.js";
7
+
8
+ const apiKeySchema = z.object({
9
+ id: z.string(),
10
+ name: z.string(),
11
+ keyPrefix: z.string(),
12
+ scopes: z.array(z.string()),
13
+ createdBy: z.string().nullable(),
14
+ lastUsedAt: z.string().nullable(),
15
+ revokedAt: z.string().nullable(),
16
+ expiresAt: z.string().nullable(),
17
+ createdAt: z.string(),
18
+ });
19
+
20
+ const listRoute = createRoute({
21
+ method: "get",
22
+ path: "/",
23
+ tags: ["Admin — API Keys"],
24
+ summary: "List API keys",
25
+ request: {
26
+ query: z.object({
27
+ limit: z.coerce.number().min(1).max(100).default(50),
28
+ offset: z.coerce.number().min(0).default(0),
29
+ includeRevoked: z.enum(["true", "false"]).default("false"),
30
+ }),
31
+ },
32
+ responses: {
33
+ 200: {
34
+ content: {
35
+ "application/json": {
36
+ schema: z.object({
37
+ keys: z.array(apiKeySchema),
38
+ total: z.number(),
39
+ limit: z.number(),
40
+ offset: z.number(),
41
+ }),
42
+ },
43
+ },
44
+ description: "Paginated API key list",
45
+ },
46
+ },
47
+ });
48
+
49
+ const createKeyRoute = createRoute({
50
+ method: "post",
51
+ path: "/",
52
+ tags: ["Admin — API Keys"],
53
+ summary: "Create a new API key",
54
+ request: {
55
+ body: {
56
+ content: {
57
+ "application/json": {
58
+ schema: z.object({
59
+ name: z.string().min(1).max(100),
60
+ scopes: z
61
+ .array(z.enum(["read", "journey-admin", "full-admin"]))
62
+ .min(1)
63
+ .default(["read"]),
64
+ expiresAt: z.string().datetime().optional(),
65
+ }),
66
+ },
67
+ },
68
+ },
69
+ },
70
+ responses: {
71
+ 201: {
72
+ content: {
73
+ "application/json": {
74
+ schema: z.object({
75
+ id: z.string(),
76
+ name: z.string(),
77
+ key: z.string(),
78
+ keyPrefix: z.string(),
79
+ scopes: z.array(z.string()),
80
+ expiresAt: z.string().nullable(),
81
+ createdAt: z.string(),
82
+ }),
83
+ },
84
+ },
85
+ description: "API key created — key is shown only once",
86
+ },
87
+ },
88
+ });
89
+
90
+ const revokeRoute = createRoute({
91
+ method: "delete",
92
+ path: "/{id}",
93
+ tags: ["Admin — API Keys"],
94
+ summary: "Revoke an API key",
95
+ request: {
96
+ params: z.object({ id: z.string().uuid() }),
97
+ },
98
+ responses: {
99
+ 200: {
100
+ content: {
101
+ "application/json": {
102
+ schema: z.object({ revoked: z.boolean() }),
103
+ },
104
+ },
105
+ description: "API key revoked",
106
+ },
107
+ 404: {
108
+ content: { "application/json": { schema: errorSchema } },
109
+ description: "API key not found",
110
+ },
111
+ },
112
+ });
113
+
114
+ function serializeKey(row: typeof apiKeys.$inferSelect) {
115
+ return {
116
+ id: row.id,
117
+ name: row.name,
118
+ keyPrefix: row.keyPrefix,
119
+ scopes: row.scopes as string[],
120
+ createdBy: row.createdBy,
121
+ lastUsedAt: row.lastUsedAt?.toISOString() ?? null,
122
+ revokedAt: row.revokedAt?.toISOString() ?? null,
123
+ expiresAt: row.expiresAt?.toISOString() ?? null,
124
+ createdAt: row.createdAt.toISOString(),
125
+ };
126
+ }
127
+
128
+ export const apiKeysRouter = new OpenAPIHono<AppEnv>()
129
+ .openapi(listRoute, async (c) => {
130
+ const { db } = c.get("container");
131
+ const { limit, offset, includeRevoked } = c.req.valid("query");
132
+
133
+ const where =
134
+ includeRevoked === "true" ? undefined : isNull(apiKeys.revokedAt);
135
+
136
+ const [rows, totalRows] = await Promise.all([
137
+ db
138
+ .select()
139
+ .from(apiKeys)
140
+ .where(where)
141
+ .orderBy(desc(apiKeys.createdAt))
142
+ .limit(limit)
143
+ .offset(offset),
144
+ db.select({ count: count() }).from(apiKeys).where(where),
145
+ ]);
146
+
147
+ return c.json(
148
+ {
149
+ keys: rows.map(serializeKey),
150
+ total: totalRows[0]?.count ?? 0,
151
+ limit,
152
+ offset,
153
+ },
154
+ 200,
155
+ );
156
+ })
157
+ .openapi(createKeyRoute, async (c) => {
158
+ const { db } = c.get("container");
159
+ const body = c.req.valid("json");
160
+ const actor = c.get("apiKey");
161
+
162
+ const { key, prefix, hash } = generateApiKey();
163
+
164
+ const [created] = await db
165
+ .insert(apiKeys)
166
+ .values({
167
+ name: body.name,
168
+ keyPrefix: prefix,
169
+ keyHash: hash,
170
+ scopes: body.scopes,
171
+ createdBy: actor?.name ?? null,
172
+ expiresAt: body.expiresAt ? new Date(body.expiresAt) : null,
173
+ })
174
+ .returning();
175
+
176
+ if (!created) throw new Error("Failed to create API key");
177
+
178
+ return c.json(
179
+ {
180
+ id: created.id,
181
+ name: created.name,
182
+ key,
183
+ keyPrefix: prefix,
184
+ scopes: created.scopes as string[],
185
+ expiresAt: created.expiresAt?.toISOString() ?? null,
186
+ createdAt: created.createdAt.toISOString(),
187
+ },
188
+ 201,
189
+ );
190
+ })
191
+ .openapi(revokeRoute, async (c) => {
192
+ const { db } = c.get("container");
193
+ const { id } = c.req.valid("param");
194
+
195
+ const rows = await db
196
+ .select()
197
+ .from(apiKeys)
198
+ .where(and(eq(apiKeys.id, id), isNull(apiKeys.revokedAt)))
199
+ .limit(1);
200
+
201
+ if (!rows[0]) {
202
+ return c.json({ error: "API key not found or already revoked" }, 404);
203
+ }
204
+
205
+ await db
206
+ .update(apiKeys)
207
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
208
+ .where(eq(apiKeys.id, id));
209
+
210
+ return c.json({ revoked: true }, 200);
211
+ });
@@ -0,0 +1,102 @@
1
+ import { auditLogs } from "@hogsend/db";
2
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
+ import { and, count, desc, eq, gte, lte } from "drizzle-orm";
4
+ import type { AppEnv } from "../../app.js";
5
+
6
+ const auditLogSchema = z.object({
7
+ id: z.string(),
8
+ actor: z.string(),
9
+ actorKeyId: z.string().nullable(),
10
+ action: z.string(),
11
+ resource: z.string(),
12
+ resourceId: z.string().nullable(),
13
+ detail: z.record(z.string(), z.unknown()).nullable(),
14
+ ipAddress: z.string().nullable(),
15
+ createdAt: z.string(),
16
+ });
17
+
18
+ const listRoute = createRoute({
19
+ method: "get",
20
+ path: "/",
21
+ tags: ["Admin — Audit"],
22
+ summary: "List audit logs",
23
+ request: {
24
+ query: z.object({
25
+ limit: z.coerce.number().min(1).max(100).default(50),
26
+ offset: z.coerce.number().min(0).default(0),
27
+ actor: z.string().optional(),
28
+ resource: z.string().optional(),
29
+ action: z.string().optional(),
30
+ from: z.string().datetime().optional(),
31
+ to: z.string().datetime().optional(),
32
+ }),
33
+ },
34
+ responses: {
35
+ 200: {
36
+ content: {
37
+ "application/json": {
38
+ schema: z.object({
39
+ logs: z.array(auditLogSchema),
40
+ total: z.number(),
41
+ limit: z.number(),
42
+ offset: z.number(),
43
+ }),
44
+ },
45
+ },
46
+ description: "Paginated audit log list",
47
+ },
48
+ },
49
+ });
50
+
51
+ function serializeLog(row: typeof auditLogs.$inferSelect) {
52
+ return {
53
+ id: row.id,
54
+ actor: row.actor,
55
+ actorKeyId: row.actorKeyId,
56
+ action: row.action,
57
+ resource: row.resource,
58
+ resourceId: row.resourceId,
59
+ detail: (row.detail ?? null) as Record<string, unknown> | null,
60
+ ipAddress: row.ipAddress,
61
+ createdAt: row.createdAt.toISOString(),
62
+ };
63
+ }
64
+
65
+ export const auditLogsRouter = new OpenAPIHono<AppEnv>().openapi(
66
+ listRoute,
67
+ async (c) => {
68
+ const { db } = c.get("container");
69
+ const { limit, offset, actor, resource, action, from, to } =
70
+ c.req.valid("query");
71
+
72
+ const conditions = [];
73
+ if (actor) conditions.push(eq(auditLogs.actor, actor));
74
+ if (resource) conditions.push(eq(auditLogs.resource, resource));
75
+ if (action) conditions.push(eq(auditLogs.action, action));
76
+ if (from) conditions.push(gte(auditLogs.createdAt, new Date(from)));
77
+ if (to) conditions.push(lte(auditLogs.createdAt, new Date(to)));
78
+
79
+ const where = conditions.length > 0 ? and(...conditions) : undefined;
80
+
81
+ const [rows, totalRows] = await Promise.all([
82
+ db
83
+ .select()
84
+ .from(auditLogs)
85
+ .where(where)
86
+ .orderBy(desc(auditLogs.createdAt))
87
+ .limit(limit)
88
+ .offset(offset),
89
+ db.select({ count: count() }).from(auditLogs).where(where),
90
+ ]);
91
+
92
+ return c.json(
93
+ {
94
+ logs: rows.map(serializeLog),
95
+ total: totalRows[0]?.count ?? 0,
96
+ limit,
97
+ offset,
98
+ },
99
+ 200,
100
+ );
101
+ },
102
+ );