@bquery/bquery 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +61 -7
  2. package/dist/component/index.d.ts +8 -0
  3. package/dist/component/index.d.ts.map +1 -1
  4. package/dist/component.es.mjs +80 -53
  5. package/dist/component.es.mjs.map +1 -1
  6. package/dist/core/collection.d.ts +46 -0
  7. package/dist/core/collection.d.ts.map +1 -1
  8. package/dist/core/element.d.ts +124 -22
  9. package/dist/core/element.d.ts.map +1 -1
  10. package/dist/core/utils.d.ts +13 -0
  11. package/dist/core/utils.d.ts.map +1 -1
  12. package/dist/core.es.mjs +298 -55
  13. package/dist/core.es.mjs.map +1 -1
  14. package/dist/full.d.ts +2 -2
  15. package/dist/full.d.ts.map +1 -1
  16. package/dist/full.es.mjs +38 -33
  17. package/dist/full.iife.js +1 -1
  18. package/dist/full.iife.js.map +1 -1
  19. package/dist/full.umd.js +1 -1
  20. package/dist/full.umd.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.es.mjs +38 -33
  23. package/dist/reactive/index.d.ts +2 -2
  24. package/dist/reactive/index.d.ts.map +1 -1
  25. package/dist/reactive/signal.d.ts +107 -0
  26. package/dist/reactive/signal.d.ts.map +1 -1
  27. package/dist/reactive.es.mjs +92 -55
  28. package/dist/reactive.es.mjs.map +1 -1
  29. package/dist/security/sanitize.d.ts.map +1 -1
  30. package/dist/security.es.mjs +136 -66
  31. package/dist/security.es.mjs.map +1 -1
  32. package/package.json +120 -120
  33. package/src/component/index.ts +414 -360
  34. package/src/core/collection.ts +454 -339
  35. package/src/core/element.ts +740 -493
  36. package/src/core/utils.ts +444 -425
  37. package/src/full.ts +106 -101
  38. package/src/index.ts +27 -27
  39. package/src/reactive/index.ts +22 -9
  40. package/src/reactive/signal.ts +506 -347
  41. package/src/security/sanitize.ts +553 -446
@@ -1,446 +1,553 @@
1
- /**
2
- * Security utilities for HTML sanitization, CSP compatibility, and Trusted Types.
3
- * All DOM writes are sanitized by default to prevent XSS attacks.
4
- *
5
- * @module bquery/security
6
- */
7
-
8
- // ============================================================================
9
- // Types
10
- // ============================================================================
11
-
12
- /**
13
- * Sanitizer configuration options.
14
- */
15
- export interface SanitizeOptions {
16
- /** Allow these additional tags (default: none) */
17
- allowTags?: string[];
18
- /** Allow these additional attributes (default: none) */
19
- allowAttributes?: string[];
20
- /** Allow data-* attributes (default: true) */
21
- allowDataAttributes?: boolean;
22
- /** Strip all tags and return plain text (default: false) */
23
- stripAllTags?: boolean;
24
- }
25
-
26
- /**
27
- * Trusted Types policy name.
28
- */
29
- const POLICY_NAME = 'bquery-sanitizer';
30
-
31
- // ============================================================================
32
- // Trusted Types Support
33
- // ============================================================================
34
-
35
- /** Window interface extended with Trusted Types */
36
- interface TrustedTypesWindow extends Window {
37
- trustedTypes?: {
38
- createPolicy: (
39
- name: string,
40
- rules: { createHTML?: (input: string) => string }
41
- ) => TrustedTypePolicy;
42
- isHTML?: (value: unknown) => boolean;
43
- };
44
- }
45
-
46
- /** Trusted Types policy interface */
47
- interface TrustedTypePolicy {
48
- createHTML: (input: string) => TrustedHTML;
49
- }
50
-
51
- /** Trusted HTML type placeholder for environments without Trusted Types */
52
- interface TrustedHTML {
53
- toString(): string;
54
- }
55
-
56
- /** Cached Trusted Types policy */
57
- let cachedPolicy: TrustedTypePolicy | null = null;
58
-
59
- /**
60
- * Check if Trusted Types API is available.
61
- * @returns True if Trusted Types are supported
62
- */
63
- export const isTrustedTypesSupported = (): boolean => {
64
- return typeof (window as TrustedTypesWindow).trustedTypes !== 'undefined';
65
- };
66
-
67
- /**
68
- * Get or create the bQuery Trusted Types policy.
69
- * @returns The Trusted Types policy or null if unsupported
70
- */
71
- export const getTrustedTypesPolicy = (): TrustedTypePolicy | null => {
72
- if (cachedPolicy) return cachedPolicy;
73
-
74
- const win = window as TrustedTypesWindow;
75
- if (!win.trustedTypes) return null;
76
-
77
- try {
78
- cachedPolicy = win.trustedTypes.createPolicy(POLICY_NAME, {
79
- createHTML: (input: string) => sanitizeHtmlCore(input),
80
- });
81
- return cachedPolicy;
82
- } catch {
83
- // Policy may already exist or be blocked by CSP
84
- console.warn(`bQuery: Could not create Trusted Types policy "${POLICY_NAME}"`);
85
- return null;
86
- }
87
- };
88
-
89
- // ============================================================================
90
- // Default Safe Lists
91
- // ============================================================================
92
-
93
- /**
94
- * Default allowed HTML tags considered safe.
95
- */
96
- const DEFAULT_ALLOWED_TAGS = new Set([
97
- 'a',
98
- 'abbr',
99
- 'address',
100
- 'article',
101
- 'aside',
102
- 'b',
103
- 'bdi',
104
- 'bdo',
105
- 'blockquote',
106
- 'br',
107
- 'button',
108
- 'caption',
109
- 'cite',
110
- 'code',
111
- 'col',
112
- 'colgroup',
113
- 'data',
114
- 'dd',
115
- 'del',
116
- 'details',
117
- 'dfn',
118
- 'div',
119
- 'dl',
120
- 'dt',
121
- 'em',
122
- 'figcaption',
123
- 'figure',
124
- 'footer',
125
- 'form',
126
- 'h1',
127
- 'h2',
128
- 'h3',
129
- 'h4',
130
- 'h5',
131
- 'h6',
132
- 'header',
133
- 'hgroup',
134
- 'hr',
135
- 'i',
136
- 'img',
137
- 'input',
138
- 'ins',
139
- 'kbd',
140
- 'label',
141
- 'legend',
142
- 'li',
143
- 'main',
144
- 'mark',
145
- 'nav',
146
- 'ol',
147
- 'optgroup',
148
- 'option',
149
- 'p',
150
- 'picture',
151
- 'pre',
152
- 'progress',
153
- 'q',
154
- 'rp',
155
- 'rt',
156
- 'ruby',
157
- 's',
158
- 'samp',
159
- 'section',
160
- 'select',
161
- 'small',
162
- 'source',
163
- 'span',
164
- 'strong',
165
- 'sub',
166
- 'summary',
167
- 'sup',
168
- 'table',
169
- 'tbody',
170
- 'td',
171
- 'textarea',
172
- 'tfoot',
173
- 'th',
174
- 'thead',
175
- 'time',
176
- 'tr',
177
- 'u',
178
- 'ul',
179
- 'var',
180
- 'wbr',
181
- ]);
182
-
183
- /**
184
- * Default allowed attributes considered safe.
185
- */
186
- const DEFAULT_ALLOWED_ATTRIBUTES = new Set([
187
- 'alt',
188
- 'class',
189
- 'dir',
190
- 'height',
191
- 'hidden',
192
- 'href',
193
- 'id',
194
- 'lang',
195
- 'loading',
196
- 'name',
197
- 'role',
198
- 'src',
199
- 'srcset',
200
- 'style',
201
- 'tabindex',
202
- 'title',
203
- 'type',
204
- 'width',
205
- 'aria-*',
206
- ]);
207
-
208
- /**
209
- * Dangerous attribute prefixes to always remove.
210
- */
211
- const DANGEROUS_ATTR_PREFIXES = ['on', 'formaction'];
212
-
213
- /**
214
- * Dangerous URL protocols to block.
215
- */
216
- const DANGEROUS_PROTOCOLS = ['javascript:', 'data:', 'vbscript:'];
217
-
218
- // ============================================================================
219
- // Core Sanitization
220
- // ============================================================================
221
-
222
- /**
223
- * Check if an attribute name is allowed.
224
- */
225
- const isAllowedAttribute = (
226
- name: string,
227
- allowedSet: Set<string>,
228
- allowDataAttrs: boolean
229
- ): boolean => {
230
- const lowerName = name.toLowerCase();
231
-
232
- // Check dangerous prefixes
233
- for (const prefix of DANGEROUS_ATTR_PREFIXES) {
234
- if (lowerName.startsWith(prefix)) return false;
235
- }
236
-
237
- // Check data attributes
238
- if (allowDataAttrs && lowerName.startsWith('data-')) return true;
239
-
240
- // Check aria attributes (allowed by default)
241
- if (lowerName.startsWith('aria-')) return true;
242
-
243
- // Check explicit allow list
244
- return allowedSet.has(lowerName);
245
- };
246
-
247
- /**
248
- * Normalize URL by removing control characters and whitespace.
249
- */
250
- const normalizeUrl = (value: string): string =>
251
- value.replace(/[\u0000-\u001F\u007F\s]+/g, '').toLowerCase();
252
-
253
- /**
254
- * Check if a URL value is safe.
255
- */
256
- const isSafeUrl = (value: string): boolean => {
257
- const normalized = normalizeUrl(value);
258
- for (const protocol of DANGEROUS_PROTOCOLS) {
259
- if (normalized.startsWith(protocol)) return false;
260
- }
261
- return true;
262
- };
263
-
264
- /**
265
- * Core sanitization logic (without Trusted Types wrapper).
266
- */
267
- const sanitizeHtmlCore = (html: string, options: SanitizeOptions = {}): string => {
268
- const {
269
- allowTags = [],
270
- allowAttributes = [],
271
- allowDataAttributes = true,
272
- stripAllTags = false,
273
- } = options;
274
-
275
- // Build combined allow sets
276
- const allowedTags = new Set([...DEFAULT_ALLOWED_TAGS, ...allowTags.map((t) => t.toLowerCase())]);
277
- const allowedAttrs = new Set([
278
- ...DEFAULT_ALLOWED_ATTRIBUTES,
279
- ...allowAttributes.map((a) => a.toLowerCase()),
280
- ]);
281
-
282
- // Use template for parsing
283
- const template = document.createElement('template');
284
- template.innerHTML = html;
285
-
286
- if (stripAllTags) {
287
- return template.content.textContent ?? '';
288
- }
289
-
290
- // Walk the DOM tree
291
- const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);
292
-
293
- const toRemove: Element[] = [];
294
-
295
- while (walker.nextNode()) {
296
- const el = walker.currentNode as Element;
297
- const tagName = el.tagName.toLowerCase();
298
-
299
- // Remove disallowed tags entirely
300
- if (!allowedTags.has(tagName)) {
301
- toRemove.push(el);
302
- continue;
303
- }
304
-
305
- // Process attributes
306
- const attrsToRemove: string[] = [];
307
- for (const attr of Array.from(el.attributes)) {
308
- const attrName = attr.name.toLowerCase();
309
-
310
- // Check if attribute is allowed
311
- if (!isAllowedAttribute(attrName, allowedAttrs, allowDataAttributes)) {
312
- attrsToRemove.push(attr.name);
313
- continue;
314
- }
315
-
316
- // Validate URL attributes
317
- if (
318
- (attrName === 'href' || attrName === 'src' || attrName === 'srcset') &&
319
- !isSafeUrl(attr.value)
320
- ) {
321
- attrsToRemove.push(attr.name);
322
- }
323
- }
324
-
325
- // Remove disallowed attributes
326
- for (const attrName of attrsToRemove) {
327
- el.removeAttribute(attrName);
328
- }
329
- }
330
-
331
- // Remove disallowed elements
332
- for (const el of toRemove) {
333
- el.remove();
334
- }
335
-
336
- return template.innerHTML;
337
- };
338
-
339
- // ============================================================================
340
- // Public API
341
- // ============================================================================
342
-
343
- /**
344
- * Sanitize HTML string, removing dangerous elements and attributes.
345
- * Uses Trusted Types when available for CSP compliance.
346
- *
347
- * @param html - The HTML string to sanitize
348
- * @param options - Sanitization options
349
- * @returns Sanitized HTML string
350
- *
351
- * @example
352
- * ```ts
353
- * const safe = sanitizeHtml('<div onclick="alert(1)">Hello</div>');
354
- * // Returns: '<div>Hello</div>'
355
- * ```
356
- */
357
- export const sanitizeHtml = (html: string, options: SanitizeOptions = {}): string => {
358
- return sanitizeHtmlCore(html, options);
359
- };
360
-
361
- /**
362
- * Create a Trusted HTML value for use with Trusted Types-enabled sites.
363
- * Falls back to regular string when Trusted Types are unavailable.
364
- *
365
- * @param html - The HTML string to wrap
366
- * @returns Trusted HTML value or sanitized string
367
- */
368
- export const createTrustedHtml = (html: string): TrustedHTML | string => {
369
- const policy = getTrustedTypesPolicy();
370
- if (policy) {
371
- return policy.createHTML(html);
372
- }
373
- return sanitizeHtml(html);
374
- };
375
-
376
- /**
377
- * Escape HTML entities to prevent XSS.
378
- * Use this for displaying user content as text.
379
- *
380
- * @param text - The text to escape
381
- * @returns Escaped HTML string
382
- *
383
- * @example
384
- * ```ts
385
- * escapeHtml('<script>alert(1)</script>');
386
- * // Returns: '&lt;script&gt;alert(1)&lt;/script&gt;'
387
- * ```
388
- */
389
- export const escapeHtml = (text: string): string => {
390
- const escapeMap: Record<string, string> = {
391
- '&': '&amp;',
392
- '<': '&lt;',
393
- '>': '&gt;',
394
- '"': '&quot;',
395
- "'": '&#x27;',
396
- '`': '&#x60;',
397
- };
398
- return text.replace(/[&<>"'`]/g, (char) => escapeMap[char]);
399
- };
400
-
401
- /**
402
- * Strip all HTML tags and return plain text.
403
- *
404
- * @param html - The HTML string to strip
405
- * @returns Plain text content
406
- */
407
- export const stripTags = (html: string): string => {
408
- return sanitizeHtmlCore(html, { stripAllTags: true });
409
- };
410
-
411
- // ============================================================================
412
- // CSP Helpers
413
- // ============================================================================
414
-
415
- /**
416
- * Generate a nonce for inline scripts/styles.
417
- * Use with Content-Security-Policy nonce directives.
418
- *
419
- * @param length - Nonce length (default: 16)
420
- * @returns Cryptographically random nonce string
421
- */
422
- export const generateNonce = (length: number = 16): string => {
423
- const array = new Uint8Array(length);
424
- crypto.getRandomValues(array);
425
- return btoa(String.fromCharCode(...array))
426
- .replace(/\+/g, '-')
427
- .replace(/\//g, '_')
428
- .replace(/=/g, '');
429
- };
430
-
431
- /**
432
- * Check if a CSP header is present with specific directive.
433
- * Useful for feature detection and fallback strategies.
434
- *
435
- * @param directive - The CSP directive to check (e.g., 'script-src')
436
- * @returns True if the directive appears to be enforced
437
- */
438
- export const hasCSPDirective = (directive: string): boolean => {
439
- // Check meta tag
440
- const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
441
- if (meta) {
442
- const content = meta.getAttribute('content') ?? '';
443
- return content.includes(directive);
444
- }
445
- return false;
446
- };
1
+ /**
2
+ * Security utilities for HTML sanitization, CSP compatibility, and Trusted Types.
3
+ * All DOM writes are sanitized by default to prevent XSS attacks.
4
+ *
5
+ * @module bquery/security
6
+ */
7
+
8
+ // ============================================================================
9
+ // Types
10
+ // ============================================================================
11
+
12
+ /**
13
+ * Sanitizer configuration options.
14
+ */
15
+ export interface SanitizeOptions {
16
+ /** Allow these additional tags (default: none) */
17
+ allowTags?: string[];
18
+ /** Allow these additional attributes (default: none) */
19
+ allowAttributes?: string[];
20
+ /** Allow data-* attributes (default: true) */
21
+ allowDataAttributes?: boolean;
22
+ /** Strip all tags and return plain text (default: false) */
23
+ stripAllTags?: boolean;
24
+ }
25
+
26
+ /**
27
+ * Trusted Types policy name.
28
+ */
29
+ const POLICY_NAME = 'bquery-sanitizer';
30
+
31
+ // ============================================================================
32
+ // Trusted Types Support
33
+ // ============================================================================
34
+
35
+ /** Window interface extended with Trusted Types */
36
+ interface TrustedTypesWindow extends Window {
37
+ trustedTypes?: {
38
+ createPolicy: (
39
+ name: string,
40
+ rules: { createHTML?: (input: string) => string }
41
+ ) => TrustedTypePolicy;
42
+ isHTML?: (value: unknown) => boolean;
43
+ };
44
+ }
45
+
46
+ /** Trusted Types policy interface */
47
+ interface TrustedTypePolicy {
48
+ createHTML: (input: string) => TrustedHTML;
49
+ }
50
+
51
+ /** Trusted HTML type placeholder for environments without Trusted Types */
52
+ interface TrustedHTML {
53
+ toString(): string;
54
+ }
55
+
56
+ /** Cached Trusted Types policy */
57
+ let cachedPolicy: TrustedTypePolicy | null = null;
58
+
59
+ /**
60
+ * Check if Trusted Types API is available.
61
+ * @returns True if Trusted Types are supported
62
+ */
63
+ export const isTrustedTypesSupported = (): boolean => {
64
+ return typeof (window as TrustedTypesWindow).trustedTypes !== 'undefined';
65
+ };
66
+
67
+ /**
68
+ * Get or create the bQuery Trusted Types policy.
69
+ * @returns The Trusted Types policy or null if unsupported
70
+ */
71
+ export const getTrustedTypesPolicy = (): TrustedTypePolicy | null => {
72
+ if (cachedPolicy) return cachedPolicy;
73
+
74
+ const win = window as TrustedTypesWindow;
75
+ if (!win.trustedTypes) return null;
76
+
77
+ try {
78
+ cachedPolicy = win.trustedTypes.createPolicy(POLICY_NAME, {
79
+ createHTML: (input: string) => sanitizeHtmlCore(input),
80
+ });
81
+ return cachedPolicy;
82
+ } catch {
83
+ // Policy may already exist or be blocked by CSP
84
+ console.warn(`bQuery: Could not create Trusted Types policy "${POLICY_NAME}"`);
85
+ return null;
86
+ }
87
+ };
88
+
89
+ // ============================================================================
90
+ // Default Safe Lists
91
+ // ============================================================================
92
+
93
+ /**
94
+ * Default allowed HTML tags considered safe.
95
+ */
96
+ const DEFAULT_ALLOWED_TAGS = new Set([
97
+ 'a',
98
+ 'abbr',
99
+ 'address',
100
+ 'article',
101
+ 'aside',
102
+ 'b',
103
+ 'bdi',
104
+ 'bdo',
105
+ 'blockquote',
106
+ 'br',
107
+ 'button',
108
+ 'caption',
109
+ 'cite',
110
+ 'code',
111
+ 'col',
112
+ 'colgroup',
113
+ 'data',
114
+ 'dd',
115
+ 'del',
116
+ 'details',
117
+ 'dfn',
118
+ 'div',
119
+ 'dl',
120
+ 'dt',
121
+ 'em',
122
+ 'figcaption',
123
+ 'figure',
124
+ 'footer',
125
+ 'form',
126
+ 'h1',
127
+ 'h2',
128
+ 'h3',
129
+ 'h4',
130
+ 'h5',
131
+ 'h6',
132
+ 'header',
133
+ 'hgroup',
134
+ 'hr',
135
+ 'i',
136
+ 'img',
137
+ 'input',
138
+ 'ins',
139
+ 'kbd',
140
+ 'label',
141
+ 'legend',
142
+ 'li',
143
+ 'main',
144
+ 'mark',
145
+ 'nav',
146
+ 'ol',
147
+ 'optgroup',
148
+ 'option',
149
+ 'p',
150
+ 'picture',
151
+ 'pre',
152
+ 'progress',
153
+ 'q',
154
+ 'rp',
155
+ 'rt',
156
+ 'ruby',
157
+ 's',
158
+ 'samp',
159
+ 'section',
160
+ 'select',
161
+ 'small',
162
+ 'source',
163
+ 'span',
164
+ 'strong',
165
+ 'sub',
166
+ 'summary',
167
+ 'sup',
168
+ 'table',
169
+ 'tbody',
170
+ 'td',
171
+ 'textarea',
172
+ 'tfoot',
173
+ 'th',
174
+ 'thead',
175
+ 'time',
176
+ 'tr',
177
+ 'u',
178
+ 'ul',
179
+ 'var',
180
+ 'wbr',
181
+ ]);
182
+
183
+ /**
184
+ * Explicitly dangerous tags that should never be allowed.
185
+ * These are checked even if somehow added to allowTags.
186
+ */
187
+ const DANGEROUS_TAGS = new Set([
188
+ 'script',
189
+ 'iframe',
190
+ 'frame',
191
+ 'frameset',
192
+ 'object',
193
+ 'embed',
194
+ 'applet',
195
+ 'link',
196
+ 'meta',
197
+ 'style',
198
+ 'base',
199
+ 'template',
200
+ 'slot',
201
+ 'math',
202
+ 'svg',
203
+ 'foreignobject',
204
+ 'noscript',
205
+ ]);
206
+
207
+ /**
208
+ * Reserved IDs that could cause DOM clobbering attacks.
209
+ * These are prevented to avoid overwriting global browser objects.
210
+ */
211
+ const RESERVED_IDS = new Set([
212
+ // Global objects
213
+ 'document',
214
+ 'window',
215
+ 'location',
216
+ 'top',
217
+ 'self',
218
+ 'parent',
219
+ 'frames',
220
+ 'history',
221
+ 'navigator',
222
+ 'screen',
223
+ // Dangerous functions
224
+ 'alert',
225
+ 'confirm',
226
+ 'prompt',
227
+ 'eval',
228
+ 'Function',
229
+ // Document properties
230
+ 'cookie',
231
+ 'domain',
232
+ 'referrer',
233
+ 'body',
234
+ 'head',
235
+ 'forms',
236
+ 'images',
237
+ 'links',
238
+ 'scripts',
239
+ // DOM traversal properties
240
+ 'children',
241
+ 'parentNode',
242
+ 'firstChild',
243
+ 'lastChild',
244
+ // Content manipulation
245
+ 'innerHTML',
246
+ 'outerHTML',
247
+ 'textContent',
248
+ ]);
249
+
250
+ /**
251
+ * Default allowed attributes considered safe.
252
+ */
253
+ const DEFAULT_ALLOWED_ATTRIBUTES = new Set([
254
+ 'alt',
255
+ 'class',
256
+ 'dir',
257
+ 'height',
258
+ 'hidden',
259
+ 'href',
260
+ 'id',
261
+ 'lang',
262
+ 'loading',
263
+ 'name',
264
+ 'role',
265
+ 'src',
266
+ 'srcset',
267
+ 'style',
268
+ 'tabindex',
269
+ 'title',
270
+ 'type',
271
+ 'width',
272
+ 'aria-*',
273
+ ]);
274
+
275
+ /**
276
+ * Dangerous attribute prefixes to always remove.
277
+ */
278
+ const DANGEROUS_ATTR_PREFIXES = ['on', 'formaction', 'xlink:', 'xmlns:'];
279
+
280
+ /**
281
+ * Dangerous URL protocols to block.
282
+ */
283
+ const DANGEROUS_PROTOCOLS = ['javascript:', 'data:', 'vbscript:', 'file:'];
284
+
285
+ // ============================================================================
286
+ // Core Sanitization
287
+ // ============================================================================
288
+
289
+ /**
290
+ * Check if an attribute name is allowed.
291
+ * @internal
292
+ */
293
+ const isAllowedAttribute = (
294
+ name: string,
295
+ allowedSet: Set<string>,
296
+ allowDataAttrs: boolean
297
+ ): boolean => {
298
+ const lowerName = name.toLowerCase();
299
+
300
+ // Check dangerous prefixes
301
+ for (const prefix of DANGEROUS_ATTR_PREFIXES) {
302
+ if (lowerName.startsWith(prefix)) return false;
303
+ }
304
+
305
+ // Check data attributes
306
+ if (allowDataAttrs && lowerName.startsWith('data-')) return true;
307
+
308
+ // Check aria attributes (allowed by default)
309
+ if (lowerName.startsWith('aria-')) return true;
310
+
311
+ // Check explicit allow list
312
+ return allowedSet.has(lowerName);
313
+ };
314
+
315
+ /**
316
+ * Check if an ID/name value could cause DOM clobbering.
317
+ * @internal
318
+ */
319
+ const isSafeIdOrName = (value: string): boolean => {
320
+ const lowerValue = value.toLowerCase().trim();
321
+ return !RESERVED_IDS.has(lowerValue);
322
+ };
323
+
324
+ /**
325
+ * Normalize URL by removing control characters, whitespace, and Unicode tricks.
326
+ * Enhanced to prevent various bypass techniques.
327
+ * @internal
328
+ */
329
+ const normalizeUrl = (value: string): string =>
330
+ value
331
+ // Remove null bytes and control characters
332
+ .replace(/[\u0000-\u001F\u007F]+/g, '')
333
+ // Remove zero-width characters that could hide malicious content
334
+ .replace(/[\u200B-\u200D\uFEFF\u2028\u2029]+/g, '')
335
+ // Remove escaped Unicode sequences
336
+ .replace(/\\u[\da-fA-F]{4}/g, '')
337
+ // Remove whitespace
338
+ .replace(/\s+/g, '')
339
+ // Normalize case
340
+ .toLowerCase();
341
+
342
+ /**
343
+ * Check if a URL value is safe.
344
+ * @internal
345
+ */
346
+ const isSafeUrl = (value: string): boolean => {
347
+ const normalized = normalizeUrl(value);
348
+ for (const protocol of DANGEROUS_PROTOCOLS) {
349
+ if (normalized.startsWith(protocol)) return false;
350
+ }
351
+ return true;
352
+ };
353
+
354
+ /**
355
+ * Core sanitization logic (without Trusted Types wrapper).
356
+ * @internal
357
+ */
358
+ const sanitizeHtmlCore = (html: string, options: SanitizeOptions = {}): string => {
359
+ const {
360
+ allowTags = [],
361
+ allowAttributes = [],
362
+ allowDataAttributes = true,
363
+ stripAllTags = false,
364
+ } = options;
365
+
366
+ // Build combined allow sets (excluding dangerous tags even if specified)
367
+ const allowedTags = new Set(
368
+ [...DEFAULT_ALLOWED_TAGS, ...allowTags.map((t) => t.toLowerCase())].filter(
369
+ (tag) => !DANGEROUS_TAGS.has(tag)
370
+ )
371
+ );
372
+ const allowedAttrs = new Set([
373
+ ...DEFAULT_ALLOWED_ATTRIBUTES,
374
+ ...allowAttributes.map((a) => a.toLowerCase()),
375
+ ]);
376
+
377
+ // Use template for parsing
378
+ const template = document.createElement('template');
379
+ template.innerHTML = html;
380
+
381
+ if (stripAllTags) {
382
+ return template.content.textContent ?? '';
383
+ }
384
+
385
+ // Walk the DOM tree
386
+ const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);
387
+
388
+ const toRemove: Element[] = [];
389
+
390
+ while (walker.nextNode()) {
391
+ const el = walker.currentNode as Element;
392
+ const tagName = el.tagName.toLowerCase();
393
+
394
+ // Remove explicitly dangerous tags even if in allow list
395
+ if (DANGEROUS_TAGS.has(tagName)) {
396
+ toRemove.push(el);
397
+ continue;
398
+ }
399
+
400
+ // Remove disallowed tags entirely
401
+ if (!allowedTags.has(tagName)) {
402
+ toRemove.push(el);
403
+ continue;
404
+ }
405
+
406
+ // Process attributes
407
+ const attrsToRemove: string[] = [];
408
+ for (const attr of Array.from(el.attributes)) {
409
+ const attrName = attr.name.toLowerCase();
410
+
411
+ // Check if attribute is allowed
412
+ if (!isAllowedAttribute(attrName, allowedAttrs, allowDataAttributes)) {
413
+ attrsToRemove.push(attr.name);
414
+ continue;
415
+ }
416
+
417
+ // Check for DOM clobbering on id and name attributes
418
+ if ((attrName === 'id' || attrName === 'name') && !isSafeIdOrName(attr.value)) {
419
+ attrsToRemove.push(attr.name);
420
+ continue;
421
+ }
422
+
423
+ // Validate URL attributes
424
+ if (
425
+ (attrName === 'href' || attrName === 'src' || attrName === 'srcset') &&
426
+ !isSafeUrl(attr.value)
427
+ ) {
428
+ attrsToRemove.push(attr.name);
429
+ }
430
+ }
431
+
432
+ // Remove disallowed attributes
433
+ for (const attrName of attrsToRemove) {
434
+ el.removeAttribute(attrName);
435
+ }
436
+ }
437
+
438
+ // Remove disallowed elements
439
+ for (const el of toRemove) {
440
+ el.remove();
441
+ }
442
+
443
+ return template.innerHTML;
444
+ };
445
+
446
+ // ============================================================================
447
+ // Public API
448
+ // ============================================================================
449
+
450
+ /**
451
+ * Sanitize HTML string, removing dangerous elements and attributes.
452
+ * Uses Trusted Types when available for CSP compliance.
453
+ *
454
+ * @param html - The HTML string to sanitize
455
+ * @param options - Sanitization options
456
+ * @returns Sanitized HTML string
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * const safe = sanitizeHtml('<div onclick="alert(1)">Hello</div>');
461
+ * // Returns: '<div>Hello</div>'
462
+ * ```
463
+ */
464
+ export const sanitizeHtml = (html: string, options: SanitizeOptions = {}): string => {
465
+ return sanitizeHtmlCore(html, options);
466
+ };
467
+
468
+ /**
469
+ * Create a Trusted HTML value for use with Trusted Types-enabled sites.
470
+ * Falls back to regular string when Trusted Types are unavailable.
471
+ *
472
+ * @param html - The HTML string to wrap
473
+ * @returns Trusted HTML value or sanitized string
474
+ */
475
+ export const createTrustedHtml = (html: string): TrustedHTML | string => {
476
+ const policy = getTrustedTypesPolicy();
477
+ if (policy) {
478
+ return policy.createHTML(html);
479
+ }
480
+ return sanitizeHtml(html);
481
+ };
482
+
483
+ /**
484
+ * Escape HTML entities to prevent XSS.
485
+ * Use this for displaying user content as text.
486
+ *
487
+ * @param text - The text to escape
488
+ * @returns Escaped HTML string
489
+ *
490
+ * @example
491
+ * ```ts
492
+ * escapeHtml('<script>alert(1)</script>');
493
+ * // Returns: '&lt;script&gt;alert(1)&lt;/script&gt;'
494
+ * ```
495
+ */
496
+ export const escapeHtml = (text: string): string => {
497
+ const escapeMap: Record<string, string> = {
498
+ '&': '&amp;',
499
+ '<': '&lt;',
500
+ '>': '&gt;',
501
+ '"': '&quot;',
502
+ "'": '&#x27;',
503
+ '`': '&#x60;',
504
+ };
505
+ return text.replace(/[&<>"'`]/g, (char) => escapeMap[char]);
506
+ };
507
+
508
+ /**
509
+ * Strip all HTML tags and return plain text.
510
+ *
511
+ * @param html - The HTML string to strip
512
+ * @returns Plain text content
513
+ */
514
+ export const stripTags = (html: string): string => {
515
+ return sanitizeHtmlCore(html, { stripAllTags: true });
516
+ };
517
+
518
+ // ============================================================================
519
+ // CSP Helpers
520
+ // ============================================================================
521
+
522
+ /**
523
+ * Generate a nonce for inline scripts/styles.
524
+ * Use with Content-Security-Policy nonce directives.
525
+ *
526
+ * @param length - Nonce length (default: 16)
527
+ * @returns Cryptographically random nonce string
528
+ */
529
+ export const generateNonce = (length: number = 16): string => {
530
+ const array = new Uint8Array(length);
531
+ crypto.getRandomValues(array);
532
+ return btoa(String.fromCharCode(...array))
533
+ .replace(/\+/g, '-')
534
+ .replace(/\//g, '_')
535
+ .replace(/=/g, '');
536
+ };
537
+
538
+ /**
539
+ * Check if a CSP header is present with specific directive.
540
+ * Useful for feature detection and fallback strategies.
541
+ *
542
+ * @param directive - The CSP directive to check (e.g., 'script-src')
543
+ * @returns True if the directive appears to be enforced
544
+ */
545
+ export const hasCSPDirective = (directive: string): boolean => {
546
+ // Check meta tag
547
+ const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
548
+ if (meta) {
549
+ const content = meta.getAttribute('content') ?? '';
550
+ return content.includes(directive);
551
+ }
552
+ return false;
553
+ };