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