@blamejs/core 0.7.4 → 0.7.19

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.
@@ -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
+ };