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.js CHANGED
@@ -110,7 +110,6 @@ var init_configuration = __esm({
110
110
  displayNameFor = {};
111
111
  isServerActionError = null;
112
112
  databaseReader = null;
113
- databaseSnapshotMode = false;
114
113
  databaseUrl = null;
115
114
  /**
116
115
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -162,9 +161,6 @@ var init_configuration = __esm({
162
161
  if (options.databaseReader !== void 0) {
163
162
  this.databaseReader = options.databaseReader;
164
163
  }
165
- if (options.databaseSnapshotMode !== void 0) {
166
- this.databaseSnapshotMode = options.databaseSnapshotMode;
167
- }
168
164
  if (options.databaseUrl !== void 0) {
169
165
  this.databaseUrl = options.databaseUrl;
170
166
  }
@@ -386,13 +382,19 @@ function randomHexBytes(byteCount) {
386
382
  function resolveCorrelation(headers) {
387
383
  if (!headers) return generate();
388
384
  const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
389
- if (ezlogs2) return ezlogs2;
385
+ if (ezlogs2 && isTrustedInboundId(ezlogs2)) return ezlogs2;
390
386
  for (const name of PLATFORM_REQUEST_ID_HEADERS) {
391
387
  const platformId = safeRead(headers, name);
392
388
  if (platformId) return wrapPlatformId(platformId);
393
389
  }
394
390
  return generate();
395
391
  }
392
+ function isTrustedInboundId(id) {
393
+ const match = INBOUND_ID.exec(id);
394
+ if (!match) return false;
395
+ const age = Date.now() - Number(match[1]);
396
+ return age <= INBOUND_MAX_AGE_MS && age >= -INBOUND_MAX_SKEW_MS;
397
+ }
396
398
  function safeRead(headers, name) {
397
399
  try {
398
400
  const value = headers.get(name);
@@ -420,7 +422,7 @@ function current() {
420
422
  function runWithCorrelation(correlationId, callback) {
421
423
  return storage.run(correlationId, callback);
422
424
  }
423
- var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage;
425
+ var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage, INBOUND_ID, INBOUND_MAX_AGE_MS, INBOUND_MAX_SKEW_MS;
424
426
  var init_correlation = __esm({
425
427
  "src/correlation.ts"() {
426
428
  init_edge_fallback();
@@ -433,6 +435,9 @@ var init_correlation = __esm({
433
435
  storage = createScopedStorage(
434
436
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
435
437
  );
438
+ INBOUND_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
439
+ INBOUND_MAX_AGE_MS = 60 * 6e4;
440
+ INBOUND_MAX_SKEW_MS = 5 * 6e4;
436
441
  }
437
442
  });
438
443
 
@@ -712,6 +717,168 @@ var init_event_builder = __esm({
712
717
  }
713
718
  });
714
719
 
720
+ // src/http/sanitize.ts
721
+ function snakeLower(key) {
722
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
723
+ }
724
+ function matchesSensitiveKey(key, substringPatterns) {
725
+ const lower = key.toLowerCase();
726
+ const snake = snakeLower(key);
727
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
728
+ return true;
729
+ }
730
+ const words = snake.split(/[^a-z0-9]+/);
731
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
732
+ }
733
+ function sanitizeRequestParams(params, userPatterns = []) {
734
+ if (params === null || params === void 0) return null;
735
+ if (!isPlainObject2(params)) return null;
736
+ const obj = params;
737
+ const cleaned = {};
738
+ for (const key of Object.keys(obj)) {
739
+ if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
740
+ cleaned[key] = obj[key];
741
+ }
742
+ if (Object.keys(cleaned).length === 0) return null;
743
+ const out = {};
744
+ for (const key of Object.keys(cleaned)) {
745
+ out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
746
+ }
747
+ return out;
748
+ }
749
+ function sanitizeValue(key, value, depth, userPatterns) {
750
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
751
+ if (isPlainObject2(value)) {
752
+ return sanitizeNestedObject(value, depth, userPatterns);
753
+ }
754
+ if (Array.isArray(value)) {
755
+ return sanitizeArrayValue(value, depth, userPatterns);
756
+ }
757
+ return value;
758
+ }
759
+ function sanitizeNestedObject(hash, depth, userPatterns) {
760
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
761
+ if (Object.keys(hash).length === 0) return {};
762
+ const out = {};
763
+ for (const k of Object.keys(hash)) {
764
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
765
+ }
766
+ return out;
767
+ }
768
+ function sanitizeArrayValue(array, depth, userPatterns) {
769
+ if (array.length === 0) return [];
770
+ const allPrimitive = array.every(isPrimitive);
771
+ if (allPrimitive) {
772
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
773
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
774
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
775
+ }
776
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
777
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
778
+ }
779
+ return {
780
+ _truncated: true,
781
+ _count: array.length,
782
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
783
+ };
784
+ }
785
+ function sanitizeArrayItem(item, depth, userPatterns) {
786
+ if (isPrimitive(item)) return item;
787
+ if (isPlainObject2(item)) {
788
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
789
+ }
790
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
791
+ return "[Object]";
792
+ }
793
+ function isSensitiveKey2(key, userPatterns) {
794
+ if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
795
+ const lower = key.toLowerCase();
796
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
797
+ }
798
+ function isPrimitive(value) {
799
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
800
+ }
801
+ function isPlainObject2(value) {
802
+ if (value === null || typeof value !== "object") return false;
803
+ const proto = Object.getPrototypeOf(value);
804
+ return proto === Object.prototype || proto === null;
805
+ }
806
+ var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS;
807
+ var init_sanitize = __esm({
808
+ "src/http/sanitize.ts"() {
809
+ SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
810
+ "password",
811
+ "passwd",
812
+ "pwd",
813
+ "token",
814
+ "access_token",
815
+ "refresh_token",
816
+ "api_token",
817
+ "auth_token",
818
+ "secret",
819
+ "api_secret",
820
+ "client_secret",
821
+ "api_key",
822
+ "apikey",
823
+ "private_key",
824
+ "privatekey",
825
+ "public_key",
826
+ "signing_key",
827
+ "secret_key",
828
+ "secretkey",
829
+ "credential",
830
+ "auth",
831
+ "authorization",
832
+ "encrypted",
833
+ "encrypted_data",
834
+ "ssn",
835
+ "social_security",
836
+ "credit_card",
837
+ "card_number",
838
+ "cvv",
839
+ "cvc",
840
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
841
+ // (PR #45). Request bodies can carry the same key material as DB
842
+ // columns (a webhook POST containing a `signature` field, an HMAC
843
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
844
+ "pem",
845
+ "cipher",
846
+ "nonce",
847
+ "salt",
848
+ "digest",
849
+ "signature",
850
+ "hmac",
851
+ // 0.2.0 additions (not yet in the Rails gem's list).
852
+ "passcode",
853
+ "cardnumber"
854
+ ]);
855
+ SENSITIVE_WORD_PATTERNS = Object.freeze([
856
+ "pin",
857
+ "otp",
858
+ "totp",
859
+ "iban",
860
+ "mfa",
861
+ "passphrase"
862
+ ]);
863
+ MAX_NESTING_DEPTH = 3;
864
+ MAX_ARRAY_DISPLAY_SIZE = 5;
865
+ FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
866
+ // Rails leftovers — kept for parity since users may funnel through a
867
+ // proxy that adds them, e.g. via a NextAuth credentials provider that
868
+ // forwards CSRF tokens.
869
+ "controller",
870
+ "action",
871
+ "format",
872
+ "authenticity_token",
873
+ "_method",
874
+ // Next.js / common JS conventions
875
+ "csrfToken",
876
+ "_csrf",
877
+ "_next"
878
+ ]);
879
+ }
880
+ });
881
+
715
882
  // src/db/shared.ts
716
883
  function emitDbEvent(input) {
717
884
  try {
@@ -738,7 +905,8 @@ function emitDbEvent(input) {
738
905
  correlation_id: current(),
739
906
  resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
740
907
  context,
741
- duration_ms: null
908
+ duration_ms: null,
909
+ timestamp: input.timestamp ?? null
742
910
  });
743
911
  pushEvent(event);
744
912
  } catch (error) {
@@ -796,8 +964,7 @@ function isMeaningfulAttribute(name) {
796
964
  return true;
797
965
  }
798
966
  function isDbSensitive(name) {
799
- const lower = name.toLowerCase();
800
- return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
967
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
801
968
  }
802
969
  function isScalar(value) {
803
970
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
@@ -877,6 +1044,7 @@ var init_shared = __esm({
877
1044
  init_buffer();
878
1045
  init_correlation();
879
1046
  init_actor();
1047
+ init_sanitize();
880
1048
  IGNORED_ATTRIBUTES = Object.freeze([
881
1049
  "id",
882
1050
  "createdAt",
@@ -907,7 +1075,19 @@ var init_shared = __esm({
907
1075
  "salt",
908
1076
  "digest",
909
1077
  "signature",
910
- "hmac"
1078
+ "hmac",
1079
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
1080
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
1081
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
1082
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
1083
+ "credential",
1084
+ "passwd",
1085
+ "passcode",
1086
+ "apikey",
1087
+ "card_number",
1088
+ "cardnumber",
1089
+ "cvv",
1090
+ "cvc"
911
1091
  ]);
912
1092
  }
913
1093
  });
@@ -1707,51 +1887,59 @@ function leadingVerb(text) {
1707
1887
  init_logger();
1708
1888
  init_shared();
1709
1889
  init_correlation();
1710
-
1711
- // src/triggers/audit-snapshot.ts
1712
- init_edge_fallback();
1713
- var storage3 = createScopedStorage(
1714
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-snapshot-storage")
1715
- );
1716
- function currentAuditSnapshot() {
1717
- return storage3.read();
1718
- }
1719
- function setAuditSnapshot(value) {
1720
- storage3.update(value);
1721
- }
1722
- function runWithAuditSnapshotScope(callback) {
1723
- return storage3.run(0n, callback);
1724
- }
1890
+ init_actor();
1725
1891
 
1726
1892
  // src/triggers/emit-dedup.ts
1727
1893
  init_edge_fallback();
1728
- var storage4 = createScopedStorage(
1894
+ var storage3 = createScopedStorage(
1729
1895
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1730
1896
  );
1731
1897
  function currentEmittedAuditIds() {
1732
- return storage4.read();
1898
+ return storage3.read();
1733
1899
  }
1734
1900
  function runWithEmittedAuditIdsScope(callback) {
1735
- const existing = storage4.read();
1901
+ const existing = storage3.read();
1736
1902
  if (existing !== null) return callback();
1737
- return storage4.run(/* @__PURE__ */ new Set(), callback);
1903
+ return storage3.run(/* @__PURE__ */ new Set(), callback);
1738
1904
  }
1739
1905
 
1740
1906
  // src/triggers/reader.ts
1741
- async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1907
+ var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
1908
+ var ORPHAN_AGE = "5 minutes";
1909
+ var PRUNE_AGE = "24 hours";
1910
+ var SWEEP_BATCH = 100;
1911
+ var PRUNE_BATCH = 2e3;
1912
+ var SWEEP_INTERVAL_MS = 1e4;
1913
+ var PRUNE_INTERVAL_MS = 10 * 6e4;
1914
+ var lastSweepAt = 0;
1915
+ var lastPruneAt = 0;
1916
+ var deleteDenied = false;
1917
+ var txCorrelation = /* @__PURE__ */ new Map();
1918
+ async function readAuditRows(exec, correlationId) {
1742
1919
  try {
1743
- const sql = snapshotMaxId === null ? `SELECT id, table_name, op, old_row, new_row, resource_id
1744
- FROM ezlogs_audit_log
1745
- WHERE correlation_id = $1
1746
- ORDER BY id ASC` : `SELECT id, table_name, op, old_row, new_row, resource_id
1747
- FROM ezlogs_audit_log
1748
- WHERE correlation_id = $1
1749
- OR (correlation_id IS NULL AND id > $2)
1750
- ORDER BY id ASC`;
1751
- const params = snapshotMaxId === null ? [correlationId] : [correlationId, snapshotMaxId.toString()];
1752
- const result = await exec(sql, params);
1753
- const rows = extractRows(result);
1754
- return rows.map((r) => normalizeAuditRow(r));
1920
+ if (!deleteDenied) {
1921
+ try {
1922
+ return sortById(
1923
+ extractRows(
1924
+ await exec(
1925
+ `DELETE FROM ezlogs_audit_log WHERE correlation_id = $1 RETURNING ${COLUMNS}`,
1926
+ [correlationId]
1927
+ )
1928
+ ).map(normalizeAuditRow)
1929
+ );
1930
+ } catch (err) {
1931
+ if (!isPermissionDenied(err)) throw err;
1932
+ deleteDenied = true;
1933
+ logger.warn(
1934
+ "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'`."
1935
+ );
1936
+ }
1937
+ }
1938
+ const result = await exec(
1939
+ `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE correlation_id = $1 ORDER BY id ASC`,
1940
+ [correlationId]
1941
+ );
1942
+ return extractRows(result).map(normalizeAuditRow);
1755
1943
  } catch (err) {
1756
1944
  logger.debug(
1757
1945
  `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
@@ -1759,22 +1947,100 @@ async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1759
1947
  return [];
1760
1948
  }
1761
1949
  }
1762
- async function takeAuditSnapshot(exec) {
1950
+ async function sweepAuditLog(exec) {
1951
+ if (deleteDenied) return 0;
1763
1952
  try {
1764
- const result = await exec(
1765
- `SELECT COALESCE(MAX(id), 0) AS max_id FROM ezlogs_audit_log`,
1953
+ const rows = sortById(
1954
+ extractRows(
1955
+ await exec(
1956
+ `DELETE FROM ezlogs_audit_log
1957
+ WHERE id IN (
1958
+ SELECT id FROM ezlogs_audit_log
1959
+ WHERE (correlation_id IS NULL
1960
+ OR captured_at < now() - interval '${ORPHAN_AGE}')
1961
+ -- Never resurface history: past the retention cap a
1962
+ -- row is pruned, not sent as new activity.
1963
+ AND captured_at > now() - interval '${PRUNE_AGE}'
1964
+ ORDER BY id
1965
+ LIMIT ${SWEEP_BATCH}
1966
+ FOR UPDATE SKIP LOCKED)
1967
+ RETURNING ${COLUMNS}`,
1968
+ []
1969
+ )
1970
+ ).map(normalizeAuditRow)
1971
+ );
1972
+ for (const row of rows) {
1973
+ const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1974
+ runWithCorrelation(
1975
+ correlationId,
1976
+ () => runWithActorScope(() => emitOne(row))
1977
+ );
1978
+ }
1979
+ return rows.length;
1980
+ } catch (err) {
1981
+ logger.debug(
1982
+ `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1983
+ );
1984
+ return 0;
1985
+ }
1986
+ }
1987
+ async function pruneAuditLog(exec) {
1988
+ if (deleteDenied) return;
1989
+ try {
1990
+ await exec(
1991
+ `DELETE FROM ezlogs_audit_log
1992
+ WHERE id IN (
1993
+ SELECT id FROM ezlogs_audit_log
1994
+ WHERE captured_at < now() - interval '${PRUNE_AGE}'
1995
+ LIMIT ${PRUNE_BATCH})`,
1766
1996
  []
1767
1997
  );
1768
- const rows = extractRows(result);
1769
- if (rows.length === 0) return;
1770
- const raw = rows[0] ?? {};
1771
- const value = typeof raw.max_id === "bigint" ? raw.max_id : typeof raw.max_id === "number" ? BigInt(raw.max_id) : typeof raw.max_id === "string" && /^\d+$/.test(raw.max_id) ? BigInt(raw.max_id) : null;
1772
- if (value === null) return;
1773
- setAuditSnapshot(value);
1774
1998
  } catch (err) {
1775
1999
  logger.debug(
1776
- `takeAuditSnapshot failed: ${err instanceof Error ? err.message : String(err)}`
2000
+ `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2001
+ );
2002
+ }
2003
+ }
2004
+ async function auditLogInstalled(exec) {
2005
+ try {
2006
+ const rows = extractRows(
2007
+ await exec(
2008
+ `SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
2009
+ []
2010
+ )
2011
+ );
2012
+ const installed = rows[0]?.installed;
2013
+ return typeof installed === "boolean" ? installed : null;
2014
+ } catch {
2015
+ return null;
2016
+ }
2017
+ }
2018
+ async function checkAuditLogAccess(exec) {
2019
+ try {
2020
+ const rows = extractRows(
2021
+ await exec(
2022
+ `SELECT current_user AS role
2023
+ FROM pg_class c
2024
+ JOIN pg_roles r ON r.rolname = current_user
2025
+ WHERE c.oid = 'public.ezlogs_audit_log'::regclass
2026
+ AND c.relrowsecurity
2027
+ AND NOT r.rolsuper
2028
+ AND NOT r.rolbypassrls
2029
+ AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
2030
+ AND NOT EXISTS (SELECT 1 FROM pg_policies p
2031
+ WHERE p.schemaname = 'public'
2032
+ AND p.tablename = 'ezlogs_audit_log')`,
2033
+ []
2034
+ )
2035
+ );
2036
+ const role = rows[0]?.role;
2037
+ if (typeof role !== "string") return false;
2038
+ logger.warn(
2039
+ `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);`
1777
2040
  );
2041
+ return true;
2042
+ } catch {
2043
+ return false;
1778
2044
  }
1779
2045
  }
1780
2046
  async function detectTriggerTrackedTables(exec) {
@@ -1811,8 +2077,19 @@ async function flushAuditLog(exec) {
1811
2077
  if (!exec) return;
1812
2078
  const correlationId = current();
1813
2079
  if (!correlationId) return;
1814
- const snapshot = currentAuditSnapshot();
1815
- const rows = await readAuditRows(exec, correlationId, snapshot);
2080
+ const rows = await readAuditRows(exec, correlationId);
2081
+ emitFresh(rows);
2082
+ const now = Date.now();
2083
+ if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
2084
+ lastPruneAt = now;
2085
+ await pruneAuditLog(exec);
2086
+ }
2087
+ if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
2088
+ lastSweepAt = now;
2089
+ await sweepAuditLog(exec);
2090
+ }
2091
+ }
2092
+ function emitFresh(rows) {
1816
2093
  if (rows.length === 0) return;
1817
2094
  const emitted = currentEmittedAuditIds();
1818
2095
  if (emitted === null) {
@@ -1825,9 +2102,26 @@ async function flushAuditLog(exec) {
1825
2102
  emitted.add(row.id);
1826
2103
  fresh.push(row);
1827
2104
  }
1828
- if (fresh.length === 0) return;
1829
2105
  emitAuditRows(fresh);
1830
2106
  }
2107
+ function correlationForTx(txid) {
2108
+ if (!txid) return generate();
2109
+ let id = txCorrelation.get(txid);
2110
+ if (!id) {
2111
+ if (txCorrelation.size >= 1e3) txCorrelation.clear();
2112
+ id = generate();
2113
+ txCorrelation.set(txid, id);
2114
+ }
2115
+ return id;
2116
+ }
2117
+ function isPermissionDenied(err) {
2118
+ return err?.code === "42501";
2119
+ }
2120
+ function sortById(rows) {
2121
+ return rows.sort(
2122
+ (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
2123
+ );
2124
+ }
1831
2125
  function emitOne(row) {
1832
2126
  const op = mapOp(row.op);
1833
2127
  if (!op) return;
@@ -1841,6 +2135,7 @@ function emitOne(row) {
1841
2135
  initialAttributes: newRow,
1842
2136
  modelInstance: newRow,
1843
2137
  displayName: null,
2138
+ timestamp: row.captured_at ?? null,
1844
2139
  _fromTrigger: true
1845
2140
  });
1846
2141
  return;
@@ -1859,6 +2154,7 @@ function emitOne(row) {
1859
2154
  // user just told the system to call this row.
1860
2155
  modelInstance: newRow,
1861
2156
  displayName: null,
2157
+ timestamp: row.captured_at ?? null,
1862
2158
  _fromTrigger: true
1863
2159
  });
1864
2160
  return;
@@ -1871,6 +2167,7 @@ function emitOne(row) {
1871
2167
  initialAttributes: oldRow,
1872
2168
  modelInstance: oldRow,
1873
2169
  displayName: null,
2170
+ timestamp: row.captured_at ?? null,
1874
2171
  _fromTrigger: true
1875
2172
  });
1876
2173
  return;
@@ -1919,6 +2216,11 @@ function extractRows(result) {
1919
2216
  }
1920
2217
  return [];
1921
2218
  }
2219
+ function toDate(value) {
2220
+ if (value == null) return null;
2221
+ const d = value instanceof Date ? value : new Date(String(value));
2222
+ return Number.isNaN(d.getTime()) ? null : d;
2223
+ }
1922
2224
  function normalizeAuditRow(raw) {
1923
2225
  const r = raw ?? {};
1924
2226
  return {
@@ -1927,7 +2229,10 @@ function normalizeAuditRow(raw) {
1927
2229
  op: r.op,
1928
2230
  old_row: r.old_row ?? null,
1929
2231
  new_row: r.new_row ?? null,
1930
- resource_id: r.resource_id == null ? null : String(r.resource_id)
2232
+ resource_id: r.resource_id == null ? null : String(r.resource_id),
2233
+ correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
2234
+ txid: r.txid == null ? null : String(r.txid),
2235
+ captured_at: toDate(r.captured_at)
1931
2236
  };
1932
2237
  }
1933
2238
  function coerceJsonb(value) {
@@ -2028,141 +2333,8 @@ function hasExcludedExtension(path, extensions) {
2028
2333
  // src/http/capture.ts
2029
2334
  init_configuration();
2030
2335
 
2031
- // src/http/sanitize.ts
2032
- var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
2033
- "password",
2034
- "passwd",
2035
- "pwd",
2036
- "token",
2037
- "access_token",
2038
- "refresh_token",
2039
- "api_token",
2040
- "auth_token",
2041
- "secret",
2042
- "api_secret",
2043
- "client_secret",
2044
- "api_key",
2045
- "apikey",
2046
- "private_key",
2047
- "privatekey",
2048
- "public_key",
2049
- "signing_key",
2050
- "secret_key",
2051
- "secretkey",
2052
- "credential",
2053
- "auth",
2054
- "authorization",
2055
- "encrypted",
2056
- "encrypted_data",
2057
- "ssn",
2058
- "social_security",
2059
- "credit_card",
2060
- "card_number",
2061
- "cvv",
2062
- "cvc",
2063
- // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
2064
- // (PR #45). Request bodies can carry the same key material as DB
2065
- // columns (a webhook POST containing a `signature` field, an HMAC
2066
- // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
2067
- "pem",
2068
- "cipher",
2069
- "nonce",
2070
- "salt",
2071
- "digest",
2072
- "signature",
2073
- "hmac"
2074
- ]);
2075
- var MAX_NESTING_DEPTH = 3;
2076
- var MAX_ARRAY_DISPLAY_SIZE = 5;
2077
- function sanitizeRequestParams(params, userPatterns = []) {
2078
- if (params === null || params === void 0) return null;
2079
- if (!isPlainObject2(params)) return null;
2080
- const obj = params;
2081
- const cleaned = {};
2082
- for (const key of Object.keys(obj)) {
2083
- if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
2084
- cleaned[key] = obj[key];
2085
- }
2086
- if (Object.keys(cleaned).length === 0) return null;
2087
- const out = {};
2088
- for (const key of Object.keys(cleaned)) {
2089
- out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
2090
- }
2091
- return out;
2092
- }
2093
- var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
2094
- // Rails leftovers — kept for parity since users may funnel through a
2095
- // proxy that adds them, e.g. via a NextAuth credentials provider that
2096
- // forwards CSRF tokens.
2097
- "controller",
2098
- "action",
2099
- "format",
2100
- "authenticity_token",
2101
- "_method",
2102
- // Next.js / common JS conventions
2103
- "csrfToken",
2104
- "_csrf",
2105
- "_next"
2106
- ]);
2107
- function sanitizeValue(key, value, depth, userPatterns) {
2108
- if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
2109
- if (isPlainObject2(value)) {
2110
- return sanitizeNestedObject(value, depth, userPatterns);
2111
- }
2112
- if (Array.isArray(value)) {
2113
- return sanitizeArrayValue(value, depth, userPatterns);
2114
- }
2115
- return value;
2116
- }
2117
- function sanitizeNestedObject(hash, depth, userPatterns) {
2118
- if (depth >= MAX_NESTING_DEPTH) return "[Object]";
2119
- if (Object.keys(hash).length === 0) return {};
2120
- const out = {};
2121
- for (const k of Object.keys(hash)) {
2122
- out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
2123
- }
2124
- return out;
2125
- }
2126
- function sanitizeArrayValue(array, depth, userPatterns) {
2127
- if (array.length === 0) return [];
2128
- const allPrimitive = array.every(isPrimitive);
2129
- if (allPrimitive) {
2130
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
2131
- const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
2132
- return `${JSON.stringify(preview)}... (${array.length} total)`;
2133
- }
2134
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
2135
- return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
2136
- }
2137
- return {
2138
- _truncated: true,
2139
- _count: array.length,
2140
- _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
2141
- };
2142
- }
2143
- function sanitizeArrayItem(item, depth, userPatterns) {
2144
- if (isPrimitive(item)) return item;
2145
- if (isPlainObject2(item)) {
2146
- return sanitizeNestedObject(item, depth + 1, userPatterns);
2147
- }
2148
- if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
2149
- return "[Object]";
2150
- }
2151
- function isSensitiveKey2(key, userPatterns) {
2152
- const lower = key.toLowerCase();
2153
- if (SENSITIVE_VARIABLE_PATTERNS.some((p) => lower.includes(p))) return true;
2154
- return userPatterns.some((p) => lower.includes(p.toLowerCase()));
2155
- }
2156
- function isPrimitive(value) {
2157
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
2158
- }
2159
- function isPlainObject2(value) {
2160
- if (value === null || typeof value !== "object") return false;
2161
- const proto = Object.getPrototypeOf(value);
2162
- return proto === Object.prototype || proto === null;
2163
- }
2164
-
2165
2336
  // src/http/source-data.ts
2337
+ init_sanitize();
2166
2338
  function buildHttpSourceData(input) {
2167
2339
  const { controller, action } = resolveControllerAction(input);
2168
2340
  const source = {
@@ -2336,6 +2508,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2336
2508
  }
2337
2509
 
2338
2510
  // src/http/graphql.ts
2511
+ init_sanitize();
2339
2512
  var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2340
2513
  var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2341
2514
  function isGraphqlPath(path) {
@@ -2877,7 +3050,7 @@ async function emitServerActionEvent(input) {
2877
3050
  const nextUrl = await readNextHeader("next-url");
2878
3051
  const userAgent = await readNextHeader("user-agent");
2879
3052
  const fromPage = referer ?? nextUrl ?? null;
2880
- const argParams = extractServerActionArgs(input.args);
3053
+ const argParams = extractServerActionArgs(input.args, input.actionName);
2881
3054
  const requestParams = argParams !== null || fromPage !== null ? { ...argParams ?? {}, ...fromPage !== null ? { from_page: fromPage } : {} } : null;
2882
3055
  const syntheticUrl = new URL(
2883
3056
  `http://localhost/__server-action/${encodeURIComponent(input.actionName)}`
@@ -2915,7 +3088,7 @@ async function emitServerActionEvent(input) {
2915
3088
  logger.error(`server-action capture emit failed: ${describeError7(error)}`);
2916
3089
  }
2917
3090
  }
2918
- function extractServerActionArgs(args) {
3091
+ function extractServerActionArgs(args, actionName) {
2919
3092
  if (!args || args.length === 0) return null;
2920
3093
  const payloadIndex = findPayloadIndex(args);
2921
3094
  if (payloadIndex !== -1) {
@@ -2928,14 +3101,98 @@ function extractServerActionArgs(args) {
2928
3101
  }
2929
3102
  return Object.keys(out2).length === 0 ? null : out2;
2930
3103
  }
3104
+ const words = actionWords(actionName);
3105
+ const flags = {
3106
+ secretAction: words.some((w) => SECRET_ACTION_WORDS.has(w)),
3107
+ paymentAction: words.some((w) => PAYMENT_ACTION_WORDS.has(w))
3108
+ };
2931
3109
  const out = {};
2932
3110
  args.forEach((a, i) => {
2933
3111
  if (isInsignificantArg(a)) return;
2934
- const v = serializeArgValue(a);
3112
+ const v = maskPositional(serializeArgValue(a), flags);
2935
3113
  if (v !== void 0) out[`arg${i}`] = v;
2936
3114
  });
2937
3115
  return Object.keys(out).length === 0 ? null : out;
2938
3116
  }
3117
+ 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;
3118
+ var CUID_V1 = /^c[a-z0-9]{24}$/;
3119
+ var CUID2 = /^[a-z][a-z0-9]{23}$/;
3120
+ var ULID = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
3121
+ var NANOID_21 = /^[A-Za-z0-9_-]{21}$/;
3122
+ function digitCount(s) {
3123
+ return s.replace(/\D/g, "").length;
3124
+ }
3125
+ function isIdShaped(s) {
3126
+ if (INT_OR_UUID.test(s) || ULID.test(s)) return true;
3127
+ if (CUID_V1.test(s) || CUID2.test(s)) return digitCount(s) >= 2;
3128
+ if (NANOID_21.test(s)) {
3129
+ return digitCount(s) >= 2 && /[a-z]/.test(s) && /[A-Z]/.test(s);
3130
+ }
3131
+ return false;
3132
+ }
3133
+ var SECRET_ACTION_WORDS = /* @__PURE__ */ new Set([
3134
+ "pin",
3135
+ "otp",
3136
+ "code",
3137
+ "verify",
3138
+ "mfa",
3139
+ "2fa",
3140
+ "cvv",
3141
+ "cvc",
3142
+ "card",
3143
+ "password",
3144
+ "passwd",
3145
+ "secret",
3146
+ "token",
3147
+ "sign",
3148
+ "signin",
3149
+ "login",
3150
+ "reset",
3151
+ "credential",
3152
+ "credentials",
3153
+ "unlock"
3154
+ ]);
3155
+ var PAYMENT_ACTION_WORDS = /* @__PURE__ */ new Set([
3156
+ "card",
3157
+ "pay",
3158
+ "payment",
3159
+ "charge",
3160
+ "checkout",
3161
+ "billing",
3162
+ "cvv",
3163
+ "cvc"
3164
+ ]);
3165
+ function actionWords(name) {
3166
+ 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);
3167
+ }
3168
+ function passesLuhn(digits) {
3169
+ let sum = 0;
3170
+ for (let i = 0; i < digits.length; i += 1) {
3171
+ let d = Number(digits[digits.length - 1 - i]);
3172
+ if (i % 2 === 1) {
3173
+ d *= 2;
3174
+ if (d > 9) d -= 9;
3175
+ }
3176
+ sum += d;
3177
+ }
3178
+ return sum % 10 === 0;
3179
+ }
3180
+ function looksLikeCardNumber(digits, paymentAction) {
3181
+ if (digits.length < 13 || digits.length > 19 || !passesLuhn(digits)) return false;
3182
+ return paymentAction || digits.length === 15 || digits.length === 16;
3183
+ }
3184
+ function maskPositional(value, flags) {
3185
+ if (Array.isArray(value)) return value.map((v) => maskPositional(v, flags));
3186
+ const digits = typeof value === "number" && Number.isInteger(value) && value >= 0 ? String(value) : typeof value === "string" && /^\d+$/.test(value) ? value : null;
3187
+ if (digits !== null) {
3188
+ if (looksLikeCardNumber(digits, flags.paymentAction)) return "[FILTERED]";
3189
+ if (flags.secretAction && digits.length >= 4 && digits.length <= 8) return "[FILTERED]";
3190
+ }
3191
+ if (typeof value === "string") {
3192
+ return isIdShaped(value) ? value : "[FILTERED]";
3193
+ }
3194
+ return value;
3195
+ }
2939
3196
  function findPayloadIndex(args) {
2940
3197
  for (let i = args.length - 1; i >= 0; i -= 1) {
2941
3198
  if (typeof FormData !== "undefined" && args[i] instanceof FormData) {
@@ -3306,28 +3563,11 @@ async function flushTriggerAuditLog() {
3306
3563
  if (!reader) return;
3307
3564
  await flushAuditLog(reader);
3308
3565
  }
3309
- async function takeTriggerAuditSnapshotIfEnabled() {
3310
- const config = configuration();
3311
- if (!config.databaseSnapshotMode) return;
3312
- if (!config.databaseReader) return;
3313
- await takeAuditSnapshot(config.databaseReader);
3314
- }
3315
3566
  function runWithActorAndAuditScope(callback) {
3316
- const config = configuration();
3317
- const hasReader = config.databaseReader != null;
3318
- const snapshotEnabled = config.databaseSnapshotMode;
3319
- if (!hasReader) {
3567
+ if (configuration().databaseReader == null) {
3320
3568
  return runWithActorScope(callback);
3321
3569
  }
3322
- return runWithActorScope(
3323
- () => runWithEmittedAuditIdsScope(() => {
3324
- if (!snapshotEnabled) return callback();
3325
- return runWithAuditSnapshotScope(async () => {
3326
- await takeTriggerAuditSnapshotIfEnabled();
3327
- return callback();
3328
- });
3329
- })
3330
- );
3570
+ return runWithActorScope(() => runWithEmittedAuditIdsScope(callback));
3331
3571
  }
3332
3572
  function isExcludedPath(path, method) {
3333
3573
  const config = configuration();
@@ -3449,7 +3689,7 @@ var ezlogs = {
3449
3689
  options.patchDatabaseClient
3450
3690
  );
3451
3691
  }
3452
- applyDatabaseReaderDefaults(options);
3692
+ applyDatabaseReaderDefaults();
3453
3693
  installBeforeExitHook();
3454
3694
  initialized = true;
3455
3695
  },
@@ -3500,26 +3740,49 @@ async function autoWireTriggerPathFromDatabaseUrl(options) {
3500
3740
  "return import(s)"
3501
3741
  );
3502
3742
  pg = await dynImport("pg");
3503
- } catch (err) {
3743
+ } catch {
3744
+ logger.warn(
3745
+ "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)."
3746
+ );
3504
3747
  return;
3505
3748
  }
3506
3749
  const pool = new pg.Pool({
3507
3750
  connectionString: options.databaseUrl,
3508
3751
  max: 4
3509
3752
  });
3753
+ const reader = (sql, params) => pool.query(sql, params);
3754
+ if (await auditLogInstalled(reader) === false) {
3755
+ warnAuditLogMissing();
3756
+ void pool.end?.().catch(() => {
3757
+ });
3758
+ return;
3759
+ }
3510
3760
  if (config.databaseReader === null) {
3511
- config.databaseReader = (sql, params) => pool.query(sql, params);
3761
+ config.databaseReader = reader;
3512
3762
  }
3513
3763
  patchPgClient(pg);
3514
- applyDatabaseReaderDefaults(options);
3764
+ void checkAuditLogAccess(reader);
3765
+ runTriggerTrackedTablesDetection();
3515
3766
  }
3516
- function applyDatabaseReaderDefaults(options) {
3767
+ function applyDatabaseReaderDefaults() {
3517
3768
  const config = configuration();
3518
- if (!config.databaseReader) return;
3519
- if (options.databaseSnapshotMode === void 0) {
3520
- config.databaseSnapshotMode = true;
3521
- }
3522
- runTriggerTrackedTablesDetection();
3769
+ const reader = config.databaseReader;
3770
+ if (!reader) return;
3771
+ auditLogInstalled(reader).then((installed) => {
3772
+ if (installed === false && config.databaseReader === reader) {
3773
+ config.databaseReader = null;
3774
+ warnAuditLogMissing();
3775
+ return;
3776
+ }
3777
+ if (installed === true) void checkAuditLogAccess(reader);
3778
+ runTriggerTrackedTablesDetection();
3779
+ }).catch(() => {
3780
+ });
3781
+ }
3782
+ function warnAuditLogMissing() {
3783
+ logger.warn(
3784
+ "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."
3785
+ );
3523
3786
  }
3524
3787
  function runTriggerTrackedTablesDetection() {
3525
3788
  const config = configuration();