ezlogs-nextjs 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,40 @@
1
+ /** The parts of a PrismaClient the correlation tagging needs. */
2
+ interface TaggingClient {
3
+ $extends: (ext: unknown) => unknown;
4
+ $transaction: (queries: unknown[]) => Promise<unknown[]>;
5
+ $executeRawUnsafe: (sql: string, ...values: unknown[]) => unknown;
6
+ }
7
+ /**
8
+ * Public factory for `prisma.$extends(ezlogsPrisma())`.
9
+ *
10
+ * Returns Prisma's callback-form extension (what
11
+ * `Prisma.defineExtension((client) => …)` returns) so the hook can
12
+ * reach the client for correlation tagging: every write made inside a
13
+ * captured request runs as
14
+ *
15
+ * client.$transaction([
16
+ * client.$executeRawUnsafe("SELECT set_config('ezlogs.correlation_id', $1, TRUE)", id),
17
+ * query(args),
18
+ * ])
19
+ *
20
+ * — Prisma's documented RLS client-extension pattern. The audit
21
+ * trigger reads that setting, so rows from a plain `PrismaClient`
22
+ * (default engine, no driver adapter) join the right request. Reads
23
+ * pass through with no extra query.
24
+ *
25
+ * Not tagged (rows ship as their own actions, never misattributed):
26
+ * writes inside a user `$transaction` (batch or interactive) — Prisma
27
+ * can't nest a transaction there.
28
+ */
1
29
  declare function ezlogsPrisma(): unknown;
30
+ /**
31
+ * The extension descriptor. `client` null = capture only, no tagging
32
+ * (the adapter-pg path tags via the patched `pg` driver instead).
33
+ * @internal exported for tests.
34
+ */
35
+ declare function buildPrismaExtension(client: TaggingClient | null): unknown;
36
+ /** @internal test-only */
37
+ declare function _resetPrismaTaggingForTests(): void;
2
38
  /**
3
39
  * Wrap a `PrismaPg` adapter so its queryRaw/executeRaw/transactionContext
4
40
  * methods run inside a snapshot the partnered `patchPrismaClient` deposits.
@@ -37,4 +73,4 @@ declare function patchPrismaPgAdapter<A extends object>(adapter: A): A;
37
73
  */
38
74
  declare function patchPrismaClient<T extends object>(prisma: T, adapter?: object): T;
39
75
 
40
- export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
76
+ export { _resetPrismaTaggingForTests, buildPrismaExtension, ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
package/dist/db/prisma.js CHANGED
@@ -120,6 +120,14 @@ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:def
120
120
  };
121
121
  }
122
122
 
123
+ // src/correlation.ts
124
+ var storage = createScopedStorage(
125
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
126
+ );
127
+ function current() {
128
+ return storage.read();
129
+ }
130
+
123
131
  // src/configuration.ts
124
132
  var DEFAULT_EXCLUDED_PATHS = Object.freeze([
125
133
  // Next.js / Vercel infrastructure noise
@@ -189,7 +197,6 @@ var Configuration = class {
189
197
  displayNameFor = {};
190
198
  isServerActionError = null;
191
199
  databaseReader = null;
192
- databaseSnapshotMode = false;
193
200
  databaseUrl = null;
194
201
  /**
195
202
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -241,9 +248,6 @@ var Configuration = class {
241
248
  if (options.databaseReader !== void 0) {
242
249
  this.databaseReader = options.databaseReader;
243
250
  }
244
- if (options.databaseSnapshotMode !== void 0) {
245
- this.databaseSnapshotMode = options.databaseSnapshotMode;
246
- }
247
251
  if (options.databaseUrl !== void 0) {
248
252
  this.databaseUrl = options.databaseUrl;
249
253
  }
@@ -486,14 +490,6 @@ function describe2(error) {
486
490
  return String(error);
487
491
  }
488
492
 
489
- // src/correlation.ts
490
- var storage = createScopedStorage(
491
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
492
- );
493
- function current() {
494
- return storage.read();
495
- }
496
-
497
493
  // src/actor.ts
498
494
  var storage2 = createScopedStorage(
499
495
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
@@ -501,6 +497,26 @@ var storage2 = createScopedStorage(
501
497
  function getCurrentActor() {
502
498
  return storage2.read();
503
499
  }
500
+ var SENSITIVE_WORD_PATTERNS = Object.freeze([
501
+ "pin",
502
+ "otp",
503
+ "totp",
504
+ "iban",
505
+ "mfa",
506
+ "passphrase"
507
+ ]);
508
+ function snakeLower(key) {
509
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
510
+ }
511
+ function matchesSensitiveKey(key, substringPatterns) {
512
+ const lower = key.toLowerCase();
513
+ const snake = snakeLower(key);
514
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
515
+ return true;
516
+ }
517
+ const words = snake.split(/[^a-z0-9]+/);
518
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
519
+ }
504
520
 
505
521
  // src/db/shared.ts
506
522
  var IGNORED_ATTRIBUTES = Object.freeze([
@@ -533,7 +549,19 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
533
549
  "salt",
534
550
  "digest",
535
551
  "signature",
536
- "hmac"
552
+ "hmac",
553
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
554
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
555
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
556
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
557
+ "credential",
558
+ "passwd",
559
+ "passcode",
560
+ "apikey",
561
+ "card_number",
562
+ "cardnumber",
563
+ "cvv",
564
+ "cvc"
537
565
  ]);
538
566
  function emitDbEvent(input) {
539
567
  try {
@@ -560,7 +588,8 @@ function emitDbEvent(input) {
560
588
  correlation_id: current(),
561
589
  resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
562
590
  context,
563
- duration_ms: null
591
+ duration_ms: null,
592
+ timestamp: input.timestamp ?? null
564
593
  });
565
594
  pushEvent(event);
566
595
  } catch (error) {
@@ -618,8 +647,7 @@ function isMeaningfulAttribute(name) {
618
647
  return true;
619
648
  }
620
649
  function isDbSensitive(name) {
621
- const lower = name.toLowerCase();
622
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
650
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
623
651
  }
624
652
  function isScalar(value) {
625
653
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
@@ -713,6 +741,9 @@ var OPERATION_TO_DB_OPERATION = {
713
741
  deleteMany: "destroy"
714
742
  };
715
743
  function ezlogsPrisma() {
744
+ return (client) => client.$extends(buildPrismaExtension(client));
745
+ }
746
+ function buildPrismaExtension(client) {
716
747
  return {
717
748
  name: "ezlogs",
718
749
  query: {
@@ -721,7 +752,7 @@ function ezlogsPrisma() {
721
752
  if (!CAPTURED_OPERATIONS.has(ctx.operation)) {
722
753
  return ctx.query(ctx.args);
723
754
  }
724
- const result = await ctx.query(ctx.args);
755
+ const result = await runTagged(client, ctx);
725
756
  try {
726
757
  recordPrismaOperation(ctx, result);
727
758
  } catch (error) {
@@ -729,10 +760,60 @@ function ezlogsPrisma() {
729
760
  }
730
761
  return result;
731
762
  }
763
+ },
764
+ // Raw writes (`$executeRaw\`UPDATE …\``) aren't model operations.
765
+ async $allOperations(ctx) {
766
+ if (ctx.operation !== "$executeRaw" && ctx.operation !== "$executeRawUnsafe") {
767
+ return ctx.query(ctx.args);
768
+ }
769
+ return runTagged(client, ctx);
732
770
  }
733
771
  }
734
772
  };
735
773
  }
774
+ var SET_CORRELATION_SQL = "SELECT set_config('ezlogs.correlation_id', $1, TRUE)";
775
+ async function runTagged(client, ctx) {
776
+ if (!shouldTag(client, ctx)) return ctx.query(ctx.args);
777
+ try {
778
+ const results = await client.$transaction([
779
+ client.$executeRawUnsafe(SET_CORRELATION_SQL, current()),
780
+ ctx.query(ctx.args)
781
+ ]);
782
+ return results[1];
783
+ } catch (error) {
784
+ if (!isTransactionUnsupported(error)) throw error;
785
+ taggingDisabled.add(client);
786
+ logger.warn(
787
+ `this Prisma client can't run transactions, so DB writes won't be linked to their request (they still show up as their own actions): ${describeError2(error)}`
788
+ );
789
+ return ctx.query(ctx.args);
790
+ }
791
+ }
792
+ var taggingDisabled = /* @__PURE__ */ new WeakSet();
793
+ function _resetPrismaTaggingForTests() {
794
+ taggingDisabled = /* @__PURE__ */ new WeakSet();
795
+ }
796
+ function shouldTag(client, ctx) {
797
+ if (!client || taggingDisabled.has(client)) return false;
798
+ if (configuration().databaseReader == null) return false;
799
+ if (!isPostgresClient(client)) return false;
800
+ if (typeof client.$transaction !== "function" || typeof client.$executeRawUnsafe !== "function") {
801
+ return false;
802
+ }
803
+ if (!current()) return false;
804
+ const params = ctx.__internalParams;
805
+ return params != null && !params.transaction;
806
+ }
807
+ function isPostgresClient(client) {
808
+ const c = client;
809
+ const provider = c._activeProvider ?? c._engineConfig?.activeProvider;
810
+ if (typeof provider !== "string") return true;
811
+ return provider === "postgresql" || provider === "postgres";
812
+ }
813
+ function isTransactionUnsupported(error) {
814
+ const message = error instanceof Error ? error.message : String(error);
815
+ return /transaction/i.test(message) && /not (?:be )?supported|unsupported|not available/i.test(message);
816
+ }
736
817
  function recordPrismaOperation(ctx, result) {
737
818
  const dbOperation = OPERATION_TO_DB_OPERATION[ctx.operation];
738
819
  if (!dbOperation) return;
@@ -921,7 +1002,7 @@ function applyEzlogsExtension(prisma) {
921
1002
  return prisma;
922
1003
  }
923
1004
  try {
924
- return client.$extends(ezlogsPrisma());
1005
+ return client.$extends(buildPrismaExtension(null));
925
1006
  } catch (error) {
926
1007
  logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
927
1008
  return prisma;
@@ -1014,4 +1095,4 @@ function isLikelyModelDelegate(value) {
1014
1095
  return typeof candidate.create === "function" && typeof candidate.findMany === "function";
1015
1096
  }
1016
1097
 
1017
- export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
1098
+ export { _resetPrismaTaggingForTests, buildPrismaExtension, ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
@@ -111,7 +111,6 @@ var Configuration = class {
111
111
  displayNameFor = {};
112
112
  isServerActionError = null;
113
113
  databaseReader = null;
114
- databaseSnapshotMode = false;
115
114
  databaseUrl = null;
116
115
  /**
117
116
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -163,9 +162,6 @@ var Configuration = class {
163
162
  if (options.databaseReader !== void 0) {
164
163
  this.databaseReader = options.databaseReader;
165
164
  }
166
- if (options.databaseSnapshotMode !== void 0) {
167
- this.databaseSnapshotMode = options.databaseSnapshotMode;
168
- }
169
165
  if (options.databaseUrl !== void 0) {
170
166
  this.databaseUrl = options.databaseUrl;
171
167
  }
@@ -493,6 +489,26 @@ var storage2 = createScopedStorage(
493
489
  function getCurrentActor() {
494
490
  return storage2.read();
495
491
  }
492
+ var SENSITIVE_WORD_PATTERNS = Object.freeze([
493
+ "pin",
494
+ "otp",
495
+ "totp",
496
+ "iban",
497
+ "mfa",
498
+ "passphrase"
499
+ ]);
500
+ function snakeLower(key) {
501
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
502
+ }
503
+ function matchesSensitiveKey(key, substringPatterns) {
504
+ const lower = key.toLowerCase();
505
+ const snake = snakeLower(key);
506
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
507
+ return true;
508
+ }
509
+ const words = snake.split(/[^a-z0-9]+/);
510
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
511
+ }
496
512
 
497
513
  // src/db/shared.ts
498
514
  var IGNORED_ATTRIBUTES = Object.freeze([
@@ -525,7 +541,19 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
525
541
  "salt",
526
542
  "digest",
527
543
  "signature",
528
- "hmac"
544
+ "hmac",
545
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
546
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
547
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
548
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
549
+ "credential",
550
+ "passwd",
551
+ "passcode",
552
+ "apikey",
553
+ "card_number",
554
+ "cardnumber",
555
+ "cvv",
556
+ "cvc"
529
557
  ]);
530
558
  function emitDbEvent(input) {
531
559
  try {
@@ -552,7 +580,8 @@ function emitDbEvent(input) {
552
580
  correlation_id: current(),
553
581
  resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
554
582
  context,
555
- duration_ms: null
583
+ duration_ms: null,
584
+ timestamp: input.timestamp ?? null
556
585
  });
557
586
  pushEvent(event);
558
587
  } catch (error) {
@@ -610,8 +639,7 @@ function isMeaningfulAttribute(name) {
610
639
  return true;
611
640
  }
612
641
  function isDbSensitive(name) {
613
- const lower = name.toLowerCase();
614
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
642
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
615
643
  }
616
644
  function isScalar(value) {
617
645
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
@@ -109,7 +109,6 @@ var Configuration = class {
109
109
  displayNameFor = {};
110
110
  isServerActionError = null;
111
111
  databaseReader = null;
112
- databaseSnapshotMode = false;
113
112
  databaseUrl = null;
114
113
  /**
115
114
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -161,9 +160,6 @@ var Configuration = class {
161
160
  if (options.databaseReader !== void 0) {
162
161
  this.databaseReader = options.databaseReader;
163
162
  }
164
- if (options.databaseSnapshotMode !== void 0) {
165
- this.databaseSnapshotMode = options.databaseSnapshotMode;
166
- }
167
163
  if (options.databaseUrl !== void 0) {
168
164
  this.databaseUrl = options.databaseUrl;
169
165
  }
@@ -491,6 +487,26 @@ var storage2 = createScopedStorage(
491
487
  function getCurrentActor() {
492
488
  return storage2.read();
493
489
  }
490
+ var SENSITIVE_WORD_PATTERNS = Object.freeze([
491
+ "pin",
492
+ "otp",
493
+ "totp",
494
+ "iban",
495
+ "mfa",
496
+ "passphrase"
497
+ ]);
498
+ function snakeLower(key) {
499
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
500
+ }
501
+ function matchesSensitiveKey(key, substringPatterns) {
502
+ const lower = key.toLowerCase();
503
+ const snake = snakeLower(key);
504
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
505
+ return true;
506
+ }
507
+ const words = snake.split(/[^a-z0-9]+/);
508
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
509
+ }
494
510
 
495
511
  // src/db/shared.ts
496
512
  var IGNORED_ATTRIBUTES = Object.freeze([
@@ -523,7 +539,19 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
523
539
  "salt",
524
540
  "digest",
525
541
  "signature",
526
- "hmac"
542
+ "hmac",
543
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
544
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
545
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
546
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
547
+ "credential",
548
+ "passwd",
549
+ "passcode",
550
+ "apikey",
551
+ "card_number",
552
+ "cardnumber",
553
+ "cvv",
554
+ "cvc"
527
555
  ]);
528
556
  function emitDbEvent(input) {
529
557
  try {
@@ -550,7 +578,8 @@ function emitDbEvent(input) {
550
578
  correlation_id: current(),
551
579
  resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
552
580
  context,
553
- duration_ms: null
581
+ duration_ms: null,
582
+ timestamp: input.timestamp ?? null
554
583
  });
555
584
  pushEvent(event);
556
585
  } catch (error) {
@@ -608,8 +637,7 @@ function isMeaningfulAttribute(name) {
608
637
  return true;
609
638
  }
610
639
  function isDbSensitive(name) {
611
- const lower = name.toLowerCase();
612
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
640
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
613
641
  }
614
642
  function isScalar(value) {
615
643
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {