@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-html — HTML content-safety primitive (b.guardHtml).
4
+ *
5
+ * Threat catalog grounded in 2026 sanitizer research (DOMPurify CVE-
6
+ * series, OWASP XSS / DOM-Clobbering / HTML5 Security cheat sheets,
7
+ * PortSwigger / Sonar / trace37 mXSS write-ups, html5sec.org).
8
+ *
9
+ * var rv = b.guardHtml.validate(input, { profile: "strict" });
10
+ * var safe = b.guardHtml.sanitize(input, { profile: "balanced" });
11
+ * var html = b.guardHtml.escapeText("<oops>"); // &lt;oops&gt;
12
+ * var attr = b.guardHtml.escapeAttr('say "hi"'); // say &quot;hi&quot;
13
+ * var g = b.guardHtml.gate({ profile: "strict" });
14
+ *
15
+ * Threat catalog covered:
16
+ *
17
+ * 1. Dangerous tags — <script>, <style>, <link>, <meta>, <base>,
18
+ * <iframe>, <object>, <embed>, <applet>, <form>, <input>,
19
+ * <button>, <textarea>, <select>, <isindex>, <marquee>, <blink>,
20
+ * <layer>, <ilayer>, <plaintext>, <listing>, <xmp>, <audio>,
21
+ * <video>, <source>, <track>, <math>, <svg>, <template>,
22
+ * <noscript>, <noembed>, <noframes>, <portal>, <dialog>,
23
+ * <keygen>, <menuitem>, <command>, <frame>, <frameset>.
24
+ * Every match per profile triggers refuse OR sanitize-strip.
25
+ *
26
+ * 2. on* event-handler attributes — every attribute matching
27
+ * /^on[a-z]/ is denied unconditionally. Catches the entire HTML5
28
+ * event-handler family (onclick, onerror, onload, onmouseover,
29
+ * onbeforeunload, onpaste, onwheel, onpointerdown, ontoggle, ...)
30
+ * without requiring a manual allowlist that rots the moment the
31
+ * WHATWG specs a new event.
32
+ *
33
+ * 3. Form-override attributes — formaction / formmethod /
34
+ * formenctype / formtarget / formnovalidate on <button> / <input>
35
+ * override the parent form's submission target (CWE-1021); always
36
+ * denied.
37
+ *
38
+ * 4. Iframe inline-HTML — srcdoc on <iframe> ships executable HTML
39
+ * directly into the document; always denied.
40
+ *
41
+ * 5. Custom-element registration — `is="..."` attribute mutates the
42
+ * element class via document.createElement(..., { is }); always
43
+ * denied.
44
+ *
45
+ * 6. CSP-bypass-shaped attributes — nonce, integrity, crossorigin
46
+ * stripped from sanitized output (operator-controlled only).
47
+ *
48
+ * 7. URL scheme validation on URL-bearing attributes — href, src,
49
+ * action, cite, longdesc, manifest, archive, codebase, data,
50
+ * classid, code, profile, ping, dynsrc, lowsrc, background,
51
+ * poster, icon, xlink:href. Per-attribute scheme allowlist:
52
+ * strict → http / https / mailto / tel only;
53
+ * balanced → +data:image/* + ftp;
54
+ * permissive → +ftp / sftp / ws / wss.
55
+ * Denied schemes (always): javascript / vbscript / livescript /
56
+ * mocha / data (outside image context) / file / mhtml / jar /
57
+ * intent / view-source.
58
+ *
59
+ * 8. CSS-injection inside style="..." attribute values — denies
60
+ * expression( (IE), behavior: (IE), -moz-binding (Firefox legacy),
61
+ * javascript: / vbscript: / livescript: inside url(), @import,
62
+ * @charset / @namespace (CSS-source-map confusion).
63
+ *
64
+ * 9. DOM clobbering — id and name attributes whose values match a
65
+ * well-known JS global (document, window, location, cookie,
66
+ * __proto__, constructor, ...) on form / input / button / anchor /
67
+ * img / iframe elements. Catches the form-element + input-name
68
+ * payload + named-property-access exfil chain.
69
+ *
70
+ * 10. mXSS hint detection — common parser-mode-shift vectors:
71
+ * <svg><p>...</svg>, <math><p>...</math>, <noscript>...</noscript>
72
+ * with quote+entity confusion, CDATA inside HTML mode, <template>
73
+ * content fragment with entity-encoded payloads. Surfaced as
74
+ * "mxss-hint" issues; refused in strict, audited in balanced.
75
+ *
76
+ * 11. Unicode bidi (CVE-2021-42574 Trojan Source) inside text and
77
+ * attribute values — same codepoint catalog as guard-csv.
78
+ *
79
+ * 12. C0 control characters, null bytes, zero-width chars in input —
80
+ * strip-or-reject per profile.
81
+ *
82
+ * 13. IE conditional comments — <!--[if ...]>...<![endif]--> can carry
83
+ * executable script in the legacy IE rendering path; refused in
84
+ * strict, stripped in balanced.
85
+ *
86
+ * 14. <base href> / <base target> — silently redirects every relative
87
+ * URL on the page; always denied.
88
+ *
89
+ * 15. <meta http-equiv> with refresh / Set-Cookie / X-XSS-Protection
90
+ * values — silent navigation + cookie injection; always denied.
91
+ *
92
+ * 16. ARIA spoofing — `role="button"` on a non-button element with
93
+ * attached event handlers (caught upstream by the on* handler
94
+ * strip); flagged for audit when role mismatches semantic tag.
95
+ *
96
+ * 17. Image-context data: URLs — sanitize allows data:image/png ;
97
+ * data:image/jpeg ; data:image/gif ; data:image/webp ;
98
+ * data:image/svg+xml requires explicit opt-in (svg embed is its
99
+ * own threat surface).
100
+ *
101
+ * 18. Total-document size cap (anti-DoS), per-attribute-value size
102
+ * cap, max-tag-depth (prevents recursion-shape parsers from
103
+ * stack-blowing), max-attribute-count-per-tag.
104
+ *
105
+ * Threat-detection regex literals are composed PROGRAMMATICALLY from
106
+ * numeric codepoint range tables (BIDI_RANGES / C0_CTRL_RANGES /
107
+ * ZERO_WIDTH_RANGES). Source file never embeds the attack characters
108
+ * themselves.
109
+ *
110
+ * Sanitize discipline: this module ships a token-level rewriter that
111
+ * preserves the allowlisted tag set and strips the rest. For HOSTILE
112
+ * sources, the documented correct response is validate + reject — not
113
+ * sanitize. mXSS bypasses against any non-DOM sanitizer are a known
114
+ * arms-race; the gate's "refuse" path is the one with strong invariants.
115
+ * Operators with display-of-untrusted-html requirements should
116
+ * additionally serve content under a strict CSP (default-src 'none' or
117
+ * sandboxed iframe).
118
+ */
119
+
120
+ var codepointClass = require("./codepoint-class");
121
+ var lazyRequire = require("./lazy-require");
122
+ var gateContract = require("./gate-contract");
123
+ var C = require("./constants");
124
+ var numericBounds = require("./numeric-bounds");
125
+ var safeUrl = require("./safe-url");
126
+ var { GuardHtmlError } = require("./framework-error");
127
+
128
+ var observability = lazyRequire(function () { return require("./observability"); });
129
+ void observability;
130
+
131
+ var _err = GuardHtmlError.factory;
132
+ var HEX_RADIX = 16; // allow:raw-byte-literal — base-16 radix, not byte size
133
+
134
+ // ---- Codepoint catalog (shared via lib/codepoint-class) ----
135
+
136
+ var C0_CTRL_RE_G = codepointClass.C0_CTRL_RE_G;
137
+ var ZW_RE_G = codepointClass.ZW_RE_G;
138
+
139
+ // ---- Tag denylists / allowlists ----
140
+
141
+ // Always-dangerous tags. Active scripts, plugin embeds, form elements,
142
+ // frames, foreign-content (svg/math), template (mxss vector), legacy
143
+ // parser-mode-shift tags, HTML5 newer-attack-surface elements.
144
+ var DANGEROUS_TAGS = Object.freeze([
145
+ "script", "style", "link", "meta", "base", "frame", "frameset",
146
+ "iframe", "object", "embed", "applet", "form", "input", "button",
147
+ "textarea", "select", "option", "optgroup", "fieldset", "legend",
148
+ "datalist", "isindex", "marquee", "blink", "layer", "ilayer",
149
+ "plaintext", "listing", "xmp", "audio", "video", "source", "track",
150
+ "math", "svg", "template", "noscript", "noembed", "noframes",
151
+ "portal", "dialog", "keygen", "menuitem", "command",
152
+ ]);
153
+
154
+ // Strict text-formatting allowlist.
155
+ var STRICT_ALLOWED_TAGS = Object.freeze([
156
+ "p", "br", "hr", "b", "i", "u", "s", "em", "strong", "code", "pre",
157
+ "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "blockquote",
158
+ "span", "div",
159
+ ]);
160
+
161
+ // Balanced — adds links, images, tables, semantic markup.
162
+ var BALANCED_ALLOWED_TAGS = Object.freeze(STRICT_ALLOWED_TAGS.concat([
163
+ "a", "img", "table", "thead", "tbody", "tfoot", "tr", "td", "th",
164
+ "caption", "colgroup", "col", "dl", "dt", "dd", "del", "ins",
165
+ "sub", "sup", "small", "abbr", "cite", "q", "kbd", "mark",
166
+ "figure", "figcaption", "address", "time",
167
+ ]));
168
+
169
+ // Permissive — every tag NOT in DANGEROUS_TAGS.
170
+ function _permissiveAllowed() {
171
+ var deny = Object.create(null);
172
+ DANGEROUS_TAGS.forEach(function (t) { deny[t] = true; });
173
+ // Common allowed set as the universe for the permissive list.
174
+ var universe = [
175
+ "html", "body", "head", "title", "main", "header", "footer",
176
+ "nav", "section", "article", "aside", "details", "summary",
177
+ "menu", "dir", "center", "font", "big", "tt", "strike",
178
+ "var", "samp", "i", "b", "u", "s", "em", "strong", "code", "pre",
179
+ "p", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6",
180
+ "ul", "ol", "li", "blockquote", "span", "div", "a", "img",
181
+ "table", "thead", "tbody", "tfoot", "tr", "td", "th", "caption",
182
+ "colgroup", "col", "dl", "dt", "dd", "del", "ins", "sub", "sup",
183
+ "small", "abbr", "cite", "q", "kbd", "mark", "figure", "figcaption",
184
+ "address", "time", "picture", "ruby", "rt", "rp", "wbr", "data",
185
+ "output", "progress", "meter", "bdo", "bdi",
186
+ ];
187
+ return Object.freeze(universe.filter(function (t) { return !deny[t]; }));
188
+ }
189
+ var PERMISSIVE_ALLOWED_TAGS = _permissiveAllowed();
190
+
191
+ // Form-override + dangerous attributes (excluding on*).
192
+ var DANGEROUS_ATTRS = Object.freeze([
193
+ "formaction", "formmethod", "formenctype", "formtarget", "formnovalidate",
194
+ "srcdoc", "is", "integrity", "nonce", "crossorigin",
195
+ "http-equiv", "manifest",
196
+ ]);
197
+
198
+ // URL-bearing attributes — values get scheme-validated.
199
+ var URL_ATTRS = Object.freeze([
200
+ "href", "src", "action", "cite", "longdesc", "manifest", "archive",
201
+ "codebase", "data", "classid", "code", "profile", "ping", "dynsrc",
202
+ "lowsrc", "background", "poster", "icon", "xlink:href",
203
+ ]);
204
+
205
+ // Always-allowed schemes (every profile).
206
+ var SAFE_SCHEMES = Object.freeze(["http", "https", "mailto", "tel"]);
207
+
208
+ // Schemes denied by default. `data` is dangerous globally except in
209
+ // image context (data:image/*) which is the only data: payload that
210
+ // can't directly script the page; the per-attribute check below honours
211
+ // that exception when allowImageData=true and the host tag is <img>.
212
+ var DANGEROUS_SCHEMES = Object.freeze([
213
+ "javascript", "vbscript", "livescript", "mocha", "ecmascript",
214
+ "file", "mhtml", "jar", "intent", "view-source", "feed", "data",
215
+ ]);
216
+
217
+ // CSS dangerous tokens — case-insensitive match against attribute
218
+ // value content.
219
+ var CSS_DANGEROUS_PATTERNS = Object.freeze([
220
+ /expression\s*\(/i,
221
+ /behavior\s*:/i,
222
+ /-moz-binding/i,
223
+ /javascript\s*:/i,
224
+ /vbscript\s*:/i,
225
+ /livescript\s*:/i,
226
+ /@import/i,
227
+ /@namespace/i,
228
+ ]);
229
+
230
+ // DOM-clobbering global-name targets. Element id/name matching one of
231
+ // these on a clobber-prone tag (form / input / button / a / img /
232
+ // iframe / object) overshadows the global access path.
233
+ var CLOBBER_GLOBALS = Object.freeze([
234
+ "document", "window", "location", "cookie", "top", "parent", "self",
235
+ "frames", "navigator", "history", "screen", "localStorage",
236
+ "sessionStorage", "indexedDB", "fetch", "XMLHttpRequest",
237
+ "atob", "btoa", "eval", "Function",
238
+ "constructor", "prototype", "__proto__", "innerHTML", "outerHTML",
239
+ "src", "href", "action", "form", "body", "head", "html",
240
+ "addEventListener", "removeEventListener", "postMessage",
241
+ "globalThis", "this", "import",
242
+ ]);
243
+
244
+ var CLOBBER_PRONE_TAGS = Object.freeze([
245
+ "form", "input", "button", "a", "img", "iframe", "object",
246
+ "embed", "select", "textarea",
247
+ ]);
248
+
249
+ var EVENT_HANDLER_RE = /^on[a-z]/i;
250
+
251
+ // ---- Profile presets ----
252
+
253
+ var PROFILES = Object.freeze({
254
+ "strict": {
255
+ allowedTags: STRICT_ALLOWED_TAGS,
256
+ allowedAttrs: Object.freeze(["class", "title", "lang", "dir"]),
257
+ urlSchemes: SAFE_SCHEMES,
258
+ allowImageData: false,
259
+ allowComments: false,
260
+ bidiPolicy: "reject",
261
+ controlPolicy: "reject",
262
+ nullBytePolicy: "reject",
263
+ zeroWidthPolicy: "strip",
264
+ cssPolicy: "reject",
265
+ domClobberPolicy: "reject",
266
+ mxssHintPolicy: "reject",
267
+ maxBytes: C.BYTES.mib(2),
268
+ maxAttrValueBytes: C.BYTES.kib(8),
269
+ maxTagDepth: 128, // allow:raw-byte-literal — tag-nesting depth count, not bytes
270
+ maxAttrsPerTag: 64, // allow:raw-byte-literal — attribute count per tag, not bytes
271
+ },
272
+ "balanced": {
273
+ allowedTags: BALANCED_ALLOWED_TAGS,
274
+ allowedAttrs: Object.freeze([
275
+ "class", "title", "lang", "dir", "alt", "href", "src", "width",
276
+ "height", "rel", "target", "colspan", "rowspan", "scope",
277
+ "datetime", "cite", "id",
278
+ ]),
279
+ urlSchemes: Object.freeze(SAFE_SCHEMES.concat(["ftp"])),
280
+ allowImageData: true,
281
+ allowComments: false,
282
+ bidiPolicy: "strip",
283
+ controlPolicy: "strip",
284
+ nullBytePolicy: "strip",
285
+ zeroWidthPolicy: "strip",
286
+ cssPolicy: "strip",
287
+ domClobberPolicy: "strip",
288
+ mxssHintPolicy: "audit",
289
+ maxBytes: C.BYTES.mib(8),
290
+ maxAttrValueBytes: C.BYTES.kib(32),
291
+ maxTagDepth: 256, // allow:raw-byte-literal — tag-nesting depth count, not bytes
292
+ maxAttrsPerTag: 128, // allow:raw-byte-literal — attribute count per tag, not bytes
293
+ },
294
+ "permissive": {
295
+ allowedTags: PERMISSIVE_ALLOWED_TAGS,
296
+ allowedAttrs: Object.freeze([
297
+ "class", "title", "lang", "dir", "alt", "href", "src", "width",
298
+ "height", "rel", "target", "colspan", "rowspan", "scope",
299
+ "datetime", "cite", "id", "tabindex", "accesskey",
300
+ ]),
301
+ urlSchemes: Object.freeze(SAFE_SCHEMES.concat(["ftp", "sftp", "ws", "wss"])),
302
+ allowImageData: true,
303
+ allowComments: true,
304
+ bidiPolicy: "audit",
305
+ controlPolicy: "strip",
306
+ nullBytePolicy: "strip",
307
+ zeroWidthPolicy: "strip",
308
+ cssPolicy: "audit",
309
+ domClobberPolicy: "audit",
310
+ mxssHintPolicy: "audit",
311
+ maxBytes: C.BYTES.mib(32),
312
+ maxAttrValueBytes: C.BYTES.kib(64),
313
+ maxTagDepth: 512, // allow:raw-byte-literal — tag-nesting depth count, not bytes
314
+ maxAttrsPerTag: 256, // allow:raw-byte-literal — attribute count per tag, not bytes
315
+ },
316
+ });
317
+
318
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
319
+ mode: "enforce",
320
+ maxRuntimeMs: C.TIME.seconds(30),
321
+ }));
322
+
323
+ var COMPLIANCE_POSTURES = Object.freeze({
324
+ "hipaa": {
325
+ allowedTags: STRICT_ALLOWED_TAGS,
326
+ bidiPolicy: "reject",
327
+ controlPolicy: "reject",
328
+ nullBytePolicy: "reject",
329
+ cssPolicy: "reject",
330
+ domClobberPolicy: "reject",
331
+ mxssHintPolicy: "reject",
332
+ forensicSnippetBytes: C.BYTES.bytes(256),
333
+ },
334
+ "pci-dss": {
335
+ allowedTags: STRICT_ALLOWED_TAGS,
336
+ bidiPolicy: "reject",
337
+ controlPolicy: "reject",
338
+ nullBytePolicy: "reject",
339
+ cssPolicy: "reject",
340
+ domClobberPolicy: "reject",
341
+ mxssHintPolicy: "reject",
342
+ urlSchemes: SAFE_SCHEMES,
343
+ forensicSnippetBytes: C.BYTES.bytes(256),
344
+ },
345
+ "gdpr": {
346
+ allowedTags: BALANCED_ALLOWED_TAGS,
347
+ bidiPolicy: "strip",
348
+ controlPolicy: "strip",
349
+ cssPolicy: "strip",
350
+ domClobberPolicy: "strip",
351
+ mxssHintPolicy: "audit",
352
+ forensicSnippetBytes: C.BYTES.bytes(128),
353
+ },
354
+ "soc2-cc7": {
355
+ allowedTags: STRICT_ALLOWED_TAGS,
356
+ bidiPolicy: "reject",
357
+ controlPolicy: "reject",
358
+ nullBytePolicy: "reject",
359
+ cssPolicy: "reject",
360
+ domClobberPolicy: "reject",
361
+ mxssHintPolicy: "reject",
362
+ forensicSnippetBytes: C.BYTES.bytes(512),
363
+ },
364
+ });
365
+
366
+ // ---- Internal helpers ----
367
+
368
+ function _resolveOpts(opts) {
369
+ return gateContract.resolveProfileAndPosture(opts, {
370
+ profiles: PROFILES,
371
+ compliancePostures: COMPLIANCE_POSTURES,
372
+ defaults: DEFAULTS,
373
+ errorClass: GuardHtmlError,
374
+ errCodePrefix: "html",
375
+ });
376
+ }
377
+
378
+ // HTML entity escape — text-content context. Encodes & < > " ' so the
379
+ // output is safe for embedding inside an element's text body.
380
+ function escapeText(value) {
381
+ var s = value == null ? "" : String(value);
382
+ return s
383
+ .replace(/&/g, "&amp;")
384
+ .replace(/</g, "&lt;")
385
+ .replace(/>/g, "&gt;")
386
+ .replace(/"/g, "&quot;")
387
+ .replace(/'/g, "&#39;");
388
+ }
389
+
390
+ // HTML entity escape — attribute-value context. Same encoding plus
391
+ // backtick (legacy IE attribute terminator) and = (unquoted-attr edge).
392
+ function escapeAttr(value) {
393
+ var s = value == null ? "" : String(value);
394
+ return s
395
+ .replace(/&/g, "&amp;")
396
+ .replace(/</g, "&lt;")
397
+ .replace(/>/g, "&gt;")
398
+ .replace(/"/g, "&quot;")
399
+ .replace(/'/g, "&#39;")
400
+ .replace(/`/g, "&#96;")
401
+ .replace(/=/g, "&#61;");
402
+ }
403
+
404
+ // _normalizeUrl — peel off entity-encoded leading whitespace and
405
+ // HTML/URL-encoded scheme prefix tricks, then return the lowercased
406
+ // scheme. Returns "" if no scheme.
407
+ function _extractScheme(rawUrl) {
408
+ var s = String(rawUrl || "").trim();
409
+ // Decode HTML numeric entities just enough to expose hidden schemes
410
+ // like &#x6A;avascript:... or &#106;avascript:...
411
+ s = s.replace(/&#x([0-9a-f]+);/gi, function (_m, h) {
412
+ return String.fromCharCode(parseInt(h, HEX_RADIX));
413
+ });
414
+ s = s.replace(/&#(\d+);/g, function (_m, d) {
415
+ return String.fromCharCode(parseInt(d, 10));
416
+ });
417
+ // Strip embedded whitespace + control chars + zero-widths the
418
+ // URL parser would tolerate.
419
+ s = s.replace(C0_CTRL_RE_G, "").replace(ZW_RE_G, "");
420
+ var m = s.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
421
+ return m ? m[1].toLowerCase() : "";
422
+ }
423
+
424
+ function _isImageDataUrl(rawUrl) {
425
+ var s = String(rawUrl || "").trim();
426
+ return /^data:image\/(png|jpeg|jpg|gif|webp);/i.test(s);
427
+ }
428
+
429
+ function _isUrlAttr(name) {
430
+ var n = name.toLowerCase();
431
+ for (var i = 0; i < URL_ATTRS.length; i += 1) {
432
+ if (URL_ATTRS[i] === n) return true;
433
+ }
434
+ return false;
435
+ }
436
+
437
+ function _isClobberProne(tag) {
438
+ var t = tag.toLowerCase();
439
+ for (var i = 0; i < CLOBBER_PRONE_TAGS.length; i += 1) {
440
+ if (CLOBBER_PRONE_TAGS[i] === t) return true;
441
+ }
442
+ return false;
443
+ }
444
+
445
+ function _isClobberGlobal(name) {
446
+ for (var i = 0; i < CLOBBER_GLOBALS.length; i += 1) {
447
+ if (CLOBBER_GLOBALS[i] === name) return true;
448
+ }
449
+ return false;
450
+ }
451
+
452
+ function _isCssDangerous(value) {
453
+ for (var i = 0; i < CSS_DANGEROUS_PATTERNS.length; i += 1) {
454
+ if (CSS_DANGEROUS_PATTERNS[i].test(value)) return true;
455
+ }
456
+ return false;
457
+ }
458
+
459
+ // ---- Tokenizer ----
460
+ //
461
+ // Pure-JS HTML scanner. NOT a full DOM parser — designed for threat
462
+ // detection and conservative tag/attr filtering. The output is a list
463
+ // of tokens: { type: "tag" | "endTag" | "comment" | "text" | "doctype",
464
+ // name, attrs, raw, start, end }. Sanitization re-walks this list and
465
+ // emits a filtered HTML string.
466
+
467
+ function _tokenize(input, maxBytes) {
468
+ var s = String(input || "");
469
+ if (s.length > maxBytes) {
470
+ throw _err("html.too-large",
471
+ "input " + s.length + " bytes exceeds maxBytes " + maxBytes);
472
+ }
473
+ var tokens = [];
474
+ var len = s.length;
475
+ var pos = 0;
476
+
477
+ while (pos < len) {
478
+ var lt = s.indexOf("<", pos);
479
+ if (lt === -1) {
480
+ tokens.push({ type: "text", raw: s.slice(pos), start: pos, end: len });
481
+ break;
482
+ }
483
+ if (lt > pos) {
484
+ tokens.push({ type: "text", raw: s.slice(pos, lt), start: pos, end: lt });
485
+ }
486
+
487
+ // Comment / CDATA / doctype
488
+ if (s.startsWith("<!--", lt)) {
489
+ var endC = s.indexOf("-->", lt + 4);
490
+ if (endC === -1) endC = len;
491
+ else endC += 3;
492
+ tokens.push({ type: "comment", raw: s.slice(lt, endC), start: lt, end: endC });
493
+ pos = endC; continue;
494
+ }
495
+ if (s.startsWith("<![CDATA[", lt)) {
496
+ var endX = s.indexOf("]]>", lt + 9);
497
+ if (endX === -1) endX = len;
498
+ else endX += 3;
499
+ tokens.push({ type: "cdata", raw: s.slice(lt, endX), start: lt, end: endX });
500
+ pos = endX; continue;
501
+ }
502
+ if (s.charAt(lt + 1) === "!") {
503
+ var endD = s.indexOf(">", lt);
504
+ if (endD === -1) endD = len;
505
+ else endD += 1;
506
+ tokens.push({ type: "doctype", raw: s.slice(lt, endD), start: lt, end: endD });
507
+ pos = endD; continue;
508
+ }
509
+
510
+ // End tag
511
+ if (s.charAt(lt + 1) === "/") {
512
+ var endE = s.indexOf(">", lt);
513
+ if (endE === -1) endE = len;
514
+ else endE += 1;
515
+ var endName = s.slice(lt + 2, endE - 1).trim().toLowerCase().split(/\s/)[0];
516
+ tokens.push({
517
+ type: "endTag", name: endName,
518
+ raw: s.slice(lt, endE), start: lt, end: endE,
519
+ });
520
+ pos = endE; continue;
521
+ }
522
+
523
+ // Start tag — find the matching `>`, but skip over `>` inside
524
+ // quoted attribute values.
525
+ var p = lt + 1;
526
+ var inQuote = "";
527
+ while (p < len) {
528
+ var ch = s.charAt(p);
529
+ if (inQuote) {
530
+ if (ch === inQuote) inQuote = "";
531
+ } else {
532
+ if (ch === '"' || ch === "'") inQuote = ch;
533
+ else if (ch === ">") break;
534
+ }
535
+ p += 1;
536
+ }
537
+ var endT = p < len ? p + 1 : len;
538
+ var raw = s.slice(lt, endT);
539
+ var inner = raw.slice(1, raw.charAt(raw.length - 1) === ">" ? raw.length - 1 : raw.length);
540
+ if (inner.endsWith("/")) inner = inner.slice(0, inner.length - 1);
541
+
542
+ var nameMatch = inner.match(/^([A-Za-z][A-Za-z0-9:-]*)/);
543
+ var tagName = nameMatch ? nameMatch[1].toLowerCase() : "";
544
+ var attrSrc = nameMatch ? inner.slice(nameMatch[0].length) : "";
545
+
546
+ var attrs = _parseAttrs(attrSrc);
547
+ tokens.push({
548
+ type: "tag", name: tagName, attrs: attrs,
549
+ raw: raw, start: lt, end: endT,
550
+ selfClosing: raw.charAt(raw.length - 2) === "/",
551
+ });
552
+ pos = endT;
553
+ }
554
+ return tokens;
555
+ }
556
+
557
+ function _parseAttrs(src) {
558
+ // Returns array of { name, value, raw } in source order. Preserves
559
+ // original casing of attribute names; consumers lowercase as needed.
560
+ var attrs = [];
561
+ var s = src.trim();
562
+ var len = s.length;
563
+ var p = 0;
564
+ while (p < len) {
565
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
566
+ if (p >= len) break;
567
+ var nameStart = p;
568
+ while (p < len && !/[\s=>/]/.test(s.charAt(p))) p += 1;
569
+ var attrName = s.slice(nameStart, p);
570
+ if (!attrName) break;
571
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
572
+ var attrValue = "";
573
+ var raw = attrName;
574
+ if (p < len && s.charAt(p) === "=") {
575
+ p += 1;
576
+ while (p < len && /\s/.test(s.charAt(p))) p += 1;
577
+ var q = s.charAt(p);
578
+ if (q === '"' || q === "'") {
579
+ var endQ = s.indexOf(q, p + 1);
580
+ if (endQ === -1) endQ = len;
581
+ attrValue = s.slice(p + 1, endQ);
582
+ raw = attrName + "=" + s.slice(p, endQ + 1);
583
+ p = endQ + 1;
584
+ } else {
585
+ var valStart = p;
586
+ while (p < len && !/[\s>]/.test(s.charAt(p))) p += 1;
587
+ attrValue = s.slice(valStart, p);
588
+ raw = attrName + "=" + attrValue;
589
+ }
590
+ }
591
+ attrs.push({ name: attrName, value: attrValue, raw: raw });
592
+ }
593
+ return attrs;
594
+ }
595
+
596
+ // ---- Detection pass ----
597
+
598
+ function _detectIssues(input, opts) {
599
+ var s = String(input || "");
600
+ // 1. Whole-input bidi / null-byte / control char threats.
601
+ var issues = codepointClass.detectCharThreats(s, opts, "html");
602
+
603
+ var tokens;
604
+ try { tokens = _tokenize(s, opts.maxBytes); }
605
+ catch (e) {
606
+ issues.push({
607
+ kind: "tokenize-failed", severity: "high", ruleId: "html.tokenize",
608
+ snippet: e && e.message,
609
+ });
610
+ return issues;
611
+ }
612
+
613
+ var allowedTags = Object.create(null);
614
+ (opts.allowedTags || []).forEach(function (t) { allowedTags[t.toLowerCase()] = true; });
615
+ var dangerousTags = Object.create(null);
616
+ DANGEROUS_TAGS.forEach(function (t) { dangerousTags[t] = true; });
617
+
618
+ var depth = 0;
619
+ for (var i = 0; i < tokens.length; i += 1) {
620
+ var tok = tokens[i];
621
+
622
+ if (tok.type === "comment") {
623
+ // IE conditional comments — `<!--[if ...]>` family.
624
+ if (/<!--\s*\[\s*if/i.test(tok.raw) && opts.allowComments !== true) {
625
+ issues.push({
626
+ kind: "ie-conditional-comment", severity: "high",
627
+ ruleId: "html.ie-conditional",
628
+ location: tok.start,
629
+ snippet: "IE conditional comment",
630
+ });
631
+ }
632
+ continue;
633
+ }
634
+
635
+ if (tok.type === "tag") {
636
+ depth += 1;
637
+ if (depth > opts.maxTagDepth) {
638
+ issues.push({
639
+ kind: "depth-cap", severity: "high", ruleId: "html.depth",
640
+ location: tok.start,
641
+ snippet: "tag nesting depth " + depth + " exceeds maxTagDepth " + opts.maxTagDepth,
642
+ });
643
+ }
644
+ if (Array.isArray(tok.attrs) && tok.attrs.length > opts.maxAttrsPerTag) {
645
+ issues.push({
646
+ kind: "attr-count-cap", severity: "high", ruleId: "html.attr-count",
647
+ location: tok.start,
648
+ snippet: "attribute count " + tok.attrs.length + " exceeds maxAttrsPerTag",
649
+ });
650
+ }
651
+ if (dangerousTags[tok.name]) {
652
+ issues.push({
653
+ kind: "dangerous-tag", severity: "critical", ruleId: "html.tag",
654
+ location: tok.start,
655
+ snippet: "dangerous tag <" + tok.name + ">",
656
+ });
657
+ } else if (Object.keys(allowedTags).length > 0 && !allowedTags[tok.name]) {
658
+ issues.push({
659
+ kind: "non-allowlisted-tag", severity: "high", ruleId: "html.tag",
660
+ location: tok.start,
661
+ snippet: "tag <" + tok.name + "> not in allowedTags",
662
+ });
663
+ }
664
+
665
+ // Per-attribute checks.
666
+ var attrs = tok.attrs || [];
667
+ for (var ai = 0; ai < attrs.length; ai += 1) {
668
+ var a = attrs[ai];
669
+ var an = a.name.toLowerCase();
670
+ if (a.value && a.value.length > opts.maxAttrValueBytes) {
671
+ issues.push({
672
+ kind: "attr-value-too-large", severity: "high",
673
+ ruleId: "html.attr-size",
674
+ location: tok.start,
675
+ snippet: "attribute " + JSON.stringify(an) + " value exceeds maxAttrValueBytes",
676
+ });
677
+ }
678
+ if (EVENT_HANDLER_RE.test(an)) { // allow:regex-no-length-cap — `an` is an attribute name from the tokenizer, length-bounded by HTML naming rules
679
+ issues.push({
680
+ kind: "event-handler", severity: "critical",
681
+ ruleId: "html.event-handler",
682
+ location: tok.start,
683
+ snippet: "event-handler attribute " + JSON.stringify(an),
684
+ });
685
+ continue;
686
+ }
687
+ if (DANGEROUS_ATTRS.indexOf(an) !== -1) {
688
+ issues.push({
689
+ kind: "dangerous-attr", severity: "critical",
690
+ ruleId: "html.attr",
691
+ location: tok.start,
692
+ snippet: "dangerous attribute " + JSON.stringify(an),
693
+ });
694
+ }
695
+ if (_isUrlAttr(an)) {
696
+ var scheme = _extractScheme(a.value);
697
+ if (scheme === "" && a.value && a.value.charAt(0) !== "#" &&
698
+ a.value.charAt(0) !== "/" && a.value.charAt(0) !== "?") {
699
+ // Relative URL — allowed.
700
+ } else if (scheme && DANGEROUS_SCHEMES.indexOf(scheme) !== -1) {
701
+ // Image-context data: special-case.
702
+ if (scheme === "data" && opts.allowImageData &&
703
+ tok.name === "img" && _isImageDataUrl(a.value)) {
704
+ // Allowed image data URL.
705
+ } else {
706
+ issues.push({
707
+ kind: "dangerous-url-scheme", severity: "critical",
708
+ ruleId: "html.url-scheme",
709
+ location: tok.start,
710
+ snippet: "dangerous URL scheme " + JSON.stringify(scheme) +
711
+ " in attribute " + JSON.stringify(an),
712
+ });
713
+ }
714
+ } else if (scheme && opts.urlSchemes &&
715
+ opts.urlSchemes.indexOf(scheme) === -1) {
716
+ if (!(scheme === "data" && opts.allowImageData &&
717
+ tok.name === "img" && _isImageDataUrl(a.value))) {
718
+ issues.push({
719
+ kind: "non-allowlisted-url-scheme", severity: "high",
720
+ ruleId: "html.url-scheme",
721
+ location: tok.start,
722
+ snippet: "URL scheme " + JSON.stringify(scheme) +
723
+ " not in profile allowlist",
724
+ });
725
+ }
726
+ }
727
+ }
728
+ if (an === "style" && opts.cssPolicy !== "allow") {
729
+ if (_isCssDangerous(a.value)) {
730
+ issues.push({
731
+ kind: "css-injection", severity: "critical",
732
+ ruleId: "html.css",
733
+ location: tok.start,
734
+ snippet: "dangerous CSS token in style attribute",
735
+ });
736
+ }
737
+ }
738
+ if ((an === "id" || an === "name") && _isClobberProne(tok.name) &&
739
+ opts.domClobberPolicy !== "allow" &&
740
+ _isClobberGlobal(a.value)) {
741
+ issues.push({
742
+ kind: "dom-clobber", severity: "critical",
743
+ ruleId: "html.dom-clobber",
744
+ location: tok.start,
745
+ snippet: "DOM-clobbering " + an + "=" + JSON.stringify(a.value) +
746
+ " on <" + tok.name + ">",
747
+ });
748
+ }
749
+ }
750
+
751
+ // mXSS hint — namespace-context-shift tags carrying nested HTML.
752
+ if ((tok.name === "svg" || tok.name === "math") &&
753
+ opts.mxssHintPolicy !== "allow") {
754
+ issues.push({
755
+ kind: "mxss-hint", severity: "high", ruleId: "html.mxss",
756
+ location: tok.start,
757
+ snippet: "<" + tok.name + "> namespace-context-shift parent (mXSS vector)",
758
+ });
759
+ }
760
+ } else if (tok.type === "endTag") {
761
+ depth = Math.max(0, depth - 1);
762
+ }
763
+ }
764
+
765
+ return issues;
766
+ }
767
+
768
+ // ---- Sanitize pass ----
769
+
770
+ function _sanitize(input, opts) {
771
+ var s = String(input || "");
772
+ if (s.length > opts.maxBytes) {
773
+ throw _err("html.too-large",
774
+ "input " + s.length + " bytes exceeds maxBytes " + opts.maxBytes);
775
+ }
776
+ codepointClass.assertNoCharThreats(s, opts, _err, "html");
777
+ s = codepointClass.applyCharStripPolicies(s, opts);
778
+
779
+ var tokens;
780
+ try { tokens = _tokenize(s, opts.maxBytes); }
781
+ catch (e) {
782
+ throw _err("html.tokenize-failed", "tokenizer failed: " + (e && e.message));
783
+ }
784
+
785
+ var allowedTags = Object.create(null);
786
+ (opts.allowedTags || []).forEach(function (t) { allowedTags[t.toLowerCase()] = true; });
787
+ var allowedAttrs = Object.create(null);
788
+ (opts.allowedAttrs || []).forEach(function (a) { allowedAttrs[a.toLowerCase()] = true; });
789
+ var dangerousTags = Object.create(null);
790
+ DANGEROUS_TAGS.forEach(function (t) { dangerousTags[t] = true; });
791
+
792
+ // Tags whose text content is itself executable in the host parser
793
+ // (script body = JS, style body = CSS). When we strip the open tag,
794
+ // also skip every token until the matching close tag so the body
795
+ // doesn't leak into output as visible text.
796
+ var BODY_DROP_TAGS = { "script": true, "style": true, "noscript": true,
797
+ "noembed": true, "noframes": true, "iframe": true,
798
+ "object": true, "embed": true, "applet": true,
799
+ "template": true, "math": true, "svg": true };
800
+
801
+ var out = [];
802
+ for (var i = 0; i < tokens.length; i += 1) {
803
+ var tok = tokens[i];
804
+ if (tok.type === "text") { out.push(tok.raw); continue; }
805
+ if (tok.type === "doctype") { continue; } // strip doctypes
806
+ if (tok.type === "cdata") { continue; } // strip cdata blocks
807
+ if (tok.type === "comment") {
808
+ if (opts.allowComments) out.push(tok.raw);
809
+ continue;
810
+ }
811
+ if (tok.type === "endTag") {
812
+ if (allowedTags[tok.name]) out.push("</" + tok.name + ">");
813
+ continue;
814
+ }
815
+ // Start tag.
816
+ if (dangerousTags[tok.name] || !allowedTags[tok.name]) {
817
+ // For tags whose body is parsed as code (script/style/etc.), skip
818
+ // forward to the matching close so the body doesn't surface as
819
+ // visible text content in sanitized output.
820
+ if (BODY_DROP_TAGS[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;
840
+ if (DANGEROUS_ATTRS.indexOf(an) !== -1) continue;
841
+ if (Object.keys(allowedAttrs).length > 0 && !allowedAttrs[an]) continue;
842
+ if (a.value && a.value.length > opts.maxAttrValueBytes) continue;
843
+ if (_isUrlAttr(an)) {
844
+ var scheme = _extractScheme(a.value);
845
+ if (scheme && DANGEROUS_SCHEMES.indexOf(scheme) !== -1) {
846
+ if (!(scheme === "data" && opts.allowImageData &&
847
+ tok.name === "img" && _isImageDataUrl(a.value))) {
848
+ continue;
849
+ }
850
+ } else if (scheme && opts.urlSchemes &&
851
+ opts.urlSchemes.indexOf(scheme) === -1) {
852
+ if (!(scheme === "data" && opts.allowImageData &&
853
+ tok.name === "img" && _isImageDataUrl(a.value))) {
854
+ continue;
855
+ }
856
+ }
857
+ }
858
+ if (an === "style" && _isCssDangerous(a.value)) continue;
859
+ if ((an === "id" || an === "name") && _isClobberProne(tok.name) &&
860
+ _isClobberGlobal(a.value)) continue;
861
+ attrParts.push(an + "=\"" + escapeAttr(a.value) + "\"");
862
+ }
863
+ var open = "<" + tok.name + (attrParts.length ? " " + attrParts.join(" ") : "") +
864
+ (tok.selfClosing ? " />" : ">");
865
+ out.push(open);
866
+ }
867
+ return out.join("");
868
+ }
869
+
870
+ // ---- Public surface ----
871
+
872
+ function validate(input, opts) {
873
+ opts = _resolveOpts(opts);
874
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
875
+ ["maxBytes", "maxAttrValueBytes", "maxTagDepth", "maxAttrsPerTag"],
876
+ "guardHtml.validate", GuardHtmlError, "html.bad-opt");
877
+
878
+ return gateContract.runIssueValidator(input, opts, _detectIssues);
879
+ }
880
+
881
+ function sanitize(input, opts) {
882
+ opts = _resolveOpts(opts);
883
+ var text = typeof input === "string"
884
+ ? input
885
+ : (Buffer.isBuffer(input) ? input.toString("utf8") : null);
886
+ if (text == null) {
887
+ throw _err("html.bad-input", "sanitize requires string or Buffer input");
888
+ }
889
+ return _sanitize(text, opts);
890
+ }
891
+
892
+ function gate(opts) {
893
+ opts = _resolveOpts(opts);
894
+ return gateContract.buildGuardGate(
895
+ opts.name || "guardHtml:" + (opts.profile || "default"),
896
+ opts,
897
+ async function (ctx) {
898
+ var text = gateContract.extractBytesAsText(ctx);
899
+ if (!text) return { ok: true, action: "serve" };
900
+ var rv = validate(text, 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
+ // Sanitize attempt — only when no policy says reject.
908
+ if (opts.bidiPolicy !== "reject" &&
909
+ opts.controlPolicy !== "reject" &&
910
+ opts.nullBytePolicy !== "reject" &&
911
+ opts.cssPolicy !== "reject" &&
912
+ opts.domClobberPolicy !== "reject" &&
913
+ opts.mxssHintPolicy !== "reject") {
914
+ try {
915
+ var clean = sanitize(text, opts);
916
+ return {
917
+ ok: true, action: "sanitize",
918
+ sanitized: Buffer.from(clean, "utf8"),
919
+ issues: rv.issues,
920
+ };
921
+ } catch (_e) { /* fall through */ }
922
+ }
923
+ return { ok: false, action: "refuse", issues: rv.issues };
924
+ });
925
+ }
926
+
927
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
928
+
929
+ function compliancePosture(name) {
930
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "html");
931
+ }
932
+
933
+ var _htmlRulePacks = gateContract.makeRulePackLoader(GuardHtmlError, "html");
934
+ var loadRulePack = _htmlRulePacks.load;
935
+
936
+ void safeUrl; // reserved for future scheme-allowlist composition
937
+
938
+ module.exports = {
939
+ // ---- guard-* family registry exports ----
940
+ NAME: "html",
941
+ KIND: "content",
942
+ MIME_TYPES: Object.freeze(["text/html", "application/xhtml+xml"]),
943
+ EXTENSIONS: Object.freeze([".html", ".htm", ".xhtml"]),
944
+ INTEGRATION_FIXTURES: Object.freeze({
945
+ kind: "content",
946
+ contentType: "text/html",
947
+ extension: ".html",
948
+ benignBytes: Buffer.from("<p>hello world</p>", "utf8"),
949
+ // Hostile: <script> tag is in the dangerous-tag denylist; refused
950
+ // unconditionally regardless of profile.
951
+ hostileBytes: Buffer.from('<p>hi</p><script>alert(1)</script>', "utf8"),
952
+ }),
953
+ // ---- primitive surface ----
954
+ validate: validate,
955
+ sanitize: sanitize,
956
+ escapeText: escapeText,
957
+ escapeAttr: escapeAttr,
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
+ STRICT_ALLOWED_TAGS: STRICT_ALLOWED_TAGS,
967
+ BALANCED_ALLOWED_TAGS: BALANCED_ALLOWED_TAGS,
968
+ PERMISSIVE_ALLOWED_TAGS: PERMISSIVE_ALLOWED_TAGS,
969
+ DANGEROUS_ATTRS: DANGEROUS_ATTRS,
970
+ URL_ATTRS: URL_ATTRS,
971
+ SAFE_SCHEMES: SAFE_SCHEMES,
972
+ DANGEROUS_SCHEMES: DANGEROUS_SCHEMES,
973
+ CLOBBER_GLOBALS: CLOBBER_GLOBALS,
974
+ CLOBBER_PRONE_TAGS: CLOBBER_PRONE_TAGS,
975
+ GuardHtmlError: GuardHtmlError,
976
+ };