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