@freshjuice/zest 1.0.0 → 2.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 (65) hide show
  1. package/README.md +178 -78
  2. package/dist/zest.d.ts +214 -0
  3. package/dist/zest.de.js +692 -305
  4. package/dist/zest.de.js.map +1 -1
  5. package/dist/zest.de.min.js +1 -1
  6. package/dist/zest.en.js +692 -305
  7. package/dist/zest.en.js.map +1 -1
  8. package/dist/zest.en.min.js +1 -1
  9. package/dist/zest.es.js +692 -305
  10. package/dist/zest.es.js.map +1 -1
  11. package/dist/zest.es.min.js +1 -1
  12. package/dist/zest.esm.js +692 -305
  13. package/dist/zest.esm.js.map +1 -1
  14. package/dist/zest.esm.min.js +1 -1
  15. package/dist/zest.fr.js +692 -305
  16. package/dist/zest.fr.js.map +1 -1
  17. package/dist/zest.fr.min.js +1 -1
  18. package/dist/zest.headless.d.ts +178 -0
  19. package/dist/zest.headless.esm.js +2299 -0
  20. package/dist/zest.headless.esm.js.map +1 -0
  21. package/dist/zest.headless.esm.min.js +1 -0
  22. package/dist/zest.it.js +692 -305
  23. package/dist/zest.it.js.map +1 -1
  24. package/dist/zest.it.min.js +1 -1
  25. package/dist/zest.ja.js +692 -305
  26. package/dist/zest.ja.js.map +1 -1
  27. package/dist/zest.ja.min.js +1 -1
  28. package/dist/zest.js +692 -305
  29. package/dist/zest.js.map +1 -1
  30. package/dist/zest.min.js +1 -1
  31. package/dist/zest.nl.js +692 -305
  32. package/dist/zest.nl.js.map +1 -1
  33. package/dist/zest.nl.min.js +1 -1
  34. package/dist/zest.pl.js +692 -305
  35. package/dist/zest.pl.js.map +1 -1
  36. package/dist/zest.pl.min.js +1 -1
  37. package/dist/zest.pt.js +692 -305
  38. package/dist/zest.pt.js.map +1 -1
  39. package/dist/zest.pt.min.js +1 -1
  40. package/dist/zest.ru.js +692 -305
  41. package/dist/zest.ru.js.map +1 -1
  42. package/dist/zest.ru.min.js +1 -1
  43. package/dist/zest.uk.js +692 -305
  44. package/dist/zest.uk.js.map +1 -1
  45. package/dist/zest.uk.min.js +1 -1
  46. package/dist/zest.zh.js +692 -305
  47. package/dist/zest.zh.js.map +1 -1
  48. package/dist/zest.zh.min.js +1 -1
  49. package/package.json +23 -4
  50. package/src/core/cookie-interceptor.js +20 -5
  51. package/src/core/known-trackers.js +41 -14
  52. package/src/core/pattern-matcher.js +20 -5
  53. package/src/core/script-blocker.js +85 -79
  54. package/src/core/security.js +204 -0
  55. package/src/core/storage-interceptor.js +5 -1
  56. package/src/core-lifecycle.js +192 -0
  57. package/src/headless.js +133 -0
  58. package/src/index.js +73 -184
  59. package/src/storage/consent-store.js +32 -8
  60. package/src/types/zest.d.ts +214 -0
  61. package/src/types/zest.headless.d.ts +178 -0
  62. package/src/ui/banner.js +11 -7
  63. package/src/ui/modal.js +16 -12
  64. package/src/ui/styles.js +25 -4
  65. package/src/ui/widget.js +3 -1
package/dist/zest.js CHANGED
@@ -1,10 +1,216 @@
1
1
  var Zest = (function () {
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * Security utilities - escaping, validation, and safe parsing helpers
6
+ *
7
+ * These helpers are used across UI components, URL/CSS validation, and
8
+ * consent-cookie parsing to provide defense-in-depth against untrusted
9
+ * config (CMS-driven, i18n-loaded, or attacker-supplied).
10
+ */
11
+
12
+ const HTML_ESCAPE_MAP = {
13
+ '&': '&',
14
+ '<': '&lt;',
15
+ '>': '&gt;',
16
+ '"': '&quot;',
17
+ "'": '&#39;',
18
+ '`': '&#96;'
19
+ };
20
+
21
+ /**
22
+ * Escape a value for safe embedding in HTML text nodes and attribute values.
23
+ * Accepts any value — non-strings are stringified first. null/undefined -> ''.
24
+ */
25
+ function escapeHTML(value) {
26
+ if (value === null || value === undefined) return '';
27
+ const str = typeof value === 'string' ? value : String(value);
28
+ return str.replace(/[&<>"'`]/g, (ch) => HTML_ESCAPE_MAP[ch]);
29
+ }
30
+
31
+ /**
32
+ * Validate a URL — return the URL if it uses http:/https:/mailto:/tel:,
33
+ * otherwise return null. Blocks javascript:, data:, vbscript:, file:, etc.
34
+ */
35
+ function safeUrl(url) {
36
+ if (typeof url !== 'string' || url.length === 0) return null;
37
+ const trimmed = url.trim();
38
+ if (trimmed.length === 0) return null;
39
+
40
+ // Relative URLs (no protocol) are safe — treat as same-origin path
41
+ if (/^[/?#]/.test(trimmed)) return trimmed;
42
+
43
+ // Check protocol explicitly, do NOT rely on URL parsing alone —
44
+ // attackers may use whitespace/control characters to confuse parsers.
45
+ const match = trimmed.match(/^([a-z][a-z0-9+.-]*):/i);
46
+ if (!match) {
47
+ // No protocol — treat as relative
48
+ return trimmed;
49
+ }
50
+
51
+ const protocol = match[1].toLowerCase();
52
+ if (protocol === 'http' || protocol === 'https' || protocol === 'mailto' || protocol === 'tel') {
53
+ return trimmed;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Validate a CSS color value. Accepts #rgb/#rrggbb/#rrggbbaa and a
60
+ * small allowlist of CSS named colors and rgb()/rgba()/hsl()/hsla()
61
+ * functional forms with numeric-only arguments.
62
+ */
63
+ const NAMED_COLORS = new Set([
64
+ 'transparent', 'black', 'white', 'red', 'green', 'blue', 'yellow',
65
+ 'orange', 'purple', 'pink', 'gray', 'grey', 'brown', 'cyan', 'magenta',
66
+ 'silver', 'gold', 'navy', 'teal', 'maroon', 'olive', 'lime', 'aqua',
67
+ 'fuchsia', 'indigo', 'violet', 'crimson', 'coral', 'salmon', 'tomato'
68
+ ]);
69
+
70
+ function safeColor(color) {
71
+ if (typeof color !== 'string') return null;
72
+ const trimmed = color.trim();
73
+
74
+ if (/^#[0-9a-fA-F]{3,8}$/.test(trimmed)) return trimmed;
75
+ if (NAMED_COLORS.has(trimmed.toLowerCase())) return trimmed;
76
+
77
+ // Functional notations: only digits, dots, commas, %, whitespace between parens
78
+ if (/^(rgb|rgba|hsl|hsla)\(\s*[\d.,%\s/]+\s*\)$/i.test(trimmed)) return trimmed;
79
+
80
+ return null;
81
+ }
82
+
83
+ /**
84
+ * Validate a regex pattern string. Rejects patterns that contain known
85
+ * catastrophic-backtracking shapes (nested quantifiers). Compiles with
86
+ * try/catch.
87
+ *
88
+ * Returns a RegExp on success, null on failure.
89
+ */
90
+ const REDOS_PATTERNS = [
91
+ /(\([^)]*[+*][^)]*\)|\[[^\]]*\]|\\w|\\d|\\s)\s*[+*]/, // nested quantifier
92
+ /\(\?[=!][^)]*[+*][^)]*\)[+*]/, // lookahead with quantifier, then quantifier
93
+ ];
94
+
95
+ function safeRegExp(pattern, flags) {
96
+ if (pattern instanceof RegExp) return pattern;
97
+ if (typeof pattern !== 'string') return null;
98
+
99
+ // Cap pattern length to limit compiled-regex state
100
+ if (pattern.length > 500) return null;
101
+
102
+ // Heuristic: reject obviously dangerous patterns
103
+ for (const bad of REDOS_PATTERNS) {
104
+ if (bad.test(pattern)) return null;
105
+ }
106
+
107
+ try {
108
+ return new RegExp(pattern, flags);
109
+ } catch (e) {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Sanitize a consent-cookie payload. Only known category keys with
116
+ * boolean values survive; prototype-polluting keys are stripped.
117
+ */
118
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
119
+
120
+ function sanitizeConsentPayload(raw, knownCategoryIds) {
121
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
122
+
123
+ const result = {
124
+ version: typeof raw.version === 'string' ? raw.version : null,
125
+ timestamp: typeof raw.timestamp === 'number' && Number.isFinite(raw.timestamp) ? raw.timestamp : null,
126
+ categories: {}
127
+ };
128
+
129
+ const cats = raw.categories;
130
+ if (!cats || typeof cats !== 'object' || Array.isArray(cats)) return null;
131
+
132
+ for (const key of knownCategoryIds) {
133
+ if (FORBIDDEN_KEYS.has(key)) continue;
134
+ if (Object.prototype.hasOwnProperty.call(cats, key)) {
135
+ result.categories[key] = cats[key] === true;
136
+ }
137
+ }
138
+
139
+ // essential is always true regardless of stored value
140
+ if (knownCategoryIds.includes('essential')) {
141
+ result.categories.essential = true;
142
+ }
143
+
144
+ return result;
145
+ }
146
+
147
+ /**
148
+ * Invoke a user-supplied callback, swallowing and logging exceptions so
149
+ * a misbehaving callback can't break the consent flow.
150
+ */
151
+ function safeInvoke(fn, ...args) {
152
+ if (typeof fn !== 'function') return undefined;
153
+ try {
154
+ return fn(...args);
155
+ } catch (e) {
156
+ try {
157
+ console.error('[Zest] User callback threw:', e);
158
+ } catch (_) {
159
+ /* no-op */
160
+ }
161
+ return undefined;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Strip comments and selector-level content from a customStyles string
167
+ * while still allowing property/value declarations scoped under the
168
+ * component selectors the author is targeting. We cannot fully sandbox
169
+ * CSS without a parser, but we can at least neutralise the most
170
+ * dangerous clickjacking vector (rules targeting Zest's own buttons).
171
+ *
172
+ * Returns the sanitized CSS string (possibly empty).
173
+ */
174
+ function sanitizeCustomStyles(css) {
175
+ if (typeof css !== 'string' || css.length === 0) return '';
176
+
177
+ // Hard cap on size to avoid runaway payloads
178
+ if (css.length > 20000) return '';
179
+
180
+ // Remove CSS comments (can hide payloads)
181
+ let out = css.replace(/\/\*[\s\S]*?\*\//g, '');
182
+
183
+ // Block at-rules that can load external resources or alter behavior
184
+ out = out.replace(/@import\s+[^;]+;?/gi, '');
185
+ out = out.replace(/@charset\s+[^;]+;?/gi, '');
186
+
187
+ // Block url() values pointing outside of data: or https:
188
+ out = out.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (match, quote, value) => {
189
+ const v = value.trim().toLowerCase();
190
+ if (v.startsWith('https:') || v.startsWith('data:image/') || v.startsWith('/') || v.startsWith('#')) {
191
+ return match;
192
+ }
193
+ return 'url(#)';
194
+ });
195
+
196
+ // Block selectors that target the built-in reject button, which could
197
+ // be used to hide it for clickjacking consent bypass.
198
+ out = out.replace(/\.zest-btn--secondary\s*\{[^}]*\}/gi, '');
199
+ out = out.replace(/\[data-action\s*=\s*["']reject-all["']\]\s*\{[^}]*\}/gi, '');
200
+ out = out.replace(/\[data-action\s*=\s*["']accept-all["']\]\s*\{[^}]*\}/gi, '');
201
+
202
+ // Block expression() (ancient IE) and -moz-binding (ancient FF)
203
+ out = out.replace(/expression\s*\([^)]*\)/gi, '');
204
+ out = out.replace(/-moz-binding\s*:[^;}]*/gi, '');
205
+
206
+ return out;
207
+ }
208
+
4
209
  /**
5
210
  * Pattern Matcher - Categorizes cookies and storage keys by pattern
6
211
  */
7
212
 
213
+
8
214
  /**
9
215
  * Default patterns for each category
10
216
  */
@@ -53,16 +259,29 @@ var Zest = (function () {
53
259
  let patterns = { ...DEFAULT_PATTERNS };
54
260
 
55
261
  /**
56
- * Set custom patterns
262
+ * Set custom patterns. User-supplied strings are validated with safeRegExp,
263
+ * which rejects catastrophic-backtracking shapes and syntax errors.
264
+ * Invalid patterns are silently dropped with a console warning.
57
265
  */
58
266
  function setPatterns(customPatterns) {
59
267
  patterns = { ...DEFAULT_PATTERNS };
268
+ if (!customPatterns || typeof customPatterns !== 'object') return;
269
+
60
270
  for (const [category, regexList] of Object.entries(customPatterns)) {
61
- if (Array.isArray(regexList)) {
62
- patterns[category] = regexList.map(p =>
63
- p instanceof RegExp ? p : new RegExp(p)
64
- );
271
+ if (!Array.isArray(regexList)) continue;
272
+
273
+ const compiled = [];
274
+ for (const p of regexList) {
275
+ const re = safeRegExp(p);
276
+ if (re) {
277
+ compiled.push(re);
278
+ } else {
279
+ try {
280
+ console.warn('[Zest] Rejected unsafe pattern:', p);
281
+ } catch (_) { /* no-op */ }
282
+ }
65
283
  }
284
+ patterns[category] = compiled;
66
285
  }
67
286
  }
68
287
 
@@ -99,6 +318,11 @@ var Zest = (function () {
99
318
  // Store original descriptor
100
319
  let originalCookieDescriptor = null;
101
320
 
321
+ // Upper bound on the number of queued cookies awaiting consent replay.
322
+ // An unbounded queue is a memory-exhaustion DoS vector — a hostile
323
+ // script could flood it with document.cookie writes.
324
+ const MAX_QUEUE_SIZE$2 = 100;
325
+
102
326
  // Queue for blocked cookies
103
327
  const cookieQueue = [];
104
328
 
@@ -168,8 +392,8 @@ var Zest = (function () {
168
392
  if (checkConsent$3(category)) {
169
393
  // Consent given - set cookie
170
394
  originalCookieDescriptor.set.call(document, value);
171
- } else {
172
- // No consent - queue for later
395
+ } else if (cookieQueue.length < MAX_QUEUE_SIZE$2) {
396
+ // No consent - queue for later (capped to prevent DoS)
173
397
  cookieQueue.push({
174
398
  value,
175
399
  name,
@@ -178,7 +402,9 @@ var Zest = (function () {
178
402
  });
179
403
  }
180
404
  },
181
- configurable: true
405
+ // configurable: false prevents a later-loaded script from
406
+ // overriding our descriptor and bypassing the interceptor.
407
+ configurable: false
182
408
  });
183
409
 
184
410
  return true;
@@ -189,6 +415,10 @@ var Zest = (function () {
189
415
  */
190
416
 
191
417
 
418
+ // Upper bound on queued operations awaiting consent replay — unbounded
419
+ // growth would be a memory-exhaustion DoS vector.
420
+ const MAX_QUEUE_SIZE$1 = 200;
421
+
192
422
  // Store originals
193
423
  let originalLocalStorage = null;
194
424
  let originalSessionStorage = null;
@@ -219,7 +449,7 @@ var Zest = (function () {
219
449
 
220
450
  if (checkConsent$2(category)) {
221
451
  target.setItem(key, value);
222
- } else {
452
+ } else if (queue.length < MAX_QUEUE_SIZE$1) {
223
453
  queue.push({
224
454
  key,
225
455
  value,
@@ -404,29 +634,56 @@ var Zest = (function () {
404
634
  };
405
635
 
406
636
  /**
407
- * Check if a URL matches any tracker in the list
637
+ * Check if a URL matches any tracker in the list.
638
+ *
639
+ * Matching is restricted to hostname (and, when the list entry contains
640
+ * a path, the URL path prefix). A naive `fullUrl.includes(domain)` was
641
+ * previously used, which would false-positive on e.g.
642
+ * https://mysite.com/page?ref=google-analytics.com
408
643
  */
409
644
  function matchesTrackerList(url, trackerList) {
645
+ let urlObj;
410
646
  try {
411
- const urlObj = new URL(url);
412
- const hostname = urlObj.hostname.toLowerCase();
413
- const fullUrl = url.toLowerCase();
414
-
415
- for (const domain of trackerList) {
416
- // Support partial matches (e.g., "matomo." matches "analytics.matomo.cloud")
417
- if (domain.endsWith('.')) {
418
- if (hostname.includes(domain.slice(0, -1))) {
419
- return true;
420
- }
421
- } else if (hostname === domain || hostname.endsWith('.' + domain)) {
647
+ urlObj = new URL(url);
648
+ } catch (e) {
649
+ return false;
650
+ }
651
+ const hostname = urlObj.hostname.toLowerCase();
652
+ const path = urlObj.pathname.toLowerCase();
653
+
654
+ for (const rawEntry of trackerList) {
655
+ if (typeof rawEntry !== 'string') continue;
656
+ const entry = rawEntry.toLowerCase();
657
+
658
+ // Partial-prefix match on hostname (entry ends with a dot),
659
+ // e.g. "matomo." matches "analytics.matomo.cloud"
660
+ if (entry.endsWith('.')) {
661
+ const needle = entry.slice(0, -1);
662
+ const segments = hostname.split('.');
663
+ if (segments.some(seg => seg === needle) || hostname.startsWith(entry)) {
422
664
  return true;
423
- } else if (fullUrl.includes(domain)) {
665
+ }
666
+ continue;
667
+ }
668
+
669
+ // Entries containing a slash specify hostname + path prefix
670
+ const slashIdx = entry.indexOf('/');
671
+ if (slashIdx !== -1) {
672
+ const entryHost = entry.slice(0, slashIdx);
673
+ const entryPath = entry.slice(slashIdx);
674
+ if ((hostname === entryHost || hostname.endsWith('.' + entryHost)) &&
675
+ path.startsWith(entryPath)) {
424
676
  return true;
425
677
  }
678
+ continue;
679
+ }
680
+
681
+ // Plain hostname: exact or subdomain match only
682
+ if (hostname === entry || hostname.endsWith('.' + entry)) {
683
+ return true;
426
684
  }
427
- } catch (e) {
428
- // Invalid URL
429
685
  }
686
+
430
687
  return false;
431
688
  }
432
689
 
@@ -473,7 +730,17 @@ var Zest = (function () {
473
730
  */
474
731
 
475
732
 
476
- // Queue for blocked scripts
733
+ // Categories the author has declared blockable. A script can self-label
734
+ // into one of these, but not into 'essential' (a common bypass).
735
+ const BLOCKABLE_CATEGORIES = new Set(['functional', 'analytics', 'marketing']);
736
+
737
+ // Upper bound on queued scripts awaiting consent replay — prevents a
738
+ // hostile page from flooding the queue with <script> nodes.
739
+ const MAX_QUEUE_SIZE = 500;
740
+
741
+ // Queue for blocked scripts — the authoritative source for replay,
742
+ // snapshotting src/inline BEFORE any DOM mutation so later tampering
743
+ // cannot hijack what gets executed.
477
744
  const scriptQueue = [];
478
745
 
479
746
  // MutationObserver instance
@@ -520,55 +787,61 @@ var Zest = (function () {
520
787
  }
521
788
 
522
789
  /**
523
- * Determine if a script should be blocked and get its category
790
+ * Determine if a script should be blocked and get its category.
791
+ *
792
+ * A self-applied 'essential' label is ignored — only explicit blockable
793
+ * categories are accepted. That prevents a third-party script from
794
+ * stamping itself with data-consent-category="essential" to slip past
795
+ * mode-based blocking.
524
796
  */
525
797
  function getScriptBlockCategory(script) {
526
- // 1. Check for explicit data-consent-category attribute (always respected)
527
- const explicitCategory = script.getAttribute('data-consent-category');
528
- if (explicitCategory) {
529
- return explicitCategory;
530
- }
531
-
532
- // 2. Skip if script has data-zest-allow attribute
798
+ // Skip if script has data-zest-allow attribute (opt-out)
533
799
  if (script.hasAttribute('data-zest-allow')) {
534
800
  return null;
535
801
  }
536
802
 
803
+ // 1. Check for explicit data-consent-category attribute.
804
+ // Only honor values from the blockable set; 'essential' and unknown
805
+ // values fall through to the other checks.
806
+ const explicitCategory = script.getAttribute('data-consent-category');
807
+ const explicitBlockable = explicitCategory && BLOCKABLE_CATEGORIES.has(explicitCategory)
808
+ ? explicitCategory
809
+ : null;
810
+
537
811
  const src = script.src;
538
812
 
539
- // No src = inline script, only block if explicitly tagged
813
+ // No src = inline script, only block if explicitly tagged (blockable only)
540
814
  if (!src) {
541
- return null;
815
+ return explicitBlockable;
542
816
  }
543
817
 
544
- // 3. Check custom blocked domains
818
+ // 2. Check custom blocked domains
545
819
  const customCategory = matchesCustomDomains(src);
546
- if (customCategory) {
547
- return customCategory;
548
- }
549
820
 
550
- // 4. Mode-based blocking
821
+ // 3. Mode-based blocking
822
+ let modeCategory = null;
551
823
  switch (blockingMode) {
552
824
  case 'manual':
553
- // Only explicit tags, already checked above
554
- return null;
825
+ break;
555
826
 
556
827
  case 'safe':
557
828
  case 'strict':
558
- // Check against known tracker lists
559
- return getCategoryForScript(src, blockingMode);
829
+ modeCategory = getCategoryForScript(src, blockingMode);
830
+ break;
560
831
 
561
832
  case 'doomsday':
562
- // Block all third-party scripts
563
833
  if (isThirdParty(src)) {
564
- // Try to categorize, default to marketing
565
- return getCategoryForScript(src, 'strict') || 'marketing';
834
+ modeCategory = getCategoryForScript(src, 'strict') || 'marketing';
566
835
  }
567
- return null;
568
-
569
- default:
570
- return null;
836
+ break;
571
837
  }
838
+
839
+ // Use the strictest category among explicit/custom/mode decisions.
840
+ // We collect all categories the script matches and pick the first
841
+ // that appears in the blockable set (any match wins — but we prefer
842
+ // the mode-assigned one since it's authoritative for third-party
843
+ // trackers that try to self-label as 'functional').
844
+ return modeCategory || customCategory || explicitBlockable;
572
845
  }
573
846
 
574
847
  /**
@@ -593,14 +866,17 @@ var Zest = (function () {
593
866
  return false;
594
867
  }
595
868
 
596
- // Store script info for later execution
869
+ // Store script info for later execution. Snapshot the src/text BEFORE
870
+ // mutating the DOM — this snapshot is the authoritative replay source
871
+ // so later DOM tampering cannot hijack the replayed script URL.
597
872
  const scriptInfo = {
598
873
  category,
599
- src: script.src,
874
+ src: script.src || '',
600
875
  inline: script.textContent,
601
876
  type: script.type,
602
877
  async: script.async,
603
878
  defer: script.defer,
879
+ element: script,
604
880
  timestamp: Date.now()
605
881
  };
606
882
 
@@ -611,77 +887,61 @@ var Zest = (function () {
611
887
  // Disable the script
612
888
  script.type = 'text/plain';
613
889
 
614
- // If it has a src, also remove it to prevent loading
890
+ // Remove src to prevent loading. We no longer stash it on the element
891
+ // (data-blocked-src was a tampering vector); scriptQueue is the single
892
+ // source of truth for replay.
615
893
  if (script.src) {
616
- script.setAttribute('data-blocked-src', script.src);
617
894
  script.removeAttribute('src');
618
895
  }
619
896
 
620
- scriptQueue.push(scriptInfo);
621
- return true;
622
- }
623
-
624
- /**
625
- * Execute a queued script
626
- */
627
- function executeScript(scriptInfo) {
628
- const script = document.createElement('script');
629
-
630
- if (scriptInfo.src) {
631
- script.src = scriptInfo.src;
632
- } else if (scriptInfo.inline) {
633
- script.textContent = scriptInfo.inline;
897
+ if (scriptQueue.length < MAX_QUEUE_SIZE) {
898
+ scriptQueue.push(scriptInfo);
634
899
  }
635
-
636
- if (scriptInfo.async) script.async = true;
637
- if (scriptInfo.defer) script.defer = true;
638
-
639
- script.setAttribute('data-zest-processed', 'executed');
640
- script.setAttribute('data-consent-executed', 'true');
641
-
642
- document.head.appendChild(script);
900
+ return true;
643
901
  }
644
902
 
645
903
  /**
646
- * Replay queued scripts for allowed categories
904
+ * Replay queued scripts for allowed categories.
905
+ *
906
+ * scriptQueue is the single source of truth for src and inline body —
907
+ * we never re-read data-* attributes from the DOM (which an attacker
908
+ * could have rewritten in the intervening time).
647
909
  */
648
910
  function replayScripts(allowedCategories) {
649
911
  const remaining = [];
650
912
 
651
913
  for (const scriptInfo of scriptQueue) {
652
- if (allowedCategories.includes(scriptInfo.category)) {
653
- executeScript(scriptInfo);
654
- } else {
914
+ if (!allowedCategories.includes(scriptInfo.category)) {
655
915
  remaining.push(scriptInfo);
916
+ continue;
917
+ }
918
+
919
+ const newScript = document.createElement('script');
920
+ if (scriptInfo.src) {
921
+ newScript.src = scriptInfo.src;
922
+ } else if (scriptInfo.inline) {
923
+ newScript.textContent = scriptInfo.inline;
924
+ }
925
+ if (scriptInfo.async) newScript.async = true;
926
+ if (scriptInfo.defer) newScript.defer = true;
927
+ if (scriptInfo.type && scriptInfo.type !== 'text/plain') {
928
+ newScript.type = scriptInfo.type;
929
+ }
930
+ newScript.setAttribute('data-zest-processed', 'executed');
931
+ newScript.setAttribute('data-consent-executed', 'true');
932
+
933
+ // If the original element is still in the DOM, replace it in place
934
+ // so execution order is preserved. Otherwise append to <head>.
935
+ const original = scriptInfo.element;
936
+ if (original && original.isConnected && original.parentNode) {
937
+ original.parentNode.replaceChild(newScript, original);
938
+ } else {
939
+ document.head.appendChild(newScript);
656
940
  }
657
941
  }
658
942
 
659
943
  scriptQueue.length = 0;
660
944
  scriptQueue.push(...remaining);
661
-
662
- // Also re-enable any blocked scripts in the DOM
663
- const blockedScripts = document.querySelectorAll('script[data-zest-processed="blocked"]');
664
- blockedScripts.forEach(script => {
665
- const category = script.getAttribute('data-consent-category');
666
- if (allowedCategories.includes(category)) {
667
- // Clone and replace to execute
668
- const newScript = document.createElement('script');
669
-
670
- const blockedSrc = script.getAttribute('data-blocked-src');
671
- if (blockedSrc) {
672
- newScript.src = blockedSrc;
673
- } else {
674
- newScript.textContent = script.textContent;
675
- }
676
-
677
- if (script.async) newScript.async = true;
678
- if (script.defer) newScript.defer = true;
679
-
680
- newScript.setAttribute('data-zest-processed', 'executed');
681
- newScript.setAttribute('data-consent-executed', 'true');
682
- script.parentNode?.replaceChild(newScript, script);
683
- }
684
- });
685
945
  }
686
946
 
687
947
  /**
@@ -1695,18 +1955,18 @@ var Zest = (function () {
1695
1955
  /**
1696
1956
  * Update configuration at runtime
1697
1957
  */
1698
- let currentConfig = null;
1958
+ let currentConfig$1 = null;
1699
1959
 
1700
1960
  function setConfig(config) {
1701
- currentConfig = mergeConfig(config);
1702
- return currentConfig;
1961
+ currentConfig$1 = mergeConfig(config);
1962
+ return currentConfig$1;
1703
1963
  }
1704
1964
 
1705
1965
  function getCurrentConfig() {
1706
- if (!currentConfig) {
1707
- currentConfig = getConfig();
1966
+ if (!currentConfig$1) {
1967
+ currentConfig$1 = getConfig();
1708
1968
  }
1709
- return currentConfig;
1969
+ return currentConfig$1;
1710
1970
  }
1711
1971
 
1712
1972
  /**
@@ -1717,6 +1977,20 @@ var Zest = (function () {
1717
1977
  const COOKIE_NAME = 'zest_consent';
1718
1978
  const CONSENT_VERSION = '1.0';
1719
1979
 
1980
+ /**
1981
+ * Return the Secure flag fragment when running over HTTPS, empty otherwise.
1982
+ * On HTTPS sites, omitting Secure lets the cookie leak over plain HTTP.
1983
+ */
1984
+ function secureAttribute() {
1985
+ try {
1986
+ return typeof location !== 'undefined' && location.protocol === 'https:'
1987
+ ? '; Secure'
1988
+ : '';
1989
+ } catch (_) {
1990
+ return '';
1991
+ }
1992
+ }
1993
+
1720
1994
  // Current consent state
1721
1995
  let consent = null;
1722
1996
 
@@ -1745,7 +2019,12 @@ var Zest = (function () {
1745
2019
  }
1746
2020
 
1747
2021
  /**
1748
- * Load consent from cookie
2022
+ * Load consent from cookie.
2023
+ *
2024
+ * The parsed cookie is validated against the expected schema via
2025
+ * sanitizeConsentPayload — only known category keys with boolean values
2026
+ * survive, so a tampered cookie can't inject prototype-polluting props
2027
+ * or unexpected category shapes.
1749
2028
  */
1750
2029
  function loadConsent() {
1751
2030
  try {
@@ -1753,9 +2032,12 @@ var Zest = (function () {
1753
2032
  const match = cookies.match(new RegExp(`${COOKIE_NAME}=([^;]+)`));
1754
2033
 
1755
2034
  if (match) {
1756
- const data = JSON.parse(decodeURIComponent(match[1]));
1757
- consent = data.categories || getDefaultConsent();
1758
- return { ...consent };
2035
+ const raw = JSON.parse(decodeURIComponent(match[1]));
2036
+ const clean = sanitizeConsentPayload(raw, getCategoryIds());
2037
+ if (clean && clean.categories) {
2038
+ consent = { ...getDefaultConsent(), ...clean.categories };
2039
+ return { ...consent };
2040
+ }
1759
2041
  }
1760
2042
  } catch (e) {
1761
2043
  // Invalid or missing cookie
@@ -1780,7 +2062,7 @@ var Zest = (function () {
1780
2062
  };
1781
2063
 
1782
2064
  const expires = new Date(Date.now() + expirationDays * 24 * 60 * 60 * 1000).toUTCString();
1783
- const cookieValue = `${COOKIE_NAME}=${encodeURIComponent(JSON.stringify(data))}; expires=${expires}; path=/; SameSite=Lax`;
2065
+ const cookieValue = `${COOKIE_NAME}=${encodeURIComponent(JSON.stringify(data))}; expires=${expires}; path=/; SameSite=Lax${secureAttribute()}`;
1784
2066
 
1785
2067
  setRawCookie(cookieValue);
1786
2068
  }
@@ -1849,7 +2131,7 @@ var Zest = (function () {
1849
2131
  * Reset consent (clear cookie)
1850
2132
  */
1851
2133
  function resetConsent() {
1852
- setRawCookie(`${COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`);
2134
+ setRawCookie(`${COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax${secureAttribute()}`);
1853
2135
  consent = null;
1854
2136
  }
1855
2137
 
@@ -1874,7 +2156,8 @@ var Zest = (function () {
1874
2156
  const match = cookies.match(new RegExp(`${COOKIE_NAME}=([^;]+)`));
1875
2157
 
1876
2158
  if (match) {
1877
- return JSON.parse(decodeURIComponent(match[1]));
2159
+ const raw = JSON.parse(decodeURIComponent(match[1]));
2160
+ return sanitizeConsentPayload(raw, getCategoryIds());
1878
2161
  }
1879
2162
  } catch (e) {
1880
2163
  // Invalid cookie
@@ -1953,15 +2236,207 @@ var Zest = (function () {
1953
2236
  return emit(EVENTS.HIDE, { type });
1954
2237
  }
1955
2238
 
2239
+ /**
2240
+ * Subscribe to an event
2241
+ */
2242
+ function on(eventName, callback) {
2243
+ document.addEventListener(eventName, callback);
2244
+ return () => document.removeEventListener(eventName, callback);
2245
+ }
2246
+
2247
+ /**
2248
+ * Subscribe to an event once
2249
+ */
2250
+ function once(eventName, callback) {
2251
+ document.addEventListener(eventName, callback, { once: true });
2252
+ }
2253
+
2254
+ /**
2255
+ * Core lifecycle - UI-agnostic initialization and consent actions.
2256
+ *
2257
+ * This module contains everything the main entry (with UI) and the
2258
+ * headless entry (no UI) share: interceptor setup, consent load/save,
2259
+ * replay, DNT handling, and the events/callbacks fan-out. It intentionally
2260
+ * does NOT import anything from `./ui/*` so tree-shakers can drop the UI
2261
+ * bundle entirely when only the headless API is used.
2262
+ */
2263
+
2264
+
2265
+ let initialized = false;
2266
+ let currentConfig = null;
2267
+
2268
+ function checkConsent(category) {
2269
+ return hasConsent(category);
2270
+ }
2271
+
2272
+ function replayAll(categories) {
2273
+ replayCookies(categories);
2274
+ replayStorage(categories);
2275
+ replayScripts(categories);
2276
+ }
2277
+
2278
+ /**
2279
+ * Run the non-UI half of init. Returns a snapshot the caller (UI or
2280
+ * headless) can use to decide what to do next.
2281
+ */
2282
+ function coreInit(userConfig = {}) {
2283
+ if (initialized) {
2284
+ return {
2285
+ alreadyInitialized: true,
2286
+ config: currentConfig,
2287
+ consent: loadConsent(),
2288
+ hasDecision: hasConsentDecision(),
2289
+ dntApplied: false
2290
+ };
2291
+ }
2292
+
2293
+ currentConfig = setConfig(userConfig);
2294
+
2295
+ // Push default-denied state to vendor consent mode APIs BEFORE any
2296
+ // third-party script has a chance to fire.
2297
+ applyConsentSignals(
2298
+ { functional: false, analytics: false, marketing: false },
2299
+ currentConfig,
2300
+ true
2301
+ );
2302
+
2303
+ if (currentConfig.patterns) {
2304
+ setPatterns(currentConfig.patterns);
2305
+ }
2306
+
2307
+ setConsentChecker$2(checkConsent);
2308
+ setConsentChecker$1(checkConsent);
2309
+ setConsentChecker(checkConsent);
2310
+
2311
+ interceptCookies();
2312
+ interceptStorage();
2313
+ startScriptBlocking(currentConfig.mode, currentConfig.blockedDomains);
2314
+
2315
+ const consent = loadConsent();
2316
+ initialized = true;
2317
+
2318
+ if (hasConsentDecision()) {
2319
+ applyConsentSignals(consent, currentConfig, false);
2320
+ }
2321
+
2322
+ // DNT / GPC handling — if the user signalled opt-out at the browser
2323
+ // level and the site opts to respect it, auto-reject before the UI
2324
+ // layer ever runs.
2325
+ const dntEnabled = isDoNotTrackEnabled();
2326
+ let dntApplied = false;
2327
+
2328
+ if (dntEnabled && currentConfig.respectDNT && currentConfig.dntBehavior !== 'ignore') {
2329
+ if (currentConfig.dntBehavior === 'reject' && !hasConsentDecision()) {
2330
+ const result = rejectAll(currentConfig.expiration);
2331
+ dntApplied = true;
2332
+ applyConsentSignals(result.current, currentConfig, false);
2333
+ emitReject(result.current);
2334
+ emitChange(result.current, result.previous);
2335
+ safeInvoke(currentConfig.callbacks?.onReject);
2336
+ safeInvoke(currentConfig.callbacks?.onChange, result.current);
2337
+ }
2338
+ }
2339
+
2340
+ emitReady(consent);
2341
+ safeInvoke(currentConfig.callbacks?.onReady, consent);
2342
+
2343
+ return {
2344
+ alreadyInitialized: false,
2345
+ config: currentConfig,
2346
+ consent,
2347
+ hasDecision: hasConsentDecision(),
2348
+ dntApplied
2349
+ };
2350
+ }
2351
+
2352
+ /**
2353
+ * Accept all categories, replay queued items, fire events + callbacks.
2354
+ * Returns { current, previous } or null if not yet initialized.
2355
+ */
2356
+ function coreAcceptAll() {
2357
+ if (!initialized) return null;
2358
+ const result = acceptAll(currentConfig.expiration);
2359
+ applyConsentSignals(result.current, currentConfig, false);
2360
+ replayAll(getCategoryIds());
2361
+ emitConsent(result.current, result.previous);
2362
+ emitChange(result.current, result.previous);
2363
+ safeInvoke(currentConfig.callbacks?.onAccept, result.current);
2364
+ safeInvoke(currentConfig.callbacks?.onChange, result.current);
2365
+ return result;
2366
+ }
2367
+
2368
+ /**
2369
+ * Reject all non-essential categories, fire events + callbacks.
2370
+ */
2371
+ function coreRejectAll() {
2372
+ if (!initialized) return null;
2373
+ const result = rejectAll(currentConfig.expiration);
2374
+ applyConsentSignals(result.current, currentConfig, false);
2375
+ emitReject(result.current);
2376
+ emitChange(result.current, result.previous);
2377
+ safeInvoke(currentConfig.callbacks?.onReject);
2378
+ safeInvoke(currentConfig.callbacks?.onChange, result.current);
2379
+ return result;
2380
+ }
2381
+
2382
+ /**
2383
+ * Save custom selections and replay only the newly-allowed categories.
2384
+ */
2385
+ function coreUpdateConsent(selections) {
2386
+ if (!initialized) return null;
2387
+ const result = updateConsent(selections, currentConfig.expiration);
2388
+ applyConsentSignals(result.current, currentConfig, false);
2389
+
2390
+ const newlyAllowed = Object.keys(result.current).filter(
2391
+ (cat) => result.current[cat] && !result.previous[cat]
2392
+ );
2393
+ if (newlyAllowed.length > 0) {
2394
+ replayAll(newlyAllowed);
2395
+ }
2396
+
2397
+ const hasNonEssential = Object.entries(selections || {}).some(
2398
+ ([cat, val]) => cat !== 'essential' && val
2399
+ );
2400
+ if (hasNonEssential) {
2401
+ emitConsent(result.current, result.previous);
2402
+ } else {
2403
+ emitReject(result.current);
2404
+ }
2405
+ emitChange(result.current, result.previous);
2406
+ safeInvoke(currentConfig.callbacks?.onChange, result.current);
2407
+ return result;
2408
+ }
2409
+
2410
+ /**
2411
+ * Clear the consent cookie. The caller is responsible for any UI reset.
2412
+ */
2413
+ function coreReset() {
2414
+ resetConsent();
2415
+ }
2416
+
2417
+ function isInitialized() {
2418
+ return initialized;
2419
+ }
2420
+
2421
+ function getActiveConfig() {
2422
+ return currentConfig;
2423
+ }
2424
+
1956
2425
  /**
1957
2426
  * Styles - Shadow DOM encapsulated CSS with theming
1958
2427
  */
1959
2428
 
2429
+
2430
+ const DEFAULT_ACCENT = '#4F46E5';
2431
+
1960
2432
  /**
1961
2433
  * Generate CSS with custom properties
1962
2434
  */
1963
2435
  function generateStyles(config) {
1964
- const accentColor = config.accentColor || '#4F46E5';
2436
+ // Only accept colors that pass strict validation — an unvalidated
2437
+ // value is a CSS-injection vector (e.g. `red; } * { display:none; /*`).
2438
+ const accentColor = safeColor(config.accentColor) || DEFAULT_ACCENT;
2439
+ const customCss = sanitizeCustomStyles(config.customStyles);
1965
2440
 
1966
2441
  return `
1967
2442
  :host {
@@ -2431,15 +2906,29 @@ var Zest = (function () {
2431
2906
  .zest-hidden {
2432
2907
  display: none !important;
2433
2908
  }
2434
- ${config.customStyles || ''}
2909
+ ${customCss}
2435
2910
  `;
2436
2911
  }
2437
2912
 
2438
2913
  /**
2439
- * Adjust color brightness
2914
+ * Adjust color brightness. Falls back to the default accent if the input
2915
+ * cannot be parsed as a hex color (non-hex inputs pass safeColor but
2916
+ * can't be brightness-shifted mathematically).
2440
2917
  */
2441
2918
  function adjustColor(hex, percent) {
2442
- const num = parseInt(hex.replace('#', ''), 16);
2919
+ if (typeof hex !== 'string' || !/^#[0-9a-fA-F]{3,8}$/.test(hex.trim())) {
2920
+ hex = DEFAULT_ACCENT;
2921
+ }
2922
+ let clean = hex.trim().replace('#', '');
2923
+ // Expand 3-digit form to 6
2924
+ if (clean.length === 3) {
2925
+ clean = clean.split('').map(c => c + c).join('');
2926
+ }
2927
+ // Strip alpha if present
2928
+ if (clean.length === 8) clean = clean.slice(0, 6);
2929
+ if (clean.length !== 6) clean = DEFAULT_ACCENT.slice(1);
2930
+
2931
+ const num = parseInt(clean, 16);
2443
2932
  const amt = Math.round(2.55 * percent);
2444
2933
  const R = Math.min(255, Math.max(0, (num >> 16) + amt));
2445
2934
  const G = Math.min(255, Math.max(0, ((num >> 8) & 0x00ff) + amt));
@@ -2460,26 +2949,29 @@ ${config.customStyles || ''}
2460
2949
  let bannerElement = null;
2461
2950
  let shadowRoot$2 = null;
2462
2951
 
2952
+ const SAFE_POSITIONS = new Set(['bottom', 'bottom-left', 'bottom-right', 'top']);
2953
+
2463
2954
  /**
2464
2955
  * Create the banner HTML
2465
2956
  */
2466
2957
  function createBannerHTML(config) {
2467
2958
  const labels = config.labels.banner;
2468
- const position = config.position || 'bottom';
2959
+ const rawPosition = config.position || 'bottom';
2960
+ const position = SAFE_POSITIONS.has(rawPosition) ? rawPosition : 'bottom';
2469
2961
 
2470
2962
  return `
2471
- <div class="zest-banner zest-banner--${position}" role="dialog" aria-modal="false" aria-label="${labels.title}">
2472
- <h2 class="zest-banner__title">${labels.title}</h2>
2473
- <p class="zest-banner__description">${labels.description}</p>
2963
+ <div class="zest-banner zest-banner--${position}" role="dialog" aria-modal="false" aria-label="${escapeHTML(labels.title)}">
2964
+ <h2 class="zest-banner__title">${escapeHTML(labels.title)}</h2>
2965
+ <p class="zest-banner__description">${escapeHTML(labels.description)}</p>
2474
2966
  <div class="zest-banner__buttons">
2475
2967
  <button type="button" class="zest-btn zest-btn--primary" data-action="accept-all">
2476
- ${labels.acceptAll}
2968
+ ${escapeHTML(labels.acceptAll)}
2477
2969
  </button>
2478
2970
  <button type="button" class="zest-btn zest-btn--secondary" data-action="reject-all">
2479
- ${labels.rejectAll}
2971
+ ${escapeHTML(labels.rejectAll)}
2480
2972
  </button>
2481
2973
  <button type="button" class="zest-btn zest-btn--ghost" data-action="settings">
2482
- ${labels.settings}
2974
+ ${escapeHTML(labels.settings)}
2483
2975
  </button>
2484
2976
  </div>
2485
2977
  </div>
@@ -2589,22 +3081,24 @@ ${config.customStyles || ''}
2589
3081
  function createCategoryHTML(category, isChecked, isRequired) {
2590
3082
  const disabled = isRequired ? 'disabled' : '';
2591
3083
  const checked = isChecked ? 'checked' : '';
3084
+ const safeId = escapeHTML(category.id);
3085
+ const safeLabel = escapeHTML(category.label);
2592
3086
 
2593
3087
  return `
2594
3088
  <div class="zest-category">
2595
3089
  <div class="zest-category__header">
2596
3090
  <div class="zest-category__info">
2597
- <span class="zest-category__label">${category.label}</span>
2598
- <p class="zest-category__description">${category.description}</p>
3091
+ <span class="zest-category__label">${safeLabel}</span>
3092
+ <p class="zest-category__description">${escapeHTML(category.description)}</p>
2599
3093
  </div>
2600
3094
  <label class="zest-toggle">
2601
3095
  <input
2602
3096
  type="checkbox"
2603
3097
  class="zest-toggle__input"
2604
- data-category="${category.id}"
3098
+ data-category="${safeId}"
2605
3099
  ${checked}
2606
3100
  ${disabled}
2607
- aria-label="${category.label}"
3101
+ aria-label="${safeLabel}"
2608
3102
  >
2609
3103
  <span class="zest-toggle__slider"></span>
2610
3104
  </label>
@@ -2628,29 +3122,30 @@ ${config.customStyles || ''}
2628
3122
  ))
2629
3123
  .join('');
2630
3124
 
2631
- const policyLink = config.policyUrl
2632
- ? `<a href="${config.policyUrl}" class="zest-link" target="_blank" rel="noopener">Privacy Policy</a>`
3125
+ const validatedPolicyUrl = config.policyUrl ? safeUrl(config.policyUrl) : null;
3126
+ const policyLink = validatedPolicyUrl
3127
+ ? `<a href="${escapeHTML(validatedPolicyUrl)}" class="zest-link" target="_blank" rel="noopener noreferrer">Privacy Policy</a>`
2633
3128
  : '';
2634
3129
 
2635
3130
  return `
2636
- <div class="zest-modal-overlay" role="dialog" aria-modal="true" aria-label="${labels.title}">
3131
+ <div class="zest-modal-overlay" role="dialog" aria-modal="true" aria-label="${escapeHTML(labels.title)}">
2637
3132
  <div class="zest-modal">
2638
3133
  <div class="zest-modal__header">
2639
- <h2 class="zest-modal__title">${labels.title}</h2>
2640
- <p class="zest-modal__description">${labels.description} ${policyLink}</p>
3134
+ <h2 class="zest-modal__title">${escapeHTML(labels.title)}</h2>
3135
+ <p class="zest-modal__description">${escapeHTML(labels.description)} ${policyLink}</p>
2641
3136
  </div>
2642
3137
  <div class="zest-modal__body">
2643
3138
  ${categoriesHTML}
2644
3139
  </div>
2645
3140
  <div class="zest-modal__footer">
2646
3141
  <button type="button" class="zest-btn zest-btn--primary" data-action="save">
2647
- ${labels.save}
3142
+ ${escapeHTML(labels.save)}
2648
3143
  </button>
2649
3144
  <button type="button" class="zest-btn zest-btn--secondary" data-action="accept-all">
2650
- ${labels.acceptAll}
3145
+ ${escapeHTML(labels.acceptAll)}
2651
3146
  </button>
2652
3147
  <button type="button" class="zest-btn zest-btn--ghost" data-action="reject-all">
2653
- ${labels.rejectAll}
3148
+ ${escapeHTML(labels.rejectAll)}
2654
3149
  </button>
2655
3150
  </div>
2656
3151
  </div>
@@ -2782,10 +3277,11 @@ ${config.customStyles || ''}
2782
3277
  */
2783
3278
  function createWidgetHTML(config) {
2784
3279
  const labels = config.labels.widget;
3280
+ const safeLabel = escapeHTML(labels.label);
2785
3281
 
2786
3282
  return `
2787
3283
  <div class="zest-widget">
2788
- <button type="button" class="zest-widget__btn" aria-label="${labels.label}" title="${labels.label}">
3284
+ <button type="button" class="zest-widget__btn" aria-label="${safeLabel}" title="${safeLabel}">
2789
3285
  <span class="zest-widget__icon">${COOKIE_ICON}</span>
2790
3286
  </button>
2791
3287
  </div>
@@ -2864,114 +3360,59 @@ ${config.customStyles || ''}
2864
3360
 
2865
3361
  /**
2866
3362
  * Zest - Lightweight Cookie Consent Toolkit
2867
- * Main entry point
3363
+ * Main entry (full build: logic + UI).
3364
+ *
3365
+ * For a logic-only build without any CSS / Shadow DOM mounting, import
3366
+ * from `@freshjuice/zest/headless` instead.
2868
3367
  */
2869
3368
 
2870
3369
 
2871
- // State
2872
- let initialized = false;
2873
- let config = null;
2874
-
2875
3370
  /**
2876
- * Consent checker function shared across interceptors
2877
- */
2878
- function checkConsent(category) {
2879
- return hasConsent(category);
2880
- }
2881
-
2882
- /**
2883
- * Replay all queued items for newly allowed categories
2884
- */
2885
- function replayAll(allowedCategories) {
2886
- replayCookies(allowedCategories);
2887
- replayStorage(allowedCategories);
2888
- replayScripts(allowedCategories);
2889
- }
2890
-
2891
- /**
2892
- * Handle accept all
3371
+ * Handle accept all delegates consent logic to core, handles UI swap.
2893
3372
  */
2894
3373
  function handleAcceptAll() {
2895
- const result = acceptAll(config.expiration);
2896
- const categories = getCategoryIds();
2897
-
2898
- applyConsentSignals(result.current, config, false);
3374
+ coreAcceptAll();
3375
+ const config = getActiveConfig();
2899
3376
 
2900
3377
  hideBanner();
2901
3378
  hideModal();
2902
3379
 
2903
- replayAll(categories);
2904
-
2905
- if (config.showWidget) {
3380
+ if (config?.showWidget) {
2906
3381
  showWidget({ onClick: handleShowSettings });
2907
3382
  }
2908
-
2909
- emitConsent(result.current, result.previous);
2910
- emitChange(result.current, result.previous);
2911
- config.callbacks?.onAccept?.(result.current);
2912
- config.callbacks?.onChange?.(result.current);
2913
3383
  }
2914
3384
 
2915
3385
  /**
2916
- * Handle reject all
3386
+ * Handle reject all.
2917
3387
  */
2918
3388
  function handleRejectAll() {
2919
- const result = rejectAll(config.expiration);
2920
-
2921
- applyConsentSignals(result.current, config, false);
3389
+ coreRejectAll();
3390
+ const config = getActiveConfig();
2922
3391
 
2923
3392
  hideBanner();
2924
3393
  hideModal();
2925
3394
 
2926
- if (config.showWidget) {
3395
+ if (config?.showWidget) {
2927
3396
  showWidget({ onClick: handleShowSettings });
2928
3397
  }
2929
-
2930
- emitReject(result.current);
2931
- emitChange(result.current, result.previous);
2932
- config.callbacks?.onReject?.();
2933
- config.callbacks?.onChange?.(result.current);
2934
3398
  }
2935
3399
 
2936
3400
  /**
2937
- * Handle save preferences from modal
3401
+ * Handle save preferences from modal.
2938
3402
  */
2939
3403
  function handleSavePreferences(selections) {
2940
- const result = updateConsent(selections, config.expiration);
2941
-
2942
- applyConsentSignals(result.current, config, false);
2943
-
2944
- // Find newly allowed categories
2945
- const newlyAllowed = Object.keys(result.current).filter(
2946
- cat => result.current[cat] && !result.previous[cat]
2947
- );
2948
-
2949
- if (newlyAllowed.length > 0) {
2950
- replayAll(newlyAllowed);
2951
- }
3404
+ coreUpdateConsent(selections);
3405
+ const config = getActiveConfig();
2952
3406
 
2953
3407
  hideModal();
2954
3408
 
2955
- if (config.showWidget) {
3409
+ if (config?.showWidget) {
2956
3410
  showWidget({ onClick: handleShowSettings });
2957
3411
  }
2958
-
2959
- // Determine if this was acceptance or rejection based on selections
2960
- const hasNonEssential = Object.entries(selections)
2961
- .some(([cat, val]) => cat !== 'essential' && val);
2962
-
2963
- if (hasNonEssential) {
2964
- emitConsent(result.current, result.previous);
2965
- } else {
2966
- emitReject(result.current);
2967
- }
2968
-
2969
- emitChange(result.current, result.previous);
2970
- config.callbacks?.onChange?.(result.current);
2971
3412
  }
2972
3413
 
2973
3414
  /**
2974
- * Handle show settings
3415
+ * Open the settings modal.
2975
3416
  */
2976
3417
  function handleShowSettings() {
2977
3418
  hideBanner();
@@ -2988,17 +3429,17 @@ ${config.customStyles || ''}
2988
3429
  }
2989
3430
 
2990
3431
  /**
2991
- * Handle close modal
3432
+ * Close the modal — either bring the widget back (decision made) or
3433
+ * fall back to the banner (no decision yet).
2992
3434
  */
2993
3435
  function handleCloseModal() {
2994
3436
  hideModal();
2995
3437
  emitHide('modal');
2996
3438
 
2997
- // Show widget if consent was already given
2998
- if (hasConsentDecision() && config.showWidget) {
3439
+ const config = getActiveConfig();
3440
+ if (hasConsentDecision() && config?.showWidget) {
2999
3441
  showWidget({ onClick: handleShowSettings });
3000
3442
  } else {
3001
- // Show banner again if no decision made
3002
3443
  showBanner({
3003
3444
  onAcceptAll: handleAcceptAll,
3004
3445
  onRejectAll: handleRejectAll,
@@ -3008,103 +3449,37 @@ ${config.customStyles || ''}
3008
3449
  }
3009
3450
 
3010
3451
  /**
3011
- * Initialize Zest
3452
+ * Initialize Zest with UI.
3012
3453
  */
3013
3454
  function init(userConfig = {}) {
3014
- if (initialized) {
3455
+ const { alreadyInitialized, consent, hasDecision, dntApplied } = coreInit(userConfig);
3456
+ if (alreadyInitialized) {
3015
3457
  console.warn('[Zest] Already initialized');
3016
3458
  return Zest;
3017
3459
  }
3018
3460
 
3019
- // Merge config
3020
- config = setConfig(userConfig);
3021
-
3022
- // Push default denied state to vendor consent mode APIs (must happen before scripts load)
3023
- applyConsentSignals(
3024
- { functional: false, analytics: false, marketing: false },
3025
- config,
3026
- true
3027
- );
3028
-
3029
- // Set patterns if provided
3030
- if (config.patterns) {
3031
- setPatterns(config.patterns);
3032
- }
3033
-
3034
- // Set up consent checkers
3035
- setConsentChecker$2(checkConsent);
3036
- setConsentChecker$1(checkConsent);
3037
- setConsentChecker(checkConsent);
3038
-
3039
- // Start interception
3040
- interceptCookies();
3041
- interceptStorage();
3042
- startScriptBlocking(config.mode, config.blockedDomains);
3043
-
3044
- // Load saved consent
3045
- const consent = loadConsent();
3046
-
3047
- initialized = true;
3048
-
3049
- // Push update for returning visitors with saved consent
3050
- if (hasConsentDecision()) {
3051
- applyConsentSignals(consent, config, false);
3052
- }
3053
-
3054
- // Check Do Not Track / Global Privacy Control
3055
- const dntEnabled = isDoNotTrackEnabled();
3056
- let dntApplied = false;
3057
-
3058
- if (dntEnabled && config.respectDNT && config.dntBehavior !== 'ignore') {
3059
- if (config.dntBehavior === 'reject' && !hasConsentDecision()) {
3060
- // Auto-reject non-essential cookies silently
3061
- const result = rejectAll(config.expiration);
3062
- dntApplied = true;
3063
-
3064
- applyConsentSignals(result.current, config, false);
3065
-
3066
- // Emit events
3067
- emitReject(result.current);
3068
- emitChange(result.current, result.previous);
3069
- config.callbacks?.onReject?.();
3070
- config.callbacks?.onChange?.(result.current);
3071
- }
3072
- // 'preselect' behavior is handled by default (banner shows with defaults off)
3073
- }
3074
-
3075
- // Emit ready event
3076
- emitReady(consent);
3077
- config.callbacks?.onReady?.(consent);
3461
+ const config = getActiveConfig();
3078
3462
 
3079
- // Show UI based on consent state
3080
- if (!hasConsentDecision() && !dntApplied) {
3081
- // No consent decision yet - show banner
3463
+ if (!hasDecision && !dntApplied) {
3082
3464
  showBanner({
3083
3465
  onAcceptAll: handleAcceptAll,
3084
3466
  onRejectAll: handleRejectAll,
3085
3467
  onSettings: handleShowSettings
3086
3468
  });
3087
3469
  emitShow('banner');
3088
- } else {
3089
- // Consent already given (or DNT auto-rejected) - show widget for reopening settings
3090
- if (config.showWidget) {
3091
- showWidget({ onClick: handleShowSettings });
3092
- }
3470
+ } else if (config?.showWidget) {
3471
+ showWidget({ onClick: handleShowSettings });
3093
3472
  }
3094
3473
 
3095
3474
  return Zest;
3096
3475
  }
3097
3476
 
3098
- /**
3099
- * Public API
3100
- */
3101
3477
  const Zest = {
3102
- // Initialization
3103
3478
  init,
3104
3479
 
3105
3480
  // Banner control
3106
3481
  show() {
3107
- if (!initialized) {
3482
+ if (!isInitialized()) {
3108
3483
  console.warn('[Zest] Not initialized. Call Zest.init() first.');
3109
3484
  return;
3110
3485
  }
@@ -3125,7 +3500,7 @@ ${config.customStyles || ''}
3125
3500
 
3126
3501
  // Settings modal
3127
3502
  showSettings() {
3128
- if (!initialized) {
3503
+ if (!isInitialized()) {
3129
3504
  console.warn('[Zest] Not initialized. Call Zest.init() first.');
3130
3505
  return;
3131
3506
  }
@@ -3137,19 +3512,19 @@ ${config.customStyles || ''}
3137
3512
  emitHide('modal');
3138
3513
  },
3139
3514
 
3140
- // Consent management
3515
+ // Consent state
3141
3516
  getConsent,
3142
3517
  hasConsent,
3143
3518
  hasConsentDecision,
3144
3519
  getConsentProof,
3145
3520
 
3146
- // DNT detection
3521
+ // DNT
3147
3522
  isDoNotTrackEnabled,
3148
3523
  getDNTDetails,
3149
3524
 
3150
- // Accept/Reject programmatically
3525
+ // Programmatic accept / reject
3151
3526
  acceptAll() {
3152
- if (!initialized) {
3527
+ if (!isInitialized()) {
3153
3528
  console.warn('[Zest] Not initialized. Call Zest.init() first.');
3154
3529
  return;
3155
3530
  }
@@ -3157,20 +3532,19 @@ ${config.customStyles || ''}
3157
3532
  },
3158
3533
 
3159
3534
  rejectAll() {
3160
- if (!initialized) {
3535
+ if (!isInitialized()) {
3161
3536
  console.warn('[Zest] Not initialized. Call Zest.init() first.');
3162
3537
  return;
3163
3538
  }
3164
3539
  handleRejectAll();
3165
3540
  },
3166
3541
 
3167
- // Reset and show banner again
3542
+ // Reset everything and reshow the banner
3168
3543
  reset() {
3169
- resetConsent();
3544
+ coreReset();
3170
3545
  hideModal();
3171
3546
  removeWidget();
3172
-
3173
- if (initialized) {
3547
+ if (isInitialized()) {
3174
3548
  showBanner({
3175
3549
  onAcceptAll: handleAcceptAll,
3176
3550
  onRejectAll: handleRejectAll,
@@ -3180,17 +3554,30 @@ ${config.customStyles || ''}
3180
3554
  }
3181
3555
  },
3182
3556
 
3183
- // Config
3557
+ // Config introspection
3184
3558
  getConfig: getCurrentConfig,
3185
3559
 
3186
3560
  // Events
3561
+ on,
3562
+ once,
3187
3563
  EVENTS
3188
3564
  };
3189
3565
 
3190
3566
  // Auto-init if config present
3191
3567
  if (typeof window !== 'undefined') {
3192
- // Make Zest available globally
3193
- window.Zest = Zest;
3568
+ // Make Zest available globally. defineProperty with writable:false +
3569
+ // configurable:false stops a later-loaded script from replacing the
3570
+ // global with a trojanned stand-in.
3571
+ try {
3572
+ Object.defineProperty(window, 'Zest', {
3573
+ value: Object.freeze(Zest),
3574
+ writable: false,
3575
+ configurable: false,
3576
+ enumerable: true
3577
+ });
3578
+ } catch (e) {
3579
+ window.Zest = Zest;
3580
+ }
3194
3581
 
3195
3582
  const autoInit = () => {
3196
3583
  const cfg = getConfig();