vibecode-anything 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,1839 @@
1
+ /**
2
+ * Zero-dependency, linear-time (ReDoS-safe) security helpers shared across
3
+ * discovery, lock integrity, and diagnostics: secret/vault redaction and
4
+ * cross-platform path/vault/secret-file containment checks.
5
+ */
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ export const VALID_DOMAINS = new Set(["cli", "web", "image", "video", "api", "repo"]);
10
+ export const ANSI = {
11
+ reset: "\x1b[0m",
12
+ bold: "\x1b[1m",
13
+ dim: "\x1b[2m",
14
+ red: "\x1b[31m",
15
+ green: "\x1b[32m",
16
+ yellow: "\x1b[33m",
17
+ cyan: "\x1b[36m"
18
+ };
19
+ export function styleAnsi(text, codes, useColor) {
20
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
21
+ }
22
+ export const FORBIDDEN_OBJECT_KEYS = new Set(["__proto__", "constructor", "prototype"]);
23
+ export function isForbiddenObjectKey(key) {
24
+ return typeof key === "string" && FORBIDDEN_OBJECT_KEYS.has(key);
25
+ }
26
+ const ASCII_UPPER_RE = /[A-Z]+/g;
27
+ /** Strictly length-preserving ASCII-only lowercase (`A-Z` -> `a-z`), immune to Unicode expansion (e.g. Turkish `İ`). */
28
+ export function asciiLower(value) {
29
+ if (typeof value !== "string" || !value)
30
+ return "";
31
+ return value.replace(ASCII_UPPER_RE, (m) => m.toLowerCase());
32
+ }
33
+ /** Expands leading `~`, `~/`, or `~\` against `os.homedir()`. */
34
+ export function expandLeadingTilde(rawPath) {
35
+ if (typeof rawPath !== "string")
36
+ return "";
37
+ if (rawPath === "~")
38
+ return os.homedir();
39
+ if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) {
40
+ return path.join(os.homedir(), rawPath.slice(2));
41
+ }
42
+ return rawPath;
43
+ }
44
+ // eslint-disable-next-line no-control-regex
45
+ const TERMINAL_STRING_SEQ_RE = /(?:\x1b[\]PX^_]|[\x90\x98\x9d\x9e\x9f])[^\x07\x1b\x9c\r\n]*(?:\x07|\x1b\\|\x9c)?/g;
46
+ // eslint-disable-next-line no-control-regex
47
+ const TERMINAL_CSI_RE = /(?:\x1b\[|\x9b)[0-?]{0,64}[ -/]{0,16}[@-~]/g;
48
+ // eslint-disable-next-line no-control-regex
49
+ const TERMINAL_ESC_OTHER_RE = /\x1b[ -/]{0,4}[0-~]/g;
50
+ // eslint-disable-next-line no-control-regex
51
+ const C1_CONTROL_RE = /[\x80-\x9f]/;
52
+ // eslint-disable-next-line no-control-regex
53
+ const HAS_UNSAFE_TERMINAL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
54
+ // eslint-disable-next-line no-control-regex
55
+ const UNSAFE_TERMINAL_CONTROLS_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]+/g;
56
+ // eslint-disable-next-line no-control-regex
57
+ const UNSAFE_PATH_CONTROL_RE = /[\x00-\x1f\x7f]/;
58
+ // C0/DEL/C1 controls, Unicode line separators, and bidi overrides.
59
+ // eslint-disable-next-line no-control-regex
60
+ export const STRICT_CONTROL_CHARS_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
61
+ // HTTP header values allow SP (0x20) and HTAB (0x09) but never NUL, CR, LF, other C0, DEL, C1, or bidi.
62
+ // eslint-disable-next-line no-control-regex
63
+ export const HEADER_VALUE_UNSAFE_RE = /[\x00-\x08\x0a-\x1f\x7f-\x9f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
64
+ export const HTTP_HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
65
+ export const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
66
+ export const USERINFO_IN_FIRST_SEG_RE = /^\/[^/?#]*@/;
67
+ /**
68
+ * Strictly O(N) linear-time stripper for ANSI CSI/OSC/DCS/APC/PM/SOS, standalone ESC,
69
+ * 8-bit C1 controls, C0 non-whitespace controls, and Trojan Source Unicode bidi/line overrides.
70
+ */
71
+ export function stripTerminalEscapes(value) {
72
+ let out = typeof value === "string" ? value : String(value ?? "");
73
+ if (!out || !HAS_UNSAFE_TERMINAL_RE.test(out))
74
+ return out;
75
+ if (out.includes("\x1b") || C1_CONTROL_RE.test(out)) {
76
+ out = out.replace(TERMINAL_STRING_SEQ_RE, "");
77
+ out = out.replace(TERMINAL_CSI_RE, "");
78
+ out = out.replace(TERMINAL_ESC_OTHER_RE, "");
79
+ }
80
+ return out.replace(UNSAFE_TERMINAL_CONTROLS_RE, "");
81
+ }
82
+ const UNC_OR_DEVICE_PATH_RE = /^[\\/]{2}/;
83
+ const WINDOWS_DRIVE_RELATIVE_RE = /^[A-Za-z]:(?![\\/])/;
84
+ const WINDOWS_DRIVE_ANY_RE = /^[A-Za-z]:/;
85
+ const WINDOWS_DRIVE_ABS_RE = /^[A-Za-z]:[\\/]/;
86
+ const TRIVIAL_DRIVE_ROOT_RE = /^[A-Za-z]:[\\/]*$/;
87
+ const TOKEN_RE = /[^\s"'`<>()[\]{}=]+/g;
88
+ const HOLDOUT_FILENAME_RE = /^holdouts?(?:-[a-z0-9._-]+)?\.json(?:\.tmp)?$/i;
89
+ const HOLDOUT_TOKEN_RE = /(?:^|[\\/_])holdouts?(?:-[a-z0-9._-]{1,64})?\.json(?:\.tmp)?(?:$|[?#:,;.])|\bholdouts?(?:-[a-z0-9._-]{1,64})?\.json(?:\.tmp)?\b/i;
90
+ const SENSITIVE_HEADER_NAME_RE = /(?:authorization|proxy[-_]?authorization|www[-_]?authenticate|proxy[-_]?authenticate|authentication|cookie|set[-_]?cookie|api[-_]?key|apikey|token(?!s(?:$|[a-z0-9_.\-\[\]])|iz(?:e|ed|es|ing|er|ers|ation)|[_.\-]?(?:counts?|limits?|usage|budget|rate)(?:$|[_.\-\[\]0-9]))|(?:^tokens$|(?:auth|access|refresh|id|session|bearer|api|csrf|xsrf|secret|oauth|jwt)[-_.]?tokens(?=$|[-_.]))|secret|bearer|csrf|xsrf|password|passwd|passphrase|credential|private[-_]?key|session(?:[-_]?id)?|jwt|hmac|signature|signing[-_]?key|webhook[-_]?secret|(?:^|[-_])auth(?:[-_](?:tokens?|key|secret|header|code|ticket|credential))?$|(?:^|[-_])sig(?:$|[-_]))/i;
91
+ const SENSITIVE_QUERY_PARAM_NAME_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|key|x[-_]api[-_]key|x[-_]auth[-_]token|secret|client[_-]?secret|password|passwd|passphrase|auth|jwt|session[_-]?(?:id|token)|sig|signature|private[_-]?key|csrf[_-]?token|xsrf[_-]?token|secret[_-]?key|access[_-]?key|cookie|set[_-]?cookie|authorization|bearer|credential|x-[a-z0-9-]{0,32}(?:key|token|secret|auth|csrf|xsrf))$/i;
92
+ export const SENSITIVE_KEY_NAME_RE = /(?:secret|token(?!s(?:$|[a-z0-9_.\-\[\]])|iz(?:e|ed|es|ing|er|ers|ation)|[_.\-]?(?:counts?|limits?|usage|budget|rate)(?:$|[_.\-\[\]0-9]))|(?:^tokens$|(?:auth|access|refresh|id|session|bearer|api|csrf|xsrf|secret|oauth|jwt)[_.\-]?tokens(?=$|[_.\-\[\]]))|password|passwd|passphrase|authorization|authentication|cookie|session|jwt|api[_-]?key|apikey|private[_-]?key|signing[_-]?key|webhook[_-]?secret|csrf|xsrf|cred(?:ential)?|auth[_-]?(?:header|key|code|ticket|user|pass))|(?:^|[_.\-[\]])(?:auth|sid|sig|signature)$|(?:^|[_.\-[\]])(?:sid|sig|signature)[_.\-[\]]|^x-[a-z0-9-]{0,24}(?:key|tokens?|secret|auth)$/i;
93
+ export function isSensitiveHeaderName(name) {
94
+ if (typeof name !== "string")
95
+ return false;
96
+ const cleaned = stripTerminalEscapes(name).trim();
97
+ if (!cleaned)
98
+ return false;
99
+ return SENSITIVE_HEADER_NAME_RE.test(cleaned);
100
+ }
101
+ export function isSensitiveQueryParamName(name) {
102
+ if (typeof name !== "string")
103
+ return false;
104
+ const cleaned = stripTerminalEscapes(name).trim();
105
+ if (!cleaned)
106
+ return false;
107
+ return SENSITIVE_QUERY_PARAM_NAME_RE.test(cleaned);
108
+ }
109
+ export function isSensitiveKeyName(name) {
110
+ if (typeof name !== "string")
111
+ return false;
112
+ const cleaned = stripTerminalEscapes(name).trim();
113
+ if (!cleaned)
114
+ return false;
115
+ return SENSITIVE_KEY_NAME_RE.test(cleaned);
116
+ }
117
+ const VAULT_ENV_ASSIGN_RE = /(\bVIBECODE_VAULT_DIR\b[ \t]*[:=][ \t]*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s'",;})&#]+)/gi;
118
+ const URL_USERINFO_RE = /(\b[a-z][a-z0-9+.-]{0,24}:\/\/)([^@\s"'`<>/?#]{1,512})(@)/gi;
119
+ const BARE_USERPASS_RE = /(^|[\s"'`(<\[=])([A-Za-z0-9._~%-]{1,64}:[^@\s"'`<>\/()[\]{}=,;]{1,128})(@[A-Za-z0-9.-]+)/g;
120
+ const SENSITIVE_QUERY_PARAM_RE = /([?&](?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|key|x[-_]api[-_]key|x[-_]auth[-_]token|secret|client[_-]?secret|password|passwd|auth|jwt|session[_-]?id|sig|signature|private[_-]?key)=)([^&#\s"'`<>]+)/gi;
121
+ const SENSITIVE_JSON_FIELD_RE = /(["']\b(?:authorization|proxy-authorization|set-cookie|cookie|x-[a-z0-9-]{0,24}(?:key|token|secret|auth)|api[_-]?key|apikey|secret|client[_-]?secret|token|jwt|access[_-]?token|refresh[_-]?token|id[_-]?token|password|passwd|private[_-]?key|session[_-]?id)\b["'][ \t]*[:=][ \t]*["'])((?:\\[^\r\n]|[^"'\\\r\n])+)(["'])/gi;
122
+ const SENSITIVE_COOKIE_RE = /("[ \t]{0,8}\b(?:set-cookie|cookie)\b[ \t]*[:=][ \t]*)(?:\\[^\r\n]|="[^"\r\n]*"?|=(?!")|[^"=\\\r\n])+|('[ \t]{0,8}\b(?:set-cookie|cookie)\b[ \t]*[:=][ \t]*)(?:\\[^\r\n]|='[^'\r\n]*'?|=(?!')|[^'=\\\r\n])+|(\b(?:set-cookie|cookie)\b[ \t]*[:=][ \t]*)[^\r\n}]+/gi;
123
+ const QUOTED_SENSITIVE_HEADER_RE = /("[ \t]{0,8}\b(?:authorization|proxy-authorization|x-[a-z0-9-]{0,24}(?:key|token|secret|auth))\b[ \t]*[:=][ \t]*)(?:\\[^\r\n]|="[^"\r\n]*"?|=(?!")|[^"=\\\r\n])+|('[ \t]{0,8}\b(?:authorization|proxy-authorization|x-[a-z0-9-]{0,24}(?:key|token|secret|auth))\b[ \t]*[:=][ \t]*)(?:\\[^\r\n]|='[^'\r\n]*'?|=(?!')|[^'=\\\r\n])+/gi;
124
+ const SENSITIVE_HEADER_VALUE_RE = /(\b(?:authorization|proxy-authorization|x-[a-z0-9-]{0,24}(?:key|token|secret|auth)|api[_-]?key|apikey|client[_-]?secret|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?id|password|passwd|secret)\b[ \t]*[:=][ \t]*)(?:"[^"\r\n]*"|'[^'\r\n]*'|(?:(?:bearer|basic|token|digest|apikey)[ \t]+)?[^\s'",;})&#]+)/gi;
125
+ const SENSITIVE_ENV_KEYWORD_RE = /secret|token|password|passwd|api_?key|private_?key|auth_?key|access_?key|signing_?key|session_?key|jwt|credential/i;
126
+ const SENSITIVE_ENV_ASSIGN_RE = /(\b[A-Z0-9_]{0,48}(?:SECRET|TOKEN|PASSWORD|PASSWD|API_?KEY|PRIVATE_?KEY|AUTH_?KEY|CLIENT_?SECRET|ACCESS_?KEY|SIGNING_?KEY|SESSION_?KEY|JWT|CREDENTIAL)[A-Z0-9_]{0,32}[ \t]*[:=][ \t]*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s"'`;|&},)#]+)/gi;
127
+ const DIGEST_AUTH_RE = /(\bDigest[ \t]+)(?:[A-Za-z0-9_]{1,32}=(?:"[^"\r\n]*"|[^\s,;]+)(?:[ \t]*,[ \t]*[A-Za-z0-9_]{1,32}=(?:"[^"\r\n]*"|[^\s,;]+))*|[A-Za-z0-9._~+/=-]{3,})/gi;
128
+ const AUTH_SCHEME_TOKEN_RE = /(\b(?:Bearer|Basic|Token|ApiKey)[ \t]+)(?:[^:\s"'`<>]{1,128}:[^\s"'`<>]{1,256}|[A-Za-z0-9._~+/=-]{3,})/gi;
129
+ const STANDALONE_API_KEY_RE = /(?<![A-Za-z0-9])(?:sk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{12,}|(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{10,}|whsec_[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{12,}|github_pat_[A-Za-z0-9_]{20,}|AIza[0-9A-Za-z_-]{20,}|A(?:KIA|SIA)[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,}|glpat-[A-Za-z0-9_-]{12,}|eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,})(?![A-Za-z0-9])/g;
130
+ const ENCODED_URL_USERINFO_RE = /(\b[a-z][a-z0-9+.-]{0,24}%3[aA]%2[fF]%2[fF])([^\s"'`<>/?#@]{1,512})(%40)/gi;
131
+ const ENCODED_QUERY_PARAM_RE = /((?:%3[fF]|%26|[?&])(?:access(?:[_-]|%5[fF])?token|id(?:[_-]|%5[fF])?token|refresh(?:[_-]|%5[fF])?token|auth(?:[_-]|%5[fF])?token|token|api(?:[_-]|%5[fF])?key|apikey|key|x(?:[-_]|%5[fF])api(?:[-_]|%5[fF])key|x(?:[-_]|%5[fF])auth(?:[-_]|%5[fF])token|secret|client(?:[_-]|%5[fF])?secret|password|passwd|auth|jwt|session(?:[_-]|%5[fF])?id|sig|signature|private(?:[_-]|%5[fF])?key)%3[dD])([^\s"'`<>&#]+)/gi;
132
+ const ENCODED_AUTH_SCHEME_RE = /(\b(?:Bearer|Basic|Token|ApiKey)%20)([^\s"'`<>&#]+)/gi;
133
+ const ENCODED_DELIM_RE = /%(?:26|23|20|0[ad]|22|27|3b|2c)/i;
134
+ const ENCODED_QUERY_DELIM_RE = /%(?:26|23|20|0[ad]|22|27)/i;
135
+ const ENCODED_SEGMENT_RE = /[^\s"'`<>()[\]{}=&#?]+/g;
136
+ const MAX_PERCENT_DECODE_BUDGET = 262_144;
137
+ const ENV_EXAMPLE_NAMES = new Set([".env.example", ".env.sample", ".env.template"]);
138
+ const SECRET_EXACT_NAMES = new Set([
139
+ ".envrc", ".npmrc", ".pypirc", ".netrc", ".htpasswd",
140
+ "id_rsa", "id_ed25519", "id_dsa", "id_ecdsa",
141
+ "credentials.json", "service-account.json",
142
+ "secrets.json", "secrets.yaml", "secrets.yml", "secrets.toml", "token.json"
143
+ ]);
144
+ const SECRET_FILE_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".crt"]);
145
+ /** Fast lowercase + backslash-to-slash normalizer (native V8 C++ ops, zero per-char JS callbacks). */
146
+ function fastLowerSlash(value) {
147
+ const lowered = value.toLowerCase();
148
+ return lowered.includes("\\") ? lowered.replaceAll("\\", "/") : lowered;
149
+ }
150
+ /** ASCII-only lowercase + backslash-to-slash preserving exact UTF-16 indices (used when splicing spaced vault prefixes). */
151
+ function asciiLowerSlashExact(value) {
152
+ const lowered = asciiLower(value);
153
+ return lowered.includes("\\") ? lowered.replaceAll("\\", "/") : lowered;
154
+ }
155
+ function isTrivialVaultPath(raw) {
156
+ const trimmed = raw.trim();
157
+ if (!trimmed || UNSAFE_PATH_CONTROL_RE.test(trimmed))
158
+ return true;
159
+ if (/^[\\/]+$/.test(trimmed) || TRIVIAL_DRIVE_ROOT_RE.test(trimmed))
160
+ return true;
161
+ const noTrailing = trimmed.replace(/[\\/]+$/, "");
162
+ if (noTrailing.length < 3 || noTrailing === "." || noTrailing === "..")
163
+ return true;
164
+ if (path.parse(noTrailing).root === noTrailing)
165
+ return true;
166
+ const expanded = expandLeadingTilde(noTrailing);
167
+ const abs = path.resolve(expanded);
168
+ if (abs === path.parse(abs).root)
169
+ return true;
170
+ if ((noTrailing === "~" || noTrailing.startsWith("~/") || noTrailing.startsWith("~\\")) && abs === path.resolve(os.homedir())) {
171
+ return true;
172
+ }
173
+ return false;
174
+ }
175
+ let cachedVault = null;
176
+ function getActiveVaultPrefixes(rawEnvVault) {
177
+ const envVault = (rawEnvVault ?? process.env.VIBECODE_VAULT_DIR?.trim()) ?? "";
178
+ if (!envVault || isTrivialVaultPath(envVault)) {
179
+ cachedVault = envVault ? { envVault, cwd: "", homedir: "", prefixes: [], realResolved: true } : null;
180
+ return [];
181
+ }
182
+ const expandedEnv = expandLeadingTilde(envVault);
183
+ const homedir = os.homedir();
184
+ const cwd = path.isAbsolute(expandedEnv) ? "" : process.cwd();
185
+ if (cachedVault &&
186
+ cachedVault.envVault === envVault &&
187
+ cachedVault.cwd === cwd &&
188
+ cachedVault.homedir === homedir &&
189
+ cachedVault.realResolved) {
190
+ return cachedVault.prefixes;
191
+ }
192
+ const out = new Set();
193
+ const addVariant = (candidate) => {
194
+ if (!candidate || isTrivialVaultPath(candidate))
195
+ return;
196
+ out.add(asciiLowerSlashExact(candidate.trim().replace(/[\\/]+$/, "")));
197
+ };
198
+ addVariant(envVault);
199
+ addVariant(expandedEnv);
200
+ const absVault = path.resolve(expandedEnv);
201
+ addVariant(absVault);
202
+ const viaAncestor = resolvePathViaExistingAncestor(absVault);
203
+ if (viaAncestor)
204
+ addVariant(viaAncestor);
205
+ let realResolved = false;
206
+ try {
207
+ if (fs.existsSync(absVault)) {
208
+ try {
209
+ if (fs.lstatSync(absVault).isSymbolicLink()) {
210
+ const linkTarget = fs.readlinkSync(absVault);
211
+ addVariant(path.resolve(path.dirname(absVault), linkTarget));
212
+ }
213
+ }
214
+ catch {
215
+ // ignore readlink failure
216
+ }
217
+ addVariant(fs.realpathSync(absVault));
218
+ realResolved = true;
219
+ }
220
+ }
221
+ catch {
222
+ // ignore inaccessible vault path
223
+ }
224
+ const prefixes = [...out].sort((a, b) => b.length - a.length);
225
+ cachedVault = { envVault, cwd, homedir, prefixes, realResolved };
226
+ return prefixes;
227
+ }
228
+ function redactSpacedVaultPrefixes(text, spacedPrefixes, vaultToken = "[REDACTED_VAULT]") {
229
+ let current = text;
230
+ for (const needle of spacedPrefixes) {
231
+ const normalized = asciiLowerSlashExact(current);
232
+ let idx = normalized.indexOf(needle);
233
+ if (idx === -1)
234
+ continue;
235
+ let out = "";
236
+ let cursor = 0;
237
+ while (idx !== -1) {
238
+ out += current.slice(cursor, idx) + vaultToken;
239
+ let end = idx + needle.length;
240
+ while (end < current.length && !/[\s"'`<>()[\]{}=]/.test(current[end]))
241
+ end++;
242
+ cursor = end;
243
+ idx = normalized.indexOf(needle, cursor);
244
+ }
245
+ out += current.slice(cursor);
246
+ current = out;
247
+ }
248
+ return current;
249
+ }
250
+ function hexVal(code) {
251
+ if (code >= 48 && code <= 57)
252
+ return code - 48;
253
+ if (code >= 65 && code <= 70)
254
+ return code - 55;
255
+ if (code >= 97 && code <= 102)
256
+ return code - 87;
257
+ return -1;
258
+ }
259
+ /** O(N) exception-free percent decoder that tolerates malformed `%` sequences. */
260
+ function safePercentDecode(raw) {
261
+ const first = raw.indexOf("%");
262
+ if (first === -1)
263
+ return raw;
264
+ const len = raw.length;
265
+ const parts = [];
266
+ let cursor = 0;
267
+ let i = first;
268
+ while (i !== -1) {
269
+ if (i + 2 < len) {
270
+ const hi = hexVal(raw.charCodeAt(i + 1));
271
+ const lo = hexVal(raw.charCodeAt(i + 2));
272
+ if (hi !== -1 && lo !== -1) {
273
+ if (i > cursor)
274
+ parts.push(raw.slice(cursor, i));
275
+ const byte = (hi << 4) | lo;
276
+ if (byte < 0x80) {
277
+ parts.push(String.fromCharCode(byte));
278
+ i += 3;
279
+ }
280
+ else {
281
+ const bytes = [byte];
282
+ i += 3;
283
+ while (i + 2 < len && raw.charCodeAt(i) === 37) {
284
+ const h2 = hexVal(raw.charCodeAt(i + 1));
285
+ const l2 = hexVal(raw.charCodeAt(i + 2));
286
+ if (h2 === -1 || l2 === -1)
287
+ break;
288
+ const b2 = (h2 << 4) | l2;
289
+ if (b2 < 0x80)
290
+ break;
291
+ bytes.push(b2);
292
+ i += 3;
293
+ }
294
+ parts.push(Buffer.from(bytes).toString("utf8"));
295
+ }
296
+ cursor = i;
297
+ i = raw.indexOf("%", cursor);
298
+ continue;
299
+ }
300
+ }
301
+ i = raw.indexOf("%", i + 1);
302
+ }
303
+ if (cursor === 0)
304
+ return raw;
305
+ if (cursor < len)
306
+ parts.push(raw.slice(cursor));
307
+ return parts.join("");
308
+ }
309
+ function redactEncodedVaultPrefixes(text, vaultPrefixes, vaultToken = "[REDACTED_VAULT]") {
310
+ if (vaultPrefixes.length === 0 || !text.includes("%"))
311
+ return text;
312
+ const needles = new Set();
313
+ const addEnc = (candidate) => {
314
+ try {
315
+ const enc = asciiLower(encodeURIComponent(candidate));
316
+ if (enc.length >= 4 && enc.includes("%")) {
317
+ needles.add(enc);
318
+ if (enc.includes("%20"))
319
+ needles.add(enc.replaceAll("%20", "+"));
320
+ }
321
+ const encUri = asciiLower(encodeURI(candidate));
322
+ if (encUri.length >= 4 && encUri.includes("%"))
323
+ needles.add(encUri);
324
+ // URLSearchParams encodes `~` -> `%7e` (Windows 8.3 RUNNER~1) and space -> `+`.
325
+ const form = asciiLower(new URLSearchParams([["", candidate]]).toString().slice(1));
326
+ if (form.length >= 4 && (form.includes("%") || form.includes("+")))
327
+ needles.add(form);
328
+ }
329
+ catch {
330
+ // ignore lone surrogates
331
+ }
332
+ };
333
+ for (const p of vaultPrefixes) {
334
+ addEnc(p);
335
+ if (p.includes("/"))
336
+ addEnc(p.replaceAll("/", "\\"));
337
+ }
338
+ if (needles.size === 0)
339
+ return text;
340
+ let current = text;
341
+ for (const needle of [...needles].sort((a, b) => b.length - a.length)) {
342
+ const lower = asciiLower(current);
343
+ let idx = lower.indexOf(needle);
344
+ if (idx === -1)
345
+ continue;
346
+ let out = "";
347
+ let cursor = 0;
348
+ while (idx !== -1) {
349
+ out += current.slice(cursor, idx) + vaultToken;
350
+ let end = idx + needle.length;
351
+ while (end < current.length && !/[\s"'`<>()[\]{}=&#]/.test(current[end])) {
352
+ if (current.charCodeAt(end) === 37 &&
353
+ end + 2 < current.length &&
354
+ ENCODED_QUERY_DELIM_RE.test(current.slice(end, end + 3))) {
355
+ break;
356
+ }
357
+ end++;
358
+ }
359
+ cursor = end;
360
+ idx = lower.indexOf(needle, cursor);
361
+ }
362
+ out += current.slice(cursor);
363
+ current = out;
364
+ }
365
+ return current;
366
+ }
367
+ function testGlobalRe(re, input) {
368
+ re.lastIndex = 0;
369
+ return re.test(input);
370
+ }
371
+ function redactPercentEncoded(text, vaultPrefixes, vaultToken = "[REDACTED_VAULT]") {
372
+ let out = redactEncodedVaultPrefixes(text, vaultPrefixes, vaultToken);
373
+ const lower = asciiLower(out);
374
+ if (lower.includes("%40") && lower.includes("%3a")) {
375
+ out = out.replace(ENCODED_URL_USERINFO_RE, "$1[REDACTED]$3");
376
+ }
377
+ if (lower.includes("%3d")) {
378
+ out = out.replace(ENCODED_QUERY_PARAM_RE, (_m, prefix, val) => {
379
+ const cut = val.search(ENCODED_QUERY_DELIM_RE);
380
+ return cut >= 0 ? `${prefix}[REDACTED]${val.slice(cut)}` : `${prefix}[REDACTED]`;
381
+ });
382
+ }
383
+ if (lower.includes("%20") &&
384
+ (lower.includes("bearer") || lower.includes("basic") || lower.includes("token") || lower.includes("apikey"))) {
385
+ out = out.replace(ENCODED_AUTH_SCHEME_RE, (_m, prefix, val) => {
386
+ const cut = val.search(ENCODED_DELIM_RE);
387
+ return cut >= 0 ? `${prefix}[REDACTED]${val.slice(cut)}` : `${prefix}[REDACTED]`;
388
+ });
389
+ }
390
+ let budget = MAX_PERCENT_DECODE_BUDGET;
391
+ out = out.replace(ENCODED_SEGMENT_RE, (seg) => {
392
+ if (budget <= 0 || seg.length < 10 || seg.length > 4096 || !seg.includes("%"))
393
+ return seg;
394
+ budget -= seg.length;
395
+ const decoded = stripTerminalEscapes(safePercentDecode(seg));
396
+ if (decoded === seg)
397
+ return seg;
398
+ const normDec = asciiLowerSlashExact(decoded);
399
+ const normDecForm = normDec.includes("+") ? normDec.replaceAll("+", " ") : normDec;
400
+ if (normDec.includes(".vibecode-vault") ||
401
+ (normDec.includes("holdout") && (hasVaultOrHoldoutSegment(decoded) || HOLDOUT_TOKEN_RE.test(decoded)))) {
402
+ return vaultToken;
403
+ }
404
+ for (const prefix of vaultPrefixes) {
405
+ if (normDec.includes(prefix) || normDecForm.includes(prefix))
406
+ return vaultToken;
407
+ }
408
+ if ((decoded.length >= 15 && testGlobalRe(STANDALONE_API_KEY_RE, decoded)) ||
409
+ (decoded.includes("@") && decoded.includes("://") && testGlobalRe(URL_USERINFO_RE, decoded)) ||
410
+ ((decoded.includes("=") || decoded.includes(":")) &&
411
+ (testGlobalRe(SENSITIVE_QUERY_PARAM_RE, decoded) ||
412
+ testGlobalRe(SENSITIVE_HEADER_VALUE_RE, decoded) ||
413
+ (SENSITIVE_ENV_KEYWORD_RE.test(decoded) && testGlobalRe(SENSITIVE_ENV_ASSIGN_RE, decoded)))) ||
414
+ ((decoded.includes(" ") || decoded.includes("\t")) && testGlobalRe(AUTH_SCHEME_TOKEN_RE, decoded))) {
415
+ return "[REDACTED]";
416
+ }
417
+ return seg;
418
+ });
419
+ return out;
420
+ }
421
+ function redactSensitiveTextCore(text, vaultToken) {
422
+ let out = stripTerminalEscapes(String(text ?? ""));
423
+ if (!out)
424
+ return "";
425
+ let norm = fastLowerSlash(out);
426
+ const rawEnvVault = process.env.VIBECODE_VAULT_DIR?.trim() ?? "";
427
+ if (!rawEnvVault)
428
+ cachedVault = null;
429
+ const expandedEnvVault = rawEnvVault ? expandLeadingTilde(rawEnvVault) : "";
430
+ const hasPercent = out.includes("%");
431
+ const needsVaultCheck = rawEnvVault.length > 0 &&
432
+ (norm.includes("/") ||
433
+ hasPercent ||
434
+ (!expandedEnvVault.includes("/") && !expandedEnvVault.includes("\\")));
435
+ const vaultPrefixes = needsVaultCheck ? getActiveVaultPrefixes(rawEnvVault) : [];
436
+ let candidateVaultPrefixes = vaultPrefixes;
437
+ if (vaultPrefixes.length > 0 && norm.includes("//")) {
438
+ const expanded = new Set(vaultPrefixes);
439
+ const hasQuad = norm.includes("////");
440
+ for (const p of vaultPrefixes) {
441
+ if (p.includes("/")) {
442
+ expanded.add(p.replaceAll("/", "//"));
443
+ if (hasQuad)
444
+ expanded.add(p.replaceAll("/", "////"));
445
+ }
446
+ }
447
+ candidateVaultPrefixes = [...expanded].sort((a, b) => b.length - a.length);
448
+ }
449
+ const matchedPrefixes = candidateVaultPrefixes.length > 0
450
+ ? candidateVaultPrefixes.filter((p) => norm.includes(fastLowerSlash(p)))
451
+ : [];
452
+ if (matchedPrefixes.length > 0) {
453
+ const spaced = matchedPrefixes.filter((p) => p.includes(" "));
454
+ if (spaced.length > 0) {
455
+ out = redactSpacedVaultPrefixes(out, spaced, vaultToken);
456
+ norm = fastLowerSlash(out);
457
+ }
458
+ }
459
+ if (norm.includes("vibecode_vault_dir")) {
460
+ out = out.replace(VAULT_ENV_ASSIGN_RE, `$1${vaultToken}`);
461
+ norm = fastLowerSlash(out);
462
+ }
463
+ const tokenPrefixes = matchedPrefixes.filter((p) => !p.includes(" ")).map(fastLowerSlash);
464
+ if (norm.includes(".vibecode-vault") || norm.includes("holdout") || tokenPrefixes.length > 0) {
465
+ out = out.replace(TOKEN_RE, (tok) => {
466
+ const normTok = fastLowerSlash(tok);
467
+ if (normTok.includes(".vibecode-vault"))
468
+ return vaultToken;
469
+ if (normTok.includes("holdout") &&
470
+ ((normTok.includes("/") && hasVaultOrHoldoutSegment(tok)) || HOLDOUT_TOKEN_RE.test(tok))) {
471
+ return vaultToken;
472
+ }
473
+ for (const prefix of tokenPrefixes) {
474
+ if (normTok.includes(prefix))
475
+ return vaultToken;
476
+ }
477
+ return tok;
478
+ });
479
+ norm = fastLowerSlash(out);
480
+ }
481
+ if (out.includes("@")) {
482
+ if (out.includes("://"))
483
+ out = out.replace(URL_USERINFO_RE, "$1[REDACTED]$3");
484
+ if (out.includes(":"))
485
+ out = out.replace(BARE_USERPASS_RE, "$1[REDACTED]$3");
486
+ }
487
+ const hasEq = out.includes("=");
488
+ const hasColon = out.includes(":");
489
+ if (hasEq || hasColon) {
490
+ if (hasEq && (out.includes("?") || out.includes("&"))) {
491
+ out = out.replace(SENSITIVE_QUERY_PARAM_RE, "$1[REDACTED]");
492
+ }
493
+ const hasQuotes = out.includes('"') || out.includes("'");
494
+ if (hasQuotes) {
495
+ out = out.replace(SENSITIVE_JSON_FIELD_RE, "$1[REDACTED]$3");
496
+ }
497
+ if (norm.includes("cookie")) {
498
+ out = out.replace(SENSITIVE_COOKIE_RE, (_match, dq, sq, bare) => `${dq ?? sq ?? bare ?? ""}[REDACTED]`);
499
+ }
500
+ if (hasQuotes && (norm.includes("authorization") || norm.includes("x-"))) {
501
+ out = out.replace(QUOTED_SENSITIVE_HEADER_RE, (_match, dq, sq) => `${dq ?? sq ?? ""}[REDACTED]`);
502
+ }
503
+ if (norm.includes("digest")) {
504
+ out = out.replace(DIGEST_AUTH_RE, "$1[REDACTED]");
505
+ }
506
+ out = out.replace(SENSITIVE_HEADER_VALUE_RE, "$1[REDACTED]");
507
+ if (SENSITIVE_ENV_KEYWORD_RE.test(out)) {
508
+ out = out.replace(SENSITIVE_ENV_ASSIGN_RE, "$1[REDACTED]");
509
+ }
510
+ }
511
+ else if (norm.includes("digest") && /digest[ \t]/i.test(out)) {
512
+ out = out.replace(DIGEST_AUTH_RE, "$1[REDACTED]");
513
+ }
514
+ if ((out.includes(" ") || out.includes("\t")) &&
515
+ (norm.includes("bearer") || norm.includes("basic") || norm.includes("token") || norm.includes("apikey"))) {
516
+ out = out.replace(AUTH_SCHEME_TOKEN_RE, "$1[REDACTED]");
517
+ }
518
+ if (out.includes("%")) {
519
+ out = redactPercentEncoded(out, vaultPrefixes, vaultToken);
520
+ }
521
+ return out.length >= 15 ? out.replace(STANDALONE_API_KEY_RE, "[REDACTED]") : out;
522
+ }
523
+ /**
524
+ * Redacts secrets, credentials, auth headers/tokens, sensitive query/env/JSON fields,
525
+ * `.vibecode-vault` paths, holdout filenames, and active `VIBECODE_VAULT_DIR` paths
526
+ * (including tilde `~/...` forms) in strict O(N) linear time (ReDoS-proof).
527
+ */
528
+ export function redactSensitiveText(text) {
529
+ return redactSensitiveTextCore(text, "[REDACTED_VAULT]");
530
+ }
531
+ /**
532
+ * Variant of `redactSensitiveText` allowing an explicit vault replacement token
533
+ * (such as `"[REDACTED_VAULT_PATH]"` for MCP responses).
534
+ */
535
+ export function redactSensitiveTextWithOptions(text, options = {}) {
536
+ return redactSensitiveTextCore(text, options.vaultToken || "[REDACTED_VAULT]");
537
+ }
538
+ /** Redacts text, strips escapes, collapses whitespace to a single line, and optionally bounds length. */
539
+ export function sanitizeSingleLine(text, maxChars) {
540
+ const stripped = stripTerminalEscapes(String(text ?? "")).trim();
541
+ if (!stripped)
542
+ return "";
543
+ const hasMax = typeof maxChars === "number" && Number.isFinite(maxChars) && maxChars > 0;
544
+ const limit = hasMax ? Math.floor(maxChars) : 0;
545
+ let bounded = stripped;
546
+ if (hasMax) {
547
+ const bufLimit = Math.max(limit + 256, 65_536);
548
+ if (bounded.length > bufLimit) {
549
+ // Collapse whitespace runs (keeping single newlines so line-scoped redactors stay intact)
550
+ // before bounding so huge space padding can never slice a secret in half at bufLimit.
551
+ bounded = bounded.replace(/[ \t]{2,}/g, " ").replace(/\r?\n[ \t\r\n]*/g, "\n").trim();
552
+ if (bounded.length > bufLimit) {
553
+ let cut = bufLimit;
554
+ while (cut > limit + 16 && !/\s/.test(bounded[cut - 1]))
555
+ cut--;
556
+ bounded = cut > limit + 16 ? bounded.slice(0, cut).trimEnd() : bounded.slice(0, bufLimit);
557
+ }
558
+ }
559
+ }
560
+ const clean = redactSensitiveText(bounded).replace(/\s+/g, " ").trim();
561
+ if (hasMax && clean.length > limit) {
562
+ return limit <= 3 ? clean.slice(0, limit) : `${clean.slice(0, limit - 3)}...`;
563
+ }
564
+ return clean;
565
+ }
566
+ /**
567
+ * Rejects NUL bytes, ASCII control chars, UNC/device paths, drive-relative paths,
568
+ * leading backslashes, Windows drive-letter paths on POSIX, and backslash-normalized
569
+ * `..` / `../` parent escapes.
570
+ */
571
+ export function hasCrossPlatformPathEscape(rawPath) {
572
+ if (typeof rawPath !== "string")
573
+ return true;
574
+ if (UNSAFE_PATH_CONTROL_RE.test(rawPath))
575
+ return true;
576
+ const raw = rawPath.trim();
577
+ if (!raw)
578
+ return false;
579
+ if (UNC_OR_DEVICE_PATH_RE.test(raw) || WINDOWS_DRIVE_RELATIVE_RE.test(raw) || raw.startsWith("\\")) {
580
+ return true;
581
+ }
582
+ if (process.platform !== "win32" && WINDOWS_DRIVE_ANY_RE.test(raw)) {
583
+ return true;
584
+ }
585
+ const isAbsLike = path.isAbsolute(raw) || WINDOWS_DRIVE_ABS_RE.test(raw);
586
+ if (!isAbsLike) {
587
+ const posixNorm = path.posix.normalize(raw.replace(/\\/g, "/"));
588
+ if (posixNorm === ".." || posixNorm.startsWith("../") || posixNorm.startsWith("/")) {
589
+ return true;
590
+ }
591
+ }
592
+ return false;
593
+ }
594
+ /**
595
+ * Checks whether `targetPath` is contained within `baseDir`, handling Windows
596
+ * case-insensitivity and cross-drive paths safely.
597
+ */
598
+ export function isPathWithinDir(targetPath, baseDir, options = {}) {
599
+ if (typeof targetPath !== "string" || typeof baseDir !== "string" || !targetPath || !baseDir)
600
+ return false;
601
+ if (UNSAFE_PATH_CONTROL_RE.test(targetPath) || UNSAFE_PATH_CONTROL_RE.test(baseDir))
602
+ return false;
603
+ const allowEqual = options.allowEqual !== false;
604
+ const resolvedBase = path.resolve(baseDir);
605
+ const resolvedTarget = path.resolve(targetPath);
606
+ const baseCmp = process.platform === "win32" ? resolvedBase.toLowerCase() : resolvedBase;
607
+ const targetCmp = process.platform === "win32" ? resolvedTarget.toLowerCase() : resolvedTarget;
608
+ const rel = path.relative(baseCmp, targetCmp);
609
+ if (rel === "")
610
+ return allowEqual;
611
+ if (path.isAbsolute(rel) || rel === ".." || rel.startsWith(`..${path.sep}`) || rel.startsWith("../")) {
612
+ return false;
613
+ }
614
+ return true;
615
+ }
616
+ /** Alias for `isPathWithinDir(targetPath, baseDir, { allowEqual: true })`. */
617
+ export function isInsideOrEqualDir(targetPath, baseDir) {
618
+ return isPathWithinDir(targetPath, baseDir, { allowEqual: true });
619
+ }
620
+ /** Checks path segments split on `/` or `\` for `.vibecode-vault`, `holdout`/`holdouts`, or `holdout(s)-*.json`. */
621
+ export function hasVaultOrHoldoutSegment(relPath) {
622
+ if (typeof relPath !== "string" || !relPath)
623
+ return false;
624
+ for (const segment of relPath.split(/[/\\]+/)) {
625
+ if (!segment)
626
+ continue;
627
+ const lower = segment.toLowerCase();
628
+ if (lower.includes(".vibecode-vault") ||
629
+ lower === "holdout" ||
630
+ lower === "holdouts" ||
631
+ HOLDOUT_FILENAME_RE.test(lower)) {
632
+ return true;
633
+ }
634
+ }
635
+ return false;
636
+ }
637
+ function collectVaultRoots() {
638
+ const roots = [];
639
+ const addRoot = (raw) => {
640
+ const expanded = expandLeadingTilde(raw.trim());
641
+ if (isTrivialVaultPath(raw) || isTrivialVaultPath(expanded))
642
+ return;
643
+ const abs = path.resolve(expanded);
644
+ if (abs === path.parse(abs).root)
645
+ return;
646
+ roots.push(abs);
647
+ const viaAncestor = resolvePathViaExistingAncestor(abs);
648
+ if (viaAncestor && viaAncestor !== abs && viaAncestor !== path.parse(viaAncestor).root) {
649
+ roots.push(viaAncestor);
650
+ }
651
+ try {
652
+ if (fs.existsSync(abs)) {
653
+ const real = fs.realpathSync(abs);
654
+ if (real !== abs && real !== path.parse(real).root)
655
+ roots.push(real);
656
+ }
657
+ }
658
+ catch {
659
+ // ignore inaccessible vault root
660
+ }
661
+ };
662
+ addRoot(path.join(os.homedir(), ".vibecode-vault"));
663
+ const envVault = process.env.VIBECODE_VAULT_DIR?.trim();
664
+ if (envVault)
665
+ addRoot(envVault);
666
+ return roots;
667
+ }
668
+ /**
669
+ * Resolves `absPath` via its deepest existing ancestor (following intermediate or dangling
670
+ * symlinks across arbitrary path depth) while rejecting symlink cycles and > `maxHops` chains.
671
+ */
672
+ export function resolvePathViaExistingAncestor(absPath, maxHops = 32) {
673
+ if (typeof absPath !== "string" || !absPath.trim() || UNSAFE_PATH_CONTROL_RE.test(absPath)) {
674
+ return null;
675
+ }
676
+ const visited = new Set();
677
+ const walk = (candidate, hopsLeft) => {
678
+ const resolved = path.resolve(candidate);
679
+ const key = process.platform === "win32" ? resolved.toLowerCase() : resolved;
680
+ if (visited.has(key) || hopsLeft < 0)
681
+ return null;
682
+ visited.add(key);
683
+ let probe = resolved;
684
+ const trailing = [];
685
+ while (true) {
686
+ let lstat;
687
+ try {
688
+ lstat = fs.lstatSync(probe);
689
+ }
690
+ catch (err) {
691
+ const code = err?.code;
692
+ if (code === "ENOENT" || code === "ENOTDIR") {
693
+ const parent = path.dirname(probe);
694
+ if (parent === probe)
695
+ return null;
696
+ trailing.push(path.basename(probe));
697
+ probe = parent;
698
+ continue;
699
+ }
700
+ return null;
701
+ }
702
+ if (lstat.isSymbolicLink()) {
703
+ let linkTarget;
704
+ try {
705
+ linkTarget = fs.readlinkSync(probe);
706
+ }
707
+ catch {
708
+ return null;
709
+ }
710
+ const nextBase = path.resolve(path.dirname(probe), linkTarget);
711
+ const nextFull = trailing.length > 0 ? path.join(nextBase, ...trailing.reverse()) : nextBase;
712
+ return walk(nextFull, hopsLeft - 1);
713
+ }
714
+ try {
715
+ const realAncestor = fs.realpathSync(probe);
716
+ return trailing.length > 0 ? path.join(realAncestor, ...trailing.reverse()) : realAncestor;
717
+ }
718
+ catch {
719
+ return null;
720
+ }
721
+ }
722
+ };
723
+ return walk(absPath, Math.max(0, Math.floor(maxHops)));
724
+ }
725
+ /**
726
+ * Returns true if `targetPath` (or its `realpathSync` / ancestor / symlink target) refers
727
+ * to a vault/holdout path or lies inside `VIBECODE_VAULT_DIR` or `~/.vibecode-vault`.
728
+ */
729
+ export function isInsideVaultDirectory(targetPath) {
730
+ if (typeof targetPath !== "string" || !targetPath.trim())
731
+ return false;
732
+ const trimmed = targetPath.trim();
733
+ if (UNSAFE_PATH_CONTROL_RE.test(trimmed))
734
+ return false;
735
+ const expanded = expandLeadingTilde(trimmed);
736
+ if (hasVaultOrHoldoutSegment(trimmed) || hasVaultOrHoldoutSegment(expanded))
737
+ return true;
738
+ const normalizedTarget = process.platform === "win32" && expanded.startsWith("\\\\?\\")
739
+ ? expanded.slice(4)
740
+ : expanded;
741
+ const resolved = path.resolve(normalizedTarget);
742
+ const candidates = new Set([resolved]);
743
+ const viaAncestor = resolvePathViaExistingAncestor(resolved);
744
+ if (viaAncestor) {
745
+ if (hasVaultOrHoldoutSegment(viaAncestor))
746
+ return true;
747
+ candidates.add(viaAncestor);
748
+ }
749
+ try {
750
+ const lstat = fs.lstatSync(resolved);
751
+ if (lstat.isSymbolicLink()) {
752
+ const linkTarget = fs.readlinkSync(resolved);
753
+ const resolvedLink = path.resolve(path.dirname(resolved), linkTarget);
754
+ if (hasVaultOrHoldoutSegment(resolvedLink))
755
+ return true;
756
+ candidates.add(resolvedLink);
757
+ const linkViaAncestor = resolvePathViaExistingAncestor(resolvedLink);
758
+ if (linkViaAncestor) {
759
+ if (hasVaultOrHoldoutSegment(linkViaAncestor))
760
+ return true;
761
+ candidates.add(linkViaAncestor);
762
+ }
763
+ }
764
+ }
765
+ catch {
766
+ // ignore missing or inaccessible target path
767
+ }
768
+ for (const vaultRoot of collectVaultRoots()) {
769
+ for (const candidate of candidates) {
770
+ if (isPathWithinDir(candidate, vaultRoot, { allowEqual: true }))
771
+ return true;
772
+ }
773
+ }
774
+ return false;
775
+ }
776
+ export function isEnvExampleFileName(baseName) {
777
+ return ENV_EXAMPLE_NAMES.has(baseName.toLowerCase());
778
+ }
779
+ /** Checks whether a relative path refers to a secret, vault/holdout, or excluded file. */
780
+ export function isSecretRelativePath(relPath, options = {}) {
781
+ if (typeof relPath !== "string" || !relPath)
782
+ return true;
783
+ const normalized = relPath.replace(/\\/g, "/");
784
+ if (hasVaultOrHoldoutSegment(normalized))
785
+ return true;
786
+ const segments = normalized.split("/");
787
+ const lastIdx = segments.length - 1;
788
+ const baseName = segments[lastIdx]?.toLowerCase() ?? "";
789
+ for (let i = 0; i < segments.length; i++) {
790
+ const seg = segments[i];
791
+ const lower = seg.toLowerCase();
792
+ if (!seg || seg === "." || seg === "..")
793
+ continue;
794
+ if (options.ignoredSegments?.has(lower))
795
+ return true;
796
+ if (lower === ".env" || lower.startsWith(".env.")) {
797
+ if (!(i === lastIdx && options.allowEnvExample && ENV_EXAMPLE_NAMES.has(lower))) {
798
+ return true;
799
+ }
800
+ }
801
+ }
802
+ if (options.allowEnvExample && ENV_EXAMPLE_NAMES.has(baseName))
803
+ return false;
804
+ if (SECRET_EXACT_NAMES.has(baseName) || baseName.includes(".secret"))
805
+ return true;
806
+ return SECRET_FILE_EXTENSIONS.has(path.posix.extname(baseName));
807
+ }
808
+ /** Rejects Windows ADS colons, leading whitespace, NTFS trailing dots/spaces, control chars, and Windows reserved device names. */
809
+ export function hasUnsafeRelativeSegment(relPath) {
810
+ if (typeof relPath !== "string")
811
+ return true;
812
+ if (STRICT_CONTROL_CHARS_RE.test(relPath))
813
+ return true;
814
+ for (const seg of relPath.split(/[/\\]+/)) {
815
+ if (!seg || seg === "." || seg === "..")
816
+ continue;
817
+ if (seg.includes(":"))
818
+ return true;
819
+ if (/^\s|[.\s]$/.test(seg))
820
+ return true;
821
+ if (WINDOWS_RESERVED_NAME_RE.test(seg))
822
+ return true;
823
+ }
824
+ return false;
825
+ }
826
+ /** Validates and normalizes a workspace-relative path, rejecting traversal, NTFS/reserved tricks, protected dirs, vault, and secrets. */
827
+ export function validateSafeWorkspaceRelPath(raw, options = {}) {
828
+ const label = options.label ?? "path";
829
+ if (typeof raw !== "string") {
830
+ return { ok: false, error: `${label}: path must be a non-empty string.` };
831
+ }
832
+ if (STRICT_CONTROL_CHARS_RE.test(raw)) {
833
+ return { ok: false, error: `${label}: path must not contain NUL or control characters.` };
834
+ }
835
+ const trimmed = raw.trim();
836
+ if (!trimmed) {
837
+ return { ok: false, error: `${label}: path must not be empty.` };
838
+ }
839
+ if (trimmed.startsWith("/") ||
840
+ trimmed.startsWith("\\") ||
841
+ path.isAbsolute(trimmed) ||
842
+ WINDOWS_DRIVE_ANY_RE.test(trimmed) ||
843
+ hasCrossPlatformPathEscape(trimmed)) {
844
+ return {
845
+ ok: false,
846
+ error: `${label}: path must be a relative path inside the workspace without traversal or drive prefixes.`
847
+ };
848
+ }
849
+ const slashNorm = trimmed.replace(/\\/g, "/");
850
+ const rawSegments = slashNorm.split("/");
851
+ const cleanSegments = [];
852
+ const blockVault = options.blockVaultOrHoldout !== false;
853
+ for (const seg of rawSegments) {
854
+ if (!seg || seg === ".")
855
+ continue;
856
+ if (seg === "..") {
857
+ return { ok: false, error: `${label}: path traversal ("..") is not allowed.` };
858
+ }
859
+ if (/^\s|[.\s]$/.test(seg)) {
860
+ return { ok: false, error: `${label}: path segments must not have leading whitespace or trailing dots/spaces.` };
861
+ }
862
+ if (seg.includes(":")) {
863
+ return { ok: false, error: `${label}: path segments must not contain ":".` };
864
+ }
865
+ if (WINDOWS_RESERVED_NAME_RE.test(seg.trim())) {
866
+ return {
867
+ ok: false,
868
+ error: `${label}: path segment ${JSON.stringify(sanitizeSingleLine(seg, 32))} is a reserved device name.`
869
+ };
870
+ }
871
+ if (blockVault && hasVaultOrHoldoutSegment(seg)) {
872
+ return { ok: false, error: `${label}: touching vault or holdout paths is not allowed.` };
873
+ }
874
+ if (options.forbiddenSegments?.has(seg.toLowerCase())) {
875
+ return { ok: false, error: `${label}: touching protected directory "${seg}" is not allowed.` };
876
+ }
877
+ cleanSegments.push(seg);
878
+ }
879
+ if (cleanSegments.length === 0) {
880
+ return { ok: false, error: `${label}: path must refer to a file or subdirectory inside the workspace, not workspace root.` };
881
+ }
882
+ const normalized = cleanSegments.join("/");
883
+ if (blockVault && hasVaultOrHoldoutSegment(normalized)) {
884
+ return { ok: false, error: `${label}: touching vault or holdout paths is not allowed.` };
885
+ }
886
+ if (options.blockSecretFiles !== false && isSecretRelativePath(normalized, { allowEnvExample: options.allowEnvExample })) {
887
+ return { ok: false, error: `${label}: touching secret or credential files is not allowed.` };
888
+ }
889
+ return { ok: true, relPath: normalized };
890
+ }
891
+ const DEFAULT_VAR_PLACEHOLDER_RE = /\{\{\s*vars\.[A-Za-z_][A-Za-z0-9_.-]{0,63}\s*\}\}/g;
892
+ /** Validates that a request path is strictly `/`-rooted on the target origin without SSRF overrides or userinfo. */
893
+ export function validateOriginRelativePath(raw, label = "path", options = {}) {
894
+ const maxLength = options.maxLength ?? 4096;
895
+ if (typeof raw !== "string") {
896
+ return { ok: false, error: `${label}: path must be a non-empty string starting with "/".` };
897
+ }
898
+ if (!raw || raw.length > maxLength) {
899
+ return { ok: false, error: `${label}: path must be between 1 and ${maxLength} characters.` };
900
+ }
901
+ if (STRICT_CONTROL_CHARS_RE.test(raw)) {
902
+ return { ok: false, error: `${label}: path must not contain control characters or CRLF.` };
903
+ }
904
+ if (!raw.startsWith("/")) {
905
+ return { ok: false, error: `${label}: path must be a relative origin path starting with "/".` };
906
+ }
907
+ if (raw.startsWith("//")) {
908
+ return { ok: false, error: `${label}: protocol-relative paths ("//...") are forbidden.` };
909
+ }
910
+ if (raw.includes("\\")) {
911
+ return { ok: false, error: `${label}: backslashes are forbidden in HTTP hook paths.` };
912
+ }
913
+ const beforeQuery = raw.split(/[?#]/, 1)[0] ?? raw;
914
+ if (beforeQuery.includes("://")) {
915
+ return { ok: false, error: `${label}: embedded URL schemes are forbidden in HTTP hook paths.` };
916
+ }
917
+ if (USERINFO_IN_FIRST_SEG_RE.test(raw)) {
918
+ return { ok: false, error: `${label}: userinfo-style "@"-delimited authority segments are forbidden.` };
919
+ }
920
+ let probe = raw;
921
+ if (options.allowVarPlaceholders !== false) {
922
+ const varRe = options.varPlaceholderRe ?? DEFAULT_VAR_PLACEHOLDER_RE;
923
+ varRe.lastIndex = 0;
924
+ probe = raw.replace(varRe, "placeholder");
925
+ }
926
+ try {
927
+ const parsed = new URL(probe, "http://fixture.invalid");
928
+ if (parsed.origin !== "http://fixture.invalid" ||
929
+ parsed.username !== "" ||
930
+ parsed.password !== "" ||
931
+ parsed.pathname.startsWith("//") ||
932
+ USERINFO_IN_FIRST_SEG_RE.test(parsed.pathname)) {
933
+ return { ok: false, error: `${label}: path must stay on the target origin without userinfo.` };
934
+ }
935
+ }
936
+ catch {
937
+ return { ok: false, error: `${label}: path is not a valid relative URL path.` };
938
+ }
939
+ return { ok: true, path: raw };
940
+ }
941
+ const EXPLICIT_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
942
+ const DISALLOWED_NO_SLASH_SCHEME_RE = /^(?:javascript|data|file|vbscript|blob|about|mailto|ftp|ftps|ws|wss|gopher):/i;
943
+ const HOST_PORT_RE = /^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\]):\d{1,5}(?:\/|$)/i;
944
+ /** Parses and validates an HTTP(S) (or optional WS/WSS) base target URL without silently rewriting non-HTTP schemes. */
945
+ export function parseSafeHttpBaseUrl(rawBase, options = {}) {
946
+ if (typeof rawBase !== "string")
947
+ throw new Error("target URL is empty");
948
+ if (STRICT_CONTROL_CHARS_RE.test(rawBase))
949
+ throw new Error("URL contains control characters");
950
+ const base = rawBase.trim();
951
+ if (!base)
952
+ throw new Error("target URL is empty");
953
+ if (/^(?:https?|wss?):\/\/\//i.test(base) ||
954
+ base.startsWith("//") ||
955
+ base.startsWith("\\")) {
956
+ throw new Error("malformed target URL");
957
+ }
958
+ const schemeEnd = base.indexOf("://");
959
+ if (schemeEnd >= 0) {
960
+ const after = base.slice(schemeEnd + 3);
961
+ const pathStart = after.search(/[/?#]/);
962
+ const authority = pathStart === -1 ? after : after.slice(0, pathStart);
963
+ if (authority.includes("\\")) {
964
+ throw new Error("malformed target URL authority");
965
+ }
966
+ }
967
+ else if (/^(?:https?|wss?):\\/i.test(base)) {
968
+ throw new Error("malformed target URL");
969
+ }
970
+ const defaultProto = options.defaultProtocol === "ws" ? "ws" : "http";
971
+ let parsed;
972
+ if (DISALLOWED_NO_SLASH_SCHEME_RE.test(base) ||
973
+ /^[a-z][a-z0-9+.-]*:\/\//i.test(base) ||
974
+ (EXPLICIT_SCHEME_RE.test(base) && !HOST_PORT_RE.test(base))) {
975
+ parsed = new URL(base);
976
+ }
977
+ else {
978
+ parsed = new URL(`${defaultProto}://${base}`);
979
+ }
980
+ const isHttp = parsed.protocol === "http:" || parsed.protocol === "https:";
981
+ const isWs = parsed.protocol === "ws:" || parsed.protocol === "wss:";
982
+ if (options.allowWs) {
983
+ if (!isHttp && !isWs) {
984
+ throw new Error(`Unsupported URL protocol "${parsed.protocol}" (only http:, https:, ws:, and wss: are allowed)`);
985
+ }
986
+ }
987
+ else if (!isHttp) {
988
+ throw new Error(`Unsupported URL protocol "${parsed.protocol}" (only http: and https: are allowed)`);
989
+ }
990
+ if (!parsed.hostname) {
991
+ throw new Error("target URL is missing a hostname");
992
+ }
993
+ return parsed;
994
+ }
995
+ /**
996
+ * Resolves `pathOrUrl` against `baseUrl` while blocking `file://`, `data:`, `javascript:`,
997
+ * `//evil`, backslash authority overrides, userinfo injection, and (by default) cross-origin redirects.
998
+ */
999
+ export function resolveSafeTargetUrl(pathOrUrl, baseUrl, options = {}) {
1000
+ if (typeof pathOrUrl !== "string")
1001
+ throw new Error("URL path must be a string");
1002
+ if (STRICT_CONTROL_CHARS_RE.test(pathOrUrl))
1003
+ throw new Error("URL contains control characters");
1004
+ const base = baseUrl instanceof URL
1005
+ ? parseSafeHttpBaseUrl(baseUrl.toString(), { allowWs: options.allowWs, defaultProtocol: options.defaultProtocol })
1006
+ : parseSafeHttpBaseUrl(baseUrl, { allowWs: options.allowWs, defaultProtocol: options.defaultProtocol });
1007
+ const trimmed = pathOrUrl.trim() || "/";
1008
+ if (trimmed.startsWith("//") || trimmed.startsWith("\\") || trimmed.startsWith("/\\")) {
1009
+ throw new Error("HTTP input.path must not use protocol-relative or backslash authority overrides");
1010
+ }
1011
+ const schemeIdx = trimmed.indexOf("://");
1012
+ if (schemeIdx >= 0) {
1013
+ const after = trimmed.slice(schemeIdx + 3);
1014
+ const pathStart = after.search(/[/?#]/);
1015
+ const authority = pathStart === -1 ? after : after.slice(0, pathStart);
1016
+ if (authority.includes("\\") || authority.includes("@")) {
1017
+ throw new Error("URL path must not include backslashes or userinfo in authority");
1018
+ }
1019
+ }
1020
+ else if (/^(?:https?|wss?):\\/i.test(trimmed)) {
1021
+ throw new Error("malformed URL path");
1022
+ }
1023
+ else if (USERINFO_IN_FIRST_SEG_RE.test(trimmed)) {
1024
+ throw new Error('URL path must not contain userinfo-style "@"-delimited first segment');
1025
+ }
1026
+ const resolved = new URL(trimmed, base);
1027
+ const isHttp = resolved.protocol === "http:" || resolved.protocol === "https:";
1028
+ const isWs = resolved.protocol === "ws:" || resolved.protocol === "wss:";
1029
+ if (options.allowWs) {
1030
+ if (!isHttp && !isWs) {
1031
+ throw new Error(`Unsupported URL protocol "${resolved.protocol}" (only http:, https:, ws:, and wss: are allowed)`);
1032
+ }
1033
+ }
1034
+ else if (!isHttp) {
1035
+ throw new Error(`Unsupported URL protocol "${resolved.protocol}" (only http: and https: are allowed)`);
1036
+ }
1037
+ if (!resolved.hostname) {
1038
+ throw new Error("Resolved URL is missing a hostname");
1039
+ }
1040
+ if (resolved.pathname.startsWith("//")) {
1041
+ throw new Error("URL path must not resolve to a protocol-relative path");
1042
+ }
1043
+ if (resolved.username !== base.username || resolved.password !== base.password) {
1044
+ throw new Error("URL path must not inject userinfo credentials");
1045
+ }
1046
+ if (USERINFO_IN_FIRST_SEG_RE.test(resolved.pathname)) {
1047
+ throw new Error('URL path must not resolve to a userinfo-style "@"-delimited segment');
1048
+ }
1049
+ if (options.allowCrossOrigin !== true && resolved.origin !== base.origin) {
1050
+ throw new Error("HTTP input.path must not redirect to a different origin than target");
1051
+ }
1052
+ if (options.normalizeWsProtocol && isHttp) {
1053
+ resolved.protocol = resolved.protocol === "https:" ? "wss:" : "ws:";
1054
+ }
1055
+ if (options.query !== undefined && isPlainObjectSafe(options.query)) {
1056
+ for (const key of Object.keys(options.query)) {
1057
+ if (isForbiddenObjectKey(key))
1058
+ continue;
1059
+ const desc = Object.getOwnPropertyDescriptor(options.query, key);
1060
+ if (!desc || !("value" in desc) || desc.value === undefined || desc.value === null)
1061
+ continue;
1062
+ const valStr = safePrimitiveToString(desc.value);
1063
+ if (valStr === null) {
1064
+ throw new Error(`Query parameter ${JSON.stringify(key)} must be a primitive value`);
1065
+ }
1066
+ if (STRICT_CONTROL_CHARS_RE.test(key) || STRICT_CONTROL_CHARS_RE.test(valStr)) {
1067
+ throw new Error("Query parameter contains control characters");
1068
+ }
1069
+ resolved.searchParams.set(key, valStr);
1070
+ }
1071
+ }
1072
+ return resolved;
1073
+ }
1074
+ // ---------------------------------------------------------------------------
1075
+ // Descriptor-safe Proxy / prototype-pollution helpers
1076
+ // ---------------------------------------------------------------------------
1077
+ export function safeIsArray(value) {
1078
+ try {
1079
+ return Array.isArray(value);
1080
+ }
1081
+ catch {
1082
+ return false;
1083
+ }
1084
+ }
1085
+ export function safeLength(arr, maxLen = Number.MAX_SAFE_INTEGER) {
1086
+ try {
1087
+ const len = arr.length;
1088
+ if (typeof len !== "number" || !Number.isFinite(len) || len <= 0)
1089
+ return 0;
1090
+ return Math.min(maxLen, Math.floor(len));
1091
+ }
1092
+ catch {
1093
+ return 0;
1094
+ }
1095
+ }
1096
+ export function isPlainObjectSafe(value) {
1097
+ if (value === null || typeof value !== "object")
1098
+ return false;
1099
+ if (safeIsArray(value))
1100
+ return false;
1101
+ try {
1102
+ const proto = Object.getPrototypeOf(value);
1103
+ return proto === Object.prototype || proto === null;
1104
+ }
1105
+ catch {
1106
+ return false;
1107
+ }
1108
+ }
1109
+ /** Proxy-safe object check accepting any non-null, non-array object (regardless of prototype). */
1110
+ export function isRecordSafe(value) {
1111
+ return value !== null && typeof value === "object" && !safeIsArray(value);
1112
+ }
1113
+ /** Own data-property read that ignores prototype pollution, never triggers getters, and catches Proxy traps. */
1114
+ export function safeOwnProp(obj, key) {
1115
+ if (!isRecordSafe(obj) || isForbiddenObjectKey(key))
1116
+ return undefined;
1117
+ try {
1118
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
1119
+ return desc && "value" in desc ? desc.value : undefined;
1120
+ }
1121
+ catch {
1122
+ return undefined;
1123
+ }
1124
+ }
1125
+ export function safeReadOwnDataProp(obj, key, label) {
1126
+ if (obj === null || obj === undefined || typeof obj !== "object") {
1127
+ return { ok: true, present: false, value: undefined };
1128
+ }
1129
+ if (isForbiddenObjectKey(key)) {
1130
+ return { ok: false, error: `${label}: forbidden property key ${JSON.stringify(sanitizeSingleLine(key, 64))}` };
1131
+ }
1132
+ try {
1133
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
1134
+ if (!desc)
1135
+ return { ok: true, present: false, value: undefined };
1136
+ if (!("value" in desc)) {
1137
+ return {
1138
+ ok: false,
1139
+ error: `${label}.${sanitizeSingleLine(key, 64)} must be a plain data property (accessor getters are not allowed)`
1140
+ };
1141
+ }
1142
+ return { ok: true, present: true, value: desc.value };
1143
+ }
1144
+ catch (err) {
1145
+ const msg = err instanceof Error ? err.message : String(err);
1146
+ return {
1147
+ ok: false,
1148
+ error: `${label}.${sanitizeSingleLine(key, 64)} could not be read safely: ${sanitizeSingleLine(msg, 160)}`
1149
+ };
1150
+ }
1151
+ }
1152
+ export function defineOwnProp(obj, key, value) {
1153
+ Object.defineProperty(obj, key, {
1154
+ value,
1155
+ enumerable: true,
1156
+ writable: true,
1157
+ configurable: true
1158
+ });
1159
+ }
1160
+ export function safeReadPlainObject(raw, label, options = {}) {
1161
+ if ((raw === undefined || raw === null) && options.allowNullish === true) {
1162
+ return { ok: true, entries: new Map() };
1163
+ }
1164
+ const policy = options.forbiddenKeyPolicy ?? "reject";
1165
+ try {
1166
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
1167
+ return { ok: false, kind: "not_plain", error: `${label}: must be a plain object.` };
1168
+ }
1169
+ const proto = Object.getPrototypeOf(raw);
1170
+ if (proto !== Object.prototype && proto !== null) {
1171
+ return { ok: false, kind: "not_plain", error: `${label}: must be a plain object.` };
1172
+ }
1173
+ const entries = new Map();
1174
+ for (const key of Object.getOwnPropertyNames(raw)) {
1175
+ if (isForbiddenObjectKey(key)) {
1176
+ if (policy === "reject") {
1177
+ return {
1178
+ ok: false,
1179
+ kind: "forbidden_key",
1180
+ key,
1181
+ error: `${label}: forbidden property key ${JSON.stringify(sanitizeSingleLine(key, 64))}.`
1182
+ };
1183
+ }
1184
+ if (policy === "skip")
1185
+ continue;
1186
+ }
1187
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
1188
+ if (!desc)
1189
+ continue;
1190
+ if (!("value" in desc)) {
1191
+ return {
1192
+ ok: false,
1193
+ kind: "accessor",
1194
+ key,
1195
+ error: `${label}.${sanitizeSingleLine(key, 64)}: accessor properties are not allowed.`
1196
+ };
1197
+ }
1198
+ if (!options.includeNonEnumerable && !desc.enumerable)
1199
+ continue;
1200
+ entries.set(key, desc.value);
1201
+ }
1202
+ return { ok: true, entries };
1203
+ }
1204
+ catch (err) {
1205
+ const msg = err instanceof Error ? err.message : String(err);
1206
+ return {
1207
+ ok: false,
1208
+ kind: "proxy_error",
1209
+ error: `${label}: object could not be read safely (${sanitizeSingleLine(msg, 160)}).`
1210
+ };
1211
+ }
1212
+ }
1213
+ export function safeReadArray(raw, label, maxItems = 10_000) {
1214
+ try {
1215
+ if (!safeIsArray(raw)) {
1216
+ return { ok: false, error: `${label}: must be an array.` };
1217
+ }
1218
+ const len = raw.length;
1219
+ if (!Number.isInteger(len) || len < 0) {
1220
+ return { ok: false, error: `${label}: invalid array length.` };
1221
+ }
1222
+ if (len > maxItems) {
1223
+ return { ok: false, error: `${label}: exceeds maximum length of ${maxItems} (got ${len}).` };
1224
+ }
1225
+ const items = [];
1226
+ for (let i = 0; i < len; i++) {
1227
+ const desc = Object.getOwnPropertyDescriptor(raw, String(i));
1228
+ if (!desc) {
1229
+ return { ok: false, error: `${label}[${i}]: sparse array holes are not allowed.` };
1230
+ }
1231
+ if (!("value" in desc)) {
1232
+ return { ok: false, error: `${label}[${i}]: accessor elements are not allowed.` };
1233
+ }
1234
+ items.push(desc.value);
1235
+ }
1236
+ return { ok: true, items };
1237
+ }
1238
+ catch (err) {
1239
+ const msg = err instanceof Error ? err.message : String(err);
1240
+ return {
1241
+ ok: false,
1242
+ error: `${label}: array could not be read safely (${sanitizeSingleLine(msg, 160)}).`
1243
+ };
1244
+ }
1245
+ }
1246
+ export function safePrimitiveToString(value) {
1247
+ if (typeof value === "string")
1248
+ return value;
1249
+ if (typeof value === "number" || typeof value === "boolean")
1250
+ return String(value);
1251
+ return null;
1252
+ }
1253
+ export function safeString(value) {
1254
+ if (value === undefined || value === null)
1255
+ return "";
1256
+ if (typeof value === "string")
1257
+ return value;
1258
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint")
1259
+ return String(value);
1260
+ if (typeof value === "symbol")
1261
+ return value.description ? `Symbol(${value.description})` : "Symbol()";
1262
+ try {
1263
+ return String(value);
1264
+ }
1265
+ catch {
1266
+ return "[unprintable]";
1267
+ }
1268
+ }
1269
+ export function clampInt(value, fallback, min, max) {
1270
+ if (typeof value !== "number" || !Number.isFinite(value))
1271
+ return fallback;
1272
+ return Math.min(max, Math.max(min, Math.floor(value)));
1273
+ }
1274
+ // ---------------------------------------------------------------------------
1275
+ // Secret collection, span-union redaction & deep object scrubbing
1276
+ // ---------------------------------------------------------------------------
1277
+ const COOKIE_ATTR_NAMES = new Set([
1278
+ "path",
1279
+ "domain",
1280
+ "expires",
1281
+ "max-age",
1282
+ "samesite",
1283
+ "priority",
1284
+ "httponly",
1285
+ "secure"
1286
+ ]);
1287
+ const VAR_TEMPLATE_VALUE_RE = /\{\{\s*vars\.[A-Za-z_][A-Za-z0-9_.-]{0,63}\s*\}\}/;
1288
+ export function collectSecretValue(secrets, raw, options = {}) {
1289
+ if (typeof raw !== "string")
1290
+ return;
1291
+ const minLen = options.minLength ?? 4;
1292
+ const trimmed = raw.trim();
1293
+ if (options.skipVarPlaceholders && VAR_TEMPLATE_VALUE_RE.test(trimmed))
1294
+ return;
1295
+ const record = (candidate) => {
1296
+ const c = candidate.trim();
1297
+ if (c.length < minLen ||
1298
+ c === "[REDACTED]" ||
1299
+ c === "[REDACTED_VAULT]" ||
1300
+ c === "[REDACTED_VAULT_PATH]" ||
1301
+ c === "[REDACTED_VAR]") {
1302
+ return;
1303
+ }
1304
+ if (options.skipVarPlaceholders && VAR_TEMPLATE_VALUE_RE.test(c))
1305
+ return;
1306
+ secrets.add(c);
1307
+ if (c.includes("%")) {
1308
+ try {
1309
+ const dec = decodeURIComponent(c).trim();
1310
+ if (dec.length >= minLen && dec !== c && dec !== "[REDACTED]")
1311
+ secrets.add(dec);
1312
+ }
1313
+ catch {
1314
+ // ignore malformed percent encoding
1315
+ }
1316
+ }
1317
+ };
1318
+ record(trimmed);
1319
+ const authMatch = /^(?:Bearer|Basic|Token|ApiKey)\s+(.+)$/i.exec(trimmed);
1320
+ if (authMatch)
1321
+ record(authMatch[1]);
1322
+ if (trimmed.includes("=")) {
1323
+ for (const part of trimmed.split(";")) {
1324
+ const eq = part.indexOf("=");
1325
+ if (eq > 0) {
1326
+ const k = part.slice(0, eq).trim().toLowerCase();
1327
+ const v = part.slice(eq + 1).trim();
1328
+ if (!COOKIE_ATTR_NAMES.has(k))
1329
+ record(v);
1330
+ }
1331
+ }
1332
+ }
1333
+ }
1334
+ export function collectUrlSecrets(secrets, rawUrl, options = {}) {
1335
+ if (typeof rawUrl !== "string")
1336
+ return;
1337
+ const trimmed = rawUrl.trim();
1338
+ if (!trimmed)
1339
+ return;
1340
+ const schemeIdx = trimmed.indexOf("://");
1341
+ if (schemeIdx > 0) {
1342
+ const afterScheme = trimmed.slice(schemeIdx + 3);
1343
+ const slashIdx = afterScheme.search(/[/?#]/);
1344
+ const authority = slashIdx === -1 ? afterScheme : afterScheme.slice(0, slashIdx);
1345
+ const atIdx = authority.lastIndexOf("@");
1346
+ if (atIdx > 0) {
1347
+ const userinfo = authority.slice(0, atIdx);
1348
+ const colonIdx = userinfo.indexOf(":");
1349
+ if (colonIdx >= 0) {
1350
+ const user = userinfo.slice(0, colonIdx);
1351
+ const pass = userinfo.slice(colonIdx + 1);
1352
+ if (pass) {
1353
+ collectSecretValue(secrets, pass, options);
1354
+ if (user)
1355
+ collectSecretValue(secrets, `${user}:${pass}`, options);
1356
+ }
1357
+ }
1358
+ else if (userinfo.length >= 6) {
1359
+ collectSecretValue(secrets, userinfo, options);
1360
+ }
1361
+ }
1362
+ }
1363
+ const qIdx = trimmed.indexOf("?");
1364
+ if (qIdx >= 0) {
1365
+ const hashIdx = trimmed.indexOf("#", qIdx);
1366
+ const queryStr = hashIdx === -1 ? trimmed.slice(qIdx + 1) : trimmed.slice(qIdx + 1, hashIdx);
1367
+ for (const part of queryStr.split("&")) {
1368
+ const eq = part.indexOf("=");
1369
+ if (eq > 0) {
1370
+ const k = part.slice(0, eq).trim();
1371
+ const v = part.slice(eq + 1);
1372
+ if (isSensitiveQueryParamName(k) || isSensitiveKeyName(k))
1373
+ collectSecretValue(secrets, v, options);
1374
+ }
1375
+ }
1376
+ }
1377
+ let parsed;
1378
+ try {
1379
+ parsed = parseSafeHttpBaseUrl(trimmed, { allowWs: true });
1380
+ }
1381
+ catch {
1382
+ return;
1383
+ }
1384
+ if (parsed.password) {
1385
+ collectSecretValue(secrets, parsed.password, options);
1386
+ if (parsed.username)
1387
+ collectSecretValue(secrets, `${parsed.username}:${parsed.password}`, options);
1388
+ }
1389
+ else if (parsed.username && parsed.username.length >= 6) {
1390
+ collectSecretValue(secrets, parsed.username, options);
1391
+ }
1392
+ for (const [k, v] of parsed.searchParams.entries()) {
1393
+ if (isSensitiveQueryParamName(k) || isSensitiveKeyName(k))
1394
+ collectSecretValue(secrets, v, options);
1395
+ }
1396
+ }
1397
+ export function collectHeaderSecrets(secrets, headers, options = {}) {
1398
+ if (!isPlainObjectSafe(headers))
1399
+ return;
1400
+ let keys;
1401
+ try {
1402
+ keys = Object.keys(headers);
1403
+ }
1404
+ catch {
1405
+ return;
1406
+ }
1407
+ for (const key of keys) {
1408
+ if (isForbiddenObjectKey(key))
1409
+ continue;
1410
+ let desc;
1411
+ try {
1412
+ desc = Object.getOwnPropertyDescriptor(headers, key);
1413
+ }
1414
+ catch {
1415
+ continue;
1416
+ }
1417
+ if (!desc || !("value" in desc) || desc.value === undefined || desc.value === null)
1418
+ continue;
1419
+ const s = safePrimitiveToString(desc.value);
1420
+ if (s === null)
1421
+ continue;
1422
+ if (isSensitiveHeaderName(key) || isSensitiveKeyName(key) || redactSensitiveText(s) !== s) {
1423
+ collectSecretValue(secrets, s, options);
1424
+ }
1425
+ }
1426
+ }
1427
+ export function collectJsonSecrets(secrets, node, options = {}) {
1428
+ const maxDepth = options.maxDepth ?? 24;
1429
+ const ancestors = new WeakSet();
1430
+ const visit = (cur, depth, parentSensitive) => {
1431
+ if (depth > maxDepth || cur === null || typeof cur !== "object")
1432
+ return;
1433
+ if (ancestors.has(cur))
1434
+ return;
1435
+ ancestors.add(cur);
1436
+ try {
1437
+ if (safeIsArray(cur)) {
1438
+ const len = safeLength(cur, 10_000);
1439
+ for (let i = 0; i < len; i++) {
1440
+ let desc;
1441
+ try {
1442
+ desc = Object.getOwnPropertyDescriptor(cur, String(i));
1443
+ }
1444
+ catch {
1445
+ continue;
1446
+ }
1447
+ if (!desc || !("value" in desc))
1448
+ continue;
1449
+ const elem = desc.value;
1450
+ if (typeof elem === "string") {
1451
+ if (parentSensitive || redactSensitiveText(elem) !== elem)
1452
+ collectSecretValue(secrets, elem, options);
1453
+ }
1454
+ else if (elem !== null && typeof elem === "object") {
1455
+ visit(elem, depth + 1, parentSensitive);
1456
+ }
1457
+ }
1458
+ return;
1459
+ }
1460
+ if (!isPlainObjectSafe(cur))
1461
+ return;
1462
+ let keys;
1463
+ try {
1464
+ keys = Object.keys(cur);
1465
+ }
1466
+ catch {
1467
+ return;
1468
+ }
1469
+ for (const k of keys) {
1470
+ if (isForbiddenObjectKey(k))
1471
+ continue;
1472
+ let desc;
1473
+ try {
1474
+ desc = Object.getOwnPropertyDescriptor(cur, k);
1475
+ }
1476
+ catch {
1477
+ continue;
1478
+ }
1479
+ if (!desc || !("value" in desc))
1480
+ continue;
1481
+ const v = desc.value;
1482
+ const keySens = parentSensitive || isSensitiveKeyName(k);
1483
+ if (typeof v === "string") {
1484
+ if (keySens || redactSensitiveText(v) !== v)
1485
+ collectSecretValue(secrets, v, options);
1486
+ }
1487
+ else if (v !== null && typeof v === "object") {
1488
+ visit(v, depth + 1, keySens);
1489
+ }
1490
+ }
1491
+ }
1492
+ finally {
1493
+ ancestors.delete(cur);
1494
+ }
1495
+ };
1496
+ visit(node, 0, false);
1497
+ }
1498
+ /** Expands a secret literal into raw + URL-encoded, lower-hex, form `+`, encodeURI, and JSON-escaped variants. */
1499
+ export function expandSecretVariants(base, hasPercent, hasPlus, hasBackslash) {
1500
+ const out = [base];
1501
+ const add = (make) => {
1502
+ try {
1503
+ const v = make();
1504
+ if (v.length >= 4 && v !== base)
1505
+ out.push(v);
1506
+ }
1507
+ catch {
1508
+ // ignore lone surrogates
1509
+ }
1510
+ };
1511
+ if (hasPercent || hasPlus) {
1512
+ let enc;
1513
+ try {
1514
+ enc = encodeURIComponent(base);
1515
+ }
1516
+ catch {
1517
+ // ignore lone surrogates
1518
+ }
1519
+ if (enc !== undefined && enc !== base) {
1520
+ if (hasPercent && enc.length >= 4) {
1521
+ out.push(enc);
1522
+ const lower = enc.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase());
1523
+ if (lower !== enc)
1524
+ out.push(lower);
1525
+ }
1526
+ if (hasPlus) {
1527
+ const plus = enc.replaceAll("%20", "+");
1528
+ if (plus.length >= 4 && (hasPercent || !plus.includes("%")))
1529
+ out.push(plus);
1530
+ }
1531
+ }
1532
+ add(() => {
1533
+ const form = new URLSearchParams([["", base]]).toString().slice(1);
1534
+ if ((!hasPercent && form.includes("%")) || (!hasPlus && form.includes("+")))
1535
+ return "";
1536
+ return form;
1537
+ });
1538
+ add(() => {
1539
+ const formLower = new URLSearchParams([["", base]])
1540
+ .toString()
1541
+ .slice(1)
1542
+ .replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase());
1543
+ if ((!hasPercent && formLower.includes("%")) || (!hasPlus && formLower.includes("+")))
1544
+ return "";
1545
+ return formLower;
1546
+ });
1547
+ if (hasPercent)
1548
+ add(() => encodeURI(base));
1549
+ }
1550
+ if (hasBackslash)
1551
+ add(() => JSON.stringify(base).slice(1, -1));
1552
+ return out;
1553
+ }
1554
+ /**
1555
+ * Replaces all occurrences of `secrets` (raw and encoded variants) in strict O(N) span-union
1556
+ * fashion so overlapping secrets and sentinel collisions cannot leave fragments.
1557
+ */
1558
+ export function redactSecretSpans(text, secrets, token = "[REDACTED]") {
1559
+ if (!text)
1560
+ return "";
1561
+ const hasPercent = text.includes("%");
1562
+ const hasPlus = text.includes("+");
1563
+ const hasBackslash = text.includes("\\");
1564
+ const needles = new Set();
1565
+ for (const s of secrets) {
1566
+ if (typeof s !== "string" || s.length < 4)
1567
+ continue;
1568
+ for (const v of expandSecretVariants(s, hasPercent, hasPlus, hasBackslash)) {
1569
+ needles.add(v);
1570
+ }
1571
+ }
1572
+ if (needles.size === 0)
1573
+ return text;
1574
+ const n = text.length;
1575
+ let covered = null;
1576
+ for (const needle of needles) {
1577
+ let idx = text.indexOf(needle);
1578
+ if (idx === -1)
1579
+ continue;
1580
+ if (covered === null)
1581
+ covered = new Uint8Array(n);
1582
+ const len = needle.length;
1583
+ for (; idx !== -1; idx = text.indexOf(needle, idx + len)) {
1584
+ covered.fill(1, idx, idx + len);
1585
+ }
1586
+ }
1587
+ if (covered === null)
1588
+ return text;
1589
+ const parts = [];
1590
+ for (let i = 0; i < n;) {
1591
+ if (covered[i] === 1) {
1592
+ parts.push(token);
1593
+ while (i < n && covered[i] === 1)
1594
+ i++;
1595
+ }
1596
+ else {
1597
+ const start = i;
1598
+ while (i < n && covered[i] === 0)
1599
+ i++;
1600
+ parts.push(text.slice(start, i));
1601
+ }
1602
+ }
1603
+ return parts.join("");
1604
+ }
1605
+ /**
1606
+ * Error-aware, depth-capped, prototype-safe, descriptor-safe, and DAG-safe deep value redactor.
1607
+ */
1608
+ export function redactDeepValue(value, options = {}) {
1609
+ const maxDepth = options.maxDepth ?? 24;
1610
+ const maxNodes = options.maxNodes;
1611
+ const maxArrayItems = options.maxArrayItems ?? 10_000;
1612
+ const redactTextFn = options.redactText ?? ((s) => redactSensitiveText(s));
1613
+ const sensitiveKeyMode = options.sensitiveKeyMode ?? "none";
1614
+ const sensitivePathAware = options.sensitivePathAware === true;
1615
+ const preserveKeys = options.preserveKeys;
1616
+ const unwrapError = options.unwrapError !== false;
1617
+ const sanitizeNonFiniteNumbers = options.sanitizeNonFiniteNumbers === true;
1618
+ const stringifyNonJsonPrimitives = options.stringifyNonJsonPrimitives === true;
1619
+ const truncatedToken = options.truncatedToken ?? "[Truncated]";
1620
+ const circularToken = options.circularToken ?? "[Circular]";
1621
+ const seen = new WeakSet();
1622
+ const cache = maxNodes !== undefined ? new Map() : null;
1623
+ let remaining = maxNodes ?? Number.POSITIVE_INFINITY;
1624
+ const scrubStr = (raw) => {
1625
+ if (!cache)
1626
+ return redactTextFn(raw);
1627
+ const hit = cache.get(raw);
1628
+ if (hit !== undefined)
1629
+ return hit;
1630
+ const red = redactTextFn(raw);
1631
+ if (cache.size < (maxNodes ?? 2000))
1632
+ cache.set(raw, red);
1633
+ return red;
1634
+ };
1635
+ const visit = (cur, depth, forceStrings) => {
1636
+ if (remaining <= 0)
1637
+ return truncatedToken;
1638
+ remaining--;
1639
+ if (typeof cur === "string") {
1640
+ if (forceStrings && cur.length > 0)
1641
+ return "[REDACTED]";
1642
+ return scrubStr(cur);
1643
+ }
1644
+ if (cur === null || cur === undefined || typeof cur === "boolean")
1645
+ return cur;
1646
+ if (typeof cur === "number") {
1647
+ return sanitizeNonFiniteNumbers && !Number.isFinite(cur) ? null : cur;
1648
+ }
1649
+ if (typeof cur !== "object") {
1650
+ return stringifyNonJsonPrimitives ? scrubStr(safeString(cur)) : cur;
1651
+ }
1652
+ if (unwrapError && cur instanceof Error) {
1653
+ let msg = "";
1654
+ try {
1655
+ msg = typeof cur.message === "string" ? cur.message : safeString(cur);
1656
+ }
1657
+ catch {
1658
+ msg = "[Unreadable]";
1659
+ }
1660
+ return scrubStr(msg);
1661
+ }
1662
+ if (depth >= maxDepth)
1663
+ return truncatedToken;
1664
+ if (seen.has(cur))
1665
+ return circularToken;
1666
+ seen.add(cur);
1667
+ try {
1668
+ if (safeIsArray(cur)) {
1669
+ const len = safeLength(cur, maxArrayItems);
1670
+ const outArr = [];
1671
+ for (let i = 0; i < len; i++) {
1672
+ if (remaining <= 0) {
1673
+ outArr.push(truncatedToken);
1674
+ break;
1675
+ }
1676
+ let desc;
1677
+ try {
1678
+ desc = Object.getOwnPropertyDescriptor(cur, String(i));
1679
+ }
1680
+ catch {
1681
+ outArr.push("[Unreadable]");
1682
+ continue;
1683
+ }
1684
+ if (!desc) {
1685
+ outArr.push(undefined);
1686
+ }
1687
+ else if (!("value" in desc)) {
1688
+ outArr.push("[Unreadable]");
1689
+ }
1690
+ else {
1691
+ outArr.push(visit(desc.value, depth + 1, forceStrings));
1692
+ }
1693
+ }
1694
+ return outArr;
1695
+ }
1696
+ let keys;
1697
+ try {
1698
+ keys = Object.keys(cur);
1699
+ }
1700
+ catch {
1701
+ return "[Unreadable]";
1702
+ }
1703
+ let pathSensitive = false;
1704
+ if (sensitivePathAware) {
1705
+ const pathProp = safeOwnProp(cur, "path");
1706
+ if (typeof pathProp === "string") {
1707
+ pathSensitive = isSensitiveKeyName(pathProp.replace(/\[[^\]]*\]/g, "").split(".").pop() ?? "") || isSensitiveKeyName(pathProp);
1708
+ }
1709
+ }
1710
+ const out = {};
1711
+ for (const k of keys) {
1712
+ if (remaining <= 0) {
1713
+ defineOwnProp(out, "_truncated", true);
1714
+ break;
1715
+ }
1716
+ if (isForbiddenObjectKey(k))
1717
+ continue;
1718
+ let desc;
1719
+ try {
1720
+ desc = Object.getOwnPropertyDescriptor(cur, k);
1721
+ }
1722
+ catch {
1723
+ continue;
1724
+ }
1725
+ if (!desc || !("value" in desc))
1726
+ continue;
1727
+ const safeKey = scrubStr(k);
1728
+ if (isForbiddenObjectKey(safeKey))
1729
+ continue;
1730
+ if (preserveKeys?.has(k)) {
1731
+ defineOwnProp(out, safeKey, desc.value);
1732
+ continue;
1733
+ }
1734
+ const keyIsSensitive = isSensitiveKeyName(k) || isSensitiveHeaderName(k);
1735
+ if (sensitiveKeyMode === "value" && (keyIsSensitive || (pathSensitive && (k === "expected" || k === "actual")))) {
1736
+ defineOwnProp(out, safeKey, "[REDACTED]");
1737
+ continue;
1738
+ }
1739
+ const nextForce = forceStrings || (sensitiveKeyMode === "strings" && keyIsSensitive);
1740
+ defineOwnProp(out, safeKey, visit(desc.value, depth + 1, nextForce));
1741
+ }
1742
+ return out;
1743
+ }
1744
+ finally {
1745
+ seen.delete(cur);
1746
+ }
1747
+ };
1748
+ return visit(value, 0, false);
1749
+ }
1750
+ // ---------------------------------------------------------------------------
1751
+ // Holdout result detection & bounded UTF-8 file reading
1752
+ // ---------------------------------------------------------------------------
1753
+ /** Descriptor-safe check whether a parity result record belongs to a holdout invariant. */
1754
+ export function isHoldoutResultRecord(result) {
1755
+ if (!isRecordSafe(result))
1756
+ return false;
1757
+ const metrics = safeOwnProp(result, "metrics");
1758
+ return (safeOwnProp(metrics, "redacted") === true ||
1759
+ safeOwnProp(metrics, "holdout") === true ||
1760
+ typeof safeOwnProp(metrics, "holdoutHint") === "string" ||
1761
+ safeOwnProp(result, "redacted") === true ||
1762
+ safeOwnProp(result, "holdout") === true ||
1763
+ typeof safeOwnProp(result, "holdoutHint") === "string");
1764
+ }
1765
+ const STRICT_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
1766
+ const READ_CHUNK_SIZE = 64 * 1024;
1767
+ /** Reads up to `maxBytes` of a regular file (or open fd) safely into UTF-8 with O_NOFOLLOW and binary guards. */
1768
+ export function readBoundedFileUtf8(filePathOrFd, maxBytes, options = {}) {
1769
+ const limit = Math.max(0, Math.floor(maxBytes));
1770
+ const ownFd = typeof filePathOrFd === "string";
1771
+ const noFollowFlag = options.noFollow !== false && typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
1772
+ let fd = ownFd ? null : filePathOrFd;
1773
+ try {
1774
+ if (ownFd) {
1775
+ if (options.noFollow !== false) {
1776
+ const lstat = fs.lstatSync(filePathOrFd);
1777
+ if (lstat.isSymbolicLink() || !lstat.isFile())
1778
+ return { ok: false, reason: "not_file" };
1779
+ if (lstat.size > limit)
1780
+ return { ok: false, reason: "oversized", size: lstat.size };
1781
+ }
1782
+ fd = fs.openSync(filePathOrFd, fs.constants.O_RDONLY | noFollowFlag);
1783
+ }
1784
+ const stat = fs.fstatSync(fd);
1785
+ if (!stat.isFile())
1786
+ return { ok: false, reason: "not_file" };
1787
+ if (stat.size > limit)
1788
+ return { ok: false, reason: "oversized", size: stat.size };
1789
+ const chunks = [];
1790
+ let totalBytes = 0;
1791
+ const scratch = Buffer.allocUnsafe(Math.min(READ_CHUNK_SIZE, limit + 1));
1792
+ while (true) {
1793
+ const remaining = limit - totalBytes + 1;
1794
+ const toRead = Math.min(scratch.length, remaining);
1795
+ const n = fs.readSync(fd, scratch, 0, toRead, null);
1796
+ if (n <= 0)
1797
+ break;
1798
+ totalBytes += n;
1799
+ if (totalBytes > limit) {
1800
+ return { ok: false, reason: "oversized", size: totalBytes };
1801
+ }
1802
+ chunks.push(Buffer.from(scratch.subarray(0, n)));
1803
+ }
1804
+ const buf = chunks.length === 0 ? Buffer.alloc(0) : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, totalBytes);
1805
+ if (options.rejectBinary && buf.includes(0)) {
1806
+ return { ok: false, reason: "binary" };
1807
+ }
1808
+ let text;
1809
+ if (options.strictUtf8) {
1810
+ try {
1811
+ text = STRICT_UTF8_DECODER.decode(buf);
1812
+ }
1813
+ catch {
1814
+ return { ok: false, reason: "binary" };
1815
+ }
1816
+ }
1817
+ else {
1818
+ text = buf.toString("utf8");
1819
+ }
1820
+ if (options.stripBom && text.charCodeAt(0) === 0xfeff) {
1821
+ text = text.slice(1);
1822
+ }
1823
+ return { ok: true, text, bytes: totalBytes };
1824
+ }
1825
+ catch (err) {
1826
+ const code = err?.code;
1827
+ return { ok: false, reason: "unreadable", ...(typeof code === "string" ? { code } : {}) };
1828
+ }
1829
+ finally {
1830
+ if (ownFd && fd !== null) {
1831
+ try {
1832
+ fs.closeSync(fd);
1833
+ }
1834
+ catch {
1835
+ // ignore close error
1836
+ }
1837
+ }
1838
+ }
1839
+ }