ezlogs-nextjs 0.2.0 → 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.
package/dist/index.js CHANGED
@@ -746,6 +746,27 @@ function sanitizeRequestParams(params, userPatterns = []) {
746
746
  }
747
747
  return out;
748
748
  }
749
+ function passesLuhn(digits) {
750
+ let sum = 0;
751
+ for (let i = 0; i < digits.length; i += 1) {
752
+ let d = Number(digits[digits.length - 1 - i]);
753
+ if (i % 2 === 1) {
754
+ d *= 2;
755
+ if (d > 9) d -= 9;
756
+ }
757
+ sum += d;
758
+ }
759
+ return sum % 10 === 0;
760
+ }
761
+ function scrubSecretsInText(text, options = {}) {
762
+ let out = text;
763
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
764
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
765
+ const digits = match.replace(/[ -]/g, "");
766
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
767
+ });
768
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
769
+ }
749
770
  function sanitizeValue(key, value, depth, userPatterns) {
750
771
  if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
751
772
  if (isPlainObject2(value)) {
@@ -803,7 +824,7 @@ function isPlainObject2(value) {
803
824
  const proto = Object.getPrototypeOf(value);
804
825
  return proto === Object.prototype || proto === null;
805
826
  }
806
- var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS;
827
+ var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS, SECRET_TEXT_PATTERNS, EMAIL;
807
828
  var init_sanitize = __esm({
808
829
  "src/http/sanitize.ts"() {
809
830
  SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
@@ -876,6 +897,16 @@ var init_sanitize = __esm({
876
897
  "_csrf",
877
898
  "_next"
878
899
  ]);
900
+ SECRET_TEXT_PATTERNS = [
901
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
902
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
903
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
904
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
905
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
906
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
907
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
908
+ ];
909
+ EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
879
910
  }
880
911
  });
881
912
 
@@ -887,14 +918,17 @@ function emitDbEvent(input) {
887
918
  if (config.allExcludedTables().includes(input.modelClass)) return;
888
919
  if (config.databaseReader && !input._fromTrigger) {
889
920
  const tracked = config.triggerTrackedTables;
890
- if (tracked === null || tracked.has(input.modelClass)) return;
921
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
891
922
  }
892
923
  if (input.operation === "update") {
893
924
  const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
894
925
  if (meaningful.length === 0) return;
895
926
  }
896
927
  const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
897
- const context = buildContext(input);
928
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
929
+ const context = buildContext(
930
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
931
+ );
898
932
  const event = build({
899
933
  source_type: "database_callback",
900
934
  source_data: {
@@ -903,7 +937,7 @@ function emitDbEvent(input) {
903
937
  },
904
938
  outcome: "success",
905
939
  correlation_id: current(),
906
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
940
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
907
941
  context,
908
942
  duration_ms: null,
909
943
  timestamp: input.timestamp ?? null
@@ -950,7 +984,7 @@ function filterMeaningfulAttributes(attrs) {
950
984
  return Object.keys(out).length === 0 ? null : out;
951
985
  }
952
986
  function filterMeaningfulChanges(changes) {
953
- return changes.filter((c) => {
987
+ return flattenNestedChanges(changes).filter((c) => {
954
988
  if (!isMeaningfulAttribute(c.attribute)) return false;
955
989
  if (!isScalar(c.to)) return false;
956
990
  if (c.from === void 0) return true;
@@ -958,6 +992,57 @@ function filterMeaningfulChanges(changes) {
958
992
  return valuesActuallyChanged(c.from, c.to);
959
993
  });
960
994
  }
995
+ function flattenNestedChanges(changes) {
996
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
997
+ const out = [];
998
+ for (const c of changes) {
999
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
1000
+ out.push(c);
1001
+ continue;
1002
+ }
1003
+ if (!isMeaningfulAttribute(c.attribute)) continue;
1004
+ const leaves = [];
1005
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
1006
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
1007
+ out.push(...leaves.slice(0, cap).map(scrubLeaf));
1008
+ }
1009
+ return out;
1010
+ }
1011
+ function collectLeafChanges(path, from, to, depth, out) {
1012
+ if (out.length > MAX_NESTED_LEAVES) return;
1013
+ const fromObj = isPlainRecord(from);
1014
+ const toObj = isPlainRecord(to);
1015
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
1016
+ const f = fromObj ? from : {};
1017
+ const t = toObj ? to : {};
1018
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
1019
+ const before = from === void 0 ? void 0 : f[key] ?? null;
1020
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
1021
+ }
1022
+ return;
1023
+ }
1024
+ if (from !== void 0 && sameJson(from, to)) return;
1025
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
1026
+ }
1027
+ function scrubLeaf(change) {
1028
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
1029
+ const out = { attribute: change.attribute, to: scrub(change.to) };
1030
+ if (change.from !== void 0) out.from = scrub(change.from);
1031
+ return out;
1032
+ }
1033
+ function isPlainRecord(value) {
1034
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1035
+ const proto = Object.getPrototypeOf(value);
1036
+ return proto === Object.prototype || proto === null;
1037
+ }
1038
+ function sameJson(a, b) {
1039
+ if (a === b) return true;
1040
+ try {
1041
+ return JSON.stringify(a) === JSON.stringify(b);
1042
+ } catch {
1043
+ return false;
1044
+ }
1045
+ }
961
1046
  function isMeaningfulAttribute(name) {
962
1047
  if (IGNORED_ATTRIBUTES.includes(name)) return false;
963
1048
  if (isDbSensitive(name)) return false;
@@ -1001,16 +1086,36 @@ function resolveDisplayName(modelClass, instance) {
1001
1086
  const resolver = config.displayNameFor[modelClass];
1002
1087
  const resolved = applyResolver(resolver, instance);
1003
1088
  if (resolved !== null) return resolved;
1004
- for (const field of ["name", "title", "number"]) {
1005
- const value = instance[field];
1006
- if (value !== null && value !== void 0 && String(value).length > 0) {
1007
- return String(value);
1089
+ const columns = /* @__PURE__ */ new Map();
1090
+ for (const key of Object.keys(instance)) {
1091
+ if (isDbSensitive(key)) continue;
1092
+ const norm = key.toLowerCase().replace(/_/g, "");
1093
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
1094
+ }
1095
+ const text = (norm) => {
1096
+ const value = columns.get(norm);
1097
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1098
+ return null;
1008
1099
  }
1100
+ const str = String(value).trim();
1101
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
1102
+ };
1103
+ for (const column of DISPLAY_NAME_COLUMNS) {
1104
+ const value = text(column);
1105
+ if (value !== null) return value;
1009
1106
  }
1107
+ return text(`${singularNorm(modelClass)}number`);
1010
1108
  } catch {
1011
1109
  }
1012
1110
  return null;
1013
1111
  }
1112
+ function singularNorm(modelClass) {
1113
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
1114
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
1115
+ if (/(ss|us|is)$/.test(norm)) return norm;
1116
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
1117
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
1118
+ }
1014
1119
  function applyResolver(resolver, instance) {
1015
1120
  if (typeof resolver === "string") {
1016
1121
  const value = instance[resolver];
@@ -1035,7 +1140,7 @@ function describeError5(error) {
1035
1140
  if (error instanceof Error) return `${error.name}: ${error.message}`;
1036
1141
  return String(error);
1037
1142
  }
1038
- var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS;
1143
+ var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS, MAX_NESTED_DEPTH, MAX_NESTED_LEAVES, MAX_UNKNOWN_FROM_LEAVES, DISPLAY_NAME_COLUMNS, MAX_DISPLAY_NAME_LENGTH;
1039
1144
  var init_shared = __esm({
1040
1145
  "src/db/shared.ts"() {
1041
1146
  init_configuration();
@@ -1051,8 +1156,6 @@ var init_shared = __esm({
1051
1156
  "created_at",
1052
1157
  "updatedAt",
1053
1158
  "updated_at",
1054
- "deletedAt",
1055
- "deleted_at",
1056
1159
  // Auth.js / NextAuth standard columns
1057
1160
  "emailVerified",
1058
1161
  "expires"
@@ -1089,6 +1192,11 @@ var init_shared = __esm({
1089
1192
  "cvv",
1090
1193
  "cvc"
1091
1194
  ]);
1195
+ MAX_NESTED_DEPTH = 3;
1196
+ MAX_NESTED_LEAVES = 20;
1197
+ MAX_UNKNOWN_FROM_LEAVES = 5;
1198
+ DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
1199
+ MAX_DISPLAY_NAME_LENGTH = 120;
1092
1200
  }
1093
1201
  });
1094
1202
 
@@ -1915,15 +2023,17 @@ var lastSweepAt = 0;
1915
2023
  var lastPruneAt = 0;
1916
2024
  var deleteDenied = false;
1917
2025
  var txCorrelation = /* @__PURE__ */ new Map();
1918
- async function readAuditRows(exec, correlationId) {
2026
+ async function readAuditRows(exec, correlationId, since = null) {
2027
+ const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
2028
+ const params = since ? [correlationId, since.toISOString()] : [correlationId];
1919
2029
  try {
1920
2030
  if (!deleteDenied) {
1921
2031
  try {
1922
2032
  return sortById(
1923
2033
  extractRows(
1924
2034
  await exec(
1925
- `DELETE FROM ezlogs_audit_log WHERE correlation_id = $1 RETURNING ${COLUMNS}`,
1926
- [correlationId]
2035
+ `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
2036
+ params
1927
2037
  )
1928
2038
  ).map(normalizeAuditRow)
1929
2039
  );
@@ -1936,8 +2046,8 @@ async function readAuditRows(exec, correlationId) {
1936
2046
  }
1937
2047
  }
1938
2048
  const result = await exec(
1939
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE correlation_id = $1 ORDER BY id ASC`,
1940
- [correlationId]
2049
+ `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
2050
+ params
1941
2051
  );
1942
2052
  return extractRows(result).map(normalizeAuditRow);
1943
2053
  } catch (err) {
@@ -1969,6 +2079,7 @@ async function sweepAuditLog(exec) {
1969
2079
  )
1970
2080
  ).map(normalizeAuditRow)
1971
2081
  );
2082
+ await loadTableMeta(exec, rows);
1972
2083
  for (const row of rows) {
1973
2084
  const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1974
2085
  runWithCorrelation(
@@ -2073,11 +2184,12 @@ function emitAuditRows(rows) {
2073
2184
  emitOne(row);
2074
2185
  }
2075
2186
  }
2076
- async function flushAuditLog(exec) {
2187
+ async function flushAuditLog(exec, options = {}) {
2077
2188
  if (!exec) return;
2078
2189
  const correlationId = current();
2079
2190
  if (!correlationId) return;
2080
- const rows = await readAuditRows(exec, correlationId);
2191
+ const rows = await readAuditRows(exec, correlationId, options.since ?? null);
2192
+ await loadTableMeta(exec, rows);
2081
2193
  emitFresh(rows);
2082
2194
  const now = Date.now();
2083
2195
  if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
@@ -2089,6 +2201,79 @@ async function flushAuditLog(exec) {
2089
2201
  await sweepAuditLog(exec);
2090
2202
  }
2091
2203
  }
2204
+ var tableMeta = /* @__PURE__ */ new Map();
2205
+ var META_RETRY_MS = 6e4;
2206
+ var metaRetryAt = 0;
2207
+ async function loadTableMeta(exec, rows) {
2208
+ if (Date.now() < metaRetryAt) return;
2209
+ const tables = [
2210
+ ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
2211
+ ];
2212
+ if (tables.length === 0) return;
2213
+ const list = tables.join(",");
2214
+ try {
2215
+ const fkRows = extractRows(
2216
+ await exec(
2217
+ `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
2218
+ FROM pg_constraint c
2219
+ JOIN pg_class cl ON cl.oid = c.conrelid
2220
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
2221
+ JOIN pg_class rf ON rf.oid = c.confrelid
2222
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
2223
+ WHERE c.contype = 'f'
2224
+ AND n.nspname = 'public'
2225
+ AND array_length(c.conkey, 1) = 1
2226
+ AND cl.relname = ANY(string_to_array($1, ','))
2227
+ ORDER BY cl.relname, a.attnum`,
2228
+ [list]
2229
+ )
2230
+ );
2231
+ const tsRows = extractRows(
2232
+ await exec(
2233
+ `SELECT cl.relname AS table_name, a.attname AS column_name
2234
+ FROM pg_attribute a
2235
+ JOIN pg_class cl ON cl.oid = a.attrelid
2236
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
2237
+ WHERE n.nspname = 'public'
2238
+ AND cl.relname = ANY(string_to_array($1, ','))
2239
+ AND a.attnum > 0
2240
+ AND NOT a.attisdropped
2241
+ AND a.atttypid = 'timestamp'::regtype`,
2242
+ [list]
2243
+ )
2244
+ );
2245
+ const fks = /* @__PURE__ */ new Map();
2246
+ for (const raw of fkRows) {
2247
+ const r = raw ?? {};
2248
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
2249
+ continue;
2250
+ }
2251
+ fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
2252
+ }
2253
+ const timestamps = /* @__PURE__ */ new Map();
2254
+ for (const raw of tsRows) {
2255
+ const r = raw ?? {};
2256
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
2257
+ timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
2258
+ }
2259
+ for (const table of tables) {
2260
+ tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
2261
+ }
2262
+ } catch (err) {
2263
+ metaRetryAt = Date.now() + META_RETRY_MS;
2264
+ logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
2265
+ }
2266
+ }
2267
+ function relatedResourceIds(table, row) {
2268
+ const out = [];
2269
+ for (const fk of tableMeta.get(table)?.fks ?? []) {
2270
+ const value = row[fk.column];
2271
+ if (typeof value === "string" || typeof value === "number") {
2272
+ out.push({ resource_type: fk.refTable, resource_id: String(value) });
2273
+ }
2274
+ }
2275
+ return out;
2276
+ }
2092
2277
  function emitFresh(rows) {
2093
2278
  if (rows.length === 0) return;
2094
2279
  const emitted = currentEmittedAuditIds();
@@ -2125,8 +2310,10 @@ function sortById(rows) {
2125
2310
  function emitOne(row) {
2126
2311
  const op = mapOp(row.op);
2127
2312
  if (!op) return;
2128
- const oldRow = coerceJsonb(row.old_row);
2129
- const newRow = coerceJsonb(row.new_row);
2313
+ const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
2314
+ const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
2315
+ const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
2316
+ const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
2130
2317
  if (op === "create" && newRow) {
2131
2318
  emitDbEvent({
2132
2319
  modelClass: row.table_name,
@@ -2136,6 +2323,7 @@ function emitOne(row) {
2136
2323
  modelInstance: newRow,
2137
2324
  displayName: null,
2138
2325
  timestamp: row.captured_at ?? null,
2326
+ relatedResourceIds: related,
2139
2327
  _fromTrigger: true
2140
2328
  });
2141
2329
  return;
@@ -2155,6 +2343,7 @@ function emitOne(row) {
2155
2343
  modelInstance: newRow,
2156
2344
  displayName: null,
2157
2345
  timestamp: row.captured_at ?? null,
2346
+ relatedResourceIds: related,
2158
2347
  _fromTrigger: true
2159
2348
  });
2160
2349
  return;
@@ -2168,11 +2357,22 @@ function emitOne(row) {
2168
2357
  modelInstance: oldRow,
2169
2358
  displayName: null,
2170
2359
  timestamp: row.captured_at ?? null,
2360
+ relatedResourceIds: related,
2171
2361
  _fromTrigger: true
2172
2362
  });
2173
2363
  return;
2174
2364
  }
2175
2365
  }
2366
+ var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
2367
+ function withUtcTimestamps(row, naiveColumns) {
2368
+ if (!row) return row;
2369
+ const out = {};
2370
+ for (const [key, value] of Object.entries(row)) {
2371
+ const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
2372
+ out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
2373
+ }
2374
+ return out;
2375
+ }
2176
2376
  function mapOp(op) {
2177
2377
  if (op === "INSERT") return "create";
2178
2378
  if (op === "UPDATE") return "update";
@@ -2306,6 +2506,7 @@ function classifyUserAgent(userAgent) {
2306
2506
 
2307
2507
  // src/http/capture.ts
2308
2508
  init_correlation();
2509
+ init_sanitize();
2309
2510
 
2310
2511
  // src/http/path-matcher.ts
2311
2512
  function pathMatches(path, pattern) {
@@ -2491,7 +2692,7 @@ function compact(obj) {
2491
2692
  }
2492
2693
  return out;
2493
2694
  }
2494
- function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2695
+ function determineOutcome(statusCode, exception, graphqlResponseErrors, responseError = null) {
2495
2696
  if (exception) {
2496
2697
  return {
2497
2698
  outcome: "failure",
@@ -2499,7 +2700,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2499
2700
  };
2500
2701
  }
2501
2702
  if (statusCode !== null && statusCode >= 400) {
2502
- return { outcome: "failure", error_message: `HTTP ${statusCode}` };
2703
+ return { outcome: "failure", error_message: responseError ?? `HTTP ${statusCode}` };
2503
2704
  }
2504
2705
  if (graphqlResponseErrors) {
2505
2706
  return { outcome: "failure", error_message: graphqlResponseErrors };
@@ -2593,6 +2794,7 @@ function captureRoute(handler, context = {}) {
2593
2794
  }
2594
2795
  const snapshot = await snapshotRequest(request);
2595
2796
  if (snapshot === null) return Promise.resolve(runHandler(...args));
2797
+ snapshot.rawParams = mergeRouteParams(snapshot.rawParams, await readRouteParams(args[1]));
2596
2798
  const correlationId = resolveCorrelation(request.headers ?? null);
2597
2799
  return await runWithCorrelation(
2598
2800
  correlationId,
@@ -2603,15 +2805,23 @@ function captureRoute(handler, context = {}) {
2603
2805
  let response = null;
2604
2806
  let exception = null;
2605
2807
  let graphqlErrorMessage = null;
2808
+ let responseErrorMessage = null;
2606
2809
  try {
2607
2810
  response = await Promise.resolve(runHandler(...args));
2608
2811
  statusCode = response.status;
2609
2812
  if (snapshot.graphqlBody !== null && response.status === 200) {
2610
2813
  graphqlErrorMessage = await readGraphqlErrors(response);
2611
2814
  }
2815
+ responseErrorMessage = await readResponseErrorMessage(response);
2612
2816
  return response;
2613
2817
  } catch (e) {
2818
+ const controlStatus = nextControlFlowStatus(e);
2819
+ if (controlStatus !== null) {
2820
+ statusCode = controlStatus;
2821
+ throw e;
2822
+ }
2614
2823
  exception = e instanceof Error ? e : new Error(String(e));
2824
+ statusCode = 500;
2615
2825
  throw e;
2616
2826
  } finally {
2617
2827
  await maybeExtractSupabaseActor();
@@ -2621,6 +2831,7 @@ function captureRoute(handler, context = {}) {
2621
2831
  statusCode,
2622
2832
  exception,
2623
2833
  graphqlErrorMessage,
2834
+ responseErrorMessage,
2624
2835
  durationMs: Date.now() - startMs,
2625
2836
  startedAt: new Date(startMs)
2626
2837
  });
@@ -2844,7 +3055,10 @@ function captureServerAction(action, actionName) {
2844
3055
  const failure = classifyServerActionResult(result);
2845
3056
  await emitServerActionEvent({
2846
3057
  actionName,
2847
- statusCode: failure ? 500 : 200,
3058
+ // A returned failure (`{ success: false, error }`) is a
3059
+ // handled refusal, not a crash: no HTTP status is
3060
+ // invented; outcome + error_message carry it.
3061
+ statusCode: failure ? null : 200,
2848
3062
  exception: failure ? new Error(failure.errorMessage) : null,
2849
3063
  durationMs: Date.now() - startMs,
2850
3064
  startedAt,
@@ -2854,9 +3068,12 @@ function captureServerAction(action, actionName) {
2854
3068
  } catch (e) {
2855
3069
  if (isNextControlFlowError(e)) {
2856
3070
  await maybeExtractSupabaseActor();
3071
+ const controlStatus = nextControlFlowStatus(e) ?? 200;
2857
3072
  await emitServerActionEvent({
2858
3073
  actionName,
2859
- statusCode: 200,
3074
+ // redirect() is a success; notFound() / forbidden()
3075
+ // keep their 4xx.
3076
+ statusCode: controlStatus >= 400 ? controlStatus : 200,
2860
3077
  exception: null,
2861
3078
  durationMs: Date.now() - startMs,
2862
3079
  startedAt,
@@ -3038,10 +3255,23 @@ function conformErrorMessage(result) {
3038
3255
  return "Form submission failed";
3039
3256
  }
3040
3257
  function isNextControlFlowError(error) {
3041
- if (!error || typeof error !== "object") return false;
3258
+ return nextControlFlowStatus(error) !== null;
3259
+ }
3260
+ function nextControlFlowStatus(error) {
3261
+ if (!error || typeof error !== "object") return null;
3042
3262
  const digest = error.digest;
3043
- if (typeof digest !== "string") return false;
3044
- return digest.startsWith("NEXT_REDIRECT") || digest.startsWith("NEXT_NOT_FOUND");
3263
+ if (typeof digest !== "string") return null;
3264
+ const parts = digest.split(";");
3265
+ if (parts[0] === "NEXT_REDIRECT") {
3266
+ const status = Number(parts[3]);
3267
+ return status >= 300 && status < 400 ? status : 307;
3268
+ }
3269
+ if (parts[0] === "NEXT_NOT_FOUND") return 404;
3270
+ if (parts[0] === "NEXT_HTTP_ERROR_FALLBACK") {
3271
+ const status = Number(parts[1]);
3272
+ return status >= 400 && status < 500 ? status : 404;
3273
+ }
3274
+ return null;
3045
3275
  }
3046
3276
  async function emitServerActionEvent(input) {
3047
3277
  try {
@@ -3063,7 +3293,7 @@ async function emitServerActionEvent(input) {
3063
3293
  rawParams: requestParams,
3064
3294
  serverActionName: input.actionName,
3065
3295
  userAgent,
3066
- remoteIp: null,
3296
+ remoteIp: extractRemoteIp(await readNextHeadersAsAdapter()),
3067
3297
  contentType: null,
3068
3298
  excludedVariableKeys: configuration().excludedGraphqlVariableKeys
3069
3299
  });
@@ -3165,18 +3395,6 @@ var PAYMENT_ACTION_WORDS = /* @__PURE__ */ new Set([
3165
3395
  function actionWords(name) {
3166
3396
  return name.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([a-zA-Z])(\d)/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
3167
3397
  }
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
3398
  function looksLikeCardNumber(digits, paymentAction) {
3181
3399
  if (digits.length < 13 || digits.length > 19 || !passesLuhn(digits)) return false;
3182
3400
  return paymentAction || digits.length === 15 || digits.length === 16;
@@ -3532,7 +3750,8 @@ async function emitEvent(input) {
3532
3750
  const { outcome, error_message } = determineOutcome(
3533
3751
  input.statusCode,
3534
3752
  input.exception,
3535
- input.graphqlErrorMessage
3753
+ input.graphqlErrorMessage,
3754
+ input.responseErrorMessage ?? null
3536
3755
  );
3537
3756
  const contextValue = buildContext2();
3538
3757
  const event = build({
@@ -3604,6 +3823,40 @@ function safeJsonParse(text) {
3604
3823
  return null;
3605
3824
  }
3606
3825
  }
3826
+ async function readRouteParams(routeContext) {
3827
+ try {
3828
+ const params = await routeContext?.params;
3829
+ if (!params || typeof params !== "object" || Array.isArray(params)) return null;
3830
+ return Object.keys(params).length > 0 ? params : null;
3831
+ } catch {
3832
+ return null;
3833
+ }
3834
+ }
3835
+ function mergeRouteParams(rawParams, routeParams) {
3836
+ if (!routeParams) return rawParams;
3837
+ if (rawParams === null || rawParams === void 0) return { ...routeParams };
3838
+ if (typeof rawParams !== "object" || Array.isArray(rawParams)) return rawParams;
3839
+ return { ...routeParams, ...rawParams };
3840
+ }
3841
+ var MAX_ERROR_BODY_LENGTH = 16384;
3842
+ async function readResponseErrorMessage(response) {
3843
+ try {
3844
+ if (response.status < 400) return null;
3845
+ if (!(response.headers.get("content-type") ?? "").includes("json")) return null;
3846
+ if (Number(response.headers.get("content-length") ?? 0) > MAX_ERROR_BODY_LENGTH) return null;
3847
+ const text = await response.clone().text();
3848
+ if (!text || text.length > MAX_ERROR_BODY_LENGTH) return null;
3849
+ const body = safeJsonParse(text);
3850
+ if (!body || typeof body !== "object") return null;
3851
+ const nested = body.error;
3852
+ const raw = [body.error, body.message, nested?.message].find(
3853
+ (v) => typeof v === "string" && v.trim().length > 0
3854
+ );
3855
+ return raw ? truncate(scrubSecretsInText(raw.trim(), { emails: true })) : null;
3856
+ } catch {
3857
+ return null;
3858
+ }
3859
+ }
3607
3860
  async function readGraphqlErrors(response) {
3608
3861
  try {
3609
3862
  const cloned = response.clone();