@stotles/better-auth-audit-logs 0.4.0-rc.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +319 -0
  3. package/dist/adapters/index.d.ts +1 -0
  4. package/dist/adapters/index.d.ts.map +1 -0
  5. package/dist/adapters/memory.d.ts +13 -0
  6. package/dist/adapters/memory.d.ts.map +1 -0
  7. package/dist/client.cjs +77 -0
  8. package/dist/client.d.ts +10 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +13 -0
  11. package/dist/endpoints/get-log.d.ts +27 -0
  12. package/dist/endpoints/get-log.d.ts.map +1 -0
  13. package/dist/endpoints/index.d.ts +3 -0
  14. package/dist/endpoints/index.d.ts.map +1 -0
  15. package/dist/endpoints/insert-log.d.ts +44 -0
  16. package/dist/endpoints/insert-log.d.ts.map +1 -0
  17. package/dist/endpoints/list-logs.d.ts +40 -0
  18. package/dist/endpoints/list-logs.d.ts.map +1 -0
  19. package/dist/hooks/after.d.ts +6 -0
  20. package/dist/hooks/after.d.ts.map +1 -0
  21. package/dist/hooks/before.d.ts +6 -0
  22. package/dist/hooks/before.d.ts.map +1 -0
  23. package/dist/hooks/index.d.ts +2 -0
  24. package/dist/hooks/index.d.ts.map +1 -0
  25. package/dist/index.cjs +828 -0
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +762 -0
  29. package/dist/internal.d.ts +16 -0
  30. package/dist/internal.d.ts.map +1 -0
  31. package/dist/plugin.d.ts +180 -0
  32. package/dist/plugin.d.ts.map +1 -0
  33. package/dist/schema.d.ts +109 -0
  34. package/dist/schema.d.ts.map +1 -0
  35. package/dist/types.d.ts +102 -0
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/utils/index.d.ts +7 -0
  38. package/dist/utils/index.d.ts.map +1 -0
  39. package/dist/utils/normalize-path.d.ts +1 -0
  40. package/dist/utils/normalize-path.d.ts.map +1 -0
  41. package/dist/utils/parse-metadata.d.ts +8 -0
  42. package/dist/utils/parse-metadata.d.ts.map +1 -0
  43. package/dist/utils/request-meta.d.ts +9 -0
  44. package/dist/utils/request-meta.d.ts.map +1 -0
  45. package/dist/utils/retry.d.ts +8 -0
  46. package/dist/utils/retry.d.ts.map +1 -0
  47. package/dist/utils/sanitize.d.ts +3 -0
  48. package/dist/utils/sanitize.d.ts.map +1 -0
  49. package/dist/utils/severity.d.ts +2 -0
  50. package/dist/utils/severity.d.ts.map +1 -0
  51. package/dist/utils/validate-entry.d.ts +8 -0
  52. package/dist/utils/validate-entry.d.ts.map +1 -0
  53. package/dist/utils/validate-metadata.d.ts +10 -0
  54. package/dist/utils/validate-metadata.d.ts.map +1 -0
  55. package/package.json +72 -0
package/dist/index.js ADDED
@@ -0,0 +1,762 @@
1
+ // src/schema.ts
2
+ import { mergeSchema } from "better-auth/db";
3
+ var baseSchema = {
4
+ auditLog: {
5
+ modelName: "auditLog",
6
+ fields: {
7
+ userId: {
8
+ type: "string",
9
+ required: false,
10
+ references: {
11
+ model: "user",
12
+ field: "id",
13
+ onDelete: "set null"
14
+ },
15
+ index: true
16
+ },
17
+ action: {
18
+ type: "string",
19
+ required: true,
20
+ sortable: true,
21
+ index: true
22
+ },
23
+ status: {
24
+ type: "string",
25
+ required: true,
26
+ sortable: true
27
+ },
28
+ severity: {
29
+ type: "string",
30
+ required: true,
31
+ sortable: true
32
+ },
33
+ ipAddress: {
34
+ type: "string",
35
+ required: false
36
+ },
37
+ userAgent: {
38
+ type: "string",
39
+ required: false,
40
+ returned: false
41
+ },
42
+ metadata: {
43
+ type: "string",
44
+ required: false
45
+ },
46
+ createdAt: {
47
+ type: "date",
48
+ required: true,
49
+ sortable: true,
50
+ index: true,
51
+ defaultValue: () => new Date
52
+ }
53
+ }
54
+ }
55
+ };
56
+ function buildSchema(options) {
57
+ return mergeSchema(baseSchema, options?.schema);
58
+ }
59
+ function getModelName(options) {
60
+ return options?.schema?.auditLog?.modelName ?? "auditLog";
61
+ }
62
+ var CRITICAL_FIELDS = ["userId", "action", "status", "severity", "metadata", "createdAt"];
63
+ function validateSchema(schema) {
64
+ const model = schema.auditLog;
65
+ if (!model) {
66
+ throw new Error("[audit-log] Schema must define an auditLog model");
67
+ }
68
+ const fields = model.fields;
69
+ if (!fields || typeof fields !== "object") {
70
+ throw new Error("[audit-log] Schema auditLog model must have fields");
71
+ }
72
+ for (const field of CRITICAL_FIELDS) {
73
+ if (!(field in fields)) {
74
+ throw new Error(`[audit-log] Schema missing critical field: ${field}`);
75
+ }
76
+ }
77
+ }
78
+
79
+ // src/hooks/before.ts
80
+ import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
81
+
82
+ // src/utils/normalize-path.ts
83
+ function normalizePath(path) {
84
+ return path.replace(/^\//, "").replace(/\//g, ":");
85
+ }
86
+ // src/utils/severity.ts
87
+ var SEVERITY_MAP = new Map([
88
+ ["ban-user", "critical"],
89
+ ["impersonate-user", "critical"],
90
+ ["delete-user", "high"],
91
+ ["delete-account", "high"],
92
+ ["revoke-sessions", "high"],
93
+ ["revoke-other-sessions", "high"],
94
+ ["sign-in", "medium"],
95
+ ["sign-out", "medium"],
96
+ ["revoke-session", "medium"],
97
+ ["two-factor", "medium"],
98
+ ["change-password", "medium"],
99
+ ["reset-password", "medium"]
100
+ ]);
101
+ function inferSeverity(action, status) {
102
+ for (const [pattern, severity] of SEVERITY_MAP) {
103
+ if (action.includes(pattern)) {
104
+ if (severity === "medium" && status === "failed")
105
+ return "high";
106
+ return severity;
107
+ }
108
+ }
109
+ return "low";
110
+ }
111
+ // src/utils/request-meta.ts
112
+ import * as betterAuthApi from "better-auth/api";
113
+ var hasWarnedMissingGetIp = false;
114
+ function getIpWrapper(req, options, logger) {
115
+ if ("getIP" in betterAuthApi) {
116
+ return betterAuthApi.getIP(req, options);
117
+ }
118
+ if ("getIp" in betterAuthApi) {
119
+ return betterAuthApi.getIp(req, options);
120
+ }
121
+ if (!hasWarnedMissingGetIp) {
122
+ hasWarnedMissingGetIp = true;
123
+ logger?.error("[audit-log] better-auth/api exposes neither getIP nor getIp; " + "IP addresses will not be captured. This likely means an incompatible better-auth version.");
124
+ }
125
+ return null;
126
+ }
127
+ function extractRequestMeta(request, headers, options, logger) {
128
+ return {
129
+ ipAddress: request ? getIpWrapper(request, options, logger) ?? null : null,
130
+ userAgent: headers?.get("user-agent") ?? null
131
+ };
132
+ }
133
+ // src/utils/sanitize.ts
134
+ var DEFAULT_PII_FIELDS = [
135
+ "password",
136
+ "newPassword",
137
+ "currentPassword",
138
+ "token",
139
+ "secret",
140
+ "apiKey",
141
+ "refreshToken",
142
+ "accessToken",
143
+ "code",
144
+ "backupCode",
145
+ "otp"
146
+ ];
147
+ async function sha256(value) {
148
+ const encoded = new TextEncoder().encode(value);
149
+ const buffer = await crypto.subtle.digest("SHA-256", encoded);
150
+ return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
151
+ }
152
+ async function redactPII(data, config) {
153
+ if (!config.enabled)
154
+ return data;
155
+ const fields = config.fields ?? DEFAULT_PII_FIELDS;
156
+ const strategy = config.strategy ?? "mask";
157
+ const result = { ...data };
158
+ for (const field of fields) {
159
+ if (!(field in result) || result[field] == null)
160
+ continue;
161
+ if (strategy === "remove") {
162
+ delete result[field];
163
+ } else if (strategy === "hash") {
164
+ result[field] = await sha256(String(result[field]));
165
+ } else {
166
+ result[field] = "[REDACTED]";
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+ // src/utils/parse-metadata.ts
172
+ function parseMetadata(raw) {
173
+ if (raw == null)
174
+ return {};
175
+ if (typeof raw === "object" && !Array.isArray(raw)) {
176
+ return raw;
177
+ }
178
+ if (typeof raw === "string") {
179
+ try {
180
+ const parsed = JSON.parse(raw);
181
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
182
+ return parsed;
183
+ }
184
+ return {};
185
+ } catch {
186
+ return {};
187
+ }
188
+ }
189
+ return {};
190
+ }
191
+ // src/utils/validate-entry.ts
192
+ import { z } from "zod";
193
+ var auditLogEntrySchema = z.object({
194
+ userId: z.string().nullable(),
195
+ action: z.string().min(1),
196
+ status: z.enum(["success", "failed"]),
197
+ severity: z.enum(["low", "medium", "high", "critical"]),
198
+ ipAddress: z.string().nullable(),
199
+ userAgent: z.string().nullable(),
200
+ metadata: z.record(z.string(), z.unknown()),
201
+ createdAt: z.date()
202
+ });
203
+ function validateEntry(entry, logger) {
204
+ const result = auditLogEntrySchema.safeParse(entry);
205
+ if (!result.success) {
206
+ logger?.warn("[audit-log] beforeLog returned invalid entry, skipping write:", result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`));
207
+ return null;
208
+ }
209
+ return result.data;
210
+ }
211
+ // src/utils/retry.ts
212
+ async function withRetry(fn, opts) {
213
+ let lastError;
214
+ for (let attempt = 0;attempt <= opts.maxRetries; attempt++) {
215
+ try {
216
+ return await fn();
217
+ } catch (err) {
218
+ lastError = err;
219
+ if (attempt < opts.maxRetries) {
220
+ const delay = opts.baseDelayMs * Math.pow(2, attempt);
221
+ await new Promise((r) => setTimeout(r, delay));
222
+ }
223
+ }
224
+ }
225
+ throw lastError;
226
+ }
227
+ // src/internal.ts
228
+ async function buildLogEntry(path, status, params) {
229
+ const action = normalizePath(path);
230
+ const severity = params.pathConfig?.severity ?? inferSeverity(action, status);
231
+ const captureOpts = {
232
+ ...params.options.capture,
233
+ ...params.pathConfig?.capture
234
+ };
235
+ const { ipAddress, userAgent } = extractRequestMeta(captureOpts.ipAddress !== false ? params.request : undefined, captureOpts.userAgent !== false ? params.headers : undefined, params.authOptions, params.logger);
236
+ let metadata = params.metadata ?? {};
237
+ if (params.options.piiRedaction.enabled) {
238
+ metadata = await redactPII(metadata, params.options.piiRedaction);
239
+ }
240
+ return {
241
+ userId: params.userId,
242
+ action,
243
+ status,
244
+ severity,
245
+ ipAddress,
246
+ userAgent,
247
+ metadata,
248
+ createdAt: new Date
249
+ };
250
+ }
251
+ async function buildLogEntryFromAction(action, status, params) {
252
+ const severity = inferSeverity(action, status);
253
+ const { ipAddress, userAgent } = extractRequestMeta(params.options.capture.ipAddress !== false ? params.request : undefined, params.options.capture.userAgent !== false ? params.headers : undefined, params.authOptions, params.logger);
254
+ let metadata = params.metadata ?? {};
255
+ if (params.options.piiRedaction.enabled) {
256
+ metadata = await redactPII(metadata, params.options.piiRedaction);
257
+ }
258
+ return {
259
+ userId: params.userId,
260
+ action,
261
+ status,
262
+ severity,
263
+ ipAddress,
264
+ userAgent,
265
+ metadata,
266
+ createdAt: new Date
267
+ };
268
+ }
269
+ async function writeEntry(ctx, entry, opts, modelName) {
270
+ const doFullWrite = async () => {
271
+ let finalEntry = entry;
272
+ if (opts.beforeLog) {
273
+ const modified = await opts.beforeLog(finalEntry, ctx);
274
+ if (modified === null)
275
+ return;
276
+ const validated = validateEntry(modified, ctx.context.logger);
277
+ if (validated === null)
278
+ return;
279
+ finalEntry = validated;
280
+ }
281
+ let written;
282
+ try {
283
+ written = await withRetry(async () => {
284
+ if (opts.storage) {
285
+ const result = { id: crypto.randomUUID(), ...finalEntry };
286
+ await opts.storage.write(result);
287
+ return result;
288
+ }
289
+ const record = await ctx.context.adapter.create({
290
+ model: modelName,
291
+ data: {
292
+ ...finalEntry,
293
+ metadata: JSON.stringify(finalEntry.metadata)
294
+ }
295
+ });
296
+ return {
297
+ ...record,
298
+ metadata: finalEntry.metadata
299
+ };
300
+ }, { maxRetries: 2, baseDelayMs: 100 });
301
+ } catch (err) {
302
+ ctx.context.logger?.error("[audit-log] storage write failed after retries", err);
303
+ opts.onWriteError?.(err, finalEntry);
304
+ throw err;
305
+ }
306
+ if (opts.afterLog)
307
+ await opts.afterLog(written);
308
+ };
309
+ if (opts.nonBlocking) {
310
+ ctx.context.runInBackground(doFullWrite().catch((err) => {
311
+ ctx.context.logger?.error("[audit-log] background write failed", err);
312
+ opts.onWriteError?.(err, entry);
313
+ }));
314
+ } else {
315
+ await doFullWrite();
316
+ }
317
+ }
318
+
319
+ // src/hooks/before.ts
320
+ function createBeforeHooks(opts, modelName) {
321
+ return [
322
+ {
323
+ matcher: (context) => !!context.path && opts.beforePaths.some((p) => context.path.startsWith(p)) && opts.shouldCapture(context.path),
324
+ handler: createAuthMiddleware(async (ctx) => {
325
+ try {
326
+ const session = await getSessionFromCtx(ctx);
327
+ const path = ctx.path;
328
+ const pathConfig = opts.getPathConfig(path);
329
+ const entry = await buildLogEntry(path, "success", {
330
+ userId: session?.user?.id ?? null,
331
+ request: ctx.request,
332
+ headers: ctx.headers,
333
+ pathConfig,
334
+ options: opts,
335
+ authOptions: ctx.context.options,
336
+ logger: ctx.context.logger
337
+ });
338
+ await writeEntry(ctx, entry, opts, modelName);
339
+ } catch (err) {
340
+ ctx.context.logger?.error("[audit-log] before hook failed", err);
341
+ }
342
+ })
343
+ }
344
+ ];
345
+ }
346
+ // src/hooks/after.ts
347
+ import { createAuthMiddleware as createAuthMiddleware2 } from "better-auth/api";
348
+ function createAfterHooks(opts, modelName) {
349
+ return [
350
+ {
351
+ matcher: (context) => !!context.path && !opts.beforePaths.some((p) => context.path.startsWith(p)) && opts.shouldCapture(context.path),
352
+ handler: createAuthMiddleware2(async (ctx) => {
353
+ try {
354
+ const path = ctx.path;
355
+ const isError = ctx.context.returned instanceof Error;
356
+ const status = isError ? "failed" : "success";
357
+ const user = ctx.context.newSession?.user ?? ctx.context.session?.user;
358
+ const pathConfig = opts.getPathConfig(path);
359
+ const metadata = {};
360
+ if (opts.capture.requestBody && ctx.body) {
361
+ metadata.requestBody = ctx.body;
362
+ }
363
+ if (isError) {
364
+ const err = ctx.context.returned;
365
+ metadata.error = {
366
+ message: err.message,
367
+ ...err.status !== undefined && { status: err.status },
368
+ ...err.code !== undefined && { code: err.code }
369
+ };
370
+ }
371
+ const entry = await buildLogEntry(path, status, {
372
+ userId: user?.id ?? null,
373
+ request: ctx.request,
374
+ headers: ctx.headers,
375
+ metadata,
376
+ pathConfig,
377
+ options: opts,
378
+ authOptions: ctx.context.options,
379
+ logger: ctx.context.logger
380
+ });
381
+ await writeEntry(ctx, entry, opts, modelName);
382
+ } catch (err) {
383
+ ctx.context.logger?.error("[audit-log] after hook failed", err);
384
+ }
385
+ })
386
+ }
387
+ ];
388
+ }
389
+ // src/endpoints/list-logs.ts
390
+ import { createAuthEndpoint, sessionMiddleware, APIError } from "better-auth/api";
391
+ import { z as z2 } from "zod";
392
+ function createListLogsEndpoint(opts, modelName) {
393
+ return createAuthEndpoint("/audit-log/list", {
394
+ method: "GET",
395
+ use: [sessionMiddleware],
396
+ query: z2.object({
397
+ userId: z2.string().optional(),
398
+ action: z2.string().optional(),
399
+ status: z2.enum(["success", "failed"]).optional(),
400
+ from: z2.string().optional(),
401
+ to: z2.string().optional(),
402
+ limit: z2.coerce.number().min(1).max(500).optional().default(50),
403
+ offset: z2.coerce.number().min(0).optional().default(0)
404
+ })
405
+ }, async (ctx) => {
406
+ const session = ctx.context.session;
407
+ const targetUserId = ctx.query.userId ?? session.user.id;
408
+ if (targetUserId !== session.user.id) {
409
+ throw new APIError("FORBIDDEN", {
410
+ message: "Cannot query other users' audit logs"
411
+ });
412
+ }
413
+ const fromDate = ctx.query.from ? new Date(ctx.query.from) : undefined;
414
+ const toDate = ctx.query.to ? new Date(ctx.query.to) : undefined;
415
+ try {
416
+ if (opts.storage?.read) {
417
+ const readOpts = {
418
+ userId: targetUserId,
419
+ action: ctx.query.action,
420
+ status: ctx.query.status,
421
+ from: fromDate,
422
+ to: toDate,
423
+ limit: ctx.query.limit,
424
+ offset: ctx.query.offset
425
+ };
426
+ const result = await opts.storage.read(readOpts);
427
+ if (result.entries.length > readOpts.limit) {
428
+ result.entries = result.entries.slice(0, readOpts.limit);
429
+ }
430
+ if (opts.piiRedaction.enabled) {
431
+ for (let i = 0;i < result.entries.length; i++) {
432
+ result.entries[i] = {
433
+ ...result.entries[i],
434
+ metadata: await redactPII(result.entries[i].metadata, opts.piiRedaction)
435
+ };
436
+ }
437
+ }
438
+ return ctx.json(result);
439
+ }
440
+ const where = [{ field: "userId", value: targetUserId }];
441
+ if (ctx.query.action) {
442
+ where.push({ field: "action", value: ctx.query.action });
443
+ }
444
+ if (ctx.query.status) {
445
+ where.push({ field: "status", value: ctx.query.status });
446
+ }
447
+ if (fromDate) {
448
+ where.push({ field: "createdAt", operator: "gte", value: fromDate });
449
+ }
450
+ if (toDate) {
451
+ where.push({ field: "createdAt", operator: "lte", value: toDate });
452
+ }
453
+ const [entries, total] = await Promise.all([
454
+ ctx.context.adapter.findMany({
455
+ model: modelName,
456
+ where,
457
+ sortBy: { field: "createdAt", direction: "desc" },
458
+ limit: ctx.query.limit,
459
+ offset: ctx.query.offset
460
+ }),
461
+ ctx.context.adapter.count({ model: modelName, where })
462
+ ]);
463
+ let parsed = entries.map((e) => ({
464
+ ...e,
465
+ metadata: parseMetadata(e["metadata"])
466
+ }));
467
+ if (opts.piiRedaction.enabled) {
468
+ parsed = await Promise.all(parsed.map(async (e) => ({
469
+ ...e,
470
+ metadata: await redactPII(e.metadata, opts.piiRedaction)
471
+ })));
472
+ }
473
+ return ctx.json({ entries: parsed, total });
474
+ } catch (err) {
475
+ if (err instanceof APIError)
476
+ throw err;
477
+ ctx.context.logger?.error("[audit-log] list failed", err);
478
+ throw new APIError("INTERNAL_SERVER_ERROR", {
479
+ message: "Failed to retrieve audit logs"
480
+ });
481
+ }
482
+ });
483
+ }
484
+ // src/endpoints/get-log.ts
485
+ import { createAuthEndpoint as createAuthEndpoint2, sessionMiddleware as sessionMiddleware2, APIError as APIError2 } from "better-auth/api";
486
+ function createGetLogEndpoint(opts, modelName) {
487
+ return createAuthEndpoint2("/audit-log/:id", { method: "GET", use: [sessionMiddleware2] }, async (ctx) => {
488
+ const id = ctx.params?.id;
489
+ if (!id) {
490
+ throw new APIError2("BAD_REQUEST", {
491
+ message: "Missing audit log entry id"
492
+ });
493
+ }
494
+ const session = ctx.context.session;
495
+ try {
496
+ if (opts.storage?.readById) {
497
+ const entry2 = await opts.storage.readById(id);
498
+ if (!entry2 || entry2.userId !== session.user.id) {
499
+ throw new APIError2("NOT_FOUND", {
500
+ message: "Audit log entry not found"
501
+ });
502
+ }
503
+ if (opts.piiRedaction.enabled) {
504
+ entry2.metadata = await redactPII(entry2.metadata, opts.piiRedaction);
505
+ }
506
+ return ctx.json(entry2);
507
+ }
508
+ const record = await ctx.context.adapter.findOne({
509
+ model: modelName,
510
+ where: [
511
+ { field: "id", value: id },
512
+ { field: "userId", value: session.user.id }
513
+ ]
514
+ });
515
+ if (!record) {
516
+ throw new APIError2("NOT_FOUND", {
517
+ message: "Audit log entry not found"
518
+ });
519
+ }
520
+ let metadata = parseMetadata(record["metadata"]);
521
+ if (opts.piiRedaction.enabled) {
522
+ metadata = await redactPII(metadata, opts.piiRedaction);
523
+ }
524
+ const entry = {
525
+ ...record,
526
+ metadata
527
+ };
528
+ return ctx.json(entry);
529
+ } catch (err) {
530
+ if (err instanceof APIError2)
531
+ throw err;
532
+ ctx.context.logger?.error("[audit-log] get failed", err);
533
+ throw new APIError2("INTERNAL_SERVER_ERROR", {
534
+ message: "Failed to retrieve audit log entry"
535
+ });
536
+ }
537
+ });
538
+ }
539
+ // src/endpoints/insert-log.ts
540
+ import { createAuthEndpoint as createAuthEndpoint3, sessionMiddleware as sessionMiddleware3, APIError as APIError3 } from "better-auth/api";
541
+ import { z as z3 } from "zod";
542
+
543
+ // src/utils/validate-metadata.ts
544
+ var DEFAULT_METADATA_LIMITS = {
545
+ maxBytes: 64 * 1024,
546
+ maxDepth: 5
547
+ };
548
+ function measureDepth(value, current = 0) {
549
+ if (current > 100)
550
+ return current;
551
+ if (typeof value !== "object" || value === null)
552
+ return current;
553
+ if (Array.isArray(value)) {
554
+ let max2 = current;
555
+ for (const item of value) {
556
+ max2 = Math.max(max2, measureDepth(item, current + 1));
557
+ }
558
+ return max2;
559
+ }
560
+ let max = current;
561
+ for (const v of Object.values(value)) {
562
+ max = Math.max(max, measureDepth(v, current + 1));
563
+ }
564
+ return max;
565
+ }
566
+ function validateMetadataSize(metadata, limits = DEFAULT_METADATA_LIMITS) {
567
+ const depth = measureDepth(metadata);
568
+ if (depth > limits.maxDepth) {
569
+ return `Metadata exceeds maximum depth of ${limits.maxDepth}`;
570
+ }
571
+ const bytes = new TextEncoder().encode(JSON.stringify(metadata)).byteLength;
572
+ if (bytes > limits.maxBytes) {
573
+ return `Metadata exceeds maximum size of ${limits.maxBytes} bytes`;
574
+ }
575
+ return null;
576
+ }
577
+
578
+ // src/endpoints/insert-log.ts
579
+ function createInsertLogEndpoint(opts, modelName) {
580
+ return createAuthEndpoint3("/audit-log/insert", {
581
+ method: "POST",
582
+ use: [sessionMiddleware3],
583
+ body: z3.object({
584
+ action: z3.string().min(1),
585
+ status: z3.enum(["success", "failed"]).optional().default("success"),
586
+ severity: z3.enum(["low", "medium", "high", "critical"]).optional(),
587
+ metadata: z3.record(z3.string(), z3.unknown()).optional().default({})
588
+ })
589
+ }, async (ctx) => {
590
+ const session = ctx.context.session;
591
+ const { action, status, severity, metadata } = ctx.body;
592
+ if (opts.metadataLimits !== false) {
593
+ const error = validateMetadataSize(metadata, opts.metadataLimits);
594
+ if (error) {
595
+ throw new APIError3("BAD_REQUEST", { message: error });
596
+ }
597
+ }
598
+ try {
599
+ const entry = await buildLogEntryFromAction(action, status, {
600
+ userId: session.user.id,
601
+ request: ctx.request,
602
+ headers: ctx.headers,
603
+ metadata,
604
+ options: opts,
605
+ authOptions: ctx.context.options,
606
+ logger: ctx.context.logger
607
+ });
608
+ if (severity) {
609
+ entry.severity = severity;
610
+ }
611
+ await writeEntry(ctx, entry, opts, modelName);
612
+ return ctx.json({ success: true });
613
+ } catch (err) {
614
+ if (err instanceof APIError3)
615
+ throw err;
616
+ ctx.context.logger?.error("[audit-log] insert failed", err);
617
+ throw new APIError3("INTERNAL_SERVER_ERROR", {
618
+ message: "Failed to insert audit log entry"
619
+ });
620
+ }
621
+ });
622
+ }
623
+ // src/plugin.ts
624
+ var DEFAULT_BEFORE_PATHS = [
625
+ "/sign-out",
626
+ "/delete-user",
627
+ "/revoke-session",
628
+ "/revoke-sessions",
629
+ "/revoke-other-sessions"
630
+ ];
631
+ function validateStorageAdapter(storage) {
632
+ if (!storage)
633
+ return;
634
+ if (typeof storage.write !== "function") {
635
+ throw new Error("[audit-log] Custom storage adapter must implement write(entry): Promise<void>");
636
+ }
637
+ if (storage.read !== undefined && typeof storage.read !== "function") {
638
+ throw new Error("[audit-log] storage.read must be a function if provided");
639
+ }
640
+ if (storage.readById !== undefined && typeof storage.readById !== "function") {
641
+ throw new Error("[audit-log] storage.readById must be a function if provided");
642
+ }
643
+ if (storage.deleteOlderThan !== undefined && typeof storage.deleteOlderThan !== "function") {
644
+ throw new Error("[audit-log] storage.deleteOlderThan must be a function if provided");
645
+ }
646
+ }
647
+ function resolveOptions(options) {
648
+ const pathsMap = new Map;
649
+ const hasPaths = (options?.paths?.length ?? 0) > 0;
650
+ for (const p of options?.paths ?? []) {
651
+ if (typeof p === "string") {
652
+ pathsMap.set(p, undefined);
653
+ } else {
654
+ pathsMap.set(p.path, p.config);
655
+ }
656
+ }
657
+ const metadataLimits = options?.metadataLimits === false ? false : {
658
+ maxBytes: options?.metadataLimits?.maxBytes ?? DEFAULT_METADATA_LIMITS.maxBytes,
659
+ maxDepth: options?.metadataLimits?.maxDepth ?? DEFAULT_METADATA_LIMITS.maxDepth
660
+ };
661
+ return {
662
+ enabled: options?.enabled ?? true,
663
+ nonBlocking: options?.nonBlocking ?? false,
664
+ storage: options?.storage,
665
+ capture: {
666
+ ipAddress: options?.capture?.ipAddress ?? true,
667
+ userAgent: options?.capture?.userAgent ?? true,
668
+ requestBody: options?.capture?.requestBody ?? false
669
+ },
670
+ piiRedaction: {
671
+ enabled: options?.piiRedaction?.enabled ?? false,
672
+ fields: options?.piiRedaction?.fields,
673
+ strategy: options?.piiRedaction?.strategy ?? "mask"
674
+ },
675
+ retention: options?.retention,
676
+ metadataLimits,
677
+ beforePaths: options?.beforePaths ?? DEFAULT_BEFORE_PATHS,
678
+ beforeLog: options?.beforeLog,
679
+ afterLog: options?.afterLog,
680
+ onWriteError: options?.onWriteError,
681
+ shouldCapture: (path) => !hasPaths || pathsMap.has(path),
682
+ getPathConfig: (path) => pathsMap.get(path)
683
+ };
684
+ }
685
+ function auditLog(options) {
686
+ validateStorageAdapter(options?.storage);
687
+ const schema = buildSchema(options);
688
+ validateSchema(schema);
689
+ const modelName = getModelName(options);
690
+ const resolved = resolveOptions(options);
691
+ const beforeHooks = resolved.enabled ? createBeforeHooks(resolved, modelName) : [];
692
+ const afterHooks = resolved.enabled ? createAfterHooks(resolved, modelName) : [];
693
+ return {
694
+ id: "audit-log",
695
+ schema,
696
+ hooks: {
697
+ before: beforeHooks,
698
+ after: afterHooks
699
+ },
700
+ endpoints: {
701
+ listAuditLogs: createListLogsEndpoint(resolved, modelName),
702
+ getAuditLog: createGetLogEndpoint(resolved, modelName),
703
+ insertAuditLog: createInsertLogEndpoint(resolved, modelName)
704
+ },
705
+ rateLimit: [
706
+ {
707
+ pathMatcher: (path) => path.startsWith("/audit-log/"),
708
+ window: 60,
709
+ max: 60
710
+ }
711
+ ]
712
+ };
713
+ }
714
+ // src/adapters/memory.ts
715
+ var DEFAULT_MAX_ENTRIES = 1e4;
716
+
717
+ class MemoryStorage {
718
+ entries = [];
719
+ maxEntries;
720
+ constructor(opts) {
721
+ this.maxEntries = opts?.maxEntries ?? DEFAULT_MAX_ENTRIES;
722
+ }
723
+ async write(entry) {
724
+ this.entries.push(entry);
725
+ if (this.entries.length > this.maxEntries) {
726
+ const excess = this.entries.length - this.maxEntries;
727
+ this.entries.splice(0, excess);
728
+ }
729
+ }
730
+ async read(opts) {
731
+ let filtered = this.entries.filter((e) => {
732
+ if (opts.userId !== undefined && e.userId !== opts.userId)
733
+ return false;
734
+ if (opts.action !== undefined && e.action !== opts.action)
735
+ return false;
736
+ if (opts.status !== undefined && e.status !== opts.status)
737
+ return false;
738
+ if (opts.from !== undefined && e.createdAt < opts.from)
739
+ return false;
740
+ if (opts.to !== undefined && e.createdAt > opts.to)
741
+ return false;
742
+ return true;
743
+ });
744
+ const total = filtered.length;
745
+ filtered = filtered.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(opts.offset, opts.offset + opts.limit);
746
+ return { entries: filtered, total };
747
+ }
748
+ async readById(id) {
749
+ return this.entries.find((e) => e.id === id) ?? null;
750
+ }
751
+ async deleteOlderThan(date) {
752
+ const before = this.entries.length;
753
+ const retained = this.entries.filter((e) => e.createdAt >= date);
754
+ this.entries.length = 0;
755
+ this.entries.push(...retained);
756
+ return before - this.entries.length;
757
+ }
758
+ }
759
+ export {
760
+ auditLog,
761
+ MemoryStorage
762
+ };