@rcooler/consent 0.0.0-stage → 0.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.
package/dist/ui.js ADDED
@@ -0,0 +1,336 @@
1
+ import { resolveNoticeLocale } from "./validation.js";
2
+ import { regionalNotices, regionalRights, restrictionNames } from "./regional.js";
3
+ export const english = {
4
+ accept: "Accept all",
5
+ reject: "Reject optional",
6
+ customize: "Customize",
7
+ settings: "Privacy preferences",
8
+ save: "Save preferences",
9
+ close: "Close",
10
+ necessary: "Necessary",
11
+ preferences: "Preferences",
12
+ analytics: "Analytics",
13
+ marketing: "Marketing",
14
+ always: "Always active",
15
+ privacy: "Privacy policy",
16
+ provider: "Provider",
17
+ destination: "Destination",
18
+ storage: "Storage",
19
+ pending: "Saving your choice…",
20
+ failed: "Your choice could not be saved. Optional services remain off. Please try again.",
21
+ inventory: "Services and storage",
22
+ sale: "Do not sell my personal information",
23
+ sharing: "Do not share my personal information for cross-context advertising",
24
+ targeted_advertising: "Opt out of targeted advertising",
25
+ sensitive_data: "Limit use of sensitive personal information",
26
+ optOut: "Do not sell or share my personal information",
27
+ gpc: "Global Privacy Control is active. Sale, sharing and targeted advertising are blocked.",
28
+ privacyRights: "Your privacy choices",
29
+ requestRights: "Request access, correction or deletion",
30
+ appeal: "Appeal a privacy decision",
31
+ processingUnknown: "Data uses have not been classified. Privacy opt-outs block this optional service.",
32
+ region: "Privacy region",
33
+ globalStrict: "Unknown or unreviewed location — optional services require consent",
34
+ rightsScope: "These controls apply to this site's registered services. Use the privacy policy or request link for account data and other processing.",
35
+ saleProcessing: "Sale of personal information",
36
+ sharingProcessing: "Sharing for cross-context advertising",
37
+ advertisingProcessing: "Targeted advertising",
38
+ sensitiveProcessing: "Use of sensitive personal information",
39
+ };
40
+ export const ukrainian = {
41
+ accept: "Прийняти все",
42
+ reject: "Відхилити необов’язкові",
43
+ customize: "Налаштувати",
44
+ settings: "Налаштування приватності",
45
+ save: "Зберегти налаштування",
46
+ close: "Закрити",
47
+ necessary: "Необхідні",
48
+ preferences: "Налаштування",
49
+ analytics: "Аналітика",
50
+ marketing: "Маркетинг",
51
+ always: "Завжди активні",
52
+ privacy: "Політика приватності",
53
+ provider: "Постачальник",
54
+ destination: "Призначення",
55
+ storage: "Сховище",
56
+ pending: "Зберігаємо ваш вибір…",
57
+ failed: "Не вдалося зберегти вибір. Необов’язкові сервіси вимкнені. Спробуйте ще раз.",
58
+ inventory: "Сервіси та сховища",
59
+ sale: "Не продавати мої персональні дані",
60
+ sharing: "Не передавати мої персональні дані для міжконтекстної реклами",
61
+ targeted_advertising: "Відмовитися від цільової реклами",
62
+ sensitive_data: "Обмежити використання чутливих персональних даних",
63
+ optOut: "Не продавати й не передавати мої персональні дані",
64
+ gpc: "Global Privacy Control активний. Продаж, передавання даних і цільову рекламу заблоковано.",
65
+ privacyRights: "Ваш вибір щодо приватності",
66
+ requestRights: "Запит на доступ, виправлення або видалення",
67
+ appeal: "Оскаржити рішення щодо приватності",
68
+ processingUnknown: "Використання даних не класифіковано. Відмова блокує цей необов’язковий сервіс.",
69
+ region: "Регіон приватності",
70
+ globalStrict: "Невідоме або не перевірене місце — необов’язкові сервіси потребують згоди",
71
+ rightsScope: "Ці налаштування діють для зареєстрованих сервісів сайту. Для даних облікового запису й іншої обробки скористайтеся політикою приватності або посиланням запиту.",
72
+ saleProcessing: "Продаж персональних даних",
73
+ sharingProcessing: "Передавання даних для міжконтекстної реклами",
74
+ advertisingProcessing: "Цільова реклама",
75
+ sensitiveProcessing: "Використання чутливих персональних даних",
76
+ };
77
+ function element(tag, text) {
78
+ const node = document.createElement(tag);
79
+ if (text !== undefined)
80
+ node.textContent = text;
81
+ return node;
82
+ }
83
+ function button(text, action) {
84
+ const node = element("button", text);
85
+ node.type = "button";
86
+ node.className = "consent-action";
87
+ node.addEventListener("click", action);
88
+ return node;
89
+ }
90
+ export function mountConsent(controller, options = {}) {
91
+ const requestedLocale = options.locale ?? (document.documentElement.lang || "en");
92
+ const locale = regionalNotices(controller.state.config, requestedLocale)[0]?.locale ??
93
+ resolveNoticeLocale(controller.state.config.policy, requestedLocale);
94
+ const labels = {
95
+ ...(locale.toLowerCase().startsWith("uk") ? ukrainian : english),
96
+ ...options.translations,
97
+ };
98
+ const host = element("div");
99
+ host.className = options.container ? "consent-root consent-preview" : "consent-root";
100
+ host.lang = locale;
101
+ host.dir = options.direction ?? (document.documentElement.dir === "rtl" ? "rtl" : "ltr");
102
+ const banner = element("section");
103
+ banner.className = "consent-banner";
104
+ banner.setAttribute("role", "region");
105
+ const title = element("h2");
106
+ const description = element("p");
107
+ const privacy = element("a", labels.privacy);
108
+ privacy.rel = "noopener noreferrer";
109
+ const status = element("p");
110
+ status.className = "consent-status";
111
+ status.setAttribute("role", "status");
112
+ status.setAttribute("aria-live", "polite");
113
+ const actions = element("div");
114
+ actions.className = "consent-actions";
115
+ const accept = button(labels.accept, () => {
116
+ void controller.decide({ preferences: true, analytics: true, marketing: true }, locale);
117
+ });
118
+ const reject = button(labels.reject, () => {
119
+ void controller.decide({ preferences: false, analytics: false, marketing: false }, locale);
120
+ closeDialog();
121
+ });
122
+ const customize = button(labels.customize, () => openDialog(customize));
123
+ actions.append(accept, reject, customize);
124
+ banner.append(title, description, privacy, actions);
125
+ const settings = button(labels.settings, () => openDialog(settings));
126
+ settings.className = "consent-action consent-preferences";
127
+ const optOut = button(labels.optOut, () => {
128
+ void controller.restrict({ sale: true, sharing: true, targeted_advertising: true, sensitive_data: false }, locale);
129
+ });
130
+ optOut.className = "consent-action consent-optout";
131
+ const shortcuts = element("div");
132
+ shortcuts.className = "consent-shortcuts";
133
+ shortcuts.append(settings, optOut);
134
+ const dialog = element("dialog");
135
+ dialog.className = "consent-dialog";
136
+ const dialogTitle = element("h2", labels.settings);
137
+ dialogTitle.id = `consent-title-${crypto.randomUUID()}`;
138
+ dialog.setAttribute("aria-labelledby", dialogTitle.id);
139
+ const dialogDescription = element("p");
140
+ const close = button(labels.close, () => closeDialog());
141
+ const fields = element("div");
142
+ fields.className = "consent-categories";
143
+ const inputs = new Map();
144
+ for (const category of ["necessary", "preferences", "analytics", "marketing"]) {
145
+ const label = element("label");
146
+ const input = element("input");
147
+ input.type = "checkbox";
148
+ input.name = category;
149
+ input.checked = category === "necessary";
150
+ input.disabled = category === "necessary";
151
+ label.append(input, document.createTextNode(labels[category] + (category === "necessary" ? ` — ${labels.always}` : "")));
152
+ fields.append(label);
153
+ inputs.set(category, input);
154
+ }
155
+ const inventory = element("div");
156
+ inventory.className = "consent-inventory";
157
+ const regional = element("div");
158
+ regional.className = "consent-regional";
159
+ const privacyFields = element("fieldset");
160
+ privacyFields.className = "consent-categories";
161
+ privacyFields.append(element("legend", labels.privacyRights));
162
+ const restrictionInputs = new Map();
163
+ for (const name of restrictionNames) {
164
+ const label = element("label");
165
+ const input = element("input");
166
+ input.type = "checkbox";
167
+ input.name = `restrict_${name}`;
168
+ restrictionInputs.set(name, input);
169
+ label.append(input, document.createTextNode(labels[name]));
170
+ privacyFields.append(label);
171
+ }
172
+ const signal = element("p");
173
+ signal.setAttribute("role", "status");
174
+ signal.className = "consent-signal";
175
+ const bannerSignal = element("p");
176
+ bannerSignal.className = "consent-signal";
177
+ banner.insertBefore(bannerSignal, actions);
178
+ const rights = element("div");
179
+ rights.className = "consent-rights";
180
+ const save = button(labels.save, () => {
181
+ void controller
182
+ .decide({
183
+ preferences: inputs.get("preferences")?.checked === true,
184
+ analytics: inputs.get("analytics")?.checked === true,
185
+ marketing: inputs.get("marketing")?.checked === true,
186
+ }, locale, {
187
+ sale: restrictionInputs.get("sale")?.checked === true,
188
+ sharing: restrictionInputs.get("sharing")?.checked === true,
189
+ targeted_advertising: restrictionInputs.get("targeted_advertising")?.checked === true,
190
+ sensitive_data: restrictionInputs.get("sensitive_data")?.checked === true,
191
+ })
192
+ .then((saved) => {
193
+ if (saved)
194
+ closeDialog();
195
+ });
196
+ });
197
+ const dialogReject = button(labels.reject, () => {
198
+ void controller.decide({ preferences: false, analytics: false, marketing: false }, locale);
199
+ closeDialog();
200
+ });
201
+ const dialogActions = element("div");
202
+ dialogActions.className = "consent-actions";
203
+ dialogActions.append(save, dialogReject, close);
204
+ dialog.append(dialogTitle, dialogDescription, regional, signal, privacyFields, element("p", labels.rightsScope), rights, fields, element("h3", labels.inventory), inventory, dialogActions);
205
+ host.append(banner, shortcuts, status, dialog);
206
+ (options.container ?? document.body).append(host);
207
+ let opener = null;
208
+ let lastPolicy = "";
209
+ function closeDialog() {
210
+ if (dialog.open)
211
+ dialog.close();
212
+ }
213
+ function openDialog(source) {
214
+ if (dialog.open)
215
+ return;
216
+ opener =
217
+ source ?? (document.activeElement instanceof HTMLElement ? document.activeElement : null);
218
+ const state = controller.state;
219
+ for (const category of ["preferences", "analytics", "marketing"]) {
220
+ const input = inputs.get(category);
221
+ if (input)
222
+ input.checked = state.choices[category];
223
+ }
224
+ for (const name of restrictionNames) {
225
+ const input = restrictionInputs.get(name);
226
+ input.checked = state.restrictions[name];
227
+ input.disabled = state.privacy_signals.gpc && name !== "sensitive_data";
228
+ }
229
+ dialog.showModal();
230
+ inputs.get("preferences")?.focus();
231
+ }
232
+ dialog.addEventListener("close", () => {
233
+ if (opener?.isConnected)
234
+ opener.focus();
235
+ });
236
+ function render(state) {
237
+ const policy = state.config.policy;
238
+ host.hidden = !state.config.enabled || (policy.services.length === 0 && !policy.regional);
239
+ if (host.hidden)
240
+ closeDialog();
241
+ const notices = regionalNotices(state.config, requestedLocale);
242
+ const notice = notices[0]?.notice;
243
+ if (notice) {
244
+ title.textContent = notice.title;
245
+ description.textContent = notice.description;
246
+ banner.setAttribute("aria-label", notice.title);
247
+ privacy.href = notice.privacy_url;
248
+ dialogDescription.textContent = notice.description;
249
+ host.lang = notices[0]?.locale ?? locale;
250
+ }
251
+ banner.hidden = state.decided && !state.error;
252
+ accept.disabled = state.pending;
253
+ save.disabled = state.pending;
254
+ status.textContent = state.pending ? labels.pending : state.error ? labels.failed : "";
255
+ signal.textContent = bannerSignal.textContent = state.privacy_signals.gpc ? labels.gpc : "";
256
+ signal.hidden = bannerSignal.hidden = !state.privacy_signals.gpc;
257
+ for (const name of restrictionNames) {
258
+ const input = restrictionInputs.get(name);
259
+ input.disabled = state.privacy_signals.gpc && name !== "sensitive_data";
260
+ if (input.disabled || !dialog.open)
261
+ input.checked = state.restrictions[name];
262
+ }
263
+ const fingerprint = JSON.stringify([policy, state.config.region]);
264
+ if (lastPolicy === fingerprint)
265
+ return;
266
+ lastPolicy = fingerprint;
267
+ regional.replaceChildren();
268
+ const location = state.config.region?.subdivision ?? state.config.region?.country;
269
+ regional.append(element("p", location ? `${labels.region}: ${location}` : labels.globalStrict));
270
+ for (const extra of notices.slice(1)) {
271
+ const section = element("section");
272
+ section.lang = extra.locale;
273
+ const link = element("a", labels.privacy);
274
+ link.href = extra.notice.privacy_url;
275
+ link.rel = "noopener noreferrer";
276
+ section.append(element("h3", extra.notice.title), element("p", extra.notice.description), link);
277
+ regional.append(section);
278
+ }
279
+ rights.replaceChildren();
280
+ const links = regionalRights(state.config, requestedLocale);
281
+ for (const [url, label] of [
282
+ [links?.request_url, labels.requestRights],
283
+ [links?.appeal_url, labels.appeal],
284
+ ]) {
285
+ if (!url)
286
+ continue;
287
+ const link = element("a", label);
288
+ link.href = url;
289
+ link.rel = "noopener noreferrer";
290
+ rights.append(link);
291
+ }
292
+ inventory.replaceChildren();
293
+ for (const service of policy.services) {
294
+ const section = element("section");
295
+ const heading = element("h4", service.name);
296
+ const body = element("p", service.description);
297
+ const provider = element("p", `${labels.provider}: ${service.provider} · ${labels[service.category]}`);
298
+ const link = element("a", labels.privacy);
299
+ link.href = service.policy_url;
300
+ link.rel = "noopener noreferrer";
301
+ section.append(heading, body, provider, link);
302
+ if (service.processing) {
303
+ const declared = restrictionNames
304
+ .filter((name) => service.processing?.[name])
305
+ .map((name) => ({
306
+ sale: labels.saleProcessing,
307
+ sharing: labels.sharingProcessing,
308
+ targeted_advertising: labels.advertisingProcessing,
309
+ sensitive_data: labels.sensitiveProcessing,
310
+ })[name]);
311
+ if (declared.length)
312
+ section.append(element("p", declared.join(" · ")));
313
+ }
314
+ else if (service.category !== "necessary")
315
+ section.append(element("p", labels.processingUnknown));
316
+ if (service.destination)
317
+ section.append(element("p", `${labels.destination}: ${service.destination}`));
318
+ if (service.storage.length) {
319
+ const list = element("ul");
320
+ for (const item of service.storage)
321
+ list.append(element("li", `${item.name} (${item.type}${item.domain ? `, ${item.domain}` : ""}${item.path ? `, ${item.path}` : ""})`));
322
+ section.append(element("p", labels.storage), list);
323
+ }
324
+ inventory.append(section);
325
+ }
326
+ }
327
+ const unsubscribe = controller.subscribe(render);
328
+ return {
329
+ open: openDialog,
330
+ destroy() {
331
+ closeDialog();
332
+ unsubscribe();
333
+ host.remove();
334
+ },
335
+ };
336
+ }
@@ -0,0 +1,10 @@
1
+ import type { Choices, Policy, PublicConfig } from "./types.js";
2
+ export declare function safeURL(value: unknown, allowPath?: boolean): value is string;
3
+ export declare function validChoices(value: unknown): value is Choices;
4
+ export declare function resolveNoticeLocale(policy: Policy, requested: string): string;
5
+ export declare function validRegionalPolicy(value: unknown): boolean;
6
+ export declare function validRegionSelection(value: unknown): boolean;
7
+ /** Returns a normalized policy. Omitted durations use the shared Go defaults. */
8
+ export declare function parsePolicy(value: unknown): Policy | null;
9
+ export declare function validatePolicy(value: unknown): value is Policy;
10
+ export declare function validateConfig(value: unknown): value is PublicConfig;
@@ -0,0 +1,296 @@
1
+ import { regionalProfiles, regionalRulesVersion, validRestrictions } from "./regional.js";
2
+ const slug = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3
+ const identifier = /^[A-Za-z0-9_-]{1,128}$/;
4
+ const locale = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
5
+ const categories = ["necessary", "preferences", "analytics", "marketing"];
6
+ const kinds = ["ga4", "iframe", "script", "custom"];
7
+ const bytes = (value) => new TextEncoder().encode(value).length;
8
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const keys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
10
+ const control = (value, allowWhitespace = false, rejectDEL = false) => [...value].some((character) => {
11
+ const code = character.charCodeAt(0);
12
+ return ((code < 32 && !(allowWhitespace && (code === 9 || code === 10))) ||
13
+ (rejectDEL && code === 127));
14
+ });
15
+ const text = (value, max) => typeof value === "string" &&
16
+ value.trim().length > 0 &&
17
+ [...value].length <= max &&
18
+ !control(value, true);
19
+ const integer = (value, max) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= max;
20
+ export function safeURL(value, allowPath = false) {
21
+ if (typeof value !== "string" ||
22
+ value.length < 1 ||
23
+ bytes(value) > 2048 ||
24
+ /[\r\n\t\\]/.test(value) ||
25
+ control(value, false, true) ||
26
+ /%(?![0-9A-Fa-f]{2})/.test(value))
27
+ return false;
28
+ if (allowPath && value.startsWith("/") && !value.startsWith("//") && !value.includes("#"))
29
+ return true;
30
+ try {
31
+ if (!/^https:\/\//.test(value) || value.slice(8).split(/[/?#]/)[0]?.includes("@"))
32
+ return false;
33
+ const url = new URL(value);
34
+ return (url.protocol === "https:" && !!url.hostname && !url.username && !url.password && !url.hash);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ export function validChoices(value) {
41
+ return (object(value) &&
42
+ Object.keys(value).length === 3 &&
43
+ ["preferences", "analytics", "marketing"].every((key) => typeof value[key] === "boolean"));
44
+ }
45
+ export function resolveNoticeLocale(policy, requested) {
46
+ if (Object.hasOwn(policy.notices, requested))
47
+ return requested;
48
+ const base = requested.split("-")[0] ?? "en";
49
+ if (Object.hasOwn(policy.notices, base))
50
+ return base;
51
+ return Object.hasOwn(policy.notices, "en") ? "en" : (Object.keys(policy.notices)[0] ?? "en");
52
+ }
53
+ function validNotice(notice) {
54
+ return (object(notice) &&
55
+ keys(notice, ["title", "description", "privacy_url"]) &&
56
+ text(notice.title, 120) &&
57
+ text(notice.description, 4000) &&
58
+ safeURL(notice.privacy_url, true));
59
+ }
60
+ function profileList(value, maximum) {
61
+ return (Array.isArray(value) &&
62
+ value.length <= maximum &&
63
+ new Set(value).size === value.length &&
64
+ value.every((profile) => typeof profile === "string" && regionalProfiles.includes(profile)));
65
+ }
66
+ export function validRegionalPolicy(value) {
67
+ if (!object(value) ||
68
+ !keys(value, ["rules_version", "applicable_profiles", "notices", "rights"]) ||
69
+ value.rules_version !== regionalRulesVersion ||
70
+ !profileList(value.applicable_profiles, 32))
71
+ return false;
72
+ if (value.notices !== undefined) {
73
+ if (!object(value.notices) || Object.keys(value.notices).length > 32)
74
+ return false;
75
+ for (const [profile, notices] of Object.entries(value.notices)) {
76
+ if (!regionalProfiles.includes(profile) ||
77
+ !object(notices) ||
78
+ Object.keys(notices).length < 1 ||
79
+ Object.keys(notices).length > 20 ||
80
+ !Object.entries(notices).every(([tag, notice]) => locale.test(tag) && validNotice(notice)))
81
+ return false;
82
+ }
83
+ }
84
+ if (value.rights !== undefined) {
85
+ if (!object(value.rights) || Object.keys(value.rights).length > 20)
86
+ return false;
87
+ for (const [tag, links] of Object.entries(value.rights)) {
88
+ if (!locale.test(tag) ||
89
+ !object(links) ||
90
+ !keys(links, ["request_url", "appeal_url"]) ||
91
+ Object.keys(links).length < 1 ||
92
+ !Object.values(links).some((url) => typeof url === "string" && url !== "") ||
93
+ !Object.values(links).every((url) => url === "" || safeURL(url, true)))
94
+ return false;
95
+ }
96
+ }
97
+ return true;
98
+ }
99
+ export function validRegionSelection(value) {
100
+ return (object(value) &&
101
+ keys(value, [
102
+ "country",
103
+ "subdivision",
104
+ "source",
105
+ "profile_id",
106
+ "applicable_profiles",
107
+ "rules_version",
108
+ "selection_id",
109
+ "resolution_version",
110
+ ]) &&
111
+ ["unknown", "host", "trusted_proxy"].includes(String(value.source)) &&
112
+ typeof value.profile_id === "string" &&
113
+ regionalProfiles.includes(value.profile_id) &&
114
+ profileList(value.applicable_profiles, 64) &&
115
+ value.rules_version === regionalRulesVersion &&
116
+ value.applicable_profiles.includes("global-strict") &&
117
+ value.applicable_profiles.includes(value.profile_id) &&
118
+ typeof value.selection_id === "string" &&
119
+ /^[a-f0-9]{64}$/.test(value.selection_id) &&
120
+ (value.country === undefined ||
121
+ value.country === "" ||
122
+ (typeof value.country === "string" && /^[A-Z]{2}$/.test(value.country))) &&
123
+ (value.subdivision === undefined ||
124
+ value.subdivision === "" ||
125
+ (typeof value.country === "string" &&
126
+ typeof value.subdivision === "string" &&
127
+ new RegExp(`^${value.country}-[A-Z0-9]{1,3}$`).test(value.subdivision))) &&
128
+ (value.source !== "unknown" ||
129
+ ((value.country === undefined || value.country === "") &&
130
+ (value.subdivision === undefined || value.subdivision === ""))) &&
131
+ (value.source === "unknown" ||
132
+ (typeof value.country === "string" && /^[A-Z]{2}$/.test(value.country))) &&
133
+ (value.resolution_version === undefined ||
134
+ value.resolution_version === "" ||
135
+ (typeof value.resolution_version === "string" && identifier.test(value.resolution_version))));
136
+ }
137
+ /** Returns a normalized policy. Omitted durations use the shared Go defaults. */
138
+ export function parsePolicy(value) {
139
+ if (!object(value))
140
+ return null;
141
+ const candidate = { expires_after_days: 180, retention_days: 365, ...value };
142
+ return validatePolicy(candidate) ? candidate : null;
143
+ }
144
+ export function validatePolicy(value) {
145
+ if (!object(value) ||
146
+ !keys(value, [
147
+ "schema_version",
148
+ "site",
149
+ "epoch",
150
+ "version",
151
+ "expires_after_days",
152
+ "retention_days",
153
+ "notices",
154
+ "services",
155
+ "regional",
156
+ ]) ||
157
+ value.schema_version !== 1 ||
158
+ typeof value.site !== "string" ||
159
+ !slug.test(value.site) ||
160
+ typeof value.epoch !== "string" ||
161
+ !identifier.test(value.epoch) ||
162
+ !integer(value.version, Number.MAX_SAFE_INTEGER) ||
163
+ !integer(value.expires_after_days, 3650) ||
164
+ !integer(value.retention_days, 3650) ||
165
+ !object(value.notices) ||
166
+ Object.keys(value.notices).length < 1 ||
167
+ Object.keys(value.notices).length > 20 ||
168
+ !Array.isArray(value.services) ||
169
+ value.services.length > 64 ||
170
+ (value.regional !== undefined && !validRegionalPolicy(value.regional)))
171
+ return false;
172
+ for (const [lang, notice] of Object.entries(value.notices)) {
173
+ if (!locale.test(lang) ||
174
+ !object(notice) ||
175
+ !keys(notice, ["title", "description", "privacy_url"]) ||
176
+ !text(notice.title, 120) ||
177
+ !text(notice.description, 4000) ||
178
+ !safeURL(notice.privacy_url, true))
179
+ return false;
180
+ }
181
+ const ids = new Set();
182
+ let ga4Count = 0;
183
+ for (const service of value.services) {
184
+ if (!object(service) ||
185
+ !keys(service, [
186
+ "id",
187
+ "name",
188
+ "description",
189
+ "provider",
190
+ "category",
191
+ "kind",
192
+ "destination",
193
+ "measurement_id",
194
+ "policy_url",
195
+ "storage",
196
+ "processing",
197
+ ]) ||
198
+ typeof service.id !== "string" ||
199
+ !slug.test(service.id) ||
200
+ ids.has(service.id) ||
201
+ !text(service.name, 120) ||
202
+ !text(service.description, 4000) ||
203
+ !text(service.provider, 200) ||
204
+ typeof service.category !== "string" ||
205
+ !categories.includes(service.category) ||
206
+ typeof service.kind !== "string" ||
207
+ !kinds.includes(service.kind) ||
208
+ !safeURL(service.policy_url, true) ||
209
+ (service.destination !== undefined &&
210
+ service.destination !== "" &&
211
+ !safeURL(service.destination)) ||
212
+ !Array.isArray(service.storage) ||
213
+ service.storage.length > 32 ||
214
+ (service.processing !== undefined &&
215
+ (!validRestrictions(service.processing) ||
216
+ (service.category === "necessary" && Object.values(service.processing).some(Boolean)))))
217
+ return false;
218
+ if (service.kind === "ga4" && ++ga4Count > 1)
219
+ return false;
220
+ if (service.kind === "ga4" &&
221
+ (service.category !== "analytics" ||
222
+ typeof service.measurement_id !== "string" ||
223
+ !/^G-[A-Z0-9]{1,32}$/.test(service.measurement_id)))
224
+ return false;
225
+ if (service.kind !== "ga4" &&
226
+ service.measurement_id !== undefined &&
227
+ service.measurement_id !== "")
228
+ return false;
229
+ const scopes = new Set();
230
+ for (const entry of service.storage) {
231
+ if (!object(entry) ||
232
+ !keys(entry, ["name", "type", "domain", "path"]) ||
233
+ !text(entry.name, 128) ||
234
+ typeof entry.type !== "string" ||
235
+ !["cookie", "localStorage"].includes(entry.type) ||
236
+ (entry.domain !== undefined &&
237
+ (typeof entry.domain !== "string" ||
238
+ bytes(entry.domain) > 253 ||
239
+ /[ /\\:@?#\r\n\t]/.test(entry.domain))) ||
240
+ (entry.path !== undefined &&
241
+ (typeof entry.path !== "string" ||
242
+ bytes(entry.path) > 512 ||
243
+ (entry.path !== "" &&
244
+ (!entry.path.startsWith("/") ||
245
+ control(entry.path, false, true) ||
246
+ entry.path.includes(";"))))))
247
+ return false;
248
+ if (entry.type === "localStorage" && (entry.domain || entry.path))
249
+ return false;
250
+ if (entry.type === "cookie" &&
251
+ (!/^[!#$%&'*+.^_`|~A-Za-z0-9-]+$/.test(entry.name) ||
252
+ (typeof entry.domain === "string" &&
253
+ entry.domain !== "" &&
254
+ (!/^\.?[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/.test(entry.domain) ||
255
+ entry.domain.includes(".."))) ||
256
+ (typeof entry.path === "string" &&
257
+ (control(entry.path, false, true) || entry.path.includes(";")))))
258
+ return false;
259
+ const scope = [entry.type, entry.name, entry.domain ?? "", entry.path ?? ""].join("\u0000");
260
+ if (scopes.has(scope))
261
+ return false;
262
+ scopes.add(scope);
263
+ }
264
+ ids.add(service.id);
265
+ }
266
+ return (bytes(JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`)) <= 262144);
267
+ }
268
+ export function validateConfig(value) {
269
+ return (object(value) &&
270
+ keys(value, [
271
+ "enabled",
272
+ "policy",
273
+ "allowed_services",
274
+ "receipt_url",
275
+ "recheck_after_seconds",
276
+ "region",
277
+ "privacy_signals",
278
+ ]) &&
279
+ typeof value.enabled === "boolean" &&
280
+ validatePolicy(value.policy) &&
281
+ Array.isArray(value.allowed_services) &&
282
+ value.allowed_services.length <= 64 &&
283
+ new Set(value.allowed_services).size === value.allowed_services.length &&
284
+ value.allowed_services.every((id) => typeof id === "string" &&
285
+ value.policy.services.some((service) => service.id === id)) &&
286
+ (value.receipt_url === undefined ||
287
+ (typeof value.receipt_url === "string" &&
288
+ value.receipt_url.startsWith("/") &&
289
+ safeURL(value.receipt_url, true))) &&
290
+ integer(value.recheck_after_seconds, 3600) &&
291
+ (value.region === undefined || validRegionSelection(value.region)) &&
292
+ (value.privacy_signals === undefined ||
293
+ (object(value.privacy_signals) &&
294
+ Object.keys(value.privacy_signals).length === 1 &&
295
+ typeof value.privacy_signals.gpc === "boolean")));
296
+ }