@blamejs/core 0.7.1 → 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 -389
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -282
  5. package/lib/api-key.js +660 -672
  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 -266
  27. package/lib/cache.js +1206 -1211
  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 +1136 -0
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -202
  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 -573
  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 -269
  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 -614
  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 -451
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -479
  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 -855
  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 -177
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -752
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -489
  146. package/lib/request-helpers.js +340 -336
  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 -630
  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 +879 -114
  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 -270
  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 -598
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -0,0 +1,976 @@
1
+ "use strict";
2
+ /**
3
+ * guard-svg — SVG content-safety primitive (b.guardSvg).
4
+ *
5
+ * Threat catalog grounded in current SVG attack-surface research
6
+ * (Fortinet anatomy of SVG attack surface; Angular GHSA-jrmj-c5cx-3cw6
7
+ * + GHSA-v4hv-rgfq-gp49 SVG animation/href XSS; SVGO CVE-2026-29074
8
+ * billion laughs DoS; siyuan-note GHSA-5hc8-qmg8-pw27 animate-element
9
+ * sanitizer bypass; cure53/DOMPurify issue #233 xlink:href filtering;
10
+ * insertScript SVG fun-time series; svg2raster-cheatsheet SSRF guide).
11
+ *
12
+ * var rv = b.guardSvg.validate(input, { profile: "strict" });
13
+ * var safe = b.guardSvg.sanitize(input, { profile: "balanced" });
14
+ * var g = b.guardSvg.gate({ profile: "strict" });
15
+ *
16
+ * Threat catalog covered:
17
+ *
18
+ * 1. Dangerous SVG tags — <script>, <foreignObject> (HTML escape
19
+ * hatch — namespace context shift to (X)HTML), <handler>,
20
+ * <listener>, <audio>, <video>, <iframe>, <embed>, <object>,
21
+ * <use> cross-origin (SSRF + XSS chain), <animate>/<set>/
22
+ * <animateMotion>/<animateTransform> (attributeName-targeting
23
+ * bypass — recent CVE class). Refused or stripped per profile.
24
+ *
25
+ * 2. SMIL animation attributeName allowlist — animate-family
26
+ * elements have an attributeName attribute that names the
27
+ * animated property. If unrestricted, attackers set
28
+ * attributeName="href" + values="javascript:alert(1)" to bypass
29
+ * sanitizers that scrub href but not animate-element targets.
30
+ * strict allowlist limits attributeName to a safe set (cx, cy, r,
31
+ * x, y, width, height, fill, stroke, opacity, transform); balanced
32
+ * adds visual properties only (no href / xlink:href / src / data).
33
+ *
34
+ * 3. on* / SMIL event-handler attribute family — every attribute
35
+ * matching /^on[a-z]/ denied (covers onclick / onerror / onload
36
+ * AND SMIL onbegin / onend / onrepeat).
37
+ *
38
+ * 4. href / xlink:href dangerous URL schemes — javascript /
39
+ * vbscript / data (outside image context on <image>) / file /
40
+ * mhtml / jar / view-source / feed denied. Entity-encoded scheme
41
+ * bypasses (`&#x6A;avascript:`) decoded before scheme check.
42
+ *
43
+ * 5. <use> element cross-origin xlink:href — same-origin (relative
44
+ * paths, fragment-only #id) allowed under strict; absolute URLs
45
+ * with scheme refused (SSRF + XSS chain).
46
+ *
47
+ * 6. <image> external href — same-origin allowed; cross-origin
48
+ * refused under strict (SSRF surface during server-side
49
+ * rasterization). Permissive allows http(s) cross-origin.
50
+ *
51
+ * 7. XML DOCTYPE declarations — refused unconditionally regardless
52
+ * of profile. Catches billion-laughs entity expansion, external
53
+ * entity loading (XXE), and SYSTEM identifier exfiltration.
54
+ *
55
+ * 8. Custom entity declarations — `<!ENTITY ...>` inside the SVG
56
+ * stream refused even when DOCTYPE is technically external.
57
+ *
58
+ * 9. CDATA sections — often used to hide payloads from naive regex
59
+ * scanners; refused under strict, audited under balanced.
60
+ *
61
+ * 10. XML processing instructions — `<?xml-stylesheet ...?>` and
62
+ * similar pre-document directives refused (CSS injection vector).
63
+ *
64
+ * 11. Compressed SVGZ payloads — magic bytes 0x1F 0x8B refused at
65
+ * gate level. Operators that need SVGZ ungzip first then re-gate
66
+ * the inner SVG.
67
+ *
68
+ * 12. CSS injection in style attribute values — same vocabulary as
69
+ * guard-html: expression( / behavior: / -moz-binding /
70
+ * javascript:/vbscript: in url() / @import / @namespace.
71
+ *
72
+ * 13. <use>-recursion DoS — `<use href="#a">` referencing `<use>`
73
+ * referencing back — caps via maxUseDepth + maxElementCount.
74
+ *
75
+ * 14. SSRF-shape attribute scan — href / xlink:href / src on <image>
76
+ * / <use> / <feImage> / <pattern> — absolute URL refused unless
77
+ * profile allows cross-origin and operator passes urlSchemes.
78
+ *
79
+ * 15. Unicode bidi (CVE-2021-42574 Trojan Source), C0 control chars,
80
+ * null bytes, zero-width chars — same codepoint catalog as
81
+ * guard-csv / guard-html.
82
+ *
83
+ * 16. Anti-DoS caps — total-document size, element-count cap (defence
84
+ * against entity-free DoS via repeated literal expansion),
85
+ * use-element nesting depth, attribute-count-per-element,
86
+ * per-attribute-value size.
87
+ *
88
+ * Threat-detection regex literals are composed PROGRAMMATICALLY from
89
+ * numeric codepoint range tables. Source file never embeds attack
90
+ * characters themselves.
91
+ */
92
+
93
+ var codepointClass = require("./codepoint-class");
94
+ var lazyRequire = require("./lazy-require");
95
+ var gateContract = require("./gate-contract");
96
+ var C = require("./constants");
97
+ var numericBounds = require("./numeric-bounds");
98
+ var safeUrl = require("./safe-url");
99
+ var { GuardSvgError } = require("./framework-error");
100
+
101
+ var observability = lazyRequire(function () { return require("./observability"); });
102
+ void observability;
103
+
104
+ var _err = GuardSvgError.factory;
105
+ var HEX_RADIX = 16; // allow:raw-byte-literal — base-16 radix, not byte size
106
+
107
+ // ---- Codepoint catalog (shared via lib/codepoint-class) ----
108
+
109
+ var C0_CTRL_RE_G = codepointClass.C0_CTRL_RE_G;
110
+ var ZW_RE_G = codepointClass.ZW_RE_G;
111
+
112
+ // ---- Tag classification ----
113
+
114
+ // Always-dangerous SVG tags. Active scripts, namespace-shift escape
115
+ // hatches, plugin embeds, animation elements (per recent CVE class),
116
+ // event-handler elements.
117
+ var DANGEROUS_TAGS = Object.freeze([
118
+ "script", "foreignobject", "handler", "listener",
119
+ "iframe", "embed", "object", "audio", "video",
120
+ "animate", "set", "animatemotion", "animatetransform", "discard",
121
+ ]);
122
+
123
+ // Animation-element family — when allowed under non-strict profiles,
124
+ // the attributeName attribute MUST be in the safe-targets allowlist.
125
+ // Animation elements are dangerous because they can target other
126
+ // elements' attributes dynamically; sanitizers that scrub href on
127
+ // elements miss the case where <animate attributeName="href" to="..."/>
128
+ // retroactively poisons the parent's href.
129
+ var ANIMATION_TAGS = Object.freeze([
130
+ "animate", "set", "animatemotion", "animatetransform",
131
+ ]);
132
+
133
+ var ANIMATION_SAFE_TARGETS = Object.freeze([
134
+ "cx", "cy", "r", "rx", "ry", "x", "y", "x1", "x2", "y1", "y2",
135
+ "width", "height", "fill", "stroke", "stroke-width", "stroke-opacity",
136
+ "fill-opacity", "opacity", "transform", "d", "points",
137
+ "viewBox", "offset", "stop-color", "stop-opacity",
138
+ ]);
139
+
140
+ // Strict allowlist — minimal text + shapes only.
141
+ var STRICT_ALLOWED_TAGS = Object.freeze([
142
+ "svg", "g", "defs", "title", "desc", "metadata",
143
+ "path", "rect", "circle", "ellipse", "line", "polyline", "polygon",
144
+ "text", "tspan", "textpath",
145
+ ]);
146
+
147
+ // Balanced — adds visual primitives, gradients, filters, masks, basic
148
+ // reuse via <use> + <symbol>, <image> with same-origin or http(s).
149
+ var BALANCED_ALLOWED_TAGS = Object.freeze(STRICT_ALLOWED_TAGS.concat([
150
+ "use", "symbol", "image", "pattern", "marker", "clippath", "mask",
151
+ "lineargradient", "radialgradient", "stop", "filter",
152
+ "fegaussianblur", "fecolormatrix", "feoffset", "feblend", "feflood",
153
+ "femerge", "femergenode", "fecomposite", "feimage", "feturbulence",
154
+ "fedisplacementmap", "felighting", "fediffuselighting",
155
+ "fespecularlighting", "fedistantlight", "fepointlight",
156
+ "fespotlight", "fecomponenttransfer", "fefunca", "fefuncr",
157
+ "fefuncg", "fefuncb", "fetile", "feconvolvematrix", "femorphology",
158
+ "switch", "a",
159
+ ]));
160
+
161
+ // Permissive — adds animation elements (with strict attributeName
162
+ // allowlist still enforced).
163
+ var PERMISSIVE_ALLOWED_TAGS = Object.freeze(BALANCED_ALLOWED_TAGS.concat([
164
+ // Animation enabled in permissive — attributeName allowlist still applies.
165
+ "animate", "set", "animatemotion", "animatetransform",
166
+ "mpath", "altglyph", "tref", "glyphref", "view",
167
+ ]));
168
+
169
+ var DANGEROUS_ATTRS = Object.freeze([
170
+ // Animation-element href targeting — even when the element is
171
+ // allowed, these attribute values can carry javascript:. Surfaced as
172
+ // a dangerous attribute whose VALUE goes through scheme validation.
173
+ "href", "xlink:href", "src", "to", "from", "by", "values",
174
+ // SMIL begin/end can carry javascript-shape conditions.
175
+ "begin", "end",
176
+ ]);
177
+
178
+ // URL-bearing attributes — values get scheme-validated.
179
+ var URL_ATTRS = Object.freeze([
180
+ "href", "xlink:href", "src", "data", "action", "formaction",
181
+ "background", "poster", "icon",
182
+ ]);
183
+
184
+ var SAFE_SCHEMES = Object.freeze(["http", "https", "mailto", "tel"]);
185
+
186
+ var DANGEROUS_SCHEMES = Object.freeze([
187
+ "javascript", "vbscript", "livescript", "mocha", "ecmascript",
188
+ "file", "mhtml", "jar", "intent", "view-source", "feed", "data",
189
+ ]);
190
+
191
+ var CSS_DANGEROUS_PATTERNS = Object.freeze([
192
+ /expression\s*\(/i,
193
+ /behavior\s*:/i,
194
+ /-moz-binding/i,
195
+ /javascript\s*:/i,
196
+ /vbscript\s*:/i,
197
+ /livescript\s*:/i,
198
+ /@import/i,
199
+ /@namespace/i,
200
+ ]);
201
+
202
+ var EVENT_HANDLER_RE = /^on[a-z]/i;
203
+
204
+ // SVGZ magic bytes — gzip-compressed SVG. 0x1F 0x8B is the gzip
205
+ // signature; SVG spec allows compressed delivery but content-safety
206
+ // gates can't peer inside without ungzipping. Refused at gate level
207
+ // regardless of profile.
208
+ var GZIP_MAGIC = Buffer.from([0x1F, 0x8B]); // allow:raw-byte-literal — gzip RFC 1952 §2.3.1 magic, not byte size
209
+
210
+ // ---- Profile presets ----
211
+
212
+ var PROFILES = Object.freeze({
213
+ "strict": {
214
+ allowedTags: STRICT_ALLOWED_TAGS,
215
+ allowedAttrs: Object.freeze([
216
+ "id", "class", "viewbox", "xmlns", "xmlns:xlink", "version",
217
+ "width", "height", "x", "y", "x1", "x2", "y1", "y2",
218
+ "cx", "cy", "r", "rx", "ry", "d", "points", "transform",
219
+ "fill", "stroke", "stroke-width", "stroke-opacity", "fill-opacity",
220
+ "opacity", "stop-color", "stop-opacity", "offset", "preserveaspectratio",
221
+ "font-family", "font-size", "text-anchor", "dominant-baseline",
222
+ "lang", "xml:lang",
223
+ ]),
224
+ urlSchemes: SAFE_SCHEMES,
225
+ allowImageData: false,
226
+ allowExternalRefs: false,
227
+ allowAnimation: false,
228
+ allowedAttrNames: ANIMATION_SAFE_TARGETS,
229
+ bidiPolicy: "reject",
230
+ controlPolicy: "reject",
231
+ nullBytePolicy: "reject",
232
+ zeroWidthPolicy: "strip",
233
+ cssPolicy: "reject",
234
+ doctypePolicy: "reject",
235
+ cdataPolicy: "reject",
236
+ processingInstrPolicy: "reject",
237
+ svgzPolicy: "reject",
238
+ maxBytes: C.BYTES.mib(2),
239
+ maxAttrValueBytes: C.BYTES.kib(8),
240
+ maxElementCount: 0x2000, // allow:raw-byte-literal — element count limit, not bytes
241
+ maxUseDepth: 8, // allow:raw-byte-literal — use-element nesting count, not bytes
242
+ maxAttrsPerTag: 64, // allow:raw-byte-literal — attribute count, not bytes
243
+ },
244
+ "balanced": {
245
+ allowedTags: BALANCED_ALLOWED_TAGS,
246
+ allowedAttrs: null, // inherit strict + add per-tag
247
+ urlSchemes: Object.freeze(SAFE_SCHEMES.concat(["ftp"])),
248
+ allowImageData: true,
249
+ allowExternalRefs: true,
250
+ allowAnimation: false,
251
+ allowedAttrNames: ANIMATION_SAFE_TARGETS,
252
+ bidiPolicy: "strip",
253
+ controlPolicy: "strip",
254
+ nullBytePolicy: "strip",
255
+ zeroWidthPolicy: "strip",
256
+ cssPolicy: "strip",
257
+ doctypePolicy: "reject",
258
+ cdataPolicy: "audit",
259
+ processingInstrPolicy: "reject",
260
+ svgzPolicy: "reject",
261
+ maxBytes: C.BYTES.mib(8),
262
+ maxAttrValueBytes: C.BYTES.kib(32),
263
+ maxElementCount: 0x10000, // allow:raw-byte-literal — element count limit, not bytes
264
+ maxUseDepth: 16, // allow:raw-byte-literal — use-element nesting count, not bytes
265
+ maxAttrsPerTag: 128, // allow:raw-byte-literal — attribute count, not bytes
266
+ },
267
+ "permissive": {
268
+ allowedTags: PERMISSIVE_ALLOWED_TAGS,
269
+ allowedAttrs: null,
270
+ urlSchemes: Object.freeze(SAFE_SCHEMES.concat(["ftp", "sftp"])),
271
+ allowImageData: true,
272
+ allowExternalRefs: true,
273
+ allowAnimation: true,
274
+ allowedAttrNames: ANIMATION_SAFE_TARGETS,
275
+ bidiPolicy: "audit",
276
+ controlPolicy: "strip",
277
+ nullBytePolicy: "strip",
278
+ zeroWidthPolicy: "strip",
279
+ cssPolicy: "audit",
280
+ doctypePolicy: "reject",
281
+ cdataPolicy: "audit",
282
+ processingInstrPolicy: "audit",
283
+ svgzPolicy: "reject",
284
+ maxBytes: C.BYTES.mib(32),
285
+ maxAttrValueBytes: C.BYTES.kib(64),
286
+ maxElementCount: 0x40000, // allow:raw-byte-literal — element count limit, not bytes
287
+ maxUseDepth: 32, // allow:raw-byte-literal — use-element nesting count, not bytes
288
+ maxAttrsPerTag: 256, // allow:raw-byte-literal — attribute count, not bytes
289
+ },
290
+ });
291
+
292
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
293
+ mode: "enforce",
294
+ maxRuntimeMs: C.TIME.seconds(30),
295
+ }));
296
+
297
+ var COMPLIANCE_POSTURES = Object.freeze({
298
+ "hipaa": {
299
+ allowedTags: STRICT_ALLOWED_TAGS,
300
+ bidiPolicy: "reject",
301
+ controlPolicy: "reject",
302
+ nullBytePolicy: "reject",
303
+ cssPolicy: "reject",
304
+ doctypePolicy: "reject",
305
+ allowExternalRefs: false,
306
+ allowAnimation: false,
307
+ forensicSnippetBytes: C.BYTES.bytes(256),
308
+ },
309
+ "pci-dss": {
310
+ allowedTags: STRICT_ALLOWED_TAGS,
311
+ bidiPolicy: "reject",
312
+ controlPolicy: "reject",
313
+ nullBytePolicy: "reject",
314
+ cssPolicy: "reject",
315
+ doctypePolicy: "reject",
316
+ allowExternalRefs: false,
317
+ allowAnimation: false,
318
+ urlSchemes: SAFE_SCHEMES,
319
+ forensicSnippetBytes: C.BYTES.bytes(256),
320
+ },
321
+ "gdpr": {
322
+ allowedTags: BALANCED_ALLOWED_TAGS,
323
+ bidiPolicy: "strip",
324
+ controlPolicy: "strip",
325
+ cssPolicy: "strip",
326
+ doctypePolicy: "reject",
327
+ allowAnimation: false,
328
+ forensicSnippetBytes: C.BYTES.bytes(128),
329
+ },
330
+ "soc2-cc7": {
331
+ allowedTags: STRICT_ALLOWED_TAGS,
332
+ bidiPolicy: "reject",
333
+ controlPolicy: "reject",
334
+ nullBytePolicy: "reject",
335
+ cssPolicy: "reject",
336
+ doctypePolicy: "reject",
337
+ allowExternalRefs: false,
338
+ allowAnimation: false,
339
+ forensicSnippetBytes: C.BYTES.bytes(512),
340
+ },
341
+ });
342
+
343
+ // ---- Internal helpers ----
344
+
345
+ function _resolveOpts(opts) {
346
+ return gateContract.resolveProfileAndPosture(opts, {
347
+ profiles: PROFILES,
348
+ compliancePostures: COMPLIANCE_POSTURES,
349
+ defaults: DEFAULTS,
350
+ errorClass: GuardSvgError,
351
+ errCodePrefix: "svg",
352
+ });
353
+ }
354
+
355
+ function _extractScheme(rawUrl) {
356
+ var s = String(rawUrl || "").trim();
357
+ s = s.replace(/&#x([0-9a-f]+);/gi, function (_m, h) {
358
+ return String.fromCharCode(parseInt(h, HEX_RADIX));
359
+ });
360
+ s = s.replace(/&#(\d+);/g, function (_m, d) {
361
+ return String.fromCharCode(parseInt(d, 10));
362
+ });
363
+ s = s.replace(C0_CTRL_RE_G, "").replace(ZW_RE_G, "");
364
+ var m = s.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
365
+ return m ? m[1].toLowerCase() : "";
366
+ }
367
+
368
+ function _isImageDataUrl(rawUrl) {
369
+ var s = String(rawUrl || "").trim();
370
+ return /^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);/i.test(s);
371
+ }
372
+
373
+ function _isFragmentRef(rawUrl) {
374
+ var s = String(rawUrl || "").trim();
375
+ return s.length === 0 || s.charAt(0) === "#";
376
+ }
377
+
378
+ function _isCssDangerous(value) {
379
+ for (var i = 0; i < CSS_DANGEROUS_PATTERNS.length; i += 1) {
380
+ if (CSS_DANGEROUS_PATTERNS[i].test(value)) return true;
381
+ }
382
+ return false;
383
+ }
384
+
385
+ // SVGZ detection — gzip magic bytes 0x1F 0x8B at byte 0.
386
+ function _isSvgz(input) {
387
+ var buf;
388
+ if (Buffer.isBuffer(input)) buf = input;
389
+ else if (typeof input === "string") buf = Buffer.from(input, "utf8");
390
+ else return false;
391
+ if (buf.length < 2) return false;
392
+ return buf[0] === GZIP_MAGIC[0] && buf[1] === GZIP_MAGIC[1];
393
+ }
394
+
395
+ // ---- Tokenizer (SVG-flavoured) ----
396
+ //
397
+ // Pure-JS XML/SVG scanner. Emits tokens: { type, name, attrs, raw,
398
+ // start, end }. Handles XML processing instructions (<?...?>),
399
+ // DOCTYPE, CDATA, comments, start/end tags, self-closing.
400
+
401
+ function _tokenize(input, maxBytes) {
402
+ var s = String(input || "");
403
+ if (s.length > maxBytes) {
404
+ throw _err("svg.too-large",
405
+ "input " + s.length + " bytes exceeds maxBytes " + maxBytes);
406
+ }
407
+ var tokens = [];
408
+ var len = s.length;
409
+ var pos = 0;
410
+
411
+ while (pos < len) {
412
+ var lt = s.indexOf("<", pos);
413
+ if (lt === -1) {
414
+ tokens.push({ type: "text", raw: s.slice(pos), start: pos, end: len });
415
+ break;
416
+ }
417
+ if (lt > pos) {
418
+ tokens.push({ type: "text", raw: s.slice(pos, lt), start: pos, end: lt });
419
+ }
420
+
421
+ if (s.startsWith("<!--", lt)) {
422
+ var endC = s.indexOf("-->", lt + 4);
423
+ if (endC === -1) endC = len; else endC += 3;
424
+ tokens.push({ type: "comment", raw: s.slice(lt, endC), start: lt, end: endC });
425
+ pos = endC; continue;
426
+ }
427
+ if (s.startsWith("<![CDATA[", lt)) {
428
+ var endX = s.indexOf("]]>", lt + 9);
429
+ if (endX === -1) endX = len; else endX += 3;
430
+ tokens.push({ type: "cdata", raw: s.slice(lt, endX), start: lt, end: endX });
431
+ pos = endX; continue;
432
+ }
433
+ if (s.startsWith("<!DOCTYPE", lt) || s.startsWith("<!doctype", lt)) {
434
+ // DOCTYPE may carry an internal subset [...] — match balanced.
435
+ var p = lt + 9;
436
+ while (p < len && s.charAt(p) !== ">" && s.charAt(p) !== "[") p += 1;
437
+ if (p < len && s.charAt(p) === "[") {
438
+ var end1 = s.indexOf("]", p);
439
+ if (end1 === -1) end1 = len;
440
+ var end2 = s.indexOf(">", end1);
441
+ if (end2 === -1) end2 = len; else end2 += 1;
442
+ tokens.push({ type: "doctype", raw: s.slice(lt, end2), start: lt, end: end2 });
443
+ pos = end2; continue;
444
+ }
445
+ var end3 = s.indexOf(">", lt);
446
+ if (end3 === -1) end3 = len; else end3 += 1;
447
+ tokens.push({ type: "doctype", raw: s.slice(lt, end3), start: lt, end: end3 });
448
+ pos = end3; continue;
449
+ }
450
+ if (s.charAt(lt + 1) === "?") {
451
+ var endP = s.indexOf("?>", lt + 2);
452
+ if (endP === -1) endP = len; else endP += 2;
453
+ tokens.push({ type: "processingInstruction", raw: s.slice(lt, endP), start: lt, end: endP });
454
+ pos = endP; continue;
455
+ }
456
+ if (s.charAt(lt + 1) === "!") {
457
+ // Other declarations (e.g. <!ENTITY ...>, <!ATTLIST ...>) — flagged.
458
+ var endD = s.indexOf(">", lt);
459
+ if (endD === -1) endD = len; else endD += 1;
460
+ tokens.push({ type: "declaration", raw: s.slice(lt, endD), start: lt, end: endD });
461
+ pos = endD; continue;
462
+ }
463
+
464
+ if (s.charAt(lt + 1) === "/") {
465
+ var endE = s.indexOf(">", lt);
466
+ if (endE === -1) endE = len; else endE += 1;
467
+ var endName = s.slice(lt + 2, endE - 1).trim().toLowerCase().split(/\s/)[0];
468
+ tokens.push({
469
+ type: "endTag", name: endName,
470
+ raw: s.slice(lt, endE), start: lt, end: endE,
471
+ });
472
+ pos = endE; continue;
473
+ }
474
+
475
+ var pp = lt + 1;
476
+ var inQuote = "";
477
+ while (pp < len) {
478
+ var ch = s.charAt(pp);
479
+ if (inQuote) { if (ch === inQuote) inQuote = ""; }
480
+ else {
481
+ if (ch === '"' || ch === "'") inQuote = ch;
482
+ else if (ch === ">") break;
483
+ }
484
+ pp += 1;
485
+ }
486
+ var endT = pp < len ? pp + 1 : len;
487
+ var raw = s.slice(lt, endT);
488
+ var inner = raw.slice(1, raw.charAt(raw.length - 1) === ">" ? raw.length - 1 : raw.length);
489
+ var selfClosing = inner.endsWith("/");
490
+ if (selfClosing) inner = inner.slice(0, inner.length - 1);
491
+
492
+ var nameMatch = inner.match(/^([A-Za-z][A-Za-z0-9:_-]*)/);
493
+ var tagName = nameMatch ? nameMatch[1].toLowerCase() : "";
494
+ var attrSrc = nameMatch ? inner.slice(nameMatch[0].length) : "";
495
+
496
+ var attrs = _parseAttrs(attrSrc);
497
+ tokens.push({
498
+ type: "tag", name: tagName, attrs: attrs,
499
+ raw: raw, start: lt, end: endT, selfClosing: selfClosing,
500
+ });
501
+ pos = endT;
502
+ }
503
+ return tokens;
504
+ }
505
+
506
+ function _parseAttrs(src) {
507
+ var attrs = [];
508
+ var s = src.trim();
509
+ var len = s.length;
510
+ var p = 0;
511
+ while (p < len) {
512
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
513
+ if (p >= len) break;
514
+ var nameStart = p;
515
+ while (p < len && !/[\s=>/]/.test(s.charAt(p))) p += 1;
516
+ var attrName = s.slice(nameStart, p);
517
+ if (!attrName) break;
518
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
519
+ var attrValue = "";
520
+ if (p < len && s.charAt(p) === "=") {
521
+ p += 1;
522
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
523
+ var q = s.charAt(p);
524
+ if (q === '"' || q === "'") {
525
+ var endQ = s.indexOf(q, p + 1);
526
+ if (endQ === -1) endQ = len;
527
+ attrValue = s.slice(p + 1, endQ);
528
+ p = endQ + 1;
529
+ } else {
530
+ var valStart = p;
531
+ while (p < len && !/[\s>]/.test(s.charAt(p))) p += 1;
532
+ attrValue = s.slice(valStart, p);
533
+ }
534
+ }
535
+ attrs.push({ name: attrName, value: attrValue });
536
+ }
537
+ return attrs;
538
+ }
539
+
540
+ // ---- Detection pass ----
541
+
542
+ function _detectIssues(input, opts) {
543
+ if (_isSvgz(input)) {
544
+ return [{
545
+ kind: "svgz-compressed", severity: "critical", ruleId: "svg.svgz",
546
+ location: 0,
547
+ snippet: "compressed SVGZ payload (gzip magic 0x1F 0x8B); ungzip + re-validate the inner SVG",
548
+ }];
549
+ }
550
+
551
+ var s = typeof input === "string" ? input : Buffer.from(input).toString("utf8");
552
+ var issues = codepointClass.detectCharThreats(s, opts, "svg");
553
+
554
+ var tokens;
555
+ try { tokens = _tokenize(s, opts.maxBytes); }
556
+ catch (e) {
557
+ issues.push({
558
+ kind: "tokenize-failed", severity: "high", ruleId: "svg.tokenize",
559
+ snippet: e && e.message,
560
+ });
561
+ return issues;
562
+ }
563
+
564
+ if (tokens.length > opts.maxElementCount) {
565
+ issues.push({
566
+ kind: "element-count-cap", severity: "high",
567
+ ruleId: "svg.element-count",
568
+ snippet: "token count " + tokens.length + " exceeds maxElementCount " + opts.maxElementCount,
569
+ });
570
+ }
571
+
572
+ var allowedTags = Object.create(null);
573
+ (opts.allowedTags || []).forEach(function (t) { allowedTags[t.toLowerCase()] = true; });
574
+ var dangerousTags = Object.create(null);
575
+ DANGEROUS_TAGS.forEach(function (t) { dangerousTags[t] = true; });
576
+ var animationTags = Object.create(null);
577
+ ANIMATION_TAGS.forEach(function (t) { animationTags[t] = true; });
578
+ var safeAttrNames = Object.create(null);
579
+ (opts.allowedAttrNames || []).forEach(function (n) { safeAttrNames[n.toLowerCase()] = true; });
580
+
581
+ var useDepth = 0;
582
+ for (var i = 0; i < tokens.length; i += 1) {
583
+ var tok = tokens[i];
584
+
585
+ if (tok.type === "doctype" && opts.doctypePolicy !== "allow") {
586
+ issues.push({
587
+ kind: "doctype", severity: "critical", ruleId: "svg.doctype",
588
+ location: tok.start,
589
+ snippet: "DOCTYPE declaration (billion-laughs / XXE vector)",
590
+ });
591
+ // Internal-subset entity declaration.
592
+ if (/<!ENTITY/i.test(tok.raw)) {
593
+ issues.push({
594
+ kind: "entity-declaration", severity: "critical",
595
+ ruleId: "svg.entity",
596
+ location: tok.start,
597
+ snippet: "<!ENTITY> declaration (entity-expansion DoS / XXE)",
598
+ });
599
+ }
600
+ continue;
601
+ }
602
+ if (tok.type === "declaration" && /<!ENTITY/i.test(tok.raw)) {
603
+ issues.push({
604
+ kind: "entity-declaration", severity: "critical",
605
+ ruleId: "svg.entity",
606
+ location: tok.start,
607
+ snippet: "<!ENTITY> declaration",
608
+ });
609
+ continue;
610
+ }
611
+ if (tok.type === "cdata" && opts.cdataPolicy !== "allow") {
612
+ issues.push({
613
+ kind: "cdata", severity: opts.cdataPolicy === "reject" ? "critical" : "warn",
614
+ ruleId: "svg.cdata",
615
+ location: tok.start,
616
+ snippet: "CDATA section (often used to hide payloads)",
617
+ });
618
+ continue;
619
+ }
620
+ if (tok.type === "processingInstruction" &&
621
+ opts.processingInstrPolicy !== "allow") {
622
+ issues.push({
623
+ kind: "processing-instruction",
624
+ severity: opts.processingInstrPolicy === "reject" ? "critical" : "warn",
625
+ ruleId: "svg.pi",
626
+ location: tok.start,
627
+ snippet: "XML processing instruction (e.g. xml-stylesheet — CSS injection vector)",
628
+ });
629
+ continue;
630
+ }
631
+
632
+ if (tok.type !== "tag") continue;
633
+
634
+ if (Array.isArray(tok.attrs) && tok.attrs.length > opts.maxAttrsPerTag) {
635
+ issues.push({
636
+ kind: "attr-count-cap", severity: "high", ruleId: "svg.attr-count",
637
+ location: tok.start,
638
+ snippet: "attribute count exceeds maxAttrsPerTag",
639
+ });
640
+ }
641
+
642
+ if (dangerousTags[tok.name]) {
643
+ // Animation tags are dangerous unless allowAnimation.
644
+ if (animationTags[tok.name] && opts.allowAnimation) {
645
+ // Allowed — fall through to attribute scan with attributeName check.
646
+ } else {
647
+ issues.push({
648
+ kind: "dangerous-tag", severity: "critical", ruleId: "svg.tag",
649
+ location: tok.start,
650
+ snippet: "dangerous SVG tag <" + tok.name + ">",
651
+ });
652
+ continue;
653
+ }
654
+ } else if (Object.keys(allowedTags).length > 0 && !allowedTags[tok.name]) {
655
+ issues.push({
656
+ kind: "non-allowlisted-tag", severity: "high", ruleId: "svg.tag",
657
+ location: tok.start,
658
+ snippet: "tag <" + tok.name + "> not in allowedTags",
659
+ });
660
+ }
661
+
662
+ if (tok.name === "use") useDepth += 1;
663
+ if (useDepth > opts.maxUseDepth) {
664
+ issues.push({
665
+ kind: "use-depth-cap", severity: "high", ruleId: "svg.use-depth",
666
+ location: tok.start,
667
+ snippet: "<use> nesting depth exceeds maxUseDepth",
668
+ });
669
+ }
670
+
671
+ var attrs = tok.attrs || [];
672
+ for (var ai = 0; ai < attrs.length; ai += 1) {
673
+ var a = attrs[ai];
674
+ var an = a.name.toLowerCase();
675
+ if (a.value && a.value.length > opts.maxAttrValueBytes) {
676
+ issues.push({
677
+ kind: "attr-value-too-large", severity: "high",
678
+ ruleId: "svg.attr-size",
679
+ location: tok.start,
680
+ snippet: "attribute " + JSON.stringify(an) + " value exceeds cap",
681
+ });
682
+ }
683
+ if (EVENT_HANDLER_RE.test(an)) { // allow:regex-no-length-cap — `an` is an attribute name from tokenizer, length-bounded by XML naming rules
684
+ issues.push({
685
+ kind: "event-handler", severity: "critical",
686
+ ruleId: "svg.event-handler",
687
+ location: tok.start,
688
+ snippet: "event-handler attribute " + JSON.stringify(an),
689
+ });
690
+ continue;
691
+ }
692
+
693
+ // attributeName on animation elements — must be in safe-targets.
694
+ if (animationTags[tok.name] && an === "attributename") {
695
+ var target = a.value.toLowerCase().trim();
696
+ if (!safeAttrNames[target]) {
697
+ issues.push({
698
+ kind: "animation-target", severity: "critical",
699
+ ruleId: "svg.animation",
700
+ location: tok.start,
701
+ snippet: "animation attributeName " + JSON.stringify(target) +
702
+ " targets non-safe attribute (potential href / xlink:href hijack)",
703
+ });
704
+ }
705
+ }
706
+
707
+ // URL-bearing attribute scheme check.
708
+ if (URL_ATTRS.indexOf(an) !== -1) {
709
+ var scheme = _extractScheme(a.value);
710
+ var fragment = _isFragmentRef(a.value);
711
+ if (!fragment && scheme && DANGEROUS_SCHEMES.indexOf(scheme) !== -1) {
712
+ // Image data exception on <image>.
713
+ if (scheme === "data" && opts.allowImageData &&
714
+ tok.name === "image" && _isImageDataUrl(a.value)) {
715
+ // allowed
716
+ } else {
717
+ issues.push({
718
+ kind: "dangerous-url-scheme", severity: "critical",
719
+ ruleId: "svg.url-scheme",
720
+ location: tok.start,
721
+ snippet: "dangerous URL scheme " + JSON.stringify(scheme) +
722
+ " in " + JSON.stringify(an),
723
+ });
724
+ }
725
+ } else if (!fragment && scheme && opts.urlSchemes &&
726
+ opts.urlSchemes.indexOf(scheme) === -1) {
727
+ if (!(scheme === "data" && opts.allowImageData &&
728
+ tok.name === "image" && _isImageDataUrl(a.value))) {
729
+ issues.push({
730
+ kind: "non-allowlisted-url-scheme", severity: "high",
731
+ ruleId: "svg.url-scheme",
732
+ location: tok.start,
733
+ snippet: "URL scheme " + JSON.stringify(scheme) +
734
+ " not in profile allowlist",
735
+ });
736
+ }
737
+ }
738
+ // Cross-origin <use> — require fragment-only when allowExternalRefs is false.
739
+ if ((tok.name === "use" || tok.name === "feimage") &&
740
+ !fragment && !opts.allowExternalRefs) {
741
+ issues.push({
742
+ kind: "external-ref", severity: "critical",
743
+ ruleId: "svg.external-ref",
744
+ location: tok.start,
745
+ snippet: "<" + tok.name + " " + an + "=> references external resource (SSRF + XSS chain)",
746
+ });
747
+ }
748
+ }
749
+
750
+ // CSS injection inside style="...".
751
+ if (an === "style" && opts.cssPolicy !== "allow") {
752
+ if (_isCssDangerous(a.value)) {
753
+ issues.push({
754
+ kind: "css-injection", severity: "critical",
755
+ ruleId: "svg.css",
756
+ location: tok.start,
757
+ snippet: "dangerous CSS token in style attribute",
758
+ });
759
+ }
760
+ }
761
+ }
762
+ }
763
+ return issues;
764
+ }
765
+
766
+ // ---- Sanitize pass ----
767
+
768
+ function _sanitize(input, opts) {
769
+ if (_isSvgz(input)) {
770
+ throw _err("svg.svgz", "compressed SVGZ payload — operator must ungzip before sanitize");
771
+ }
772
+ var s = typeof input === "string" ? input : Buffer.from(input).toString("utf8");
773
+ if (s.length > opts.maxBytes) {
774
+ throw _err("svg.too-large",
775
+ "input " + s.length + " bytes exceeds maxBytes " + opts.maxBytes);
776
+ }
777
+ codepointClass.assertNoCharThreats(s, opts, _err, "svg");
778
+
779
+ s = codepointClass.applyCharStripPolicies(s, opts);
780
+
781
+ var tokens = _tokenize(s, opts.maxBytes);
782
+ var allowedTags = Object.create(null);
783
+ (opts.allowedTags || []).forEach(function (t) { allowedTags[t.toLowerCase()] = true; });
784
+ var dangerousTags = Object.create(null);
785
+ DANGEROUS_TAGS.forEach(function (t) { dangerousTags[t] = true; });
786
+ var animationTags = Object.create(null);
787
+ ANIMATION_TAGS.forEach(function (t) { animationTags[t] = true; });
788
+ var safeAttrNames = Object.create(null);
789
+ (opts.allowedAttrNames || []).forEach(function (n) { safeAttrNames[n.toLowerCase()] = true; });
790
+
791
+ var BODY_DROP = { "script": true, "foreignobject": true, "handler": true,
792
+ "listener": true, "iframe": true, "embed": true,
793
+ "object": true, "audio": true, "video": true };
794
+
795
+ var out = [];
796
+ for (var i = 0; i < tokens.length; i += 1) {
797
+ var tok = tokens[i];
798
+ if (tok.type === "text") { out.push(tok.raw); continue; }
799
+ if (tok.type === "doctype" || tok.type === "declaration") continue;
800
+ if (tok.type === "cdata") continue;
801
+ if (tok.type === "processingInstruction") continue;
802
+ if (tok.type === "comment") continue;
803
+ if (tok.type === "endTag") {
804
+ if (allowedTags[tok.name]) out.push("</" + tok.name + ">");
805
+ continue;
806
+ }
807
+ var allowed = !dangerousTags[tok.name] && allowedTags[tok.name];
808
+ if (animationTags[tok.name] && opts.allowAnimation && allowedTags[tok.name]) {
809
+ // Animation element — re-check attributeName.
810
+ var safeAnimation = true;
811
+ (tok.attrs || []).forEach(function (a) {
812
+ if (a.name.toLowerCase() === "attributename" &&
813
+ !safeAttrNames[a.value.toLowerCase().trim()]) {
814
+ safeAnimation = false;
815
+ }
816
+ });
817
+ if (!safeAnimation) allowed = false;
818
+ }
819
+ if (!allowed) {
820
+ if (BODY_DROP[tok.name] && !tok.selfClosing) {
821
+ var depth2 = 1;
822
+ var j = i + 1;
823
+ while (j < tokens.length && depth2 > 0) {
824
+ var t2 = tokens[j];
825
+ if (t2.type === "tag" && t2.name === tok.name && !t2.selfClosing) depth2 += 1;
826
+ else if (t2.type === "endTag" && t2.name === tok.name) depth2 -= 1;
827
+ j += 1;
828
+ }
829
+ i = j - 1;
830
+ }
831
+ continue;
832
+ }
833
+
834
+ var attrParts = [];
835
+ var attrs = tok.attrs || [];
836
+ for (var ai = 0; ai < attrs.length; ai += 1) {
837
+ var a = attrs[ai];
838
+ var an = a.name.toLowerCase();
839
+ if (EVENT_HANDLER_RE.test(an)) continue; // allow:regex-no-length-cap — `an` is a tokenized attribute name, bounded
840
+ if (a.value && a.value.length > opts.maxAttrValueBytes) continue;
841
+ if (URL_ATTRS.indexOf(an) !== -1) {
842
+ var scheme = _extractScheme(a.value);
843
+ var fragment = _isFragmentRef(a.value);
844
+ if (!fragment && scheme && DANGEROUS_SCHEMES.indexOf(scheme) !== -1) {
845
+ if (!(scheme === "data" && opts.allowImageData &&
846
+ tok.name === "image" && _isImageDataUrl(a.value))) {
847
+ continue;
848
+ }
849
+ } else if (!fragment && scheme && opts.urlSchemes &&
850
+ opts.urlSchemes.indexOf(scheme) === -1) {
851
+ if (!(scheme === "data" && opts.allowImageData &&
852
+ tok.name === "image" && _isImageDataUrl(a.value))) {
853
+ continue;
854
+ }
855
+ }
856
+ if ((tok.name === "use" || tok.name === "feimage") &&
857
+ !fragment && !opts.allowExternalRefs) continue;
858
+ }
859
+ if (an === "style" && _isCssDangerous(a.value)) continue;
860
+ attrParts.push(an + "=\"" + a.value
861
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;")
862
+ .replace(/>/g, "&gt;").replace(/"/g, "&quot;") + "\"");
863
+ }
864
+ var open = "<" + tok.name + (attrParts.length ? " " + attrParts.join(" ") : "") +
865
+ (tok.selfClosing ? "/>" : ">");
866
+ out.push(open);
867
+ }
868
+ return out.join("");
869
+ }
870
+
871
+ // ---- Public surface ----
872
+
873
+ function validate(input, opts) {
874
+ opts = _resolveOpts(opts);
875
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
876
+ ["maxBytes", "maxElementCount", "maxUseDepth"],
877
+ "guardSvg.validate", GuardSvgError, "svg.bad-opt");
878
+
879
+ var bad = gateContract.badInputResultIfNotStringOrBuffer(input);
880
+ if (bad) return bad;
881
+ return gateContract.aggregateIssues(_detectIssues(input, opts));
882
+ }
883
+
884
+ function sanitize(input, opts) {
885
+ opts = _resolveOpts(opts);
886
+ if (typeof input !== "string" && !Buffer.isBuffer(input)) {
887
+ throw _err("svg.bad-input", "sanitize requires string or Buffer input");
888
+ }
889
+ return _sanitize(input, opts);
890
+ }
891
+
892
+ function gate(opts) {
893
+ opts = _resolveOpts(opts);
894
+ return gateContract.buildGuardGate(
895
+ opts.name || "guardSvg:" + (opts.profile || "default"),
896
+ opts,
897
+ async function (ctx) {
898
+ var bytes = ctx.bytes;
899
+ if (!bytes) return { ok: true, action: "serve" };
900
+ var rv = validate(bytes, opts);
901
+ if (rv.issues.length === 0) return { ok: true, action: "serve" };
902
+ var hasCritical = rv.issues.some(function (i) {
903
+ return i.severity === "critical" || i.severity === "high";
904
+ });
905
+ if (!hasCritical) return { ok: true, action: "audit-only", issues: rv.issues };
906
+
907
+ // SVGZ never sanitizable — refuse.
908
+ if (rv.issues.some(function (i) { return i.kind === "svgz-compressed"; })) {
909
+ return { ok: false, action: "refuse", issues: rv.issues };
910
+ }
911
+
912
+ if (opts.bidiPolicy !== "reject" &&
913
+ opts.controlPolicy !== "reject" &&
914
+ opts.nullBytePolicy !== "reject" &&
915
+ opts.cssPolicy !== "reject" &&
916
+ opts.doctypePolicy !== "reject") {
917
+ try {
918
+ var clean = sanitize(bytes, opts);
919
+ return {
920
+ ok: true, action: "sanitize",
921
+ sanitized: Buffer.from(clean, "utf8"),
922
+ issues: rv.issues,
923
+ };
924
+ } catch (_e) { /* fall through */ }
925
+ }
926
+ return { ok: false, action: "refuse", issues: rv.issues };
927
+ });
928
+ }
929
+
930
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
931
+
932
+ function compliancePosture(name) {
933
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "svg");
934
+ }
935
+
936
+ var _svgRulePacks = gateContract.makeRulePackLoader(GuardSvgError, "svg");
937
+ var loadRulePack = _svgRulePacks.load;
938
+
939
+ void safeUrl;
940
+
941
+ module.exports = {
942
+ // ---- guard-* family registry exports ----
943
+ NAME: "svg",
944
+ KIND: "content",
945
+ MIME_TYPES: Object.freeze(["image/svg+xml"]),
946
+ EXTENSIONS: Object.freeze([".svg", ".svgz"]),
947
+ INTEGRATION_FIXTURES: Object.freeze({
948
+ kind: "content",
949
+ contentType: "image/svg+xml",
950
+ extension: ".svg",
951
+ benignBytes: Buffer.from('<svg><circle r="10"/></svg>', "utf8"),
952
+ // Hostile: <script> inside SVG; refused regardless of profile.
953
+ hostileBytes: Buffer.from('<svg><script>alert(1)</script></svg>', "utf8"),
954
+ }),
955
+ // ---- primitive surface ----
956
+ validate: validate,
957
+ sanitize: sanitize,
958
+ gate: gate,
959
+ buildProfile: buildProfile,
960
+ compliancePosture: compliancePosture,
961
+ loadRulePack: loadRulePack,
962
+ PROFILES: PROFILES,
963
+ DEFAULTS: DEFAULTS,
964
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
965
+ DANGEROUS_TAGS: DANGEROUS_TAGS,
966
+ ANIMATION_TAGS: ANIMATION_TAGS,
967
+ ANIMATION_SAFE_TARGETS: ANIMATION_SAFE_TARGETS,
968
+ STRICT_ALLOWED_TAGS: STRICT_ALLOWED_TAGS,
969
+ BALANCED_ALLOWED_TAGS: BALANCED_ALLOWED_TAGS,
970
+ PERMISSIVE_ALLOWED_TAGS: PERMISSIVE_ALLOWED_TAGS,
971
+ DANGEROUS_ATTRS: DANGEROUS_ATTRS,
972
+ URL_ATTRS: URL_ATTRS,
973
+ SAFE_SCHEMES: SAFE_SCHEMES,
974
+ DANGEROUS_SCHEMES: DANGEROUS_SCHEMES,
975
+ GuardSvgError: GuardSvgError,
976
+ };