ezlogs-nextjs 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,168 @@ 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 sanitizeValue(key, value, depth, userPatterns) {
752
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
753
+ if (isPlainObject2(value)) {
754
+ return sanitizeNestedObject(value, depth, userPatterns);
755
+ }
756
+ if (Array.isArray(value)) {
757
+ return sanitizeArrayValue(value, depth, userPatterns);
758
+ }
759
+ return value;
760
+ }
761
+ function sanitizeNestedObject(hash, depth, userPatterns) {
762
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
763
+ if (Object.keys(hash).length === 0) return {};
764
+ const out = {};
765
+ for (const k of Object.keys(hash)) {
766
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
767
+ }
768
+ return out;
769
+ }
770
+ function sanitizeArrayValue(array, depth, userPatterns) {
771
+ if (array.length === 0) return [];
772
+ const allPrimitive = array.every(isPrimitive);
773
+ if (allPrimitive) {
774
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
775
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
776
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
777
+ }
778
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
779
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
780
+ }
781
+ return {
782
+ _truncated: true,
783
+ _count: array.length,
784
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
785
+ };
786
+ }
787
+ function sanitizeArrayItem(item, depth, userPatterns) {
788
+ if (isPrimitive(item)) return item;
789
+ if (isPlainObject2(item)) {
790
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
791
+ }
792
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
793
+ return "[Object]";
794
+ }
795
+ function isSensitiveKey2(key, userPatterns) {
796
+ if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
797
+ const lower = key.toLowerCase();
798
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
799
+ }
800
+ function isPrimitive(value) {
801
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
802
+ }
803
+ function isPlainObject2(value) {
804
+ if (value === null || typeof value !== "object") return false;
805
+ const proto = Object.getPrototypeOf(value);
806
+ return proto === Object.prototype || proto === null;
807
+ }
808
+ var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS;
809
+ var init_sanitize = __esm({
810
+ "src/http/sanitize.ts"() {
811
+ SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
812
+ "password",
813
+ "passwd",
814
+ "pwd",
815
+ "token",
816
+ "access_token",
817
+ "refresh_token",
818
+ "api_token",
819
+ "auth_token",
820
+ "secret",
821
+ "api_secret",
822
+ "client_secret",
823
+ "api_key",
824
+ "apikey",
825
+ "private_key",
826
+ "privatekey",
827
+ "public_key",
828
+ "signing_key",
829
+ "secret_key",
830
+ "secretkey",
831
+ "credential",
832
+ "auth",
833
+ "authorization",
834
+ "encrypted",
835
+ "encrypted_data",
836
+ "ssn",
837
+ "social_security",
838
+ "credit_card",
839
+ "card_number",
840
+ "cvv",
841
+ "cvc",
842
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
843
+ // (PR #45). Request bodies can carry the same key material as DB
844
+ // columns (a webhook POST containing a `signature` field, an HMAC
845
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
846
+ "pem",
847
+ "cipher",
848
+ "nonce",
849
+ "salt",
850
+ "digest",
851
+ "signature",
852
+ "hmac",
853
+ // 0.2.0 additions (not yet in the Rails gem's list).
854
+ "passcode",
855
+ "cardnumber"
856
+ ]);
857
+ SENSITIVE_WORD_PATTERNS = Object.freeze([
858
+ "pin",
859
+ "otp",
860
+ "totp",
861
+ "iban",
862
+ "mfa",
863
+ "passphrase"
864
+ ]);
865
+ MAX_NESTING_DEPTH = 3;
866
+ MAX_ARRAY_DISPLAY_SIZE = 5;
867
+ FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
868
+ // Rails leftovers — kept for parity since users may funnel through a
869
+ // proxy that adds them, e.g. via a NextAuth credentials provider that
870
+ // forwards CSRF tokens.
871
+ "controller",
872
+ "action",
873
+ "format",
874
+ "authenticity_token",
875
+ "_method",
876
+ // Next.js / common JS conventions
877
+ "csrfToken",
878
+ "_csrf",
879
+ "_next"
880
+ ]);
881
+ }
882
+ });
883
+
717
884
  // src/db/shared.ts
718
885
  function emitDbEvent(input) {
719
886
  try {
@@ -740,7 +907,8 @@ function emitDbEvent(input) {
740
907
  correlation_id: current(),
741
908
  resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
742
909
  context,
743
- duration_ms: null
910
+ duration_ms: null,
911
+ timestamp: input.timestamp ?? null
744
912
  });
745
913
  pushEvent(event);
746
914
  } catch (error) {
@@ -798,8 +966,7 @@ function isMeaningfulAttribute(name) {
798
966
  return true;
799
967
  }
800
968
  function isDbSensitive(name) {
801
- const lower = name.toLowerCase();
802
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
969
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
803
970
  }
804
971
  function isScalar(value) {
805
972
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
@@ -879,6 +1046,7 @@ var init_shared = __esm({
879
1046
  init_buffer();
880
1047
  init_correlation();
881
1048
  init_actor();
1049
+ init_sanitize();
882
1050
  IGNORED_ATTRIBUTES = Object.freeze([
883
1051
  "id",
884
1052
  "createdAt",
@@ -909,7 +1077,19 @@ var init_shared = __esm({
909
1077
  "salt",
910
1078
  "digest",
911
1079
  "signature",
912
- "hmac"
1080
+ "hmac",
1081
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
1082
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
1083
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
1084
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
1085
+ "credential",
1086
+ "passwd",
1087
+ "passcode",
1088
+ "apikey",
1089
+ "card_number",
1090
+ "cardnumber",
1091
+ "cvv",
1092
+ "cvc"
913
1093
  ]);
914
1094
  }
915
1095
  });
@@ -1709,51 +1889,59 @@ function leadingVerb(text) {
1709
1889
  init_logger();
1710
1890
  init_shared();
1711
1891
  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
- }
1892
+ init_actor();
1727
1893
 
1728
1894
  // src/triggers/emit-dedup.ts
1729
1895
  init_edge_fallback();
1730
- var storage4 = createScopedStorage(
1896
+ var storage3 = createScopedStorage(
1731
1897
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1732
1898
  );
1733
1899
  function currentEmittedAuditIds() {
1734
- return storage4.read();
1900
+ return storage3.read();
1735
1901
  }
1736
1902
  function runWithEmittedAuditIdsScope(callback) {
1737
- const existing = storage4.read();
1903
+ const existing = storage3.read();
1738
1904
  if (existing !== null) return callback();
1739
- return storage4.run(/* @__PURE__ */ new Set(), callback);
1905
+ return storage3.run(/* @__PURE__ */ new Set(), callback);
1740
1906
  }
1741
1907
 
1742
1908
  // src/triggers/reader.ts
1743
- async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1909
+ var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
1910
+ var ORPHAN_AGE = "5 minutes";
1911
+ var PRUNE_AGE = "24 hours";
1912
+ var SWEEP_BATCH = 100;
1913
+ var PRUNE_BATCH = 2e3;
1914
+ var SWEEP_INTERVAL_MS = 1e4;
1915
+ var PRUNE_INTERVAL_MS = 10 * 6e4;
1916
+ var lastSweepAt = 0;
1917
+ var lastPruneAt = 0;
1918
+ var deleteDenied = false;
1919
+ var txCorrelation = /* @__PURE__ */ new Map();
1920
+ async function readAuditRows(exec, correlationId) {
1744
1921
  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));
1922
+ if (!deleteDenied) {
1923
+ try {
1924
+ return sortById(
1925
+ extractRows(
1926
+ await exec(
1927
+ `DELETE FROM ezlogs_audit_log WHERE correlation_id = $1 RETURNING ${COLUMNS}`,
1928
+ [correlationId]
1929
+ )
1930
+ ).map(normalizeAuditRow)
1931
+ );
1932
+ } catch (err) {
1933
+ if (!isPermissionDenied(err)) throw err;
1934
+ deleteDenied = true;
1935
+ logger.warn(
1936
+ "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'`."
1937
+ );
1938
+ }
1939
+ }
1940
+ const result = await exec(
1941
+ `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE correlation_id = $1 ORDER BY id ASC`,
1942
+ [correlationId]
1943
+ );
1944
+ return extractRows(result).map(normalizeAuditRow);
1757
1945
  } catch (err) {
1758
1946
  logger.debug(
1759
1947
  `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
@@ -1761,22 +1949,100 @@ async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1761
1949
  return [];
1762
1950
  }
1763
1951
  }
1764
- async function takeAuditSnapshot(exec) {
1952
+ async function sweepAuditLog(exec) {
1953
+ if (deleteDenied) return 0;
1765
1954
  try {
1766
- const result = await exec(
1767
- `SELECT COALESCE(MAX(id), 0) AS max_id FROM ezlogs_audit_log`,
1955
+ const rows = sortById(
1956
+ extractRows(
1957
+ await exec(
1958
+ `DELETE FROM ezlogs_audit_log
1959
+ WHERE id IN (
1960
+ SELECT id FROM ezlogs_audit_log
1961
+ WHERE (correlation_id IS NULL
1962
+ OR captured_at < now() - interval '${ORPHAN_AGE}')
1963
+ -- Never resurface history: past the retention cap a
1964
+ -- row is pruned, not sent as new activity.
1965
+ AND captured_at > now() - interval '${PRUNE_AGE}'
1966
+ ORDER BY id
1967
+ LIMIT ${SWEEP_BATCH}
1968
+ FOR UPDATE SKIP LOCKED)
1969
+ RETURNING ${COLUMNS}`,
1970
+ []
1971
+ )
1972
+ ).map(normalizeAuditRow)
1973
+ );
1974
+ for (const row of rows) {
1975
+ const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1976
+ runWithCorrelation(
1977
+ correlationId,
1978
+ () => runWithActorScope(() => emitOne(row))
1979
+ );
1980
+ }
1981
+ return rows.length;
1982
+ } catch (err) {
1983
+ logger.debug(
1984
+ `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1985
+ );
1986
+ return 0;
1987
+ }
1988
+ }
1989
+ async function pruneAuditLog(exec) {
1990
+ if (deleteDenied) return;
1991
+ try {
1992
+ await exec(
1993
+ `DELETE FROM ezlogs_audit_log
1994
+ WHERE id IN (
1995
+ SELECT id FROM ezlogs_audit_log
1996
+ WHERE captured_at < now() - interval '${PRUNE_AGE}'
1997
+ LIMIT ${PRUNE_BATCH})`,
1768
1998
  []
1769
1999
  );
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
2000
  } catch (err) {
1777
2001
  logger.debug(
1778
- `takeAuditSnapshot failed: ${err instanceof Error ? err.message : String(err)}`
2002
+ `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2003
+ );
2004
+ }
2005
+ }
2006
+ async function auditLogInstalled(exec) {
2007
+ try {
2008
+ const rows = extractRows(
2009
+ await exec(
2010
+ `SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
2011
+ []
2012
+ )
2013
+ );
2014
+ const installed = rows[0]?.installed;
2015
+ return typeof installed === "boolean" ? installed : null;
2016
+ } catch {
2017
+ return null;
2018
+ }
2019
+ }
2020
+ async function checkAuditLogAccess(exec) {
2021
+ try {
2022
+ const rows = extractRows(
2023
+ await exec(
2024
+ `SELECT current_user AS role
2025
+ FROM pg_class c
2026
+ JOIN pg_roles r ON r.rolname = current_user
2027
+ WHERE c.oid = 'public.ezlogs_audit_log'::regclass
2028
+ AND c.relrowsecurity
2029
+ AND NOT r.rolsuper
2030
+ AND NOT r.rolbypassrls
2031
+ AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
2032
+ AND NOT EXISTS (SELECT 1 FROM pg_policies p
2033
+ WHERE p.schemaname = 'public'
2034
+ AND p.tablename = 'ezlogs_audit_log')`,
2035
+ []
2036
+ )
2037
+ );
2038
+ const role = rows[0]?.role;
2039
+ if (typeof role !== "string") return false;
2040
+ logger.warn(
2041
+ `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
2042
  );
2043
+ return true;
2044
+ } catch {
2045
+ return false;
1780
2046
  }
1781
2047
  }
1782
2048
  async function detectTriggerTrackedTables(exec) {
@@ -1813,8 +2079,19 @@ async function flushAuditLog(exec) {
1813
2079
  if (!exec) return;
1814
2080
  const correlationId = current();
1815
2081
  if (!correlationId) return;
1816
- const snapshot = currentAuditSnapshot();
1817
- const rows = await readAuditRows(exec, correlationId, snapshot);
2082
+ const rows = await readAuditRows(exec, correlationId);
2083
+ emitFresh(rows);
2084
+ const now = Date.now();
2085
+ if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
2086
+ lastPruneAt = now;
2087
+ await pruneAuditLog(exec);
2088
+ }
2089
+ if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
2090
+ lastSweepAt = now;
2091
+ await sweepAuditLog(exec);
2092
+ }
2093
+ }
2094
+ function emitFresh(rows) {
1818
2095
  if (rows.length === 0) return;
1819
2096
  const emitted = currentEmittedAuditIds();
1820
2097
  if (emitted === null) {
@@ -1827,9 +2104,26 @@ async function flushAuditLog(exec) {
1827
2104
  emitted.add(row.id);
1828
2105
  fresh.push(row);
1829
2106
  }
1830
- if (fresh.length === 0) return;
1831
2107
  emitAuditRows(fresh);
1832
2108
  }
2109
+ function correlationForTx(txid) {
2110
+ if (!txid) return generate();
2111
+ let id = txCorrelation.get(txid);
2112
+ if (!id) {
2113
+ if (txCorrelation.size >= 1e3) txCorrelation.clear();
2114
+ id = generate();
2115
+ txCorrelation.set(txid, id);
2116
+ }
2117
+ return id;
2118
+ }
2119
+ function isPermissionDenied(err) {
2120
+ return err?.code === "42501";
2121
+ }
2122
+ function sortById(rows) {
2123
+ return rows.sort(
2124
+ (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
2125
+ );
2126
+ }
1833
2127
  function emitOne(row) {
1834
2128
  const op = mapOp(row.op);
1835
2129
  if (!op) return;
@@ -1843,6 +2137,7 @@ function emitOne(row) {
1843
2137
  initialAttributes: newRow,
1844
2138
  modelInstance: newRow,
1845
2139
  displayName: null,
2140
+ timestamp: row.captured_at ?? null,
1846
2141
  _fromTrigger: true
1847
2142
  });
1848
2143
  return;
@@ -1861,6 +2156,7 @@ function emitOne(row) {
1861
2156
  // user just told the system to call this row.
1862
2157
  modelInstance: newRow,
1863
2158
  displayName: null,
2159
+ timestamp: row.captured_at ?? null,
1864
2160
  _fromTrigger: true
1865
2161
  });
1866
2162
  return;
@@ -1873,6 +2169,7 @@ function emitOne(row) {
1873
2169
  initialAttributes: oldRow,
1874
2170
  modelInstance: oldRow,
1875
2171
  displayName: null,
2172
+ timestamp: row.captured_at ?? null,
1876
2173
  _fromTrigger: true
1877
2174
  });
1878
2175
  return;
@@ -1921,6 +2218,11 @@ function extractRows(result) {
1921
2218
  }
1922
2219
  return [];
1923
2220
  }
2221
+ function toDate(value) {
2222
+ if (value == null) return null;
2223
+ const d = value instanceof Date ? value : new Date(String(value));
2224
+ return Number.isNaN(d.getTime()) ? null : d;
2225
+ }
1924
2226
  function normalizeAuditRow(raw) {
1925
2227
  const r = raw ?? {};
1926
2228
  return {
@@ -1929,7 +2231,10 @@ function normalizeAuditRow(raw) {
1929
2231
  op: r.op,
1930
2232
  old_row: r.old_row ?? null,
1931
2233
  new_row: r.new_row ?? null,
1932
- resource_id: r.resource_id == null ? null : String(r.resource_id)
2234
+ resource_id: r.resource_id == null ? null : String(r.resource_id),
2235
+ correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
2236
+ txid: r.txid == null ? null : String(r.txid),
2237
+ captured_at: toDate(r.captured_at)
1933
2238
  };
1934
2239
  }
1935
2240
  function coerceJsonb(value) {
@@ -2030,141 +2335,8 @@ function hasExcludedExtension(path, extensions) {
2030
2335
  // src/http/capture.ts
2031
2336
  init_configuration();
2032
2337
 
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
2338
  // src/http/source-data.ts
2339
+ init_sanitize();
2168
2340
  function buildHttpSourceData(input) {
2169
2341
  const { controller, action } = resolveControllerAction(input);
2170
2342
  const source = {
@@ -2338,6 +2510,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2338
2510
  }
2339
2511
 
2340
2512
  // src/http/graphql.ts
2513
+ init_sanitize();
2341
2514
  var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2342
2515
  var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2343
2516
  function isGraphqlPath(path) {
@@ -2879,7 +3052,7 @@ async function emitServerActionEvent(input) {
2879
3052
  const nextUrl = await readNextHeader("next-url");
2880
3053
  const userAgent = await readNextHeader("user-agent");
2881
3054
  const fromPage = referer ?? nextUrl ?? null;
2882
- const argParams = extractServerActionArgs(input.args);
3055
+ const argParams = extractServerActionArgs(input.args, input.actionName);
2883
3056
  const requestParams = argParams !== null || fromPage !== null ? { ...argParams ?? {}, ...fromPage !== null ? { from_page: fromPage } : {} } : null;
2884
3057
  const syntheticUrl = new URL(
2885
3058
  `http://localhost/__server-action/${encodeURIComponent(input.actionName)}`
@@ -2917,7 +3090,7 @@ async function emitServerActionEvent(input) {
2917
3090
  logger.error(`server-action capture emit failed: ${describeError7(error)}`);
2918
3091
  }
2919
3092
  }
2920
- function extractServerActionArgs(args) {
3093
+ function extractServerActionArgs(args, actionName) {
2921
3094
  if (!args || args.length === 0) return null;
2922
3095
  const payloadIndex = findPayloadIndex(args);
2923
3096
  if (payloadIndex !== -1) {
@@ -2930,14 +3103,98 @@ function extractServerActionArgs(args) {
2930
3103
  }
2931
3104
  return Object.keys(out2).length === 0 ? null : out2;
2932
3105
  }
3106
+ const words = actionWords(actionName);
3107
+ const flags = {
3108
+ secretAction: words.some((w) => SECRET_ACTION_WORDS.has(w)),
3109
+ paymentAction: words.some((w) => PAYMENT_ACTION_WORDS.has(w))
3110
+ };
2933
3111
  const out = {};
2934
3112
  args.forEach((a, i) => {
2935
3113
  if (isInsignificantArg(a)) return;
2936
- const v = serializeArgValue(a);
3114
+ const v = maskPositional(serializeArgValue(a), flags);
2937
3115
  if (v !== void 0) out[`arg${i}`] = v;
2938
3116
  });
2939
3117
  return Object.keys(out).length === 0 ? null : out;
2940
3118
  }
3119
+ 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;
3120
+ var CUID_V1 = /^c[a-z0-9]{24}$/;
3121
+ var CUID2 = /^[a-z][a-z0-9]{23}$/;
3122
+ var ULID = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
3123
+ var NANOID_21 = /^[A-Za-z0-9_-]{21}$/;
3124
+ function digitCount(s) {
3125
+ return s.replace(/\D/g, "").length;
3126
+ }
3127
+ function isIdShaped(s) {
3128
+ if (INT_OR_UUID.test(s) || ULID.test(s)) return true;
3129
+ if (CUID_V1.test(s) || CUID2.test(s)) return digitCount(s) >= 2;
3130
+ if (NANOID_21.test(s)) {
3131
+ return digitCount(s) >= 2 && /[a-z]/.test(s) && /[A-Z]/.test(s);
3132
+ }
3133
+ return false;
3134
+ }
3135
+ var SECRET_ACTION_WORDS = /* @__PURE__ */ new Set([
3136
+ "pin",
3137
+ "otp",
3138
+ "code",
3139
+ "verify",
3140
+ "mfa",
3141
+ "2fa",
3142
+ "cvv",
3143
+ "cvc",
3144
+ "card",
3145
+ "password",
3146
+ "passwd",
3147
+ "secret",
3148
+ "token",
3149
+ "sign",
3150
+ "signin",
3151
+ "login",
3152
+ "reset",
3153
+ "credential",
3154
+ "credentials",
3155
+ "unlock"
3156
+ ]);
3157
+ var PAYMENT_ACTION_WORDS = /* @__PURE__ */ new Set([
3158
+ "card",
3159
+ "pay",
3160
+ "payment",
3161
+ "charge",
3162
+ "checkout",
3163
+ "billing",
3164
+ "cvv",
3165
+ "cvc"
3166
+ ]);
3167
+ function actionWords(name) {
3168
+ 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);
3169
+ }
3170
+ function passesLuhn(digits) {
3171
+ let sum = 0;
3172
+ for (let i = 0; i < digits.length; i += 1) {
3173
+ let d = Number(digits[digits.length - 1 - i]);
3174
+ if (i % 2 === 1) {
3175
+ d *= 2;
3176
+ if (d > 9) d -= 9;
3177
+ }
3178
+ sum += d;
3179
+ }
3180
+ return sum % 10 === 0;
3181
+ }
3182
+ function looksLikeCardNumber(digits, paymentAction) {
3183
+ if (digits.length < 13 || digits.length > 19 || !passesLuhn(digits)) return false;
3184
+ return paymentAction || digits.length === 15 || digits.length === 16;
3185
+ }
3186
+ function maskPositional(value, flags) {
3187
+ if (Array.isArray(value)) return value.map((v) => maskPositional(v, flags));
3188
+ const digits = typeof value === "number" && Number.isInteger(value) && value >= 0 ? String(value) : typeof value === "string" && /^\d+$/.test(value) ? value : null;
3189
+ if (digits !== null) {
3190
+ if (looksLikeCardNumber(digits, flags.paymentAction)) return "[FILTERED]";
3191
+ if (flags.secretAction && digits.length >= 4 && digits.length <= 8) return "[FILTERED]";
3192
+ }
3193
+ if (typeof value === "string") {
3194
+ return isIdShaped(value) ? value : "[FILTERED]";
3195
+ }
3196
+ return value;
3197
+ }
2941
3198
  function findPayloadIndex(args) {
2942
3199
  for (let i = args.length - 1; i >= 0; i -= 1) {
2943
3200
  if (typeof FormData !== "undefined" && args[i] instanceof FormData) {
@@ -3308,28 +3565,11 @@ async function flushTriggerAuditLog() {
3308
3565
  if (!reader) return;
3309
3566
  await flushAuditLog(reader);
3310
3567
  }
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
3568
  function runWithActorAndAuditScope(callback) {
3318
- const config = configuration();
3319
- const hasReader = config.databaseReader != null;
3320
- const snapshotEnabled = config.databaseSnapshotMode;
3321
- if (!hasReader) {
3569
+ if (configuration().databaseReader == null) {
3322
3570
  return runWithActorScope(callback);
3323
3571
  }
3324
- return runWithActorScope(
3325
- () => runWithEmittedAuditIdsScope(() => {
3326
- if (!snapshotEnabled) return callback();
3327
- return runWithAuditSnapshotScope(async () => {
3328
- await takeTriggerAuditSnapshotIfEnabled();
3329
- return callback();
3330
- });
3331
- })
3332
- );
3572
+ return runWithActorScope(() => runWithEmittedAuditIdsScope(callback));
3333
3573
  }
3334
3574
  function isExcludedPath(path, method) {
3335
3575
  const config = configuration();
@@ -3451,7 +3691,7 @@ var ezlogs = {
3451
3691
  options.patchDatabaseClient
3452
3692
  );
3453
3693
  }
3454
- applyDatabaseReaderDefaults(options);
3694
+ applyDatabaseReaderDefaults();
3455
3695
  installBeforeExitHook();
3456
3696
  initialized = true;
3457
3697
  },
@@ -3502,26 +3742,49 @@ async function autoWireTriggerPathFromDatabaseUrl(options) {
3502
3742
  "return import(s)"
3503
3743
  );
3504
3744
  pg = await dynImport("pg");
3505
- } catch (err) {
3745
+ } catch {
3746
+ logger.warn(
3747
+ "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)."
3748
+ );
3506
3749
  return;
3507
3750
  }
3508
3751
  const pool = new pg.Pool({
3509
3752
  connectionString: options.databaseUrl,
3510
3753
  max: 4
3511
3754
  });
3755
+ const reader = (sql, params) => pool.query(sql, params);
3756
+ if (await auditLogInstalled(reader) === false) {
3757
+ warnAuditLogMissing();
3758
+ void pool.end?.().catch(() => {
3759
+ });
3760
+ return;
3761
+ }
3512
3762
  if (config.databaseReader === null) {
3513
- config.databaseReader = (sql, params) => pool.query(sql, params);
3763
+ config.databaseReader = reader;
3514
3764
  }
3515
3765
  patchPgClient(pg);
3516
- applyDatabaseReaderDefaults(options);
3766
+ void checkAuditLogAccess(reader);
3767
+ runTriggerTrackedTablesDetection();
3517
3768
  }
3518
- function applyDatabaseReaderDefaults(options) {
3769
+ function applyDatabaseReaderDefaults() {
3519
3770
  const config = configuration();
3520
- if (!config.databaseReader) return;
3521
- if (options.databaseSnapshotMode === void 0) {
3522
- config.databaseSnapshotMode = true;
3523
- }
3524
- runTriggerTrackedTablesDetection();
3771
+ const reader = config.databaseReader;
3772
+ if (!reader) return;
3773
+ auditLogInstalled(reader).then((installed) => {
3774
+ if (installed === false && config.databaseReader === reader) {
3775
+ config.databaseReader = null;
3776
+ warnAuditLogMissing();
3777
+ return;
3778
+ }
3779
+ if (installed === true) void checkAuditLogAccess(reader);
3780
+ runTriggerTrackedTablesDetection();
3781
+ }).catch(() => {
3782
+ });
3783
+ }
3784
+ function warnAuditLogMissing() {
3785
+ logger.warn(
3786
+ "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."
3787
+ );
3525
3788
  }
3526
3789
  function runTriggerTrackedTablesDetection() {
3527
3790
  const config = configuration();