@bquery/bquery 1.1.1 → 1.1.2
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.
- package/README.md +3 -0
- package/dist/full.iife.js +1 -1
- package/dist/full.iife.js.map +1 -1
- package/dist/full.umd.js +1 -1
- package/dist/full.umd.js.map +1 -1
- package/dist/security/sanitize.d.ts.map +1 -1
- package/dist/security.es.mjs +95 -74
- package/dist/security.es.mjs.map +1 -1
- package/package.json +1 -1
- package/src/security/sanitize.ts +72 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../src/security/sanitize.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,wDAAwD;IACxD,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,8CAA8C;IAC9C,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,4DAA4D;IAC5D,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAsBD,qCAAqC;AACrC,UAAU,iBAAiB;IACzB,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,WAAW,CAAC;CAC5C;AAED,2EAA2E;AAC3E,UAAU,WAAW;IACnB,QAAQ,IAAI,MAAM,CAAC;CACpB;AAKD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAO,OAE1C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBAAiB,GAAG,IAgB5D,CAAC;
|
|
1
|
+
{"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../src/security/sanitize.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,wDAAwD;IACxD,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,8CAA8C;IAC9C,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,4DAA4D;IAC5D,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAsBD,qCAAqC;AACrC,UAAU,iBAAiB;IACzB,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,WAAW,CAAC;CAC5C;AAED,2EAA2E;AAC3E,UAAU,WAAW;IACnB,QAAQ,IAAI,MAAM,CAAC;CACpB;AAKD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAO,OAE1C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBAAiB,GAAG,IAgB5D,CAAC;AAmbF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,MAAM,EAAE,UAAS,eAAoB,KAAG,MAE1E,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,WAAW,GAAG,MAM9D,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,UAAU,GAAI,MAAM,MAAM,KAAG,MAUzC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,SAAS,GAAI,MAAM,MAAM,KAAG,MAExC,CAAC;AAMF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,GAAI,SAAQ,MAAW,KAAG,MAOnD,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAI,WAAW,MAAM,KAAG,OAQnD,CAAC"}
|
package/dist/security.es.mjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
const
|
|
2
|
-
let
|
|
3
|
-
const
|
|
4
|
-
if (
|
|
5
|
-
const
|
|
6
|
-
if (!
|
|
1
|
+
const w = "bquery-sanitizer";
|
|
2
|
+
let u = null;
|
|
3
|
+
const F = () => typeof window.trustedTypes < "u", C = () => {
|
|
4
|
+
if (u) return u;
|
|
5
|
+
const t = window;
|
|
6
|
+
if (!t.trustedTypes) return null;
|
|
7
7
|
try {
|
|
8
|
-
return
|
|
9
|
-
createHTML: (
|
|
10
|
-
}),
|
|
8
|
+
return u = t.trustedTypes.createPolicy(w, {
|
|
9
|
+
createHTML: (e) => m(e)
|
|
10
|
+
}), u;
|
|
11
11
|
} catch {
|
|
12
|
-
return console.warn(`bQuery: Could not create Trusted Types policy "${
|
|
12
|
+
return console.warn(`bQuery: Could not create Trusted Types policy "${w}"`), null;
|
|
13
13
|
}
|
|
14
|
-
},
|
|
14
|
+
}, E = /* @__PURE__ */ new Set([
|
|
15
15
|
"a",
|
|
16
16
|
"abbr",
|
|
17
17
|
"address",
|
|
@@ -96,7 +96,7 @@ const x = () => typeof window.trustedTypes < "u", y = () => {
|
|
|
96
96
|
"ul",
|
|
97
97
|
"var",
|
|
98
98
|
"wbr"
|
|
99
|
-
]),
|
|
99
|
+
]), b = /* @__PURE__ */ new Set([
|
|
100
100
|
"script",
|
|
101
101
|
"iframe",
|
|
102
102
|
"frame",
|
|
@@ -114,7 +114,7 @@ const x = () => typeof window.trustedTypes < "u", y = () => {
|
|
|
114
114
|
"svg",
|
|
115
115
|
"foreignobject",
|
|
116
116
|
"noscript"
|
|
117
|
-
]),
|
|
117
|
+
]), v = /* @__PURE__ */ new Set([
|
|
118
118
|
// Global objects
|
|
119
119
|
"document",
|
|
120
120
|
"window",
|
|
@@ -151,7 +151,7 @@ const x = () => typeof window.trustedTypes < "u", y = () => {
|
|
|
151
151
|
"innerHTML",
|
|
152
152
|
"outerHTML",
|
|
153
153
|
"textContent"
|
|
154
|
-
]),
|
|
154
|
+
]), N = /* @__PURE__ */ new Set([
|
|
155
155
|
"alt",
|
|
156
156
|
"class",
|
|
157
157
|
"dir",
|
|
@@ -162,79 +162,100 @@ const x = () => typeof window.trustedTypes < "u", y = () => {
|
|
|
162
162
|
"lang",
|
|
163
163
|
"loading",
|
|
164
164
|
"name",
|
|
165
|
+
"rel",
|
|
165
166
|
"role",
|
|
166
167
|
"src",
|
|
167
168
|
"srcset",
|
|
168
169
|
"style",
|
|
169
170
|
"tabindex",
|
|
171
|
+
"target",
|
|
170
172
|
"title",
|
|
171
173
|
"type",
|
|
172
174
|
"width",
|
|
173
175
|
"aria-*"
|
|
174
|
-
]),
|
|
175
|
-
const
|
|
176
|
-
for (const
|
|
177
|
-
if (
|
|
178
|
-
return o &&
|
|
179
|
-
},
|
|
180
|
-
const
|
|
181
|
-
return !
|
|
182
|
-
},
|
|
183
|
-
const
|
|
184
|
-
for (const o of
|
|
185
|
-
if (
|
|
176
|
+
]), x = ["on", "formaction", "xlink:", "xmlns:"], R = ["javascript:", "data:", "vbscript:", "file:"], O = (t, e, o) => {
|
|
177
|
+
const s = t.toLowerCase();
|
|
178
|
+
for (const i of x)
|
|
179
|
+
if (s.startsWith(i)) return !1;
|
|
180
|
+
return o && s.startsWith("data-") || s.startsWith("aria-") ? !0 : e.has(s);
|
|
181
|
+
}, U = (t) => {
|
|
182
|
+
const e = t.toLowerCase().trim();
|
|
183
|
+
return !v.has(e);
|
|
184
|
+
}, W = (t) => t.replace(/[\u0000-\u001F\u007F]+/g, "").replace(/[\u200B-\u200D\uFEFF\u2028\u2029]+/g, "").replace(/\\u[\da-fA-F]{4}/g, "").replace(/\s+/g, "").toLowerCase(), _ = (t) => {
|
|
185
|
+
const e = W(t);
|
|
186
|
+
for (const o of R)
|
|
187
|
+
if (e.startsWith(o)) return !1;
|
|
186
188
|
return !0;
|
|
187
|
-
},
|
|
189
|
+
}, D = (t) => {
|
|
190
|
+
try {
|
|
191
|
+
const e = t.trim();
|
|
192
|
+
if (e.startsWith("//"))
|
|
193
|
+
return !0;
|
|
194
|
+
const o = e.toLowerCase();
|
|
195
|
+
return /^[a-z][a-z0-9+.-]*:/i.test(e) && !o.startsWith("http://") && !o.startsWith("https://") ? !0 : !o.startsWith("http://") && !o.startsWith("https://") ? !1 : typeof window > "u" || !window.location ? !0 : new URL(e, window.location.href).origin !== window.location.origin;
|
|
196
|
+
} catch {
|
|
197
|
+
return !0;
|
|
198
|
+
}
|
|
199
|
+
}, m = (t, e = {}) => {
|
|
188
200
|
const {
|
|
189
201
|
allowTags: o = [],
|
|
190
|
-
allowAttributes:
|
|
191
|
-
allowDataAttributes:
|
|
192
|
-
stripAllTags:
|
|
193
|
-
} =
|
|
194
|
-
[...
|
|
195
|
-
(r) => !
|
|
202
|
+
allowAttributes: s = [],
|
|
203
|
+
allowDataAttributes: i = !0,
|
|
204
|
+
stripAllTags: T = !1
|
|
205
|
+
} = e, y = new Set(
|
|
206
|
+
[...E, ...o.map((r) => r.toLowerCase())].filter(
|
|
207
|
+
(r) => !b.has(r)
|
|
196
208
|
)
|
|
197
|
-
),
|
|
198
|
-
...
|
|
199
|
-
...
|
|
200
|
-
]),
|
|
201
|
-
if (
|
|
202
|
-
return
|
|
203
|
-
const
|
|
204
|
-
for (;
|
|
205
|
-
const r =
|
|
206
|
-
if (
|
|
209
|
+
), A = /* @__PURE__ */ new Set([
|
|
210
|
+
...N,
|
|
211
|
+
...s.map((r) => r.toLowerCase())
|
|
212
|
+
]), c = document.createElement("template");
|
|
213
|
+
if (c.innerHTML = t, T)
|
|
214
|
+
return c.content.textContent ?? "";
|
|
215
|
+
const h = document.createTreeWalker(c.content, NodeFilter.SHOW_ELEMENT), d = [];
|
|
216
|
+
for (; h.nextNode(); ) {
|
|
217
|
+
const r = h.currentNode, p = r.tagName.toLowerCase();
|
|
218
|
+
if (b.has(p)) {
|
|
207
219
|
d.push(r);
|
|
208
220
|
continue;
|
|
209
221
|
}
|
|
210
|
-
if (!
|
|
222
|
+
if (!y.has(p)) {
|
|
211
223
|
d.push(r);
|
|
212
224
|
continue;
|
|
213
225
|
}
|
|
214
|
-
const
|
|
226
|
+
const l = [];
|
|
215
227
|
for (const n of Array.from(r.attributes)) {
|
|
216
|
-
const
|
|
217
|
-
if (!
|
|
218
|
-
|
|
228
|
+
const a = n.name.toLowerCase();
|
|
229
|
+
if (!O(a, A, i)) {
|
|
230
|
+
l.push(n.name);
|
|
219
231
|
continue;
|
|
220
232
|
}
|
|
221
|
-
if ((
|
|
222
|
-
|
|
233
|
+
if ((a === "id" || a === "name") && !U(n.value)) {
|
|
234
|
+
l.push(n.name);
|
|
223
235
|
continue;
|
|
224
236
|
}
|
|
225
|
-
(
|
|
237
|
+
(a === "href" || a === "src" || a === "srcset") && !_(n.value) && l.push(n.name);
|
|
226
238
|
}
|
|
227
|
-
for (const n of
|
|
239
|
+
for (const n of l)
|
|
228
240
|
r.removeAttribute(n);
|
|
241
|
+
if (p === "a") {
|
|
242
|
+
const n = r.getAttribute("href"), L = r.getAttribute("target")?.toLowerCase() === "_blank", S = n && D(n);
|
|
243
|
+
if (L || S) {
|
|
244
|
+
const g = r.getAttribute("rel"), f = new Set(
|
|
245
|
+
g ? g.split(/\s+/).filter(Boolean) : []
|
|
246
|
+
);
|
|
247
|
+
f.add("noopener"), f.add("noreferrer"), r.setAttribute("rel", Array.from(f).join(" "));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
229
250
|
}
|
|
230
251
|
for (const r of d)
|
|
231
252
|
r.remove();
|
|
232
|
-
return
|
|
233
|
-
},
|
|
234
|
-
const
|
|
235
|
-
return
|
|
236
|
-
},
|
|
237
|
-
const
|
|
253
|
+
return c.innerHTML;
|
|
254
|
+
}, k = (t, e = {}) => m(t, e), H = (t) => {
|
|
255
|
+
const e = C();
|
|
256
|
+
return e ? e.createHTML(t) : k(t);
|
|
257
|
+
}, P = (t) => {
|
|
258
|
+
const e = {
|
|
238
259
|
"&": "&",
|
|
239
260
|
"<": "<",
|
|
240
261
|
">": ">",
|
|
@@ -242,23 +263,23 @@ const x = () => typeof window.trustedTypes < "u", y = () => {
|
|
|
242
263
|
"'": "'",
|
|
243
264
|
"`": "`"
|
|
244
265
|
};
|
|
245
|
-
return
|
|
246
|
-
},
|
|
247
|
-
const
|
|
248
|
-
return crypto.getRandomValues(
|
|
249
|
-
},
|
|
250
|
-
const
|
|
251
|
-
return
|
|
266
|
+
return t.replace(/[&<>"'`]/g, (o) => e[o]);
|
|
267
|
+
}, M = (t) => m(t, { stripAllTags: !0 }), z = (t = 16) => {
|
|
268
|
+
const e = new Uint8Array(t);
|
|
269
|
+
return crypto.getRandomValues(e), btoa(String.fromCharCode(...e)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
270
|
+
}, j = (t) => {
|
|
271
|
+
const e = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
|
|
272
|
+
return e ? (e.getAttribute("content") ?? "").includes(t) : !1;
|
|
252
273
|
};
|
|
253
274
|
export {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
275
|
+
H as createTrustedHtml,
|
|
276
|
+
P as escapeHtml,
|
|
277
|
+
z as generateNonce,
|
|
278
|
+
C as getTrustedTypesPolicy,
|
|
279
|
+
j as hasCSPDirective,
|
|
280
|
+
F as isTrustedTypesSupported,
|
|
281
|
+
k as sanitize,
|
|
282
|
+
k as sanitizeHtml,
|
|
283
|
+
M as stripTags
|
|
263
284
|
};
|
|
264
285
|
//# sourceMappingURL=security.es.mjs.map
|
package/dist/security.es.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"security.es.mjs","sources":["../src/security/sanitize.ts"],"sourcesContent":["/**\r\n * Security utilities for HTML sanitization, CSP compatibility, and Trusted Types.\r\n * All DOM writes are sanitized by default to prevent XSS attacks.\r\n *\r\n * @module bquery/security\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * Sanitizer configuration options.\r\n */\r\nexport interface SanitizeOptions {\r\n /** Allow these additional tags (default: none) */\r\n allowTags?: string[];\r\n /** Allow these additional attributes (default: none) */\r\n allowAttributes?: string[];\r\n /** Allow data-* attributes (default: true) */\r\n allowDataAttributes?: boolean;\r\n /** Strip all tags and return plain text (default: false) */\r\n stripAllTags?: boolean;\r\n}\r\n\r\n/**\r\n * Trusted Types policy name.\r\n */\r\nconst POLICY_NAME = 'bquery-sanitizer';\r\n\r\n// ============================================================================\r\n// Trusted Types Support\r\n// ============================================================================\r\n\r\n/** Window interface extended with Trusted Types */\r\ninterface TrustedTypesWindow extends Window {\r\n trustedTypes?: {\r\n createPolicy: (\r\n name: string,\r\n rules: { createHTML?: (input: string) => string }\r\n ) => TrustedTypePolicy;\r\n isHTML?: (value: unknown) => boolean;\r\n };\r\n}\r\n\r\n/** Trusted Types policy interface */\r\ninterface TrustedTypePolicy {\r\n createHTML: (input: string) => TrustedHTML;\r\n}\r\n\r\n/** Trusted HTML type placeholder for environments without Trusted Types */\r\ninterface TrustedHTML {\r\n toString(): string;\r\n}\r\n\r\n/** Cached Trusted Types policy */\r\nlet cachedPolicy: TrustedTypePolicy | null = null;\r\n\r\n/**\r\n * Check if Trusted Types API is available.\r\n * @returns True if Trusted Types are supported\r\n */\r\nexport const isTrustedTypesSupported = (): boolean => {\r\n return typeof (window as TrustedTypesWindow).trustedTypes !== 'undefined';\r\n};\r\n\r\n/**\r\n * Get or create the bQuery Trusted Types policy.\r\n * @returns The Trusted Types policy or null if unsupported\r\n */\r\nexport const getTrustedTypesPolicy = (): TrustedTypePolicy | null => {\r\n if (cachedPolicy) return cachedPolicy;\r\n\r\n const win = window as TrustedTypesWindow;\r\n if (!win.trustedTypes) return null;\r\n\r\n try {\r\n cachedPolicy = win.trustedTypes.createPolicy(POLICY_NAME, {\r\n createHTML: (input: string) => sanitizeHtmlCore(input),\r\n });\r\n return cachedPolicy;\r\n } catch {\r\n // Policy may already exist or be blocked by CSP\r\n console.warn(`bQuery: Could not create Trusted Types policy \"${POLICY_NAME}\"`);\r\n return null;\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Default Safe Lists\r\n// ============================================================================\r\n\r\n/**\r\n * Default allowed HTML tags considered safe.\r\n */\r\nconst DEFAULT_ALLOWED_TAGS = new Set([\r\n 'a',\r\n 'abbr',\r\n 'address',\r\n 'article',\r\n 'aside',\r\n 'b',\r\n 'bdi',\r\n 'bdo',\r\n 'blockquote',\r\n 'br',\r\n 'button',\r\n 'caption',\r\n 'cite',\r\n 'code',\r\n 'col',\r\n 'colgroup',\r\n 'data',\r\n 'dd',\r\n 'del',\r\n 'details',\r\n 'dfn',\r\n 'div',\r\n 'dl',\r\n 'dt',\r\n 'em',\r\n 'figcaption',\r\n 'figure',\r\n 'footer',\r\n 'form',\r\n 'h1',\r\n 'h2',\r\n 'h3',\r\n 'h4',\r\n 'h5',\r\n 'h6',\r\n 'header',\r\n 'hgroup',\r\n 'hr',\r\n 'i',\r\n 'img',\r\n 'input',\r\n 'ins',\r\n 'kbd',\r\n 'label',\r\n 'legend',\r\n 'li',\r\n 'main',\r\n 'mark',\r\n 'nav',\r\n 'ol',\r\n 'optgroup',\r\n 'option',\r\n 'p',\r\n 'picture',\r\n 'pre',\r\n 'progress',\r\n 'q',\r\n 'rp',\r\n 'rt',\r\n 'ruby',\r\n 's',\r\n 'samp',\r\n 'section',\r\n 'select',\r\n 'small',\r\n 'source',\r\n 'span',\r\n 'strong',\r\n 'sub',\r\n 'summary',\r\n 'sup',\r\n 'table',\r\n 'tbody',\r\n 'td',\r\n 'textarea',\r\n 'tfoot',\r\n 'th',\r\n 'thead',\r\n 'time',\r\n 'tr',\r\n 'u',\r\n 'ul',\r\n 'var',\r\n 'wbr',\r\n]);\r\n\r\n/**\r\n * Explicitly dangerous tags that should never be allowed.\r\n * These are checked even if somehow added to allowTags.\r\n */\r\nconst DANGEROUS_TAGS = new Set([\r\n 'script',\r\n 'iframe',\r\n 'frame',\r\n 'frameset',\r\n 'object',\r\n 'embed',\r\n 'applet',\r\n 'link',\r\n 'meta',\r\n 'style',\r\n 'base',\r\n 'template',\r\n 'slot',\r\n 'math',\r\n 'svg',\r\n 'foreignobject',\r\n 'noscript',\r\n]);\r\n\r\n/**\r\n * Reserved IDs that could cause DOM clobbering attacks.\r\n * These are prevented to avoid overwriting global browser objects.\r\n */\r\nconst RESERVED_IDS = new Set([\r\n // Global objects\r\n 'document',\r\n 'window',\r\n 'location',\r\n 'top',\r\n 'self',\r\n 'parent',\r\n 'frames',\r\n 'history',\r\n 'navigator',\r\n 'screen',\r\n // Dangerous functions\r\n 'alert',\r\n 'confirm',\r\n 'prompt',\r\n 'eval',\r\n 'Function',\r\n // Document properties\r\n 'cookie',\r\n 'domain',\r\n 'referrer',\r\n 'body',\r\n 'head',\r\n 'forms',\r\n 'images',\r\n 'links',\r\n 'scripts',\r\n // DOM traversal properties\r\n 'children',\r\n 'parentNode',\r\n 'firstChild',\r\n 'lastChild',\r\n // Content manipulation\r\n 'innerHTML',\r\n 'outerHTML',\r\n 'textContent',\r\n]);\r\n\r\n/**\r\n * Default allowed attributes considered safe.\r\n */\r\nconst DEFAULT_ALLOWED_ATTRIBUTES = new Set([\r\n 'alt',\r\n 'class',\r\n 'dir',\r\n 'height',\r\n 'hidden',\r\n 'href',\r\n 'id',\r\n 'lang',\r\n 'loading',\r\n 'name',\r\n 'role',\r\n 'src',\r\n 'srcset',\r\n 'style',\r\n 'tabindex',\r\n 'title',\r\n 'type',\r\n 'width',\r\n 'aria-*',\r\n]);\r\n\r\n/**\r\n * Dangerous attribute prefixes to always remove.\r\n */\r\nconst DANGEROUS_ATTR_PREFIXES = ['on', 'formaction', 'xlink:', 'xmlns:'];\r\n\r\n/**\r\n * Dangerous URL protocols to block.\r\n */\r\nconst DANGEROUS_PROTOCOLS = ['javascript:', 'data:', 'vbscript:', 'file:'];\r\n\r\n// ============================================================================\r\n// Core Sanitization\r\n// ============================================================================\r\n\r\n/**\r\n * Check if an attribute name is allowed.\r\n * @internal\r\n */\r\nconst isAllowedAttribute = (\r\n name: string,\r\n allowedSet: Set<string>,\r\n allowDataAttrs: boolean\r\n): boolean => {\r\n const lowerName = name.toLowerCase();\r\n\r\n // Check dangerous prefixes\r\n for (const prefix of DANGEROUS_ATTR_PREFIXES) {\r\n if (lowerName.startsWith(prefix)) return false;\r\n }\r\n\r\n // Check data attributes\r\n if (allowDataAttrs && lowerName.startsWith('data-')) return true;\r\n\r\n // Check aria attributes (allowed by default)\r\n if (lowerName.startsWith('aria-')) return true;\r\n\r\n // Check explicit allow list\r\n return allowedSet.has(lowerName);\r\n};\r\n\r\n/**\r\n * Check if an ID/name value could cause DOM clobbering.\r\n * @internal\r\n */\r\nconst isSafeIdOrName = (value: string): boolean => {\r\n const lowerValue = value.toLowerCase().trim();\r\n return !RESERVED_IDS.has(lowerValue);\r\n};\r\n\r\n/**\r\n * Normalize URL by removing control characters, whitespace, and Unicode tricks.\r\n * Enhanced to prevent various bypass techniques.\r\n * @internal\r\n */\r\nconst normalizeUrl = (value: string): string =>\r\n value\r\n // Remove null bytes and control characters\r\n .replace(/[\\u0000-\\u001F\\u007F]+/g, '')\r\n // Remove zero-width characters that could hide malicious content\r\n .replace(/[\\u200B-\\u200D\\uFEFF\\u2028\\u2029]+/g, '')\r\n // Remove escaped Unicode sequences\r\n .replace(/\\\\u[\\da-fA-F]{4}/g, '')\r\n // Remove whitespace\r\n .replace(/\\s+/g, '')\r\n // Normalize case\r\n .toLowerCase();\r\n\r\n/**\r\n * Check if a URL value is safe.\r\n * @internal\r\n */\r\nconst isSafeUrl = (value: string): boolean => {\r\n const normalized = normalizeUrl(value);\r\n for (const protocol of DANGEROUS_PROTOCOLS) {\r\n if (normalized.startsWith(protocol)) return false;\r\n }\r\n return true;\r\n};\r\n\r\n/**\r\n * Core sanitization logic (without Trusted Types wrapper).\r\n * @internal\r\n */\r\nconst sanitizeHtmlCore = (html: string, options: SanitizeOptions = {}): string => {\r\n const {\r\n allowTags = [],\r\n allowAttributes = [],\r\n allowDataAttributes = true,\r\n stripAllTags = false,\r\n } = options;\r\n\r\n // Build combined allow sets (excluding dangerous tags even if specified)\r\n const allowedTags = new Set(\r\n [...DEFAULT_ALLOWED_TAGS, ...allowTags.map((t) => t.toLowerCase())].filter(\r\n (tag) => !DANGEROUS_TAGS.has(tag)\r\n )\r\n );\r\n const allowedAttrs = new Set([\r\n ...DEFAULT_ALLOWED_ATTRIBUTES,\r\n ...allowAttributes.map((a) => a.toLowerCase()),\r\n ]);\r\n\r\n // Use template for parsing\r\n const template = document.createElement('template');\r\n template.innerHTML = html;\r\n\r\n if (stripAllTags) {\r\n return template.content.textContent ?? '';\r\n }\r\n\r\n // Walk the DOM tree\r\n const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);\r\n\r\n const toRemove: Element[] = [];\r\n\r\n while (walker.nextNode()) {\r\n const el = walker.currentNode as Element;\r\n const tagName = el.tagName.toLowerCase();\r\n\r\n // Remove explicitly dangerous tags even if in allow list\r\n if (DANGEROUS_TAGS.has(tagName)) {\r\n toRemove.push(el);\r\n continue;\r\n }\r\n\r\n // Remove disallowed tags entirely\r\n if (!allowedTags.has(tagName)) {\r\n toRemove.push(el);\r\n continue;\r\n }\r\n\r\n // Process attributes\r\n const attrsToRemove: string[] = [];\r\n for (const attr of Array.from(el.attributes)) {\r\n const attrName = attr.name.toLowerCase();\r\n\r\n // Check if attribute is allowed\r\n if (!isAllowedAttribute(attrName, allowedAttrs, allowDataAttributes)) {\r\n attrsToRemove.push(attr.name);\r\n continue;\r\n }\r\n\r\n // Check for DOM clobbering on id and name attributes\r\n if ((attrName === 'id' || attrName === 'name') && !isSafeIdOrName(attr.value)) {\r\n attrsToRemove.push(attr.name);\r\n continue;\r\n }\r\n\r\n // Validate URL attributes\r\n if (\r\n (attrName === 'href' || attrName === 'src' || attrName === 'srcset') &&\r\n !isSafeUrl(attr.value)\r\n ) {\r\n attrsToRemove.push(attr.name);\r\n }\r\n }\r\n\r\n // Remove disallowed attributes\r\n for (const attrName of attrsToRemove) {\r\n el.removeAttribute(attrName);\r\n }\r\n }\r\n\r\n // Remove disallowed elements\r\n for (const el of toRemove) {\r\n el.remove();\r\n }\r\n\r\n return template.innerHTML;\r\n};\r\n\r\n// ============================================================================\r\n// Public API\r\n// ============================================================================\r\n\r\n/**\r\n * Sanitize HTML string, removing dangerous elements and attributes.\r\n * Uses Trusted Types when available for CSP compliance.\r\n *\r\n * @param html - The HTML string to sanitize\r\n * @param options - Sanitization options\r\n * @returns Sanitized HTML string\r\n *\r\n * @example\r\n * ```ts\r\n * const safe = sanitizeHtml('<div onclick=\"alert(1)\">Hello</div>');\r\n * // Returns: '<div>Hello</div>'\r\n * ```\r\n */\r\nexport const sanitizeHtml = (html: string, options: SanitizeOptions = {}): string => {\r\n return sanitizeHtmlCore(html, options);\r\n};\r\n\r\n/**\r\n * Create a Trusted HTML value for use with Trusted Types-enabled sites.\r\n * Falls back to regular string when Trusted Types are unavailable.\r\n *\r\n * @param html - The HTML string to wrap\r\n * @returns Trusted HTML value or sanitized string\r\n */\r\nexport const createTrustedHtml = (html: string): TrustedHTML | string => {\r\n const policy = getTrustedTypesPolicy();\r\n if (policy) {\r\n return policy.createHTML(html);\r\n }\r\n return sanitizeHtml(html);\r\n};\r\n\r\n/**\r\n * Escape HTML entities to prevent XSS.\r\n * Use this for displaying user content as text.\r\n *\r\n * @param text - The text to escape\r\n * @returns Escaped HTML string\r\n *\r\n * @example\r\n * ```ts\r\n * escapeHtml('<script>alert(1)</script>');\r\n * // Returns: '<script>alert(1)</script>'\r\n * ```\r\n */\r\nexport const escapeHtml = (text: string): string => {\r\n const escapeMap: Record<string, string> = {\r\n '&': '&',\r\n '<': '<',\r\n '>': '>',\r\n '\"': '"',\r\n \"'\": ''',\r\n '`': '`',\r\n };\r\n return text.replace(/[&<>\"'`]/g, (char) => escapeMap[char]);\r\n};\r\n\r\n/**\r\n * Strip all HTML tags and return plain text.\r\n *\r\n * @param html - The HTML string to strip\r\n * @returns Plain text content\r\n */\r\nexport const stripTags = (html: string): string => {\r\n return sanitizeHtmlCore(html, { stripAllTags: true });\r\n};\r\n\r\n// ============================================================================\r\n// CSP Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Generate a nonce for inline scripts/styles.\r\n * Use with Content-Security-Policy nonce directives.\r\n *\r\n * @param length - Nonce length (default: 16)\r\n * @returns Cryptographically random nonce string\r\n */\r\nexport const generateNonce = (length: number = 16): string => {\r\n const array = new Uint8Array(length);\r\n crypto.getRandomValues(array);\r\n return btoa(String.fromCharCode(...array))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '');\r\n};\r\n\r\n/**\r\n * Check if a CSP header is present with specific directive.\r\n * Useful for feature detection and fallback strategies.\r\n *\r\n * @param directive - The CSP directive to check (e.g., 'script-src')\r\n * @returns True if the directive appears to be enforced\r\n */\r\nexport const hasCSPDirective = (directive: string): boolean => {\r\n // Check meta tag\r\n const meta = document.querySelector('meta[http-equiv=\"Content-Security-Policy\"]');\r\n if (meta) {\r\n const content = meta.getAttribute('content') ?? '';\r\n return content.includes(directive);\r\n }\r\n return false;\r\n};\r\n"],"names":["POLICY_NAME","cachedPolicy","isTrustedTypesSupported","getTrustedTypesPolicy","win","input","sanitizeHtmlCore","DEFAULT_ALLOWED_TAGS","DANGEROUS_TAGS","RESERVED_IDS","DEFAULT_ALLOWED_ATTRIBUTES","DANGEROUS_ATTR_PREFIXES","DANGEROUS_PROTOCOLS","isAllowedAttribute","name","allowedSet","allowDataAttrs","lowerName","prefix","isSafeIdOrName","value","lowerValue","normalizeUrl","isSafeUrl","normalized","protocol","html","options","allowTags","allowAttributes","allowDataAttributes","stripAllTags","allowedTags","t","tag","allowedAttrs","a","template","walker","toRemove","el","tagName","attrsToRemove","attr","attrName","sanitizeHtml","createTrustedHtml","policy","escapeHtml","text","escapeMap","char","stripTags","generateNonce","length","array","hasCSPDirective","directive","meta"],"mappings":"AA4BA,MAAMA,IAAc;AA4BpB,IAAIC,IAAyC;AAMtC,MAAMC,IAA0B,MAC9B,OAAQ,OAA8B,eAAiB,KAOnDC,IAAwB,MAAgC;AACnE,MAAIF,EAAc,QAAOA;AAEzB,QAAMG,IAAM;AACZ,MAAI,CAACA,EAAI,aAAc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gBAAO,gBAAgBC,CAAK,GACrB,KAAK,OAAO,aAAa,GAAGA,CAAK,CAAC,EACtC,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,MAAM,EAAE;AACrB,GASaC,IAAkB,CAACC,MAA+B;AAE7D,QAAMC,IAAO,SAAS,cAAc,4CAA4C;AAChF,SAAIA,KACcA,EAAK,aAAa,SAAS,KAAK,IACjC,SAASD,CAAS,IAE5B;AACT;"}
|
|
1
|
+
{"version":3,"file":"security.es.mjs","sources":["../src/security/sanitize.ts"],"sourcesContent":["/**\r\n * Security utilities for HTML sanitization, CSP compatibility, and Trusted Types.\r\n * All DOM writes are sanitized by default to prevent XSS attacks.\r\n *\r\n * @module bquery/security\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * Sanitizer configuration options.\r\n */\r\nexport interface SanitizeOptions {\r\n /** Allow these additional tags (default: none) */\r\n allowTags?: string[];\r\n /** Allow these additional attributes (default: none) */\r\n allowAttributes?: string[];\r\n /** Allow data-* attributes (default: true) */\r\n allowDataAttributes?: boolean;\r\n /** Strip all tags and return plain text (default: false) */\r\n stripAllTags?: boolean;\r\n}\r\n\r\n/**\r\n * Trusted Types policy name.\r\n */\r\nconst POLICY_NAME = 'bquery-sanitizer';\r\n\r\n// ============================================================================\r\n// Trusted Types Support\r\n// ============================================================================\r\n\r\n/** Window interface extended with Trusted Types */\r\ninterface TrustedTypesWindow extends Window {\r\n trustedTypes?: {\r\n createPolicy: (\r\n name: string,\r\n rules: { createHTML?: (input: string) => string }\r\n ) => TrustedTypePolicy;\r\n isHTML?: (value: unknown) => boolean;\r\n };\r\n}\r\n\r\n/** Trusted Types policy interface */\r\ninterface TrustedTypePolicy {\r\n createHTML: (input: string) => TrustedHTML;\r\n}\r\n\r\n/** Trusted HTML type placeholder for environments without Trusted Types */\r\ninterface TrustedHTML {\r\n toString(): string;\r\n}\r\n\r\n/** Cached Trusted Types policy */\r\nlet cachedPolicy: TrustedTypePolicy | null = null;\r\n\r\n/**\r\n * Check if Trusted Types API is available.\r\n * @returns True if Trusted Types are supported\r\n */\r\nexport const isTrustedTypesSupported = (): boolean => {\r\n return typeof (window as TrustedTypesWindow).trustedTypes !== 'undefined';\r\n};\r\n\r\n/**\r\n * Get or create the bQuery Trusted Types policy.\r\n * @returns The Trusted Types policy or null if unsupported\r\n */\r\nexport const getTrustedTypesPolicy = (): TrustedTypePolicy | null => {\r\n if (cachedPolicy) return cachedPolicy;\r\n\r\n const win = window as TrustedTypesWindow;\r\n if (!win.trustedTypes) return null;\r\n\r\n try {\r\n cachedPolicy = win.trustedTypes.createPolicy(POLICY_NAME, {\r\n createHTML: (input: string) => sanitizeHtmlCore(input),\r\n });\r\n return cachedPolicy;\r\n } catch {\r\n // Policy may already exist or be blocked by CSP\r\n console.warn(`bQuery: Could not create Trusted Types policy \"${POLICY_NAME}\"`);\r\n return null;\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Default Safe Lists\r\n// ============================================================================\r\n\r\n/**\r\n * Default allowed HTML tags considered safe.\r\n */\r\nconst DEFAULT_ALLOWED_TAGS = new Set([\r\n 'a',\r\n 'abbr',\r\n 'address',\r\n 'article',\r\n 'aside',\r\n 'b',\r\n 'bdi',\r\n 'bdo',\r\n 'blockquote',\r\n 'br',\r\n 'button',\r\n 'caption',\r\n 'cite',\r\n 'code',\r\n 'col',\r\n 'colgroup',\r\n 'data',\r\n 'dd',\r\n 'del',\r\n 'details',\r\n 'dfn',\r\n 'div',\r\n 'dl',\r\n 'dt',\r\n 'em',\r\n 'figcaption',\r\n 'figure',\r\n 'footer',\r\n 'form',\r\n 'h1',\r\n 'h2',\r\n 'h3',\r\n 'h4',\r\n 'h5',\r\n 'h6',\r\n 'header',\r\n 'hgroup',\r\n 'hr',\r\n 'i',\r\n 'img',\r\n 'input',\r\n 'ins',\r\n 'kbd',\r\n 'label',\r\n 'legend',\r\n 'li',\r\n 'main',\r\n 'mark',\r\n 'nav',\r\n 'ol',\r\n 'optgroup',\r\n 'option',\r\n 'p',\r\n 'picture',\r\n 'pre',\r\n 'progress',\r\n 'q',\r\n 'rp',\r\n 'rt',\r\n 'ruby',\r\n 's',\r\n 'samp',\r\n 'section',\r\n 'select',\r\n 'small',\r\n 'source',\r\n 'span',\r\n 'strong',\r\n 'sub',\r\n 'summary',\r\n 'sup',\r\n 'table',\r\n 'tbody',\r\n 'td',\r\n 'textarea',\r\n 'tfoot',\r\n 'th',\r\n 'thead',\r\n 'time',\r\n 'tr',\r\n 'u',\r\n 'ul',\r\n 'var',\r\n 'wbr',\r\n]);\r\n\r\n/**\r\n * Explicitly dangerous tags that should never be allowed.\r\n * These are checked even if somehow added to allowTags.\r\n */\r\nconst DANGEROUS_TAGS = new Set([\r\n 'script',\r\n 'iframe',\r\n 'frame',\r\n 'frameset',\r\n 'object',\r\n 'embed',\r\n 'applet',\r\n 'link',\r\n 'meta',\r\n 'style',\r\n 'base',\r\n 'template',\r\n 'slot',\r\n 'math',\r\n 'svg',\r\n 'foreignobject',\r\n 'noscript',\r\n]);\r\n\r\n/**\r\n * Reserved IDs that could cause DOM clobbering attacks.\r\n * These are prevented to avoid overwriting global browser objects.\r\n */\r\nconst RESERVED_IDS = new Set([\r\n // Global objects\r\n 'document',\r\n 'window',\r\n 'location',\r\n 'top',\r\n 'self',\r\n 'parent',\r\n 'frames',\r\n 'history',\r\n 'navigator',\r\n 'screen',\r\n // Dangerous functions\r\n 'alert',\r\n 'confirm',\r\n 'prompt',\r\n 'eval',\r\n 'Function',\r\n // Document properties\r\n 'cookie',\r\n 'domain',\r\n 'referrer',\r\n 'body',\r\n 'head',\r\n 'forms',\r\n 'images',\r\n 'links',\r\n 'scripts',\r\n // DOM traversal properties\r\n 'children',\r\n 'parentNode',\r\n 'firstChild',\r\n 'lastChild',\r\n // Content manipulation\r\n 'innerHTML',\r\n 'outerHTML',\r\n 'textContent',\r\n]);\r\n\r\n/**\r\n * Default allowed attributes considered safe.\r\n */\r\nconst DEFAULT_ALLOWED_ATTRIBUTES = new Set([\r\n 'alt',\r\n 'class',\r\n 'dir',\r\n 'height',\r\n 'hidden',\r\n 'href',\r\n 'id',\r\n 'lang',\r\n 'loading',\r\n 'name',\r\n 'rel',\r\n 'role',\r\n 'src',\r\n 'srcset',\r\n 'style',\r\n 'tabindex',\r\n 'target',\r\n 'title',\r\n 'type',\r\n 'width',\r\n 'aria-*',\r\n]);\r\n\r\n/**\r\n * Dangerous attribute prefixes to always remove.\r\n */\r\nconst DANGEROUS_ATTR_PREFIXES = ['on', 'formaction', 'xlink:', 'xmlns:'];\r\n\r\n/**\r\n * Dangerous URL protocols to block.\r\n */\r\nconst DANGEROUS_PROTOCOLS = ['javascript:', 'data:', 'vbscript:', 'file:'];\r\n\r\n// ============================================================================\r\n// Core Sanitization\r\n// ============================================================================\r\n\r\n/**\r\n * Check if an attribute name is allowed.\r\n * @internal\r\n */\r\nconst isAllowedAttribute = (\r\n name: string,\r\n allowedSet: Set<string>,\r\n allowDataAttrs: boolean\r\n): boolean => {\r\n const lowerName = name.toLowerCase();\r\n\r\n // Check dangerous prefixes\r\n for (const prefix of DANGEROUS_ATTR_PREFIXES) {\r\n if (lowerName.startsWith(prefix)) return false;\r\n }\r\n\r\n // Check data attributes\r\n if (allowDataAttrs && lowerName.startsWith('data-')) return true;\r\n\r\n // Check aria attributes (allowed by default)\r\n if (lowerName.startsWith('aria-')) return true;\r\n\r\n // Check explicit allow list\r\n return allowedSet.has(lowerName);\r\n};\r\n\r\n/**\r\n * Check if an ID/name value could cause DOM clobbering.\r\n * @internal\r\n */\r\nconst isSafeIdOrName = (value: string): boolean => {\r\n const lowerValue = value.toLowerCase().trim();\r\n return !RESERVED_IDS.has(lowerValue);\r\n};\r\n\r\n/**\r\n * Normalize URL by removing control characters, whitespace, and Unicode tricks.\r\n * Enhanced to prevent various bypass techniques.\r\n * @internal\r\n */\r\nconst normalizeUrl = (value: string): string =>\r\n value\r\n // Remove null bytes and control characters\r\n .replace(/[\\u0000-\\u001F\\u007F]+/g, '')\r\n // Remove zero-width characters that could hide malicious content\r\n .replace(/[\\u200B-\\u200D\\uFEFF\\u2028\\u2029]+/g, '')\r\n // Remove escaped Unicode sequences\r\n .replace(/\\\\u[\\da-fA-F]{4}/g, '')\r\n // Remove whitespace\r\n .replace(/\\s+/g, '')\r\n // Normalize case\r\n .toLowerCase();\r\n\r\n/**\r\n * Check if a URL value is safe.\r\n * @internal\r\n */\r\nconst isSafeUrl = (value: string): boolean => {\r\n const normalized = normalizeUrl(value);\r\n for (const protocol of DANGEROUS_PROTOCOLS) {\r\n if (normalized.startsWith(protocol)) return false;\r\n }\r\n return true;\r\n};\r\n\r\n/**\r\n * Check if a URL is external (different origin).\r\n * @internal\r\n */\r\nconst isExternalUrl = (url: string): boolean => {\r\n try {\r\n // Normalize URL by trimming whitespace\r\n const trimmedUrl = url.trim();\r\n \r\n // Protocol-relative URLs (//example.com) are always external.\r\n // CRITICAL: This check must run before the relative-URL check below;\r\n // otherwise, a protocol-relative URL like \"//evil.com\" would be treated\r\n // as a non-http(s) relative URL and incorrectly classified as same-origin.\r\n // Handling them up front guarantees correct security classification.\r\n if (trimmedUrl.startsWith('//')) {\r\n return true;\r\n }\r\n \r\n // Normalize URL for case-insensitive protocol checks\r\n const lowerUrl = trimmedUrl.toLowerCase();\r\n \r\n // Check for non-http(s) protocols which are considered external/special\r\n // (mailto:, tel:, ftp:, etc.)\r\n const hasProtocol = /^[a-z][a-z0-9+.-]*:/i.test(trimmedUrl);\r\n if (hasProtocol && !lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {\r\n // These are special protocols, not traditional \"external\" links\r\n // but we treat them as external for security consistency\r\n return true;\r\n }\r\n \r\n // Relative URLs are not external\r\n if (!lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {\r\n return false;\r\n }\r\n \r\n // In non-browser environments (e.g., Node.js), treat all absolute URLs as external\r\n if (typeof window === 'undefined' || !window.location) {\r\n return true;\r\n }\r\n \r\n const urlObj = new URL(trimmedUrl, window.location.href);\r\n return urlObj.origin !== window.location.origin;\r\n } catch {\r\n // If URL parsing fails, treat as potentially external for safety\r\n return true;\r\n }\r\n};\r\n\r\n/**\r\n * Core sanitization logic (without Trusted Types wrapper).\r\n * @internal\r\n */\r\nconst sanitizeHtmlCore = (html: string, options: SanitizeOptions = {}): string => {\r\n const {\r\n allowTags = [],\r\n allowAttributes = [],\r\n allowDataAttributes = true,\r\n stripAllTags = false,\r\n } = options;\r\n\r\n // Build combined allow sets (excluding dangerous tags even if specified)\r\n const allowedTags = new Set(\r\n [...DEFAULT_ALLOWED_TAGS, ...allowTags.map((t) => t.toLowerCase())].filter(\r\n (tag) => !DANGEROUS_TAGS.has(tag)\r\n )\r\n );\r\n const allowedAttrs = new Set([\r\n ...DEFAULT_ALLOWED_ATTRIBUTES,\r\n ...allowAttributes.map((a) => a.toLowerCase()),\r\n ]);\r\n\r\n // Use template for parsing\r\n const template = document.createElement('template');\r\n template.innerHTML = html;\r\n\r\n if (stripAllTags) {\r\n return template.content.textContent ?? '';\r\n }\r\n\r\n // Walk the DOM tree\r\n const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);\r\n\r\n const toRemove: Element[] = [];\r\n\r\n while (walker.nextNode()) {\r\n const el = walker.currentNode as Element;\r\n const tagName = el.tagName.toLowerCase();\r\n\r\n // Remove explicitly dangerous tags even if in allow list\r\n if (DANGEROUS_TAGS.has(tagName)) {\r\n toRemove.push(el);\r\n continue;\r\n }\r\n\r\n // Remove disallowed tags entirely\r\n if (!allowedTags.has(tagName)) {\r\n toRemove.push(el);\r\n continue;\r\n }\r\n\r\n // Process attributes\r\n const attrsToRemove: string[] = [];\r\n for (const attr of Array.from(el.attributes)) {\r\n const attrName = attr.name.toLowerCase();\r\n\r\n // Check if attribute is allowed\r\n if (!isAllowedAttribute(attrName, allowedAttrs, allowDataAttributes)) {\r\n attrsToRemove.push(attr.name);\r\n continue;\r\n }\r\n\r\n // Check for DOM clobbering on id and name attributes\r\n if ((attrName === 'id' || attrName === 'name') && !isSafeIdOrName(attr.value)) {\r\n attrsToRemove.push(attr.name);\r\n continue;\r\n }\r\n\r\n // Validate URL attributes\r\n if (\r\n (attrName === 'href' || attrName === 'src' || attrName === 'srcset') &&\r\n !isSafeUrl(attr.value)\r\n ) {\r\n attrsToRemove.push(attr.name);\r\n }\r\n }\r\n\r\n // Remove disallowed attributes\r\n for (const attrName of attrsToRemove) {\r\n el.removeAttribute(attrName);\r\n }\r\n\r\n // Add rel=\"noopener noreferrer\" to external links for security\r\n if (tagName === 'a') {\r\n const href = el.getAttribute('href');\r\n const target = el.getAttribute('target');\r\n const hasTargetBlank = target?.toLowerCase() === '_blank';\r\n const isExternal = href && isExternalUrl(href);\r\n\r\n // Add security attributes to links opening in new window or external links\r\n if (hasTargetBlank || isExternal) {\r\n const existingRel = el.getAttribute('rel');\r\n const relValues = new Set(\r\n existingRel ? existingRel.split(/\\s+/).filter(Boolean) : []\r\n );\r\n \r\n // Add noopener and noreferrer\r\n relValues.add('noopener');\r\n relValues.add('noreferrer');\r\n \r\n el.setAttribute('rel', Array.from(relValues).join(' '));\r\n }\r\n }\r\n }\r\n\r\n // Remove disallowed elements\r\n for (const el of toRemove) {\r\n el.remove();\r\n }\r\n\r\n return template.innerHTML;\r\n};\r\n\r\n// ============================================================================\r\n// Public API\r\n// ============================================================================\r\n\r\n/**\r\n * Sanitize HTML string, removing dangerous elements and attributes.\r\n * Uses Trusted Types when available for CSP compliance.\r\n *\r\n * @param html - The HTML string to sanitize\r\n * @param options - Sanitization options\r\n * @returns Sanitized HTML string\r\n *\r\n * @example\r\n * ```ts\r\n * const safe = sanitizeHtml('<div onclick=\"alert(1)\">Hello</div>');\r\n * // Returns: '<div>Hello</div>'\r\n * ```\r\n */\r\nexport const sanitizeHtml = (html: string, options: SanitizeOptions = {}): string => {\r\n return sanitizeHtmlCore(html, options);\r\n};\r\n\r\n/**\r\n * Create a Trusted HTML value for use with Trusted Types-enabled sites.\r\n * Falls back to regular string when Trusted Types are unavailable.\r\n *\r\n * @param html - The HTML string to wrap\r\n * @returns Trusted HTML value or sanitized string\r\n */\r\nexport const createTrustedHtml = (html: string): TrustedHTML | string => {\r\n const policy = getTrustedTypesPolicy();\r\n if (policy) {\r\n return policy.createHTML(html);\r\n }\r\n return sanitizeHtml(html);\r\n};\r\n\r\n/**\r\n * Escape HTML entities to prevent XSS.\r\n * Use this for displaying user content as text.\r\n *\r\n * @param text - The text to escape\r\n * @returns Escaped HTML string\r\n *\r\n * @example\r\n * ```ts\r\n * escapeHtml('<script>alert(1)</script>');\r\n * // Returns: '<script>alert(1)</script>'\r\n * ```\r\n */\r\nexport const escapeHtml = (text: string): string => {\r\n const escapeMap: Record<string, string> = {\r\n '&': '&',\r\n '<': '<',\r\n '>': '>',\r\n '\"': '"',\r\n \"'\": ''',\r\n '`': '`',\r\n };\r\n return text.replace(/[&<>\"'`]/g, (char) => escapeMap[char]);\r\n};\r\n\r\n/**\r\n * Strip all HTML tags and return plain text.\r\n *\r\n * @param html - The HTML string to strip\r\n * @returns Plain text content\r\n */\r\nexport const stripTags = (html: string): string => {\r\n return sanitizeHtmlCore(html, { stripAllTags: true });\r\n};\r\n\r\n// ============================================================================\r\n// CSP Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Generate a nonce for inline scripts/styles.\r\n * Use with Content-Security-Policy nonce directives.\r\n *\r\n * @param length - Nonce length (default: 16)\r\n * @returns Cryptographically random nonce string\r\n */\r\nexport const generateNonce = (length: number = 16): string => {\r\n const array = new Uint8Array(length);\r\n crypto.getRandomValues(array);\r\n return btoa(String.fromCharCode(...array))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=/g, '');\r\n};\r\n\r\n/**\r\n * Check if a CSP header is present with specific directive.\r\n * Useful for feature detection and fallback strategies.\r\n *\r\n * @param directive - The CSP directive to check (e.g., 'script-src')\r\n * @returns True if the directive appears to be enforced\r\n */\r\nexport const hasCSPDirective = (directive: string): boolean => {\r\n // Check meta tag\r\n const meta = document.querySelector('meta[http-equiv=\"Content-Security-Policy\"]');\r\n if (meta) {\r\n const content = meta.getAttribute('content') ?? '';\r\n return content.includes(directive);\r\n }\r\n return false;\r\n};\r\n"],"names":["POLICY_NAME","cachedPolicy","isTrustedTypesSupported","getTrustedTypesPolicy","win","input","sanitizeHtmlCore","DEFAULT_ALLOWED_TAGS","DANGEROUS_TAGS","RESERVED_IDS","DEFAULT_ALLOWED_ATTRIBUTES","DANGEROUS_ATTR_PREFIXES","DANGEROUS_PROTOCOLS","isAllowedAttribute","name","allowedSet","allowDataAttrs","lowerName","prefix","isSafeIdOrName","value","lowerValue","normalizeUrl","isSafeUrl","normalized","protocol","isExternalUrl","url","trimmedUrl","lowerUrl","html","options","allowTags","allowAttributes","allowDataAttributes","stripAllTags","allowedTags","t","tag","allowedAttrs","a","template","walker","toRemove","el","tagName","attrsToRemove","attr","attrName","href","hasTargetBlank","isExternal","existingRel","relValues","sanitizeHtml","createTrustedHtml","policy","escapeHtml","text","escapeMap","char","stripTags","generateNonce","length","array","hasCSPDirective","directive","meta"],"mappings":"AA4BA,MAAMA,IAAc;AA4BpB,IAAIC,IAAyC;AAMtC,MAAMC,IAA0B,MAC9B,OAAQ,OAA8B,eAAiB,KAOnDC,IAAwB,MAAgC;AACnE,MAAIF,EAAc,QAAOA;AAEzB,QAAMG,IAAM;AACZ,MAAI,CAACA,EAAI,aAAc,QAAO;AAE9B,MAAI;AACF,WAAAH,IAAeG,EAAI,aAAa,aAAaJ,GAAa;AAAA,MACxD,YAAY,CAACK,MAAkBC,EAAiBD,CAAK;AAAA,IAAA,CACtD,GACMJ;AAAA,EACT,QAAQ;AAEN,mBAAQ,KAAK,kDAAkDD,CAAW,GAAG,GACtE;AAAA,EACT;AACF,GASMO,wBAA2B,IAAI;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC,GAMKC,wBAAqB,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC,GAMKC,wBAAmB,IAAI;AAAA;AAAA,EAE3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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AAMD;AACf,IAAAC,EAAG,OAAA;AAGL,SAAOH,EAAS;AAClB,GAoBaa,IAAe,CAACxB,GAAcC,IAA2B,OAC7DzB,EAAiBwB,GAAMC,CAAO,GAU1BwB,IAAoB,CAACzB,MAAuC;AACvE,QAAM0B,IAASrD,EAAA;AACf,SAAIqD,IACKA,EAAO,WAAW1B,CAAI,IAExBwB,EAAaxB,CAAI;AAC1B,GAea2B,IAAa,CAACC,MAAyB;AAClD,QAAMC,IAAoC;AAAA,IACxC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EAAA;AAEP,SAAOD,EAAK,QAAQ,aAAa,CAACE,MAASD,EAAUC,CAAI,CAAC;AAC5D,GAQaC,IAAY,CAAC/B,MACjBxB,EAAiBwB,GAAM,EAAE,cAAc,IAAM,GAczCgC,IAAgB,CAACC,IAAiB,OAAe;AAC5D,QAAMC,IAAQ,IAAI,WAAWD,CAAM;AACnC,gBAAO,gBAAgBC,CAAK,GACrB,KAAK,OAAO,aAAa,GAAGA,CAAK,CAAC,EACtC,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,MAAM,EAAE;AACrB,GASaC,IAAkB,CAACC,MAA+B;AAE7D,QAAMC,IAAO,SAAS,cAAc,4CAA4C;AAChF,SAAIA,KACcA,EAAK,aAAa,SAAS,KAAK,IACjC,SAASD,CAAS,IAE5B;AACT;"}
|
package/package.json
CHANGED
package/src/security/sanitize.ts
CHANGED
|
@@ -261,11 +261,13 @@ const DEFAULT_ALLOWED_ATTRIBUTES = new Set([
|
|
|
261
261
|
'lang',
|
|
262
262
|
'loading',
|
|
263
263
|
'name',
|
|
264
|
+
'rel',
|
|
264
265
|
'role',
|
|
265
266
|
'src',
|
|
266
267
|
'srcset',
|
|
267
268
|
'style',
|
|
268
269
|
'tabindex',
|
|
270
|
+
'target',
|
|
269
271
|
'title',
|
|
270
272
|
'type',
|
|
271
273
|
'width',
|
|
@@ -351,6 +353,54 @@ const isSafeUrl = (value: string): boolean => {
|
|
|
351
353
|
return true;
|
|
352
354
|
};
|
|
353
355
|
|
|
356
|
+
/**
|
|
357
|
+
* Check if a URL is external (different origin).
|
|
358
|
+
* @internal
|
|
359
|
+
*/
|
|
360
|
+
const isExternalUrl = (url: string): boolean => {
|
|
361
|
+
try {
|
|
362
|
+
// Normalize URL by trimming whitespace
|
|
363
|
+
const trimmedUrl = url.trim();
|
|
364
|
+
|
|
365
|
+
// Protocol-relative URLs (//example.com) are always external.
|
|
366
|
+
// CRITICAL: This check must run before the relative-URL check below;
|
|
367
|
+
// otherwise, a protocol-relative URL like "//evil.com" would be treated
|
|
368
|
+
// as a non-http(s) relative URL and incorrectly classified as same-origin.
|
|
369
|
+
// Handling them up front guarantees correct security classification.
|
|
370
|
+
if (trimmedUrl.startsWith('//')) {
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Normalize URL for case-insensitive protocol checks
|
|
375
|
+
const lowerUrl = trimmedUrl.toLowerCase();
|
|
376
|
+
|
|
377
|
+
// Check for non-http(s) protocols which are considered external/special
|
|
378
|
+
// (mailto:, tel:, ftp:, etc.)
|
|
379
|
+
const hasProtocol = /^[a-z][a-z0-9+.-]*:/i.test(trimmedUrl);
|
|
380
|
+
if (hasProtocol && !lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {
|
|
381
|
+
// These are special protocols, not traditional "external" links
|
|
382
|
+
// but we treat them as external for security consistency
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Relative URLs are not external
|
|
387
|
+
if (!lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// In non-browser environments (e.g., Node.js), treat all absolute URLs as external
|
|
392
|
+
if (typeof window === 'undefined' || !window.location) {
|
|
393
|
+
return true;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const urlObj = new URL(trimmedUrl, window.location.href);
|
|
397
|
+
return urlObj.origin !== window.location.origin;
|
|
398
|
+
} catch {
|
|
399
|
+
// If URL parsing fails, treat as potentially external for safety
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
|
|
354
404
|
/**
|
|
355
405
|
* Core sanitization logic (without Trusted Types wrapper).
|
|
356
406
|
* @internal
|
|
@@ -433,6 +483,28 @@ const sanitizeHtmlCore = (html: string, options: SanitizeOptions = {}): string =
|
|
|
433
483
|
for (const attrName of attrsToRemove) {
|
|
434
484
|
el.removeAttribute(attrName);
|
|
435
485
|
}
|
|
486
|
+
|
|
487
|
+
// Add rel="noopener noreferrer" to external links for security
|
|
488
|
+
if (tagName === 'a') {
|
|
489
|
+
const href = el.getAttribute('href');
|
|
490
|
+
const target = el.getAttribute('target');
|
|
491
|
+
const hasTargetBlank = target?.toLowerCase() === '_blank';
|
|
492
|
+
const isExternal = href && isExternalUrl(href);
|
|
493
|
+
|
|
494
|
+
// Add security attributes to links opening in new window or external links
|
|
495
|
+
if (hasTargetBlank || isExternal) {
|
|
496
|
+
const existingRel = el.getAttribute('rel');
|
|
497
|
+
const relValues = new Set(
|
|
498
|
+
existingRel ? existingRel.split(/\s+/).filter(Boolean) : []
|
|
499
|
+
);
|
|
500
|
+
|
|
501
|
+
// Add noopener and noreferrer
|
|
502
|
+
relValues.add('noopener');
|
|
503
|
+
relValues.add('noreferrer');
|
|
504
|
+
|
|
505
|
+
el.setAttribute('rel', Array.from(relValues).join(' '));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
436
508
|
}
|
|
437
509
|
|
|
438
510
|
// Remove disallowed elements
|