ezlogs-nextjs 0.1.4 → 0.3.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.
Files changed (40) hide show
  1. package/README.md +106 -11
  2. package/bin/install-triggers.cjs +49 -11
  3. package/dist/actors/index.d.cts +1 -1
  4. package/dist/actors/index.d.ts +1 -1
  5. package/dist/{configuration-3Pei_XZ_.d.cts → configuration-OHLNivON.d.cts} +11 -20
  6. package/dist/{configuration-3Pei_XZ_.d.ts → configuration-OHLNivON.d.ts} +11 -20
  7. package/dist/db/drizzle.cjs +154 -18
  8. package/dist/db/drizzle.js +154 -18
  9. package/dist/db/prisma.cjs +242 -45
  10. package/dist/db/prisma.d.cts +39 -1
  11. package/dist/db/prisma.d.ts +39 -1
  12. package/dist/db/prisma.js +241 -46
  13. package/dist/db/supabase.cjs +154 -18
  14. package/dist/db/supabase.js +154 -18
  15. package/dist/index.cjs +761 -245
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +761 -245
  19. package/dist/jobs/bullmq.cjs +973 -16
  20. package/dist/jobs/bullmq.d.cts +8 -3
  21. package/dist/jobs/bullmq.d.ts +8 -3
  22. package/dist/jobs/bullmq.js +973 -16
  23. package/dist/jobs/inngest.cjs +880 -14
  24. package/dist/jobs/inngest.d.cts +7 -5
  25. package/dist/jobs/inngest.d.ts +7 -5
  26. package/dist/jobs/inngest.js +880 -14
  27. package/dist/jobs/supabase-queues.cjs +878 -16
  28. package/dist/jobs/supabase-queues.js +878 -16
  29. package/dist/jobs/trigger.cjs +914 -42
  30. package/dist/jobs/trigger.js +914 -42
  31. package/dist/jobs/upstash-workflow.cjs +914 -14
  32. package/dist/jobs/upstash-workflow.d.cts +16 -2
  33. package/dist/jobs/upstash-workflow.d.ts +16 -2
  34. package/dist/jobs/upstash-workflow.js +914 -15
  35. package/dist/triggers/index.cjs +405 -76
  36. package/dist/triggers/index.d.cts +36 -41
  37. package/dist/triggers/index.d.ts +36 -41
  38. package/dist/triggers/index.js +404 -74
  39. package/package.json +5 -1
  40. package/sql/postgres/00_install.sql +244 -21
package/dist/index.js CHANGED
@@ -110,7 +110,6 @@ var init_configuration = __esm({
110
110
  displayNameFor = {};
111
111
  isServerActionError = null;
112
112
  databaseReader = null;
113
- databaseSnapshotMode = false;
114
113
  databaseUrl = null;
115
114
  /**
116
115
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -162,9 +161,6 @@ var init_configuration = __esm({
162
161
  if (options.databaseReader !== void 0) {
163
162
  this.databaseReader = options.databaseReader;
164
163
  }
165
- if (options.databaseSnapshotMode !== void 0) {
166
- this.databaseSnapshotMode = options.databaseSnapshotMode;
167
- }
168
164
  if (options.databaseUrl !== void 0) {
169
165
  this.databaseUrl = options.databaseUrl;
170
166
  }
@@ -386,13 +382,19 @@ function randomHexBytes(byteCount) {
386
382
  function resolveCorrelation(headers) {
387
383
  if (!headers) return generate();
388
384
  const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
389
- if (ezlogs2) return ezlogs2;
385
+ if (ezlogs2 && isTrustedInboundId(ezlogs2)) return ezlogs2;
390
386
  for (const name of PLATFORM_REQUEST_ID_HEADERS) {
391
387
  const platformId = safeRead(headers, name);
392
388
  if (platformId) return wrapPlatformId(platformId);
393
389
  }
394
390
  return generate();
395
391
  }
392
+ function isTrustedInboundId(id) {
393
+ const match = INBOUND_ID.exec(id);
394
+ if (!match) return false;
395
+ const age = Date.now() - Number(match[1]);
396
+ return age <= INBOUND_MAX_AGE_MS && age >= -INBOUND_MAX_SKEW_MS;
397
+ }
396
398
  function safeRead(headers, name) {
397
399
  try {
398
400
  const value = headers.get(name);
@@ -420,7 +422,7 @@ function current() {
420
422
  function runWithCorrelation(correlationId, callback) {
421
423
  return storage.run(correlationId, callback);
422
424
  }
423
- var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage;
425
+ var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage, INBOUND_ID, INBOUND_MAX_AGE_MS, INBOUND_MAX_SKEW_MS;
424
426
  var init_correlation = __esm({
425
427
  "src/correlation.ts"() {
426
428
  init_edge_fallback();
@@ -433,6 +435,9 @@ var init_correlation = __esm({
433
435
  storage = createScopedStorage(
434
436
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
435
437
  );
438
+ INBOUND_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
439
+ INBOUND_MAX_AGE_MS = 60 * 6e4;
440
+ INBOUND_MAX_SKEW_MS = 5 * 6e4;
436
441
  }
437
442
  });
438
443
 
@@ -712,6 +717,199 @@ var init_event_builder = __esm({
712
717
  }
713
718
  });
714
719
 
720
+ // src/http/sanitize.ts
721
+ function snakeLower(key) {
722
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
723
+ }
724
+ function matchesSensitiveKey(key, substringPatterns) {
725
+ const lower = key.toLowerCase();
726
+ const snake = snakeLower(key);
727
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
728
+ return true;
729
+ }
730
+ const words = snake.split(/[^a-z0-9]+/);
731
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
732
+ }
733
+ function sanitizeRequestParams(params, userPatterns = []) {
734
+ if (params === null || params === void 0) return null;
735
+ if (!isPlainObject2(params)) return null;
736
+ const obj = params;
737
+ const cleaned = {};
738
+ for (const key of Object.keys(obj)) {
739
+ if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
740
+ cleaned[key] = obj[key];
741
+ }
742
+ if (Object.keys(cleaned).length === 0) return null;
743
+ const out = {};
744
+ for (const key of Object.keys(cleaned)) {
745
+ out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
746
+ }
747
+ return out;
748
+ }
749
+ function passesLuhn(digits) {
750
+ let sum = 0;
751
+ for (let i = 0; i < digits.length; i += 1) {
752
+ let d = Number(digits[digits.length - 1 - i]);
753
+ if (i % 2 === 1) {
754
+ d *= 2;
755
+ if (d > 9) d -= 9;
756
+ }
757
+ sum += d;
758
+ }
759
+ return sum % 10 === 0;
760
+ }
761
+ function scrubSecretsInText(text, options = {}) {
762
+ let out = text;
763
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
764
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
765
+ const digits = match.replace(/[ -]/g, "");
766
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
767
+ });
768
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
769
+ }
770
+ function sanitizeValue(key, value, depth, userPatterns) {
771
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
772
+ if (isPlainObject2(value)) {
773
+ return sanitizeNestedObject(value, depth, userPatterns);
774
+ }
775
+ if (Array.isArray(value)) {
776
+ return sanitizeArrayValue(value, depth, userPatterns);
777
+ }
778
+ return value;
779
+ }
780
+ function sanitizeNestedObject(hash, depth, userPatterns) {
781
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
782
+ if (Object.keys(hash).length === 0) return {};
783
+ const out = {};
784
+ for (const k of Object.keys(hash)) {
785
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
786
+ }
787
+ return out;
788
+ }
789
+ function sanitizeArrayValue(array, depth, userPatterns) {
790
+ if (array.length === 0) return [];
791
+ const allPrimitive = array.every(isPrimitive);
792
+ if (allPrimitive) {
793
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
794
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
795
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
796
+ }
797
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
798
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
799
+ }
800
+ return {
801
+ _truncated: true,
802
+ _count: array.length,
803
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
804
+ };
805
+ }
806
+ function sanitizeArrayItem(item, depth, userPatterns) {
807
+ if (isPrimitive(item)) return item;
808
+ if (isPlainObject2(item)) {
809
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
810
+ }
811
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
812
+ return "[Object]";
813
+ }
814
+ function isSensitiveKey2(key, userPatterns) {
815
+ if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
816
+ const lower = key.toLowerCase();
817
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
818
+ }
819
+ function isPrimitive(value) {
820
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
821
+ }
822
+ function isPlainObject2(value) {
823
+ if (value === null || typeof value !== "object") return false;
824
+ const proto = Object.getPrototypeOf(value);
825
+ return proto === Object.prototype || proto === null;
826
+ }
827
+ var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS, SECRET_TEXT_PATTERNS, EMAIL;
828
+ var init_sanitize = __esm({
829
+ "src/http/sanitize.ts"() {
830
+ SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
831
+ "password",
832
+ "passwd",
833
+ "pwd",
834
+ "token",
835
+ "access_token",
836
+ "refresh_token",
837
+ "api_token",
838
+ "auth_token",
839
+ "secret",
840
+ "api_secret",
841
+ "client_secret",
842
+ "api_key",
843
+ "apikey",
844
+ "private_key",
845
+ "privatekey",
846
+ "public_key",
847
+ "signing_key",
848
+ "secret_key",
849
+ "secretkey",
850
+ "credential",
851
+ "auth",
852
+ "authorization",
853
+ "encrypted",
854
+ "encrypted_data",
855
+ "ssn",
856
+ "social_security",
857
+ "credit_card",
858
+ "card_number",
859
+ "cvv",
860
+ "cvc",
861
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
862
+ // (PR #45). Request bodies can carry the same key material as DB
863
+ // columns (a webhook POST containing a `signature` field, an HMAC
864
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
865
+ "pem",
866
+ "cipher",
867
+ "nonce",
868
+ "salt",
869
+ "digest",
870
+ "signature",
871
+ "hmac",
872
+ // 0.2.0 additions (not yet in the Rails gem's list).
873
+ "passcode",
874
+ "cardnumber"
875
+ ]);
876
+ SENSITIVE_WORD_PATTERNS = Object.freeze([
877
+ "pin",
878
+ "otp",
879
+ "totp",
880
+ "iban",
881
+ "mfa",
882
+ "passphrase"
883
+ ]);
884
+ MAX_NESTING_DEPTH = 3;
885
+ MAX_ARRAY_DISPLAY_SIZE = 5;
886
+ FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
887
+ // Rails leftovers — kept for parity since users may funnel through a
888
+ // proxy that adds them, e.g. via a NextAuth credentials provider that
889
+ // forwards CSRF tokens.
890
+ "controller",
891
+ "action",
892
+ "format",
893
+ "authenticity_token",
894
+ "_method",
895
+ // Next.js / common JS conventions
896
+ "csrfToken",
897
+ "_csrf",
898
+ "_next"
899
+ ]);
900
+ SECRET_TEXT_PATTERNS = [
901
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
902
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
903
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
904
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
905
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
906
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
907
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
908
+ ];
909
+ EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
910
+ }
911
+ });
912
+
715
913
  // src/db/shared.ts
716
914
  function emitDbEvent(input) {
717
915
  try {
@@ -720,14 +918,17 @@ function emitDbEvent(input) {
720
918
  if (config.allExcludedTables().includes(input.modelClass)) return;
721
919
  if (config.databaseReader && !input._fromTrigger) {
722
920
  const tracked = config.triggerTrackedTables;
723
- if (tracked === null || tracked.has(input.modelClass)) return;
921
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
724
922
  }
725
923
  if (input.operation === "update") {
726
924
  const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
727
925
  if (meaningful.length === 0) return;
728
926
  }
729
927
  const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
730
- const context = buildContext(input);
928
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
929
+ const context = buildContext(
930
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
931
+ );
731
932
  const event = build({
732
933
  source_type: "database_callback",
733
934
  source_data: {
@@ -736,9 +937,10 @@ function emitDbEvent(input) {
736
937
  },
737
938
  outcome: "success",
738
939
  correlation_id: current(),
739
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
940
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
740
941
  context,
741
- duration_ms: null
942
+ duration_ms: null,
943
+ timestamp: input.timestamp ?? null
742
944
  });
743
945
  pushEvent(event);
744
946
  } catch (error) {
@@ -782,7 +984,7 @@ function filterMeaningfulAttributes(attrs) {
782
984
  return Object.keys(out).length === 0 ? null : out;
783
985
  }
784
986
  function filterMeaningfulChanges(changes) {
785
- return changes.filter((c) => {
987
+ return flattenNestedChanges(changes).filter((c) => {
786
988
  if (!isMeaningfulAttribute(c.attribute)) return false;
787
989
  if (!isScalar(c.to)) return false;
788
990
  if (c.from === void 0) return true;
@@ -790,14 +992,64 @@ function filterMeaningfulChanges(changes) {
790
992
  return valuesActuallyChanged(c.from, c.to);
791
993
  });
792
994
  }
995
+ function flattenNestedChanges(changes) {
996
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
997
+ const out = [];
998
+ for (const c of changes) {
999
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
1000
+ out.push(c);
1001
+ continue;
1002
+ }
1003
+ if (!isMeaningfulAttribute(c.attribute)) continue;
1004
+ const leaves = [];
1005
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
1006
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
1007
+ out.push(...leaves.slice(0, cap).map(scrubLeaf));
1008
+ }
1009
+ return out;
1010
+ }
1011
+ function collectLeafChanges(path, from, to, depth, out) {
1012
+ if (out.length > MAX_NESTED_LEAVES) return;
1013
+ const fromObj = isPlainRecord(from);
1014
+ const toObj = isPlainRecord(to);
1015
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
1016
+ const f = fromObj ? from : {};
1017
+ const t = toObj ? to : {};
1018
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
1019
+ const before = from === void 0 ? void 0 : f[key] ?? null;
1020
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
1021
+ }
1022
+ return;
1023
+ }
1024
+ if (from !== void 0 && sameJson(from, to)) return;
1025
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
1026
+ }
1027
+ function scrubLeaf(change) {
1028
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
1029
+ const out = { attribute: change.attribute, to: scrub(change.to) };
1030
+ if (change.from !== void 0) out.from = scrub(change.from);
1031
+ return out;
1032
+ }
1033
+ function isPlainRecord(value) {
1034
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1035
+ const proto = Object.getPrototypeOf(value);
1036
+ return proto === Object.prototype || proto === null;
1037
+ }
1038
+ function sameJson(a, b) {
1039
+ if (a === b) return true;
1040
+ try {
1041
+ return JSON.stringify(a) === JSON.stringify(b);
1042
+ } catch {
1043
+ return false;
1044
+ }
1045
+ }
793
1046
  function isMeaningfulAttribute(name) {
794
1047
  if (IGNORED_ATTRIBUTES.includes(name)) return false;
795
1048
  if (isDbSensitive(name)) return false;
796
1049
  return true;
797
1050
  }
798
1051
  function isDbSensitive(name) {
799
- const lower = name.toLowerCase();
800
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
1052
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
801
1053
  }
802
1054
  function isScalar(value) {
803
1055
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
@@ -834,16 +1086,36 @@ function resolveDisplayName(modelClass, instance) {
834
1086
  const resolver = config.displayNameFor[modelClass];
835
1087
  const resolved = applyResolver(resolver, instance);
836
1088
  if (resolved !== null) return resolved;
837
- for (const field of ["name", "title", "number"]) {
838
- const value = instance[field];
839
- if (value !== null && value !== void 0 && String(value).length > 0) {
840
- return String(value);
1089
+ const columns = /* @__PURE__ */ new Map();
1090
+ for (const key of Object.keys(instance)) {
1091
+ if (isDbSensitive(key)) continue;
1092
+ const norm = key.toLowerCase().replace(/_/g, "");
1093
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
1094
+ }
1095
+ const text = (norm) => {
1096
+ const value = columns.get(norm);
1097
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1098
+ return null;
841
1099
  }
1100
+ const str = String(value).trim();
1101
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
1102
+ };
1103
+ for (const column of DISPLAY_NAME_COLUMNS) {
1104
+ const value = text(column);
1105
+ if (value !== null) return value;
842
1106
  }
1107
+ return text(`${singularNorm(modelClass)}number`);
843
1108
  } catch {
844
1109
  }
845
1110
  return null;
846
1111
  }
1112
+ function singularNorm(modelClass) {
1113
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
1114
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
1115
+ if (/(ss|us|is)$/.test(norm)) return norm;
1116
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
1117
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
1118
+ }
847
1119
  function applyResolver(resolver, instance) {
848
1120
  if (typeof resolver === "string") {
849
1121
  const value = instance[resolver];
@@ -868,7 +1140,7 @@ function describeError5(error) {
868
1140
  if (error instanceof Error) return `${error.name}: ${error.message}`;
869
1141
  return String(error);
870
1142
  }
871
- var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS;
1143
+ var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS, MAX_NESTED_DEPTH, MAX_NESTED_LEAVES, MAX_UNKNOWN_FROM_LEAVES, DISPLAY_NAME_COLUMNS, MAX_DISPLAY_NAME_LENGTH;
872
1144
  var init_shared = __esm({
873
1145
  "src/db/shared.ts"() {
874
1146
  init_configuration();
@@ -877,14 +1149,13 @@ var init_shared = __esm({
877
1149
  init_buffer();
878
1150
  init_correlation();
879
1151
  init_actor();
1152
+ init_sanitize();
880
1153
  IGNORED_ATTRIBUTES = Object.freeze([
881
1154
  "id",
882
1155
  "createdAt",
883
1156
  "created_at",
884
1157
  "updatedAt",
885
1158
  "updated_at",
886
- "deletedAt",
887
- "deleted_at",
888
1159
  // Auth.js / NextAuth standard columns
889
1160
  "emailVerified",
890
1161
  "expires"
@@ -907,8 +1178,25 @@ var init_shared = __esm({
907
1178
  "salt",
908
1179
  "digest",
909
1180
  "signature",
910
- "hmac"
1181
+ "hmac",
1182
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
1183
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
1184
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
1185
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
1186
+ "credential",
1187
+ "passwd",
1188
+ "passcode",
1189
+ "apikey",
1190
+ "card_number",
1191
+ "cardnumber",
1192
+ "cvv",
1193
+ "cvc"
911
1194
  ]);
1195
+ MAX_NESTED_DEPTH = 3;
1196
+ MAX_NESTED_LEAVES = 20;
1197
+ MAX_UNKNOWN_FROM_LEAVES = 5;
1198
+ DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
1199
+ MAX_DISPLAY_NAME_LENGTH = 120;
912
1200
  }
913
1201
  });
914
1202
 
@@ -1707,51 +1995,61 @@ function leadingVerb(text) {
1707
1995
  init_logger();
1708
1996
  init_shared();
1709
1997
  init_correlation();
1710
-
1711
- // src/triggers/audit-snapshot.ts
1712
- init_edge_fallback();
1713
- var storage3 = createScopedStorage(
1714
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-snapshot-storage")
1715
- );
1716
- function currentAuditSnapshot() {
1717
- return storage3.read();
1718
- }
1719
- function setAuditSnapshot(value) {
1720
- storage3.update(value);
1721
- }
1722
- function runWithAuditSnapshotScope(callback) {
1723
- return storage3.run(0n, callback);
1724
- }
1998
+ init_actor();
1725
1999
 
1726
2000
  // src/triggers/emit-dedup.ts
1727
2001
  init_edge_fallback();
1728
- var storage4 = createScopedStorage(
2002
+ var storage3 = createScopedStorage(
1729
2003
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1730
2004
  );
1731
2005
  function currentEmittedAuditIds() {
1732
- return storage4.read();
2006
+ return storage3.read();
1733
2007
  }
1734
2008
  function runWithEmittedAuditIdsScope(callback) {
1735
- const existing = storage4.read();
2009
+ const existing = storage3.read();
1736
2010
  if (existing !== null) return callback();
1737
- return storage4.run(/* @__PURE__ */ new Set(), callback);
2011
+ return storage3.run(/* @__PURE__ */ new Set(), callback);
1738
2012
  }
1739
2013
 
1740
2014
  // src/triggers/reader.ts
1741
- async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
2015
+ var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
2016
+ var ORPHAN_AGE = "5 minutes";
2017
+ var PRUNE_AGE = "24 hours";
2018
+ var SWEEP_BATCH = 100;
2019
+ var PRUNE_BATCH = 2e3;
2020
+ var SWEEP_INTERVAL_MS = 1e4;
2021
+ var PRUNE_INTERVAL_MS = 10 * 6e4;
2022
+ var lastSweepAt = 0;
2023
+ var lastPruneAt = 0;
2024
+ var deleteDenied = false;
2025
+ var txCorrelation = /* @__PURE__ */ new Map();
2026
+ async function readAuditRows(exec, correlationId, since = null) {
2027
+ const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
2028
+ const params = since ? [correlationId, since.toISOString()] : [correlationId];
1742
2029
  try {
1743
- const sql = snapshotMaxId === null ? `SELECT id, table_name, op, old_row, new_row, resource_id
1744
- FROM ezlogs_audit_log
1745
- WHERE correlation_id = $1
1746
- ORDER BY id ASC` : `SELECT id, table_name, op, old_row, new_row, resource_id
1747
- FROM ezlogs_audit_log
1748
- WHERE correlation_id = $1
1749
- OR (correlation_id IS NULL AND id > $2)
1750
- ORDER BY id ASC`;
1751
- const params = snapshotMaxId === null ? [correlationId] : [correlationId, snapshotMaxId.toString()];
1752
- const result = await exec(sql, params);
1753
- const rows = extractRows(result);
1754
- return rows.map((r) => normalizeAuditRow(r));
2030
+ if (!deleteDenied) {
2031
+ try {
2032
+ return sortById(
2033
+ extractRows(
2034
+ await exec(
2035
+ `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
2036
+ params
2037
+ )
2038
+ ).map(normalizeAuditRow)
2039
+ );
2040
+ } catch (err) {
2041
+ if (!isPermissionDenied(err)) throw err;
2042
+ deleteDenied = true;
2043
+ logger.warn(
2044
+ "the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
2045
+ );
2046
+ }
2047
+ }
2048
+ const result = await exec(
2049
+ `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
2050
+ params
2051
+ );
2052
+ return extractRows(result).map(normalizeAuditRow);
1755
2053
  } catch (err) {
1756
2054
  logger.debug(
1757
2055
  `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
@@ -1759,24 +2057,103 @@ async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1759
2057
  return [];
1760
2058
  }
1761
2059
  }
1762
- async function takeAuditSnapshot(exec) {
2060
+ async function sweepAuditLog(exec) {
2061
+ if (deleteDenied) return 0;
1763
2062
  try {
1764
- const result = await exec(
1765
- `SELECT COALESCE(MAX(id), 0) AS max_id FROM ezlogs_audit_log`,
2063
+ const rows = sortById(
2064
+ extractRows(
2065
+ await exec(
2066
+ `DELETE FROM ezlogs_audit_log
2067
+ WHERE id IN (
2068
+ SELECT id FROM ezlogs_audit_log
2069
+ WHERE (correlation_id IS NULL
2070
+ OR captured_at < now() - interval '${ORPHAN_AGE}')
2071
+ -- Never resurface history: past the retention cap a
2072
+ -- row is pruned, not sent as new activity.
2073
+ AND captured_at > now() - interval '${PRUNE_AGE}'
2074
+ ORDER BY id
2075
+ LIMIT ${SWEEP_BATCH}
2076
+ FOR UPDATE SKIP LOCKED)
2077
+ RETURNING ${COLUMNS}`,
2078
+ []
2079
+ )
2080
+ ).map(normalizeAuditRow)
2081
+ );
2082
+ await loadTableMeta(exec, rows);
2083
+ for (const row of rows) {
2084
+ const correlationId = row.correlation_id ?? correlationForTx(row.txid);
2085
+ runWithCorrelation(
2086
+ correlationId,
2087
+ () => runWithActorScope(() => emitOne(row))
2088
+ );
2089
+ }
2090
+ return rows.length;
2091
+ } catch (err) {
2092
+ logger.debug(
2093
+ `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2094
+ );
2095
+ return 0;
2096
+ }
2097
+ }
2098
+ async function pruneAuditLog(exec) {
2099
+ if (deleteDenied) return;
2100
+ try {
2101
+ await exec(
2102
+ `DELETE FROM ezlogs_audit_log
2103
+ WHERE id IN (
2104
+ SELECT id FROM ezlogs_audit_log
2105
+ WHERE captured_at < now() - interval '${PRUNE_AGE}'
2106
+ LIMIT ${PRUNE_BATCH})`,
1766
2107
  []
1767
2108
  );
1768
- const rows = extractRows(result);
1769
- if (rows.length === 0) return;
1770
- const raw = rows[0] ?? {};
1771
- const value = typeof raw.max_id === "bigint" ? raw.max_id : typeof raw.max_id === "number" ? BigInt(raw.max_id) : typeof raw.max_id === "string" && /^\d+$/.test(raw.max_id) ? BigInt(raw.max_id) : null;
1772
- if (value === null) return;
1773
- setAuditSnapshot(value);
1774
2109
  } catch (err) {
1775
2110
  logger.debug(
1776
- `takeAuditSnapshot failed: ${err instanceof Error ? err.message : String(err)}`
2111
+ `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1777
2112
  );
1778
2113
  }
1779
2114
  }
2115
+ async function auditLogInstalled(exec) {
2116
+ try {
2117
+ const rows = extractRows(
2118
+ await exec(
2119
+ `SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
2120
+ []
2121
+ )
2122
+ );
2123
+ const installed = rows[0]?.installed;
2124
+ return typeof installed === "boolean" ? installed : null;
2125
+ } catch {
2126
+ return null;
2127
+ }
2128
+ }
2129
+ async function checkAuditLogAccess(exec) {
2130
+ try {
2131
+ const rows = extractRows(
2132
+ await exec(
2133
+ `SELECT current_user AS role
2134
+ FROM pg_class c
2135
+ JOIN pg_roles r ON r.rolname = current_user
2136
+ WHERE c.oid = 'public.ezlogs_audit_log'::regclass
2137
+ AND c.relrowsecurity
2138
+ AND NOT r.rolsuper
2139
+ AND NOT r.rolbypassrls
2140
+ AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
2141
+ AND NOT EXISTS (SELECT 1 FROM pg_policies p
2142
+ WHERE p.schemaname = 'public'
2143
+ AND p.tablename = 'ezlogs_audit_log')`,
2144
+ []
2145
+ )
2146
+ );
2147
+ const role = rows[0]?.role;
2148
+ if (typeof role !== "string") return false;
2149
+ logger.warn(
2150
+ `the database role "${role}" is not the owner of ezlogs_audit_log, which has row-level security, so the agent reads 0 rows and no DB changes are sent. As the table owner, run: GRANT SELECT, DELETE ON ezlogs_audit_log TO "${role}"; CREATE POLICY ezlogs_reader ON ezlogs_audit_log TO "${role}" USING (true);`
2151
+ );
2152
+ return true;
2153
+ } catch {
2154
+ return false;
2155
+ }
2156
+ }
1780
2157
  async function detectTriggerTrackedTables(exec) {
1781
2158
  try {
1782
2159
  const result = await exec(
@@ -1807,12 +2184,97 @@ function emitAuditRows(rows) {
1807
2184
  emitOne(row);
1808
2185
  }
1809
2186
  }
1810
- async function flushAuditLog(exec) {
2187
+ async function flushAuditLog(exec, options = {}) {
1811
2188
  if (!exec) return;
1812
2189
  const correlationId = current();
1813
2190
  if (!correlationId) return;
1814
- const snapshot = currentAuditSnapshot();
1815
- const rows = await readAuditRows(exec, correlationId, snapshot);
2191
+ const rows = await readAuditRows(exec, correlationId, options.since ?? null);
2192
+ await loadTableMeta(exec, rows);
2193
+ emitFresh(rows);
2194
+ const now = Date.now();
2195
+ if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
2196
+ lastPruneAt = now;
2197
+ await pruneAuditLog(exec);
2198
+ }
2199
+ if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
2200
+ lastSweepAt = now;
2201
+ await sweepAuditLog(exec);
2202
+ }
2203
+ }
2204
+ var tableMeta = /* @__PURE__ */ new Map();
2205
+ var META_RETRY_MS = 6e4;
2206
+ var metaRetryAt = 0;
2207
+ async function loadTableMeta(exec, rows) {
2208
+ if (Date.now() < metaRetryAt) return;
2209
+ const tables = [
2210
+ ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
2211
+ ];
2212
+ if (tables.length === 0) return;
2213
+ const list = tables.join(",");
2214
+ try {
2215
+ const fkRows = extractRows(
2216
+ await exec(
2217
+ `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
2218
+ FROM pg_constraint c
2219
+ JOIN pg_class cl ON cl.oid = c.conrelid
2220
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
2221
+ JOIN pg_class rf ON rf.oid = c.confrelid
2222
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
2223
+ WHERE c.contype = 'f'
2224
+ AND n.nspname = 'public'
2225
+ AND array_length(c.conkey, 1) = 1
2226
+ AND cl.relname = ANY(string_to_array($1, ','))
2227
+ ORDER BY cl.relname, a.attnum`,
2228
+ [list]
2229
+ )
2230
+ );
2231
+ const tsRows = extractRows(
2232
+ await exec(
2233
+ `SELECT cl.relname AS table_name, a.attname AS column_name
2234
+ FROM pg_attribute a
2235
+ JOIN pg_class cl ON cl.oid = a.attrelid
2236
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
2237
+ WHERE n.nspname = 'public'
2238
+ AND cl.relname = ANY(string_to_array($1, ','))
2239
+ AND a.attnum > 0
2240
+ AND NOT a.attisdropped
2241
+ AND a.atttypid = 'timestamp'::regtype`,
2242
+ [list]
2243
+ )
2244
+ );
2245
+ const fks = /* @__PURE__ */ new Map();
2246
+ for (const raw of fkRows) {
2247
+ const r = raw ?? {};
2248
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
2249
+ continue;
2250
+ }
2251
+ fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
2252
+ }
2253
+ const timestamps = /* @__PURE__ */ new Map();
2254
+ for (const raw of tsRows) {
2255
+ const r = raw ?? {};
2256
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
2257
+ timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
2258
+ }
2259
+ for (const table of tables) {
2260
+ tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
2261
+ }
2262
+ } catch (err) {
2263
+ metaRetryAt = Date.now() + META_RETRY_MS;
2264
+ logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
2265
+ }
2266
+ }
2267
+ function relatedResourceIds(table, row) {
2268
+ const out = [];
2269
+ for (const fk of tableMeta.get(table)?.fks ?? []) {
2270
+ const value = row[fk.column];
2271
+ if (typeof value === "string" || typeof value === "number") {
2272
+ out.push({ resource_type: fk.refTable, resource_id: String(value) });
2273
+ }
2274
+ }
2275
+ return out;
2276
+ }
2277
+ function emitFresh(rows) {
1816
2278
  if (rows.length === 0) return;
1817
2279
  const emitted = currentEmittedAuditIds();
1818
2280
  if (emitted === null) {
@@ -1825,14 +2287,33 @@ async function flushAuditLog(exec) {
1825
2287
  emitted.add(row.id);
1826
2288
  fresh.push(row);
1827
2289
  }
1828
- if (fresh.length === 0) return;
1829
2290
  emitAuditRows(fresh);
1830
2291
  }
2292
+ function correlationForTx(txid) {
2293
+ if (!txid) return generate();
2294
+ let id = txCorrelation.get(txid);
2295
+ if (!id) {
2296
+ if (txCorrelation.size >= 1e3) txCorrelation.clear();
2297
+ id = generate();
2298
+ txCorrelation.set(txid, id);
2299
+ }
2300
+ return id;
2301
+ }
2302
+ function isPermissionDenied(err) {
2303
+ return err?.code === "42501";
2304
+ }
2305
+ function sortById(rows) {
2306
+ return rows.sort(
2307
+ (a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2308
+ );
2309
+ }
1831
2310
  function emitOne(row) {
1832
2311
  const op = mapOp(row.op);
1833
2312
  if (!op) return;
1834
- const oldRow = coerceJsonb(row.old_row);
1835
- const newRow = coerceJsonb(row.new_row);
2313
+ const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
2314
+ const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
2315
+ const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
2316
+ const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
1836
2317
  if (op === "create" && newRow) {
1837
2318
  emitDbEvent({
1838
2319
  modelClass: row.table_name,
@@ -1841,6 +2322,8 @@ function emitOne(row) {
1841
2322
  initialAttributes: newRow,
1842
2323
  modelInstance: newRow,
1843
2324
  displayName: null,
2325
+ timestamp: row.captured_at ?? null,
2326
+ relatedResourceIds: related,
1844
2327
  _fromTrigger: true
1845
2328
  });
1846
2329
  return;
@@ -1859,6 +2342,8 @@ function emitOne(row) {
1859
2342
  // user just told the system to call this row.
1860
2343
  modelInstance: newRow,
1861
2344
  displayName: null,
2345
+ timestamp: row.captured_at ?? null,
2346
+ relatedResourceIds: related,
1862
2347
  _fromTrigger: true
1863
2348
  });
1864
2349
  return;
@@ -1871,11 +2356,23 @@ function emitOne(row) {
1871
2356
  initialAttributes: oldRow,
1872
2357
  modelInstance: oldRow,
1873
2358
  displayName: null,
2359
+ timestamp: row.captured_at ?? null,
2360
+ relatedResourceIds: related,
1874
2361
  _fromTrigger: true
1875
2362
  });
1876
2363
  return;
1877
2364
  }
1878
2365
  }
2366
+ var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
2367
+ function withUtcTimestamps(row, naiveColumns) {
2368
+ if (!row) return row;
2369
+ const out = {};
2370
+ for (const [key, value] of Object.entries(row)) {
2371
+ const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
2372
+ out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
2373
+ }
2374
+ return out;
2375
+ }
1879
2376
  function mapOp(op) {
1880
2377
  if (op === "INSERT") return "create";
1881
2378
  if (op === "UPDATE") return "update";
@@ -1919,6 +2416,11 @@ function extractRows(result) {
1919
2416
  }
1920
2417
  return [];
1921
2418
  }
2419
+ function toDate(value) {
2420
+ if (value == null) return null;
2421
+ const d = value instanceof Date ? value : new Date(String(value));
2422
+ return Number.isNaN(d.getTime()) ? null : d;
2423
+ }
1922
2424
  function normalizeAuditRow(raw) {
1923
2425
  const r = raw ?? {};
1924
2426
  return {
@@ -1927,7 +2429,10 @@ function normalizeAuditRow(raw) {
1927
2429
  op: r.op,
1928
2430
  old_row: r.old_row ?? null,
1929
2431
  new_row: r.new_row ?? null,
1930
- resource_id: r.resource_id == null ? null : String(r.resource_id)
2432
+ resource_id: r.resource_id == null ? null : String(r.resource_id),
2433
+ correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
2434
+ txid: r.txid == null ? null : String(r.txid),
2435
+ captured_at: toDate(r.captured_at)
1931
2436
  };
1932
2437
  }
1933
2438
  function coerceJsonb(value) {
@@ -2001,6 +2506,7 @@ function classifyUserAgent(userAgent) {
2001
2506
 
2002
2507
  // src/http/capture.ts
2003
2508
  init_correlation();
2509
+ init_sanitize();
2004
2510
 
2005
2511
  // src/http/path-matcher.ts
2006
2512
  function pathMatches(path, pattern) {
@@ -2028,141 +2534,8 @@ function hasExcludedExtension(path, extensions) {
2028
2534
  // src/http/capture.ts
2029
2535
  init_configuration();
2030
2536
 
2031
- // src/http/sanitize.ts
2032
- var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
2033
- "password",
2034
- "passwd",
2035
- "pwd",
2036
- "token",
2037
- "access_token",
2038
- "refresh_token",
2039
- "api_token",
2040
- "auth_token",
2041
- "secret",
2042
- "api_secret",
2043
- "client_secret",
2044
- "api_key",
2045
- "apikey",
2046
- "private_key",
2047
- "privatekey",
2048
- "public_key",
2049
- "signing_key",
2050
- "secret_key",
2051
- "secretkey",
2052
- "credential",
2053
- "auth",
2054
- "authorization",
2055
- "encrypted",
2056
- "encrypted_data",
2057
- "ssn",
2058
- "social_security",
2059
- "credit_card",
2060
- "card_number",
2061
- "cvv",
2062
- "cvc",
2063
- // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
2064
- // (PR #45). Request bodies can carry the same key material as DB
2065
- // columns (a webhook POST containing a `signature` field, an HMAC
2066
- // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
2067
- "pem",
2068
- "cipher",
2069
- "nonce",
2070
- "salt",
2071
- "digest",
2072
- "signature",
2073
- "hmac"
2074
- ]);
2075
- var MAX_NESTING_DEPTH = 3;
2076
- var MAX_ARRAY_DISPLAY_SIZE = 5;
2077
- function sanitizeRequestParams(params, userPatterns = []) {
2078
- if (params === null || params === void 0) return null;
2079
- if (!isPlainObject2(params)) return null;
2080
- const obj = params;
2081
- const cleaned = {};
2082
- for (const key of Object.keys(obj)) {
2083
- if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
2084
- cleaned[key] = obj[key];
2085
- }
2086
- if (Object.keys(cleaned).length === 0) return null;
2087
- const out = {};
2088
- for (const key of Object.keys(cleaned)) {
2089
- out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
2090
- }
2091
- return out;
2092
- }
2093
- var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
2094
- // Rails leftovers — kept for parity since users may funnel through a
2095
- // proxy that adds them, e.g. via a NextAuth credentials provider that
2096
- // forwards CSRF tokens.
2097
- "controller",
2098
- "action",
2099
- "format",
2100
- "authenticity_token",
2101
- "_method",
2102
- // Next.js / common JS conventions
2103
- "csrfToken",
2104
- "_csrf",
2105
- "_next"
2106
- ]);
2107
- function sanitizeValue(key, value, depth, userPatterns) {
2108
- if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
2109
- if (isPlainObject2(value)) {
2110
- return sanitizeNestedObject(value, depth, userPatterns);
2111
- }
2112
- if (Array.isArray(value)) {
2113
- return sanitizeArrayValue(value, depth, userPatterns);
2114
- }
2115
- return value;
2116
- }
2117
- function sanitizeNestedObject(hash, depth, userPatterns) {
2118
- if (depth >= MAX_NESTING_DEPTH) return "[Object]";
2119
- if (Object.keys(hash).length === 0) return {};
2120
- const out = {};
2121
- for (const k of Object.keys(hash)) {
2122
- out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
2123
- }
2124
- return out;
2125
- }
2126
- function sanitizeArrayValue(array, depth, userPatterns) {
2127
- if (array.length === 0) return [];
2128
- const allPrimitive = array.every(isPrimitive);
2129
- if (allPrimitive) {
2130
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
2131
- const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
2132
- return `${JSON.stringify(preview)}... (${array.length} total)`;
2133
- }
2134
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
2135
- return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
2136
- }
2137
- return {
2138
- _truncated: true,
2139
- _count: array.length,
2140
- _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
2141
- };
2142
- }
2143
- function sanitizeArrayItem(item, depth, userPatterns) {
2144
- if (isPrimitive(item)) return item;
2145
- if (isPlainObject2(item)) {
2146
- return sanitizeNestedObject(item, depth + 1, userPatterns);
2147
- }
2148
- if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
2149
- return "[Object]";
2150
- }
2151
- function isSensitiveKey2(key, userPatterns) {
2152
- const lower = key.toLowerCase();
2153
- if (SENSITIVE_VARIABLE_PATTERNS.some((p) => lower.includes(p))) return true;
2154
- return userPatterns.some((p) => lower.includes(p.toLowerCase()));
2155
- }
2156
- function isPrimitive(value) {
2157
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
2158
- }
2159
- function isPlainObject2(value) {
2160
- if (value === null || typeof value !== "object") return false;
2161
- const proto = Object.getPrototypeOf(value);
2162
- return proto === Object.prototype || proto === null;
2163
- }
2164
-
2165
2537
  // src/http/source-data.ts
2538
+ init_sanitize();
2166
2539
  function buildHttpSourceData(input) {
2167
2540
  const { controller, action } = resolveControllerAction(input);
2168
2541
  const source = {
@@ -2319,7 +2692,7 @@ function compact(obj) {
2319
2692
  }
2320
2693
  return out;
2321
2694
  }
2322
- function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2695
+ function determineOutcome(statusCode, exception, graphqlResponseErrors, responseError = null) {
2323
2696
  if (exception) {
2324
2697
  return {
2325
2698
  outcome: "failure",
@@ -2327,7 +2700,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2327
2700
  };
2328
2701
  }
2329
2702
  if (statusCode !== null && statusCode >= 400) {
2330
- return { outcome: "failure", error_message: `HTTP ${statusCode}` };
2703
+ return { outcome: "failure", error_message: responseError ?? `HTTP ${statusCode}` };
2331
2704
  }
2332
2705
  if (graphqlResponseErrors) {
2333
2706
  return { outcome: "failure", error_message: graphqlResponseErrors };
@@ -2336,6 +2709,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2336
2709
  }
2337
2710
 
2338
2711
  // src/http/graphql.ts
2712
+ init_sanitize();
2339
2713
  var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2340
2714
  var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2341
2715
  function isGraphqlPath(path) {
@@ -2420,6 +2794,7 @@ function captureRoute(handler, context = {}) {
2420
2794
  }
2421
2795
  const snapshot = await snapshotRequest(request);
2422
2796
  if (snapshot === null) return Promise.resolve(runHandler(...args));
2797
+ snapshot.rawParams = mergeRouteParams(snapshot.rawParams, await readRouteParams(args[1]));
2423
2798
  const correlationId = resolveCorrelation(request.headers ?? null);
2424
2799
  return await runWithCorrelation(
2425
2800
  correlationId,
@@ -2430,15 +2805,23 @@ function captureRoute(handler, context = {}) {
2430
2805
  let response = null;
2431
2806
  let exception = null;
2432
2807
  let graphqlErrorMessage = null;
2808
+ let responseErrorMessage = null;
2433
2809
  try {
2434
2810
  response = await Promise.resolve(runHandler(...args));
2435
2811
  statusCode = response.status;
2436
2812
  if (snapshot.graphqlBody !== null && response.status === 200) {
2437
2813
  graphqlErrorMessage = await readGraphqlErrors(response);
2438
2814
  }
2815
+ responseErrorMessage = await readResponseErrorMessage(response);
2439
2816
  return response;
2440
2817
  } catch (e) {
2818
+ const controlStatus = nextControlFlowStatus(e);
2819
+ if (controlStatus !== null) {
2820
+ statusCode = controlStatus;
2821
+ throw e;
2822
+ }
2441
2823
  exception = e instanceof Error ? e : new Error(String(e));
2824
+ statusCode = 500;
2442
2825
  throw e;
2443
2826
  } finally {
2444
2827
  await maybeExtractSupabaseActor();
@@ -2448,6 +2831,7 @@ function captureRoute(handler, context = {}) {
2448
2831
  statusCode,
2449
2832
  exception,
2450
2833
  graphqlErrorMessage,
2834
+ responseErrorMessage,
2451
2835
  durationMs: Date.now() - startMs,
2452
2836
  startedAt: new Date(startMs)
2453
2837
  });
@@ -2671,7 +3055,10 @@ function captureServerAction(action, actionName) {
2671
3055
  const failure = classifyServerActionResult(result);
2672
3056
  await emitServerActionEvent({
2673
3057
  actionName,
2674
- statusCode: failure ? 500 : 200,
3058
+ // A returned failure (`{ success: false, error }`) is a
3059
+ // handled refusal, not a crash: no HTTP status is
3060
+ // invented; outcome + error_message carry it.
3061
+ statusCode: failure ? null : 200,
2675
3062
  exception: failure ? new Error(failure.errorMessage) : null,
2676
3063
  durationMs: Date.now() - startMs,
2677
3064
  startedAt,
@@ -2681,9 +3068,12 @@ function captureServerAction(action, actionName) {
2681
3068
  } catch (e) {
2682
3069
  if (isNextControlFlowError(e)) {
2683
3070
  await maybeExtractSupabaseActor();
3071
+ const controlStatus = nextControlFlowStatus(e) ?? 200;
2684
3072
  await emitServerActionEvent({
2685
3073
  actionName,
2686
- statusCode: 200,
3074
+ // redirect() is a success; notFound() / forbidden()
3075
+ // keep their 4xx.
3076
+ statusCode: controlStatus >= 400 ? controlStatus : 200,
2687
3077
  exception: null,
2688
3078
  durationMs: Date.now() - startMs,
2689
3079
  startedAt,
@@ -2865,10 +3255,23 @@ function conformErrorMessage(result) {
2865
3255
  return "Form submission failed";
2866
3256
  }
2867
3257
  function isNextControlFlowError(error) {
2868
- if (!error || typeof error !== "object") return false;
3258
+ return nextControlFlowStatus(error) !== null;
3259
+ }
3260
+ function nextControlFlowStatus(error) {
3261
+ if (!error || typeof error !== "object") return null;
2869
3262
  const digest = error.digest;
2870
- if (typeof digest !== "string") return false;
2871
- return digest.startsWith("NEXT_REDIRECT") || digest.startsWith("NEXT_NOT_FOUND");
3263
+ if (typeof digest !== "string") return null;
3264
+ const parts = digest.split(";");
3265
+ if (parts[0] === "NEXT_REDIRECT") {
3266
+ const status = Number(parts[3]);
3267
+ return status >= 300 && status < 400 ? status : 307;
3268
+ }
3269
+ if (parts[0] === "NEXT_NOT_FOUND") return 404;
3270
+ if (parts[0] === "NEXT_HTTP_ERROR_FALLBACK") {
3271
+ const status = Number(parts[1]);
3272
+ return status >= 400 && status < 500 ? status : 404;
3273
+ }
3274
+ return null;
2872
3275
  }
2873
3276
  async function emitServerActionEvent(input) {
2874
3277
  try {
@@ -2877,7 +3280,7 @@ async function emitServerActionEvent(input) {
2877
3280
  const nextUrl = await readNextHeader("next-url");
2878
3281
  const userAgent = await readNextHeader("user-agent");
2879
3282
  const fromPage = referer ?? nextUrl ?? null;
2880
- const argParams = extractServerActionArgs(input.args);
3283
+ const argParams = extractServerActionArgs(input.args, input.actionName);
2881
3284
  const requestParams = argParams !== null || fromPage !== null ? { ...argParams ?? {}, ...fromPage !== null ? { from_page: fromPage } : {} } : null;
2882
3285
  const syntheticUrl = new URL(
2883
3286
  `http://localhost/__server-action/${encodeURIComponent(input.actionName)}`
@@ -2890,7 +3293,7 @@ async function emitServerActionEvent(input) {
2890
3293
  rawParams: requestParams,
2891
3294
  serverActionName: input.actionName,
2892
3295
  userAgent,
2893
- remoteIp: null,
3296
+ remoteIp: extractRemoteIp(await readNextHeadersAsAdapter()),
2894
3297
  contentType: null,
2895
3298
  excludedVariableKeys: configuration().excludedGraphqlVariableKeys
2896
3299
  });
@@ -2915,7 +3318,7 @@ async function emitServerActionEvent(input) {
2915
3318
  logger.error(`server-action capture emit failed: ${describeError7(error)}`);
2916
3319
  }
2917
3320
  }
2918
- function extractServerActionArgs(args) {
3321
+ function extractServerActionArgs(args, actionName) {
2919
3322
  if (!args || args.length === 0) return null;
2920
3323
  const payloadIndex = findPayloadIndex(args);
2921
3324
  if (payloadIndex !== -1) {
@@ -2928,14 +3331,86 @@ function extractServerActionArgs(args) {
2928
3331
  }
2929
3332
  return Object.keys(out2).length === 0 ? null : out2;
2930
3333
  }
3334
+ const words = actionWords(actionName);
3335
+ const flags = {
3336
+ secretAction: words.some((w) => SECRET_ACTION_WORDS.has(w)),
3337
+ paymentAction: words.some((w) => PAYMENT_ACTION_WORDS.has(w))
3338
+ };
2931
3339
  const out = {};
2932
3340
  args.forEach((a, i) => {
2933
3341
  if (isInsignificantArg(a)) return;
2934
- const v = serializeArgValue(a);
3342
+ const v = maskPositional(serializeArgValue(a), flags);
2935
3343
  if (v !== void 0) out[`arg${i}`] = v;
2936
3344
  });
2937
3345
  return Object.keys(out).length === 0 ? null : out;
2938
3346
  }
3347
+ var INT_OR_UUID = /^(?:\d{1,20}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
3348
+ var CUID_V1 = /^c[a-z0-9]{24}$/;
3349
+ var CUID2 = /^[a-z][a-z0-9]{23}$/;
3350
+ var ULID = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
3351
+ var NANOID_21 = /^[A-Za-z0-9_-]{21}$/;
3352
+ function digitCount(s) {
3353
+ return s.replace(/\D/g, "").length;
3354
+ }
3355
+ function isIdShaped(s) {
3356
+ if (INT_OR_UUID.test(s) || ULID.test(s)) return true;
3357
+ if (CUID_V1.test(s) || CUID2.test(s)) return digitCount(s) >= 2;
3358
+ if (NANOID_21.test(s)) {
3359
+ return digitCount(s) >= 2 && /[a-z]/.test(s) && /[A-Z]/.test(s);
3360
+ }
3361
+ return false;
3362
+ }
3363
+ var SECRET_ACTION_WORDS = /* @__PURE__ */ new Set([
3364
+ "pin",
3365
+ "otp",
3366
+ "code",
3367
+ "verify",
3368
+ "mfa",
3369
+ "2fa",
3370
+ "cvv",
3371
+ "cvc",
3372
+ "card",
3373
+ "password",
3374
+ "passwd",
3375
+ "secret",
3376
+ "token",
3377
+ "sign",
3378
+ "signin",
3379
+ "login",
3380
+ "reset",
3381
+ "credential",
3382
+ "credentials",
3383
+ "unlock"
3384
+ ]);
3385
+ var PAYMENT_ACTION_WORDS = /* @__PURE__ */ new Set([
3386
+ "card",
3387
+ "pay",
3388
+ "payment",
3389
+ "charge",
3390
+ "checkout",
3391
+ "billing",
3392
+ "cvv",
3393
+ "cvc"
3394
+ ]);
3395
+ function actionWords(name) {
3396
+ return name.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([a-zA-Z])(\d)/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
3397
+ }
3398
+ function looksLikeCardNumber(digits, paymentAction) {
3399
+ if (digits.length < 13 || digits.length > 19 || !passesLuhn(digits)) return false;
3400
+ return paymentAction || digits.length === 15 || digits.length === 16;
3401
+ }
3402
+ function maskPositional(value, flags) {
3403
+ if (Array.isArray(value)) return value.map((v) => maskPositional(v, flags));
3404
+ const digits = typeof value === "number" && Number.isInteger(value) && value >= 0 ? String(value) : typeof value === "string" && /^\d+$/.test(value) ? value : null;
3405
+ if (digits !== null) {
3406
+ if (looksLikeCardNumber(digits, flags.paymentAction)) return "[FILTERED]";
3407
+ if (flags.secretAction && digits.length >= 4 && digits.length <= 8) return "[FILTERED]";
3408
+ }
3409
+ if (typeof value === "string") {
3410
+ return isIdShaped(value) ? value : "[FILTERED]";
3411
+ }
3412
+ return value;
3413
+ }
2939
3414
  function findPayloadIndex(args) {
2940
3415
  for (let i = args.length - 1; i >= 0; i -= 1) {
2941
3416
  if (typeof FormData !== "undefined" && args[i] instanceof FormData) {
@@ -3275,7 +3750,8 @@ async function emitEvent(input) {
3275
3750
  const { outcome, error_message } = determineOutcome(
3276
3751
  input.statusCode,
3277
3752
  input.exception,
3278
- input.graphqlErrorMessage
3753
+ input.graphqlErrorMessage,
3754
+ input.responseErrorMessage ?? null
3279
3755
  );
3280
3756
  const contextValue = buildContext2();
3281
3757
  const event = build({
@@ -3306,28 +3782,11 @@ async function flushTriggerAuditLog() {
3306
3782
  if (!reader) return;
3307
3783
  await flushAuditLog(reader);
3308
3784
  }
3309
- async function takeTriggerAuditSnapshotIfEnabled() {
3310
- const config = configuration();
3311
- if (!config.databaseSnapshotMode) return;
3312
- if (!config.databaseReader) return;
3313
- await takeAuditSnapshot(config.databaseReader);
3314
- }
3315
3785
  function runWithActorAndAuditScope(callback) {
3316
- const config = configuration();
3317
- const hasReader = config.databaseReader != null;
3318
- const snapshotEnabled = config.databaseSnapshotMode;
3319
- if (!hasReader) {
3786
+ if (configuration().databaseReader == null) {
3320
3787
  return runWithActorScope(callback);
3321
3788
  }
3322
- return runWithActorScope(
3323
- () => runWithEmittedAuditIdsScope(() => {
3324
- if (!snapshotEnabled) return callback();
3325
- return runWithAuditSnapshotScope(async () => {
3326
- await takeTriggerAuditSnapshotIfEnabled();
3327
- return callback();
3328
- });
3329
- })
3330
- );
3789
+ return runWithActorScope(() => runWithEmittedAuditIdsScope(callback));
3331
3790
  }
3332
3791
  function isExcludedPath(path, method) {
3333
3792
  const config = configuration();
@@ -3364,6 +3823,40 @@ function safeJsonParse(text) {
3364
3823
  return null;
3365
3824
  }
3366
3825
  }
3826
+ async function readRouteParams(routeContext) {
3827
+ try {
3828
+ const params = await routeContext?.params;
3829
+ if (!params || typeof params !== "object" || Array.isArray(params)) return null;
3830
+ return Object.keys(params).length > 0 ? params : null;
3831
+ } catch {
3832
+ return null;
3833
+ }
3834
+ }
3835
+ function mergeRouteParams(rawParams, routeParams) {
3836
+ if (!routeParams) return rawParams;
3837
+ if (rawParams === null || rawParams === void 0) return { ...routeParams };
3838
+ if (typeof rawParams !== "object" || Array.isArray(rawParams)) return rawParams;
3839
+ return { ...routeParams, ...rawParams };
3840
+ }
3841
+ var MAX_ERROR_BODY_LENGTH = 16384;
3842
+ async function readResponseErrorMessage(response) {
3843
+ try {
3844
+ if (response.status < 400) return null;
3845
+ if (!(response.headers.get("content-type") ?? "").includes("json")) return null;
3846
+ if (Number(response.headers.get("content-length") ?? 0) > MAX_ERROR_BODY_LENGTH) return null;
3847
+ const text = await response.clone().text();
3848
+ if (!text || text.length > MAX_ERROR_BODY_LENGTH) return null;
3849
+ const body = safeJsonParse(text);
3850
+ if (!body || typeof body !== "object") return null;
3851
+ const nested = body.error;
3852
+ const raw = [body.error, body.message, nested?.message].find(
3853
+ (v) => typeof v === "string" && v.trim().length > 0
3854
+ );
3855
+ return raw ? truncate(scrubSecretsInText(raw.trim(), { emails: true })) : null;
3856
+ } catch {
3857
+ return null;
3858
+ }
3859
+ }
3367
3860
  async function readGraphqlErrors(response) {
3368
3861
  try {
3369
3862
  const cloned = response.clone();
@@ -3449,7 +3942,7 @@ var ezlogs = {
3449
3942
  options.patchDatabaseClient
3450
3943
  );
3451
3944
  }
3452
- applyDatabaseReaderDefaults(options);
3945
+ applyDatabaseReaderDefaults();
3453
3946
  installBeforeExitHook();
3454
3947
  initialized = true;
3455
3948
  },
@@ -3500,26 +3993,49 @@ async function autoWireTriggerPathFromDatabaseUrl(options) {
3500
3993
  "return import(s)"
3501
3994
  );
3502
3995
  pg = await dynImport("pg");
3503
- } catch (err) {
3996
+ } catch {
3997
+ logger.warn(
3998
+ "a Postgres URL is configured but the `pg` package is not installed, so trigger-based DB capture is off. Run `npm i pg` and `npx ezlogs-nextjs install-triggers`, or use a per-ORM adapter (docs/database.md)."
3999
+ );
3504
4000
  return;
3505
4001
  }
3506
4002
  const pool = new pg.Pool({
3507
4003
  connectionString: options.databaseUrl,
3508
4004
  max: 4
3509
4005
  });
4006
+ const reader = (sql, params) => pool.query(sql, params);
4007
+ if (await auditLogInstalled(reader) === false) {
4008
+ warnAuditLogMissing();
4009
+ void pool.end?.().catch(() => {
4010
+ });
4011
+ return;
4012
+ }
3510
4013
  if (config.databaseReader === null) {
3511
- config.databaseReader = (sql, params) => pool.query(sql, params);
4014
+ config.databaseReader = reader;
3512
4015
  }
3513
4016
  patchPgClient(pg);
3514
- applyDatabaseReaderDefaults(options);
4017
+ void checkAuditLogAccess(reader);
4018
+ runTriggerTrackedTablesDetection();
3515
4019
  }
3516
- function applyDatabaseReaderDefaults(options) {
4020
+ function applyDatabaseReaderDefaults() {
3517
4021
  const config = configuration();
3518
- if (!config.databaseReader) return;
3519
- if (options.databaseSnapshotMode === void 0) {
3520
- config.databaseSnapshotMode = true;
3521
- }
3522
- runTriggerTrackedTablesDetection();
4022
+ const reader = config.databaseReader;
4023
+ if (!reader) return;
4024
+ auditLogInstalled(reader).then((installed) => {
4025
+ if (installed === false && config.databaseReader === reader) {
4026
+ config.databaseReader = null;
4027
+ warnAuditLogMissing();
4028
+ return;
4029
+ }
4030
+ if (installed === true) void checkAuditLogAccess(reader);
4031
+ runTriggerTrackedTablesDetection();
4032
+ }).catch(() => {
4033
+ });
4034
+ }
4035
+ function warnAuditLogMissing() {
4036
+ logger.warn(
4037
+ "table `ezlogs_audit_log` was not found, so trigger-based DB capture is off. Run `npx ezlogs-nextjs install-triggers` against this database and restart."
4038
+ );
3523
4039
  }
3524
4040
  function runTriggerTrackedTablesDetection() {
3525
4041
  const config = configuration();