@blamejs/core 0.7.4 → 0.7.18

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 (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -0,0 +1,724 @@
1
+ "use strict";
2
+ /**
3
+ * guard-filename — filename content-safety primitive (b.guardFilename).
4
+ *
5
+ * Threat catalog grounded in current research: OWASP Path Traversal +
6
+ * WSTG file-inclusion testing guides; CWE-22 / CWE-23 / CWE-35 / CWE-73
7
+ * / CWE-78 / CWE-434 / CWE-36; PortSwigger File-path-traversal series
8
+ * (null-byte bypass + extension validation); Memento-RTLO + RTL-Spiegel
9
+ * file-name spoofing reports (CVE-2021-42574 in filename context); Kevin
10
+ * Boone overlong UTF-8 sequence write-up.
11
+ *
12
+ * var rv = b.guardFilename.validate("../etc/passwd", { profile: "strict" });
13
+ * var safe = b.guardFilename.sanitize("My File‮.txt", { profile: "balanced" });
14
+ * var g = b.guardFilename.gate({ profile: "strict" });
15
+ *
16
+ * Threat catalog covered:
17
+ *
18
+ * 1. Path traversal — `..`, `../`, `..\\`, percent-encoded `%2e%2e`,
19
+ * double-encoded `%252e%252e`, UTF-8 overlong `0xC0 0xAE` for `.`
20
+ * and `0xC0 0xAF` for `/`. Refused regardless of profile.
21
+ *
22
+ * 2. Null-byte truncation — `file.txt\x00.exe` — string ends at null
23
+ * in C-shaped APIs while validation sees `.txt`. Refused.
24
+ *
25
+ * 3. Windows reserved device names — CON / PRN / AUX / NUL / COM1-9 /
26
+ * LPT1-9 / CLOCK$ — even with extensions (CON.txt is reserved).
27
+ * Case-insensitive match. Refused.
28
+ *
29
+ * 4. NTFS alternate data streams — `file.txt:hidden.exe`. Colon is
30
+ * the ADS separator on NTFS. Refused.
31
+ *
32
+ * 5. Leading/trailing whitespace + trailing dots — Windows strips
33
+ * them silently, so `secret.txt ` and `secret.txt.` save as
34
+ * `secret.txt`. Refused under strict, stripped under balanced.
35
+ *
36
+ * 6. Unicode bidi / RTLO — CVE-2021-42574 in filename context. The
37
+ * Memento-RTLO toolkit weaponizes this: `Photo01By‮gpj.SCR`
38
+ * displays as `Photo01ByRCS.jpg` while the OS opens `.SCR`.
39
+ * Refused regardless of profile.
40
+ *
41
+ * 7. Zero-width / invisible-formatting chars — used to hide the real
42
+ * extension between the visible name and what the OS sees.
43
+ *
44
+ * 8. Homoglyph chars — Cyrillic / Greek / fullwidth Latin mixed with
45
+ * ASCII letters in a single name. Operator-decided severity per
46
+ * profile.
47
+ *
48
+ * 9. Path separators inside a leaf-name — `file/with/slashes` and
49
+ * `\\` variants. Reserved-character check.
50
+ *
51
+ * 10. Reserved characters — Windows: `< > : " / \ | ? *` plus the C0
52
+ * controls and DEL. Refused under strict / balanced; permissive
53
+ * strips and re-checks length.
54
+ *
55
+ * 11. UNC paths — `\\server\share\file` syntax. Refused (network-path
56
+ * resolution is outside the local-file scope).
57
+ *
58
+ * 12. Length caps — Windows MAX_PATH 260, NTFS 32767, ext4 255 bytes
59
+ * per component. Default leaf cap 255 bytes; total-path cap 260.
60
+ *
61
+ * 13. Empty / dot components — `..//.//file` after normalization. The
62
+ * validator surfaces these as path-traversal-shape issues.
63
+ *
64
+ * 14. Single-dot leaf — name === "." or ".." refused.
65
+ *
66
+ * 15. Allowlist mode — operators can pass `extensionAllowlist:
67
+ * [".png", ".jpg", ".pdf"]` to require a single allowed extension.
68
+ * The validator catches double-extension bypass: `file.jpg.exe`
69
+ * lands at the last dot's extension `.exe` and is refused.
70
+ *
71
+ * 16. Shell-shortcut extensions — `.lnk`, `.url`, `.desktop`, `.scr`,
72
+ * `.bat`, `.cmd`, `.com`, `.pif`, `.vbs`, `.js`, `.jse`, `.wsf`,
73
+ * `.wsh`, `.ps1`, `.psm1`, `.app`, `.deb`, `.rpm`, `.msi`. Refused
74
+ * under strict; balanced/permissive emit a warn-level audit issue.
75
+ *
76
+ * 17. UTF-8 overlong encoding — bytes that decode to ASCII separators
77
+ * via non-shortest-form encoding (Unicode standard prohibits, but
78
+ * legacy decoders accept them).
79
+ *
80
+ * 18. Anti-DoS caps — total filename byte length, total component
81
+ * count when the operator allows path-shape (default: leaf only).
82
+ *
83
+ * Threat-detection regex literals composed programmatically from numeric
84
+ * codepoint range tables (lib/codepoint-class). Source file never
85
+ * embeds attack characters.
86
+ */
87
+
88
+ var codepointClass = require("./codepoint-class");
89
+ var lazyRequire = require("./lazy-require");
90
+ var gateContract = require("./gate-contract");
91
+ var C = require("./constants");
92
+ var numericBounds = require("./numeric-bounds");
93
+ var { GuardFilenameError } = require("./framework-error");
94
+
95
+ var observability = lazyRequire(function () { return require("./observability"); });
96
+ void observability;
97
+
98
+ var _err = GuardFilenameError.factory;
99
+
100
+ // Reserved characters that must not appear in a filename leaf.
101
+ // Windows: < > : " / \ | ? *
102
+ // Unix: /
103
+ // Both: null and C0 controls (handled separately via codepoint-class)
104
+ var RESERVED_CHARS_RE = /[<>:"/\\|?*]/;
105
+
106
+ // Windows reserved device names (case-insensitive). Match either the
107
+ // bare name or `<name>.<anything>`.
108
+ var WIN_RESERVED_NAMES = Object.freeze([
109
+ "CON", "PRN", "AUX", "NUL",
110
+ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
111
+ "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
112
+ "CLOCK$", "CONFIG$",
113
+ ]);
114
+
115
+ // Path-traversal indicators (anchored matches on raw and percent-decoded
116
+ // forms).
117
+ var PATH_TRAVERSAL_RE = /(^|[/\\])\.\.($|[/\\])/;
118
+ var PERCENT_ENCODED_TRAVERSAL_RE = /%2e%2e|%252e%252e|%c0%ae|%c0%af/i;
119
+ var URL_ENCODED_SLASH_RE = /%2f|%5c|%c0%af|%c1%9c/i;
120
+
121
+ // Shell-shortcut / executable extension family — refused under strict,
122
+ // audited under balanced/permissive.
123
+ var SHELL_EXEC_EXTS = Object.freeze([
124
+ ".lnk", ".url", ".desktop", ".scr", ".bat", ".cmd", ".com", ".pif",
125
+ ".vbs", ".vbe", ".js", ".jse", ".wsf", ".wsh", ".ps1", ".psm1",
126
+ ".app", ".deb", ".rpm", ".msi", ".dmg", ".pkg", ".bin", ".sh",
127
+ ".exe", ".dll", ".so", ".dylib", ".jar", ".class",
128
+ ".reg", ".cpl", ".inf", ".hta", ".chm", ".scf",
129
+ ]);
130
+
131
+ var HEX_RADIX = 16; // allow:raw-byte-literal — base-16 radix, not byte size
132
+
133
+ // Visual-confusable letter ranges that homoglyph against ASCII —
134
+ // Cyrillic / Greek / fullwidth Latin. Only flagged when mixed with
135
+ // ASCII letters in the same filename.
136
+ var HOMOGLYPH_RANGES = [[0x0400, 0x04FF], [0x0370, 0x03FF], [0xFF21, 0xFF5A]];
137
+ var HOMOGLYPH_RE = new RegExp("[" + codepointClass.charClass(HOMOGLYPH_RANGES) + "]"); // allow:dynamic-regex — codepoints from HOMOGLYPH_RANGES literal table
138
+
139
+ // ---- Profile presets ----
140
+
141
+ var PROFILES = Object.freeze({
142
+ "strict": {
143
+ bidiPolicy: "reject",
144
+ controlPolicy: "reject",
145
+ nullBytePolicy: "reject",
146
+ zeroWidthPolicy: "reject",
147
+ homoglyphPolicy: "reject",
148
+ traversalPolicy: "reject",
149
+ reservedCharPolicy: "reject",
150
+ reservedNamePolicy: "reject",
151
+ adsPolicy: "reject",
152
+ leadingTrailingPolicy: "reject",
153
+ shellExecExtPolicy: "reject",
154
+ pathSeparatorsPolicy: "reject", // forbid path components, leaf-name only
155
+ unicodeNormalization: "NFC",
156
+ requireAscii: true,
157
+ extensionAllowlist: null, // null = any single extension
158
+ requireSingleDot: true, // ".tar.gz" not allowed
159
+ maxBytes: 64, // allow:raw-byte-literal — leaf-name byte cap, not byte size
160
+ maxComponents: 1, // allow:raw-byte-literal — single leaf only, not bytes
161
+ },
162
+ "balanced": {
163
+ bidiPolicy: "reject",
164
+ controlPolicy: "reject",
165
+ nullBytePolicy: "reject",
166
+ zeroWidthPolicy: "strip",
167
+ homoglyphPolicy: "audit",
168
+ traversalPolicy: "reject",
169
+ reservedCharPolicy: "reject",
170
+ reservedNamePolicy: "reject",
171
+ adsPolicy: "reject",
172
+ leadingTrailingPolicy: "strip",
173
+ shellExecExtPolicy: "audit",
174
+ pathSeparatorsPolicy: "reject",
175
+ unicodeNormalization: "NFC",
176
+ requireAscii: false,
177
+ extensionAllowlist: null,
178
+ requireSingleDot: false, // ".tar.gz" allowed
179
+ maxBytes: 255, // allow:raw-byte-literal — POSIX max-component, not byte size
180
+ maxComponents: 1, // allow:raw-byte-literal — single leaf only, not bytes
181
+ },
182
+ "permissive": {
183
+ bidiPolicy: "reject",
184
+ controlPolicy: "strip",
185
+ nullBytePolicy: "reject",
186
+ zeroWidthPolicy: "strip",
187
+ homoglyphPolicy: "audit",
188
+ traversalPolicy: "reject",
189
+ reservedCharPolicy: "strip",
190
+ reservedNamePolicy: "audit", // operator may want to accept on non-Windows targets
191
+ adsPolicy: "reject",
192
+ leadingTrailingPolicy: "strip",
193
+ shellExecExtPolicy: "audit",
194
+ pathSeparatorsPolicy: "audit", // operator opts in to multi-component paths
195
+ unicodeNormalization: "NFC",
196
+ requireAscii: false,
197
+ extensionAllowlist: null,
198
+ requireSingleDot: false,
199
+ maxBytes: 255, // allow:raw-byte-literal — POSIX max-component, not byte size
200
+ maxComponents: 16, // allow:raw-byte-literal — multi-component path cap, not bytes
201
+ },
202
+ });
203
+
204
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
205
+ mode: "enforce",
206
+ maxRuntimeMs: C.TIME.seconds(5),
207
+ }));
208
+
209
+ var COMPLIANCE_POSTURES = Object.freeze({
210
+ "hipaa": {
211
+ bidiPolicy: "reject", controlPolicy: "reject", nullBytePolicy: "reject",
212
+ zeroWidthPolicy: "reject", homoglyphPolicy: "reject",
213
+ traversalPolicy: "reject", reservedCharPolicy: "reject",
214
+ reservedNamePolicy: "reject", adsPolicy: "reject",
215
+ leadingTrailingPolicy: "reject", shellExecExtPolicy: "reject",
216
+ pathSeparatorsPolicy: "reject",
217
+ requireAscii: true,
218
+ forensicSnippetBytes: C.BYTES.bytes(256),
219
+ },
220
+ "pci-dss": {
221
+ bidiPolicy: "reject", controlPolicy: "reject", nullBytePolicy: "reject",
222
+ zeroWidthPolicy: "reject", homoglyphPolicy: "reject",
223
+ traversalPolicy: "reject", reservedCharPolicy: "reject",
224
+ reservedNamePolicy: "reject", adsPolicy: "reject",
225
+ leadingTrailingPolicy: "reject", shellExecExtPolicy: "reject",
226
+ pathSeparatorsPolicy: "reject",
227
+ requireAscii: true,
228
+ forensicSnippetBytes: C.BYTES.bytes(256),
229
+ },
230
+ "gdpr": {
231
+ bidiPolicy: "strip", controlPolicy: "strip", nullBytePolicy: "reject",
232
+ zeroWidthPolicy: "strip",
233
+ traversalPolicy: "reject", reservedCharPolicy: "reject",
234
+ leadingTrailingPolicy: "strip",
235
+ forensicSnippetBytes: C.BYTES.bytes(128),
236
+ },
237
+ "soc2-cc7": {
238
+ bidiPolicy: "reject", controlPolicy: "reject", nullBytePolicy: "reject",
239
+ zeroWidthPolicy: "reject", traversalPolicy: "reject",
240
+ reservedCharPolicy: "reject", reservedNamePolicy: "reject",
241
+ adsPolicy: "reject", shellExecExtPolicy: "reject",
242
+ pathSeparatorsPolicy: "reject",
243
+ forensicSnippetBytes: C.BYTES.bytes(512),
244
+ },
245
+ });
246
+
247
+ // ---- Helpers ----
248
+
249
+ function _resolveOpts(opts) {
250
+ return gateContract.resolveProfileAndPosture(opts, {
251
+ profiles: PROFILES,
252
+ compliancePostures: COMPLIANCE_POSTURES,
253
+ defaults: DEFAULTS,
254
+ errorClass: GuardFilenameError,
255
+ errCodePrefix: "filename",
256
+ });
257
+ }
258
+
259
+ function _normalizeNFC(s) {
260
+ try { return s.normalize ? s.normalize("NFC") : s; }
261
+ catch (_e) { return s; }
262
+ }
263
+
264
+ function _isWinReserved(name) {
265
+ // Reserved-name check applies to the base (without extension) AND to
266
+ // the entire leaf — both `CON` and `CON.txt` collide with the device.
267
+ var upper = name.toUpperCase();
268
+ for (var i = 0; i < WIN_RESERVED_NAMES.length; i += 1) {
269
+ var r = WIN_RESERVED_NAMES[i];
270
+ if (upper === r) return true;
271
+ if (upper.indexOf(r + ".") === 0) return true;
272
+ }
273
+ return false;
274
+ }
275
+
276
+ function _hasOverlongUtf8(buf) {
277
+ // Buffer-level scan for non-shortest UTF-8 sequences — `0xC0 0xXX`
278
+ // and `0xC1 0xXX` are always invalid (would encode ASCII via 2 bytes
279
+ // instead of 1), and `0xE0 0x80-9F` / `0xF0 0x80-8F` are 3/4-byte
280
+ // overlongs. Reject the whole class.
281
+ if (!Buffer.isBuffer(buf)) return false;
282
+ for (var i = 0; i < buf.length - 1; i += 1) {
283
+ var b0 = buf[i];
284
+ if (b0 === 0xC0 || b0 === 0xC1) return true;
285
+ if (b0 === 0xE0 && buf[i + 1] >= 0x80 && buf[i + 1] <= 0x9F) return true;
286
+ if (b0 === 0xF0 && buf[i + 1] >= 0x80 && buf[i + 1] <= 0x8F) return true;
287
+ }
288
+ return false;
289
+ }
290
+
291
+ function _splitExt(name) {
292
+ var idx = name.lastIndexOf(".");
293
+ if (idx <= 0) return { base: name, ext: "" };
294
+ return { base: name.slice(0, idx), ext: name.slice(idx) };
295
+ }
296
+
297
+ function _stripLeadingTrailing(s) {
298
+ return s.replace(/^[\s.]+|[\s.]+$/g, "");
299
+ }
300
+
301
+ // ---- Detection pass ----
302
+
303
+ function _detectIssues(input, opts) {
304
+ var issues = [];
305
+
306
+ // Buffer-level checks BEFORE utf8 conversion (overlong encoding
307
+ // would be invisible after toString).
308
+ if (Buffer.isBuffer(input)) {
309
+ if (_hasOverlongUtf8(input)) {
310
+ issues.push({
311
+ kind: "overlong-utf8", severity: "critical",
312
+ ruleId: "filename.overlong-utf8",
313
+ snippet: "non-shortest-form UTF-8 sequence in filename bytes (RFC 3629 §3 prohibits)",
314
+ });
315
+ }
316
+ }
317
+
318
+ var name = typeof input === "string"
319
+ ? input
320
+ : (Buffer.isBuffer(input) ? input.toString("utf8") : "");
321
+
322
+ if (name.length === 0) {
323
+ issues.push({
324
+ kind: "empty", severity: "critical", ruleId: "filename.empty",
325
+ snippet: "filename is empty",
326
+ });
327
+ return issues;
328
+ }
329
+
330
+ // 1. Bidi / null / control / zero-width via shared codepoint class.
331
+ issues.push.apply(issues, codepointClass.detectCharThreats(name, opts, "filename"));
332
+ if (opts.zeroWidthPolicy !== "allow" && opts.zeroWidthPolicy !== "strip") {
333
+ var zwMatch = name.match(codepointClass.ZERO_WIDTH_RE);
334
+ if (zwMatch) {
335
+ issues.push({
336
+ kind: "zero-width", severity: "high", ruleId: "filename.zero-width",
337
+ location: zwMatch.index,
338
+ snippet: "zero-width / invisible-formatting char U+" +
339
+ zwMatch[0].charCodeAt(0).toString(HEX_RADIX),
340
+ });
341
+ }
342
+ }
343
+
344
+ // 2. Path traversal — raw + percent-encoded forms. `name` is bounded
345
+ // by the maxBytes check at the end of this function (issues are
346
+ // reported all-at-once; an oversized name still gets traversal-shape
347
+ // detection so operators see the full failure surface).
348
+ if (opts.traversalPolicy !== "allow") {
349
+ if (PATH_TRAVERSAL_RE.test(name) || /^\.\.$/.test(name) || name === "..") { // allow:regex-no-length-cap — operator-supplied filename, length checked separately
350
+ issues.push({
351
+ kind: "path-traversal", severity: "critical",
352
+ ruleId: "filename.traversal",
353
+ snippet: ".. component (CWE-22 / CWE-23)",
354
+ });
355
+ }
356
+ if (PERCENT_ENCODED_TRAVERSAL_RE.test(name)) { // allow:regex-no-length-cap — operator-supplied filename, length checked separately
357
+ issues.push({
358
+ kind: "path-traversal-encoded", severity: "critical",
359
+ ruleId: "filename.traversal-encoded",
360
+ snippet: "percent-encoded path-traversal sequence detected",
361
+ });
362
+ }
363
+ if (URL_ENCODED_SLASH_RE.test(name)) { // allow:regex-no-length-cap — operator-supplied filename, length checked separately
364
+ issues.push({
365
+ kind: "url-encoded-separator", severity: "high",
366
+ ruleId: "filename.url-encoded-separator",
367
+ snippet: "percent-encoded path separator",
368
+ });
369
+ }
370
+ }
371
+
372
+ // 3. Path separators in leaf — pathSeparatorsPolicy controls.
373
+ if (opts.pathSeparatorsPolicy !== "allow" && opts.pathSeparatorsPolicy !== "audit") {
374
+ if (name.indexOf("/") !== -1 || name.indexOf("\\") !== -1) {
375
+ issues.push({
376
+ kind: "path-separator-in-leaf", severity: "high",
377
+ ruleId: "filename.path-separator",
378
+ snippet: "filename leaf contains a path separator (/ or \\)",
379
+ });
380
+ }
381
+ }
382
+
383
+ // 4. UNC paths — `\\server\share\...` or `//server/share/...`
384
+ if (/^\\\\|^\/\//.test(name)) {
385
+ issues.push({
386
+ kind: "unc-path", severity: "critical",
387
+ ruleId: "filename.unc",
388
+ snippet: "UNC network path (\\\\server\\share)",
389
+ });
390
+ }
391
+
392
+ // 5. Reserved characters — < > : " | ? * (slashes handled separately).
393
+ if (opts.reservedCharPolicy !== "allow") {
394
+ var resMatch = name.match(/[<>:"|?*]/);
395
+ if (resMatch) {
396
+ issues.push({
397
+ kind: "reserved-char", severity: "high",
398
+ ruleId: "filename.reserved-char",
399
+ location: resMatch.index,
400
+ snippet: "reserved character " + JSON.stringify(resMatch[0]) +
401
+ " (Windows file system)",
402
+ });
403
+ }
404
+ }
405
+
406
+ // 6. NTFS alternate data streams — `name:stream`.
407
+ if (opts.adsPolicy !== "allow") {
408
+ if (/:[^:\\/]+$/.test(name) && name.charAt(0) !== "/") {
409
+ // Only flag when there's a `:` followed by stream-name characters
410
+ // and we're NOT at the start (relative path indicator).
411
+ issues.push({
412
+ kind: "ntfs-ads", severity: "critical",
413
+ ruleId: "filename.ntfs-ads",
414
+ snippet: "NTFS alternate data stream syntax (name:stream)",
415
+ });
416
+ }
417
+ }
418
+
419
+ // 7. Windows reserved device names.
420
+ if (opts.reservedNamePolicy !== "allow") {
421
+ if (_isWinReserved(name)) {
422
+ issues.push({
423
+ kind: "reserved-name", severity: "critical",
424
+ ruleId: "filename.reserved-name",
425
+ snippet: "filename collides with Windows reserved device name",
426
+ });
427
+ }
428
+ }
429
+
430
+ // 8. Leading / trailing whitespace + trailing dots — Windows strips them.
431
+ if (opts.leadingTrailingPolicy !== "allow") {
432
+ if (/^\s|\s$|\.$/.test(name)) {
433
+ issues.push({
434
+ kind: "leading-trailing-strip", severity: "high",
435
+ ruleId: "filename.leading-trailing",
436
+ snippet: "leading/trailing whitespace or trailing dot (Windows silently strips)",
437
+ });
438
+ }
439
+ }
440
+
441
+ // 9. Single-dot leaf-names.
442
+ if (name === "." || name === "..") {
443
+ issues.push({
444
+ kind: "dot-leaf", severity: "critical", ruleId: "filename.dot-leaf",
445
+ snippet: "filename is " + JSON.stringify(name),
446
+ });
447
+ }
448
+
449
+ // 10. Homoglyph-with-ASCII mix.
450
+ if (opts.homoglyphPolicy !== "allow" && /[A-Za-z]/.test(name)) {
451
+ var hMatch = name.match(HOMOGLYPH_RE);
452
+ if (hMatch) {
453
+ issues.push({
454
+ kind: "homoglyph", severity: opts.homoglyphPolicy === "reject" ? "critical" : "warn",
455
+ ruleId: "filename.homoglyph",
456
+ location: hMatch.index,
457
+ snippet: "homoglyph U+" + hMatch[0].charCodeAt(0).toString(HEX_RADIX) +
458
+ " mixed with ASCII letters in filename",
459
+ });
460
+ }
461
+ }
462
+
463
+ // 11. ASCII-only requirement.
464
+ if (opts.requireAscii) {
465
+ var nonAscii = name.match(/[^\x20-\x7E]/);
466
+ if (nonAscii) {
467
+ issues.push({
468
+ kind: "non-ascii", severity: "high",
469
+ ruleId: "filename.non-ascii",
470
+ location: nonAscii.index,
471
+ snippet: "non-ASCII character (profile requires ASCII-only)",
472
+ });
473
+ }
474
+ }
475
+
476
+ // 12. Length cap.
477
+ var byteLen = Buffer.byteLength(name, "utf8");
478
+ if (byteLen > opts.maxBytes) {
479
+ issues.push({
480
+ kind: "too-long", severity: "high", ruleId: "filename.length",
481
+ snippet: "filename " + byteLen + " bytes exceeds maxBytes " + opts.maxBytes,
482
+ });
483
+ }
484
+
485
+ // 13. Multi-dot when requireSingleDot.
486
+ if (opts.requireSingleDot) {
487
+ var dotCount = (name.match(/\./g) || []).length;
488
+ if (dotCount > 1) {
489
+ issues.push({
490
+ kind: "multiple-dots", severity: "high", ruleId: "filename.multiple-dots",
491
+ snippet: "filename has " + dotCount + " dots (profile requires single)",
492
+ });
493
+ }
494
+ }
495
+
496
+ // 14. Extension allowlist.
497
+ if (Array.isArray(opts.extensionAllowlist) && opts.extensionAllowlist.length > 0) {
498
+ var split = _splitExt(name);
499
+ var ext = split.ext.toLowerCase();
500
+ var allowed = opts.extensionAllowlist.map(function (e) { return e.toLowerCase(); });
501
+ if (!ext || allowed.indexOf(ext) === -1) {
502
+ issues.push({
503
+ kind: "ext-not-allowlisted", severity: "critical",
504
+ ruleId: "filename.ext-allowlist",
505
+ snippet: "extension " + JSON.stringify(ext || "") +
506
+ " not in allowlist " + JSON.stringify(allowed),
507
+ });
508
+ }
509
+ }
510
+
511
+ // 15. Shell-shortcut / executable extensions.
512
+ if (opts.shellExecExtPolicy !== "allow") {
513
+ var splitX = _splitExt(name);
514
+ var extX = splitX.ext.toLowerCase();
515
+ if (extX && SHELL_EXEC_EXTS.indexOf(extX) !== -1) {
516
+ issues.push({
517
+ kind: "shell-exec-ext",
518
+ severity: opts.shellExecExtPolicy === "reject" ? "critical" : "warn",
519
+ ruleId: "filename.shell-exec-ext",
520
+ snippet: "shell-shortcut / executable extension " + JSON.stringify(extX),
521
+ });
522
+ }
523
+ // Double-extension: name has two dots and inner is a "harmless"
524
+ // disguise extension while outer is an executable.
525
+ var dotIndices = [];
526
+ for (var di = 0; di < name.length; di += 1) {
527
+ if (name.charAt(di) === ".") dotIndices.push(di);
528
+ }
529
+ if (dotIndices.length >= 2) {
530
+ var lastExt = name.slice(dotIndices[dotIndices.length - 1]).toLowerCase();
531
+ if (SHELL_EXEC_EXTS.indexOf(lastExt) !== -1) {
532
+ issues.push({
533
+ kind: "double-extension", severity: "critical",
534
+ ruleId: "filename.double-extension",
535
+ snippet: "double-extension with executable last segment " + JSON.stringify(lastExt),
536
+ });
537
+ }
538
+ }
539
+ }
540
+
541
+ return issues;
542
+ }
543
+
544
+ // ---- Sanitize pass ----
545
+
546
+ function _sanitize(input, opts) {
547
+ var name = typeof input === "string"
548
+ ? input
549
+ : (Buffer.isBuffer(input) ? input.toString("utf8") : "");
550
+ if (name.length === 0) {
551
+ throw _err("filename.empty", "sanitize requires non-empty filename");
552
+ }
553
+ if (Buffer.isBuffer(input) && _hasOverlongUtf8(input)) {
554
+ throw _err("filename.overlong-utf8", "filename has overlong UTF-8 sequence — cannot sanitize");
555
+ }
556
+
557
+ // Codepoint-class reject + strip via shared helpers.
558
+ codepointClass.assertNoCharThreats(name, opts, _err, "filename");
559
+ name = codepointClass.applyCharStripPolicies(name, opts);
560
+
561
+ // Unicode normalize before further checks.
562
+ if (opts.unicodeNormalization === "NFC") name = _normalizeNFC(name);
563
+
564
+ // Reject path traversal even in sanitize — there's no safe sanitization.
565
+ if (opts.traversalPolicy === "reject") {
566
+ // allow:regex-no-length-cap — operator-supplied filename; sanitize caller threw on length above
567
+ if (PATH_TRAVERSAL_RE.test(name) || PERCENT_ENCODED_TRAVERSAL_RE.test(name) ||
568
+ name === "." || name === "..") {
569
+ throw _err("filename.traversal", "filename contains path-traversal sequence");
570
+ }
571
+ }
572
+ if (/^\\\\|^\/\//.test(name)) {
573
+ throw _err("filename.unc", "UNC path syntax");
574
+ }
575
+
576
+ // Strip leading/trailing whitespace and trailing dots if policy says so.
577
+ if (opts.leadingTrailingPolicy === "strip") {
578
+ name = _stripLeadingTrailing(name);
579
+ } else if (opts.leadingTrailingPolicy === "reject" &&
580
+ /^\s|\s$|\.$/.test(name)) {
581
+ throw _err("filename.leading-trailing",
582
+ "filename has leading/trailing whitespace or trailing dot");
583
+ }
584
+
585
+ // Strip reserved chars when policy says strip.
586
+ if (opts.reservedCharPolicy === "strip") {
587
+ name = name.replace(RESERVED_CHARS_RE, "_"); // allow:dynamic-regex — RESERVED_CHARS_RE is a compile-time literal
588
+ name = name.replace(/[<>:"|?*]/g, "_");
589
+ } else if (opts.reservedCharPolicy === "reject") {
590
+ if (/[<>:"|?*]/.test(name)) {
591
+ throw _err("filename.reserved-char", "filename contains reserved character");
592
+ }
593
+ if (opts.pathSeparatorsPolicy === "reject" &&
594
+ (name.indexOf("/") !== -1 || name.indexOf("\\") !== -1)) {
595
+ throw _err("filename.path-separator", "filename leaf contains path separator");
596
+ }
597
+ }
598
+
599
+ // Reserved-name check — append underscore prefix to disambiguate.
600
+ if (opts.reservedNamePolicy !== "allow" && _isWinReserved(name)) {
601
+ if (opts.reservedNamePolicy === "reject") {
602
+ throw _err("filename.reserved-name",
603
+ "filename collides with Windows reserved device name");
604
+ }
605
+ name = "_" + name;
606
+ }
607
+
608
+ // ADS detection.
609
+ if (opts.adsPolicy === "reject" && /:[^:\\/]+$/.test(name)) {
610
+ throw _err("filename.ntfs-ads", "filename contains NTFS alternate data stream syntax");
611
+ }
612
+
613
+ // Length cap.
614
+ if (Buffer.byteLength(name, "utf8") > opts.maxBytes) {
615
+ throw _err("filename.length", "filename exceeds maxBytes " + opts.maxBytes);
616
+ }
617
+
618
+ if (name.length === 0) {
619
+ throw _err("filename.empty", "sanitize produced empty filename");
620
+ }
621
+ return name;
622
+ }
623
+
624
+ // ---- Public surface ----
625
+
626
+ function validate(input, opts) {
627
+ opts = _resolveOpts(opts);
628
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
629
+ ["maxBytes", "maxComponents"],
630
+ "guardFilename.validate", GuardFilenameError, "filename.bad-opt");
631
+
632
+ var bad = gateContract.badInputResultIfNotStringOrBuffer(input);
633
+ if (bad) return bad;
634
+ return gateContract.aggregateIssues(_detectIssues(input, opts));
635
+ }
636
+
637
+ function sanitize(input, opts) {
638
+ opts = _resolveOpts(opts);
639
+ if (typeof input !== "string" && !Buffer.isBuffer(input)) {
640
+ throw _err("filename.bad-input", "sanitize requires string or Buffer input");
641
+ }
642
+ return _sanitize(input, opts);
643
+ }
644
+
645
+ function gate(opts) {
646
+ opts = _resolveOpts(opts);
647
+ return gateContract.buildGuardGate(
648
+ opts.name || "guardFilename:" + (opts.profile || "default"),
649
+ opts,
650
+ async function (ctx) {
651
+ // Filename-shape ctx — operator passes filename via ctx.filename.
652
+ var name = ctx && (ctx.filename || ctx.name || "");
653
+ if (!name) return { ok: true, action: "serve" };
654
+ var rv = validate(name, opts);
655
+ if (rv.issues.length === 0) return { ok: true, action: "serve" };
656
+ var hasCritical = rv.issues.some(function (i) {
657
+ return i.severity === "critical" || i.severity === "high";
658
+ });
659
+ if (!hasCritical) return { ok: true, action: "audit-only", issues: rv.issues };
660
+
661
+ // Sanitize-eligibility — every reject-policy must be off.
662
+ var canSanitize = opts.bidiPolicy !== "reject" &&
663
+ opts.controlPolicy !== "reject" &&
664
+ opts.nullBytePolicy !== "reject" &&
665
+ opts.traversalPolicy !== "reject" &&
666
+ opts.reservedCharPolicy !== "reject" &&
667
+ opts.reservedNamePolicy !== "reject" &&
668
+ opts.adsPolicy !== "reject" &&
669
+ opts.pathSeparatorsPolicy !== "reject" &&
670
+ opts.leadingTrailingPolicy !== "reject";
671
+ if (canSanitize) {
672
+ try {
673
+ var clean = sanitize(name, opts);
674
+ return {
675
+ ok: true, action: "sanitize",
676
+ sanitizedFilename: clean,
677
+ issues: rv.issues,
678
+ };
679
+ } catch (_e) { /* fall through */ }
680
+ }
681
+ return { ok: false, action: "refuse", issues: rv.issues };
682
+ });
683
+ }
684
+
685
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
686
+
687
+ function compliancePosture(name) {
688
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "filename");
689
+ }
690
+
691
+ var _filenameRulePacks = gateContract.makeRulePackLoader(GuardFilenameError, "filename");
692
+ var loadRulePack = _filenameRulePacks.load;
693
+
694
+ module.exports = {
695
+ // ---- guard-* family identity ----
696
+ // Filename is a different axis from content-bytes (operators
697
+ // typically apply both: guardFilename on the upload's name, plus
698
+ // guardCsv / guardHtml / guardSvg / etc. on the body). guard-filename
699
+ // is therefore a STANDALONE primitive — it does NOT register into
700
+ // b.guardAll's content-type-routed dispatch (no canonical mime / ext
701
+ // per the registry contract). Operators wire it directly via
702
+ // b.fileUpload({ filenameSafety: gate }) and similar host opts.
703
+ NAME: "filename",
704
+ KIND: "filename", // filename-string guard (consumes ctx.filename)
705
+ INTEGRATION_FIXTURES: Object.freeze({
706
+ kind: "filename",
707
+ benignFilename: "report-2026-Q1.txt",
708
+ // Hostile: path-traversal in filename (CWE-22 class).
709
+ hostileFilename: "../etc/passwd",
710
+ }),
711
+ // ---- primitive surface ----
712
+ validate: validate,
713
+ sanitize: sanitize,
714
+ gate: gate,
715
+ buildProfile: buildProfile,
716
+ compliancePosture: compliancePosture,
717
+ loadRulePack: loadRulePack,
718
+ PROFILES: PROFILES,
719
+ DEFAULTS: DEFAULTS,
720
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
721
+ WIN_RESERVED_NAMES: WIN_RESERVED_NAMES,
722
+ SHELL_EXEC_EXTS: SHELL_EXEC_EXTS,
723
+ GuardFilenameError: GuardFilenameError,
724
+ };