@rcooler/consent 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +56 -2
- package/dist/consent.css +1 -0
- package/dist/headless.d.ts +18 -0
- package/dist/headless.js +734 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/initialize.d.ts +13 -0
- package/dist/initialize.js +44 -0
- package/dist/integrations.d.ts +19 -0
- package/dist/integrations.js +233 -0
- package/dist/network.d.ts +3 -0
- package/dist/network.js +58 -0
- package/dist/regional.d.ts +14 -0
- package/dist/regional.js +73 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +19 -0
- package/dist/types.d.ts +132 -0
- package/dist/types.js +11 -0
- package/dist/ui.d.ts +51 -0
- package/dist/ui.js +348 -0
- package/dist/validation.d.ts +10 -0
- package/dist/validation.js +318 -0
- package/package.json +34 -4
package/dist/headless.js
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
import { fetchJSON, sameOriginURL } from "./network.js";
|
|
2
|
+
import { deniedChoices, noRestrictions } from "./types.js";
|
|
3
|
+
import { regionalNotices, restrictionNames, serviceRestricted, validRestrictions, } from "./regional.js";
|
|
4
|
+
import { resolveNoticeLocale, validateConfig, validChoices } from "./validation.js";
|
|
5
|
+
const hasGrant = (choices) => Object.values(choices).some(Boolean);
|
|
6
|
+
const clone = (value) => JSON.parse(JSON.stringify(value));
|
|
7
|
+
/** No optional resource is created by this state machine without an explicit adapter. */
|
|
8
|
+
export function createConsent(options) {
|
|
9
|
+
if (!validateConfig(options.config))
|
|
10
|
+
throw new Error("Invalid consent configuration");
|
|
11
|
+
let config = clone(options.config);
|
|
12
|
+
const now = options.now ?? Date.now;
|
|
13
|
+
const origin = options.origin ?? location.origin;
|
|
14
|
+
const reload = options.reload ?? (() => location.reload());
|
|
15
|
+
const events = options.events ?? window;
|
|
16
|
+
const fetcher = options.fetcher ?? fetch;
|
|
17
|
+
const locale = options.locale ??
|
|
18
|
+
(typeof document !== "undefined" ? document.documentElement.lang || "en" : "en");
|
|
19
|
+
const configURL = options.configURL ? sameOriginURL(options.configURL, origin) : undefined;
|
|
20
|
+
if (config.receipt_url)
|
|
21
|
+
sameOriginURL(config.receipt_url, origin);
|
|
22
|
+
let storage;
|
|
23
|
+
try {
|
|
24
|
+
storage = options.storage ?? localStorage;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
/* Storage denial is handled by save/read. */
|
|
28
|
+
}
|
|
29
|
+
const cookies = options.cookies ?? (typeof document !== "undefined" ? document : undefined);
|
|
30
|
+
const key = `rcooler.consent.v1.${config.policy.site}`;
|
|
31
|
+
const privacyKey = `rcooler.consent.privacy.v1.${config.policy.site}`;
|
|
32
|
+
const listeners = new Set();
|
|
33
|
+
const registrations = new Map();
|
|
34
|
+
const retries = new Set();
|
|
35
|
+
let generation = 0;
|
|
36
|
+
let destroyed = false;
|
|
37
|
+
let healthy = config.enabled && !configURL;
|
|
38
|
+
let checking;
|
|
39
|
+
let pending = false;
|
|
40
|
+
let error = null;
|
|
41
|
+
let decision = null;
|
|
42
|
+
/** A refusal which storage would not accept; it still stands for this page. */
|
|
43
|
+
let unsaved = null;
|
|
44
|
+
let choices = deniedChoices();
|
|
45
|
+
let lastCheck = now();
|
|
46
|
+
let reloadRequested = false;
|
|
47
|
+
let restrictions = readRestrictions();
|
|
48
|
+
let lastSignal = gpc();
|
|
49
|
+
function gpc() {
|
|
50
|
+
try {
|
|
51
|
+
return (config.privacy_signals?.gpc === true ||
|
|
52
|
+
(options.privacySignal
|
|
53
|
+
? options.privacySignal()
|
|
54
|
+
: typeof navigator !== "undefined" &&
|
|
55
|
+
navigator.globalPrivacyControl ===
|
|
56
|
+
true));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// A failing injected signal provider cannot restore an optional permission.
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function effectiveRestrictions() {
|
|
64
|
+
return gpc()
|
|
65
|
+
? { ...restrictions, sale: true, sharing: true, targeted_advertising: true }
|
|
66
|
+
: { ...restrictions };
|
|
67
|
+
}
|
|
68
|
+
function readRestrictions() {
|
|
69
|
+
try {
|
|
70
|
+
const raw = storage?.getItem(privacyKey);
|
|
71
|
+
if (!raw)
|
|
72
|
+
return noRestrictions();
|
|
73
|
+
if (raw.length > 1024)
|
|
74
|
+
throw new Error("Invalid privacy preferences");
|
|
75
|
+
const value = JSON.parse(raw);
|
|
76
|
+
if (!validRestrictions(value))
|
|
77
|
+
throw new Error("Invalid privacy preferences");
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return { sale: true, sharing: true, targeted_advertising: true, sensitive_data: true };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function saveRestrictions(value) {
|
|
85
|
+
try {
|
|
86
|
+
if (!storage)
|
|
87
|
+
return false;
|
|
88
|
+
const encoded = JSON.stringify(value);
|
|
89
|
+
if (storage.getItem(privacyKey) !== encoded)
|
|
90
|
+
storage.setItem(privacyKey, encoded);
|
|
91
|
+
return storage.getItem(privacyKey) === encoded;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function read() {
|
|
98
|
+
try {
|
|
99
|
+
const raw = storage?.getItem(key) ?? "null";
|
|
100
|
+
if (raw.length > 16384)
|
|
101
|
+
return null;
|
|
102
|
+
const value = JSON.parse(raw);
|
|
103
|
+
if (!value ||
|
|
104
|
+
value.site !== config.policy.site ||
|
|
105
|
+
value.epoch !== config.policy.epoch ||
|
|
106
|
+
value.policy_version !== config.policy.version ||
|
|
107
|
+
(value.region?.selection_id ?? "") !== (config.region?.selection_id ?? "") ||
|
|
108
|
+
(value.restrictions !== undefined && !validRestrictions(value.restrictions)) ||
|
|
109
|
+
(config.region &&
|
|
110
|
+
(!validRestrictions(value.restrictions) ||
|
|
111
|
+
!value.privacy_signals ||
|
|
112
|
+
typeof value.privacy_signals.gpc !== "boolean")) ||
|
|
113
|
+
!validChoices(value.choices) ||
|
|
114
|
+
typeof value.event_id !== "string" ||
|
|
115
|
+
!/^[A-Za-z0-9_-]{1,128}$/.test(value.event_id) ||
|
|
116
|
+
typeof value.locale !== "string" ||
|
|
117
|
+
!/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(value.locale) ||
|
|
118
|
+
typeof value.decided_at !== "string" ||
|
|
119
|
+
(value.receipt_id !== undefined &&
|
|
120
|
+
(typeof value.receipt_id !== "string" ||
|
|
121
|
+
!/^[A-Za-z0-9_-]{1,128}$/.test(value.receipt_id))) ||
|
|
122
|
+
!Number.isSafeInteger(value.sequence) ||
|
|
123
|
+
value.sequence <= 0 ||
|
|
124
|
+
!Number.isFinite(value.expires_at) ||
|
|
125
|
+
value.expires_at <= now() ||
|
|
126
|
+
value.expires_at >
|
|
127
|
+
Date.parse(value.decided_at) + config.policy.expires_after_days * 86400000 ||
|
|
128
|
+
!Number.isFinite(Date.parse(value.decided_at)) ||
|
|
129
|
+
Date.parse(value.decided_at) > now() + 60000 ||
|
|
130
|
+
typeof value.acknowledged !== "boolean" ||
|
|
131
|
+
(hasGrant(value.choices) &&
|
|
132
|
+
(!value.acknowledged || (config.receipt_url && !value.receipt_id))))
|
|
133
|
+
return null;
|
|
134
|
+
// A persisted receipt can retain a denial even if the separate privacy write failed.
|
|
135
|
+
if (value.restrictions)
|
|
136
|
+
for (const name of restrictionNames)
|
|
137
|
+
restrictions[name] ||= value.restrictions[name];
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function save(value) {
|
|
145
|
+
try {
|
|
146
|
+
if (!storage)
|
|
147
|
+
return false;
|
|
148
|
+
storage.setItem(key, JSON.stringify(value));
|
|
149
|
+
return storage.getItem(key) === JSON.stringify(value);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function clearStored() {
|
|
156
|
+
try {
|
|
157
|
+
storage?.removeItem(key);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
/* Denial remains in memory. */
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function standing() {
|
|
164
|
+
return read() ?? (unsaved && unsaved.expires_at > now() ? unsaved : null);
|
|
165
|
+
}
|
|
166
|
+
function state() {
|
|
167
|
+
return {
|
|
168
|
+
config: clone(config),
|
|
169
|
+
choices: { ...choices },
|
|
170
|
+
decided: decision !== null && decision.source !== "privacy_signal",
|
|
171
|
+
pending,
|
|
172
|
+
error,
|
|
173
|
+
restrictions: effectiveRestrictions(),
|
|
174
|
+
privacy_signals: { gpc: gpc() },
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function emit() {
|
|
178
|
+
for (const listener of listeners)
|
|
179
|
+
listener(state());
|
|
180
|
+
}
|
|
181
|
+
function allowed(serviceID) {
|
|
182
|
+
if (destroyed || !healthy || !config.enabled || (decision && decision.expires_at <= now()))
|
|
183
|
+
return false;
|
|
184
|
+
const service = config.policy.services.find((item) => item.id === serviceID);
|
|
185
|
+
return Boolean(service &&
|
|
186
|
+
(service.category === "necessary" || !(lastSignal && !gpc())) &&
|
|
187
|
+
!serviceRestricted(service, effectiveRestrictions(), gpc()) &&
|
|
188
|
+
config.allowed_services.includes(serviceID) &&
|
|
189
|
+
(service.category === "necessary" || choices[service.category]));
|
|
190
|
+
}
|
|
191
|
+
function cleanStorage(service) {
|
|
192
|
+
for (const entry of service.storage) {
|
|
193
|
+
try {
|
|
194
|
+
if (entry.type === "localStorage") {
|
|
195
|
+
if (entry.name !== key && entry.name !== privacyKey)
|
|
196
|
+
storage?.removeItem(entry.name);
|
|
197
|
+
}
|
|
198
|
+
else if (cookies) {
|
|
199
|
+
// Only exact, declared cookie names are removed. HttpOnly and third-party storage require host cleanup.
|
|
200
|
+
if (!/^[!#$%&'*+.^_`|~A-Za-z0-9-]+$/.test(entry.name))
|
|
201
|
+
continue;
|
|
202
|
+
const domain = entry.domain ? `; Domain=${entry.domain}` : "";
|
|
203
|
+
// Browsers ignore any write to a prefixed cookie, expiry included, without Secure.
|
|
204
|
+
const secure = /^__(?:Secure|Host)-/i.test(entry.name) ? "; Secure" : "";
|
|
205
|
+
cookies.cookie = `${entry.name}=; Max-Age=0; Path=${entry.path || "/"}${domain}; SameSite=Lax${secure}`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
/* Cleanup must never prevent denial. */
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function stop(id, registration) {
|
|
214
|
+
if (!registration.abort)
|
|
215
|
+
return;
|
|
216
|
+
registration.abort.abort();
|
|
217
|
+
delete registration.abort;
|
|
218
|
+
try {
|
|
219
|
+
registration.cleanup?.();
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
/* A host cleanup failure cannot restore consent. */
|
|
223
|
+
}
|
|
224
|
+
delete registration.cleanup;
|
|
225
|
+
const service = config.policy.services.find((item) => item.id === id);
|
|
226
|
+
if (service)
|
|
227
|
+
cleanStorage(service);
|
|
228
|
+
if (registration.started && registration.adapter.reloadOnRevoke && !reloadRequested) {
|
|
229
|
+
reloadRequested = true;
|
|
230
|
+
reload();
|
|
231
|
+
}
|
|
232
|
+
registration.started = false;
|
|
233
|
+
}
|
|
234
|
+
function cleanDenied(requested) {
|
|
235
|
+
for (const service of config.policy.services) {
|
|
236
|
+
if ((service.category !== "necessary" && !requested[service.category]) ||
|
|
237
|
+
serviceRestricted(service, effectiveRestrictions(), gpc()))
|
|
238
|
+
cleanStorage(service);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function reconcile() {
|
|
242
|
+
for (const [id, registration] of registrations) {
|
|
243
|
+
if (!allowed(id)) {
|
|
244
|
+
stop(id, registration);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (registration.abort)
|
|
248
|
+
continue;
|
|
249
|
+
const service = config.policy.services.find((item) => item.id === id);
|
|
250
|
+
if (!service)
|
|
251
|
+
continue;
|
|
252
|
+
const abort = new AbortController();
|
|
253
|
+
registration.abort = abort;
|
|
254
|
+
// Mark before invoking: a synchronous provider load also requires reload on withdrawal.
|
|
255
|
+
registration.started = true;
|
|
256
|
+
try {
|
|
257
|
+
const result = registration.adapter.activate({
|
|
258
|
+
service: clone(service),
|
|
259
|
+
signal: abort.signal,
|
|
260
|
+
isAllowed: () => !abort.signal.aborted && allowed(id),
|
|
261
|
+
});
|
|
262
|
+
void Promise.resolve(result)
|
|
263
|
+
.then((cleanup) => {
|
|
264
|
+
if (!cleanup)
|
|
265
|
+
return;
|
|
266
|
+
if (abort.signal.aborted || !allowed(id))
|
|
267
|
+
cleanup();
|
|
268
|
+
else
|
|
269
|
+
registration.cleanup = cleanup;
|
|
270
|
+
})
|
|
271
|
+
.catch(() => {
|
|
272
|
+
if (registration.abort !== abort)
|
|
273
|
+
return;
|
|
274
|
+
if (!abort.signal.aborted) {
|
|
275
|
+
error = "service_failed";
|
|
276
|
+
emit();
|
|
277
|
+
}
|
|
278
|
+
stop(id, registration);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
if (registration.abort !== abort)
|
|
283
|
+
continue;
|
|
284
|
+
stop(id, registration);
|
|
285
|
+
error = "service_failed";
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function deny(reason, clear = true) {
|
|
290
|
+
generation++;
|
|
291
|
+
choices = deniedChoices();
|
|
292
|
+
pending = false;
|
|
293
|
+
error = reason;
|
|
294
|
+
decision = null;
|
|
295
|
+
if (clear) {
|
|
296
|
+
unsaved = null;
|
|
297
|
+
clearStored();
|
|
298
|
+
}
|
|
299
|
+
cleanDenied(choices);
|
|
300
|
+
reconcile();
|
|
301
|
+
emit();
|
|
302
|
+
}
|
|
303
|
+
/** Applies a re-read choice without restarting services which it still permits. */
|
|
304
|
+
function restore(value) {
|
|
305
|
+
decision = value;
|
|
306
|
+
choices = value ? { ...value.choices } : deniedChoices();
|
|
307
|
+
cleanDenied(choices);
|
|
308
|
+
reconcile();
|
|
309
|
+
emit();
|
|
310
|
+
}
|
|
311
|
+
function validAck(value, eventID) {
|
|
312
|
+
if (!value || typeof value !== "object")
|
|
313
|
+
return false;
|
|
314
|
+
const ack = value;
|
|
315
|
+
return (ack.event_id === eventID &&
|
|
316
|
+
typeof ack.receipt_id === "string" &&
|
|
317
|
+
/^[A-Za-z0-9_-]{1,128}$/.test(ack.receipt_id) &&
|
|
318
|
+
typeof ack.received_at === "string" &&
|
|
319
|
+
typeof ack.expires_at === "string" &&
|
|
320
|
+
Number.isFinite(Date.parse(ack.received_at)) &&
|
|
321
|
+
Number.isFinite(Date.parse(ack.expires_at)) &&
|
|
322
|
+
Date.parse(ack.expires_at) > now());
|
|
323
|
+
}
|
|
324
|
+
async function post(value) {
|
|
325
|
+
if (!config.receipt_url)
|
|
326
|
+
return undefined;
|
|
327
|
+
const submission = {
|
|
328
|
+
event_id: value.event_id,
|
|
329
|
+
site: value.site,
|
|
330
|
+
epoch: value.epoch,
|
|
331
|
+
policy_version: value.policy_version,
|
|
332
|
+
locale: value.locale,
|
|
333
|
+
choices: value.choices,
|
|
334
|
+
decided_at: value.decided_at,
|
|
335
|
+
sequence: value.sequence,
|
|
336
|
+
...(value.previous_receipt_id ? { previous_receipt_id: value.previous_receipt_id } : {}),
|
|
337
|
+
...(value.region ? { region: value.region } : {}),
|
|
338
|
+
privacy_signals: value.privacy_signals ?? { gpc: false },
|
|
339
|
+
restrictions: value.restrictions ?? noRestrictions(),
|
|
340
|
+
};
|
|
341
|
+
const response = await fetchJSON(sameOriginURL(config.receipt_url, origin), {
|
|
342
|
+
method: "POST",
|
|
343
|
+
headers: { "Content-Type": "application/json" },
|
|
344
|
+
body: JSON.stringify(submission),
|
|
345
|
+
}, fetcher);
|
|
346
|
+
if (!validAck(response, value.event_id))
|
|
347
|
+
throw new Error("Invalid consent receipt");
|
|
348
|
+
return response;
|
|
349
|
+
}
|
|
350
|
+
function recordDenial(value, attempt = 0) {
|
|
351
|
+
void post(value)
|
|
352
|
+
.then((ack) => {
|
|
353
|
+
if (destroyed ||
|
|
354
|
+
decision?.event_id !== value.event_id ||
|
|
355
|
+
read()?.event_id !== value.event_id)
|
|
356
|
+
return;
|
|
357
|
+
if (ack) {
|
|
358
|
+
value.receipt_id = ack.receipt_id;
|
|
359
|
+
value.acknowledged = true;
|
|
360
|
+
save(value);
|
|
361
|
+
decision = value;
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
.catch(() => {
|
|
365
|
+
if (destroyed || decision?.event_id !== value.event_id || attempt >= 2)
|
|
366
|
+
return;
|
|
367
|
+
const timer = setTimeout(() => {
|
|
368
|
+
retries.delete(timer);
|
|
369
|
+
recordDenial(value, attempt + 1);
|
|
370
|
+
}, 1000 * (attempt + 1));
|
|
371
|
+
retries.add(timer);
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
const controller = {
|
|
375
|
+
get state() {
|
|
376
|
+
return state();
|
|
377
|
+
},
|
|
378
|
+
subscribe(listener) {
|
|
379
|
+
listeners.add(listener);
|
|
380
|
+
listener(state());
|
|
381
|
+
return () => listeners.delete(listener);
|
|
382
|
+
},
|
|
383
|
+
isAllowed: allowed,
|
|
384
|
+
async decide(requested, requestedLocale, requestedRestrictions) {
|
|
385
|
+
if (destroyed ||
|
|
386
|
+
!validChoices(requested) ||
|
|
387
|
+
(requestedRestrictions !== undefined && !validRestrictions(requestedRestrictions)))
|
|
388
|
+
return false;
|
|
389
|
+
const priorRestrictions = restrictions;
|
|
390
|
+
// Accept-all only affects service categories. It never cancels a privacy opt-out.
|
|
391
|
+
restrictions = requestedRestrictions ? { ...requestedRestrictions } : effectiveRestrictions();
|
|
392
|
+
restrictions = effectiveRestrictions();
|
|
393
|
+
const relaxing = restrictionNames.some((name) => priorRestrictions[name] && !restrictions[name]);
|
|
394
|
+
// Lifting an opt-out cannot activate an earlier category grant before a new receipt.
|
|
395
|
+
if (relaxing) {
|
|
396
|
+
choices = deniedChoices();
|
|
397
|
+
clearStored();
|
|
398
|
+
reconcile();
|
|
399
|
+
}
|
|
400
|
+
const privacySaved = saveRestrictions(restrictions);
|
|
401
|
+
if (!privacySaved && relaxing) {
|
|
402
|
+
restrictions = priorRestrictions;
|
|
403
|
+
deny("storage_unavailable");
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
const previous = decision;
|
|
407
|
+
const token = ++generation;
|
|
408
|
+
// One instant: a later expiry base would exceed the lifetime which restoring a choice checks.
|
|
409
|
+
const decidedAt = now();
|
|
410
|
+
const sequence = Math.max(previous?.sequence ?? 0, decidedAt) + 1;
|
|
411
|
+
const value = {
|
|
412
|
+
event_id: crypto.randomUUID(),
|
|
413
|
+
site: config.policy.site,
|
|
414
|
+
epoch: config.policy.epoch,
|
|
415
|
+
policy_version: config.policy.version,
|
|
416
|
+
locale: regionalNotices(config, requestedLocale ?? locale)[0]?.locale ??
|
|
417
|
+
resolveNoticeLocale(config.policy, requestedLocale ?? locale),
|
|
418
|
+
choices: { ...requested },
|
|
419
|
+
decided_at: new Date(decidedAt).toISOString(),
|
|
420
|
+
sequence,
|
|
421
|
+
expires_at: decidedAt + config.policy.expires_after_days * 86400000,
|
|
422
|
+
acknowledged: !config.receipt_url,
|
|
423
|
+
...(config.region ? { region: clone(config.region) } : {}),
|
|
424
|
+
privacy_signals: { gpc: gpc() },
|
|
425
|
+
restrictions: { ...restrictions },
|
|
426
|
+
};
|
|
427
|
+
if (previous?.receipt_id)
|
|
428
|
+
value.previous_receipt_id = previous.receipt_id;
|
|
429
|
+
// Apply every withdrawal before any storage or network operation.
|
|
430
|
+
choices = {
|
|
431
|
+
preferences: choices.preferences && requested.preferences,
|
|
432
|
+
analytics: choices.analytics && requested.analytics,
|
|
433
|
+
marketing: choices.marketing && requested.marketing,
|
|
434
|
+
};
|
|
435
|
+
pending = hasGrant(requested);
|
|
436
|
+
error = null;
|
|
437
|
+
cleanDenied(requested);
|
|
438
|
+
reconcile();
|
|
439
|
+
const saved = save(value);
|
|
440
|
+
unsaved = !saved && !hasGrant(requested) ? value : null;
|
|
441
|
+
// A refusal which cannot be written must not leave an earlier grant to be restored.
|
|
442
|
+
if (unsaved)
|
|
443
|
+
clearStored();
|
|
444
|
+
decision = value;
|
|
445
|
+
emit();
|
|
446
|
+
if (!hasGrant(requested)) {
|
|
447
|
+
pending = false;
|
|
448
|
+
emit();
|
|
449
|
+
if (config.receipt_url)
|
|
450
|
+
recordDenial(value);
|
|
451
|
+
return true;
|
|
452
|
+
}
|
|
453
|
+
if (!saved) {
|
|
454
|
+
deny("storage_unavailable");
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
try {
|
|
458
|
+
if (configURL && !healthy)
|
|
459
|
+
await controller.recheck();
|
|
460
|
+
if (token !== generation || destroyed)
|
|
461
|
+
return false;
|
|
462
|
+
if (!healthy || !config.enabled)
|
|
463
|
+
throw new Error("Configuration unavailable");
|
|
464
|
+
const ack = await post(value);
|
|
465
|
+
// Storage must still contain this exact pending choice; another tab may already have denied it.
|
|
466
|
+
const stored = JSON.parse(storage?.getItem(key) ?? "null");
|
|
467
|
+
if (destroyed || token !== generation)
|
|
468
|
+
return false;
|
|
469
|
+
if (stored?.event_id !== value.event_id) {
|
|
470
|
+
deny("save_failed", false);
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
if (gpc() && !value.privacy_signals?.gpc) {
|
|
474
|
+
synchronizePrivacy();
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
value.acknowledged = true;
|
|
478
|
+
if (ack) {
|
|
479
|
+
value.receipt_id = ack.receipt_id;
|
|
480
|
+
value.expires_at = Math.min(value.expires_at, Date.parse(ack.expires_at));
|
|
481
|
+
}
|
|
482
|
+
if (!save(value))
|
|
483
|
+
throw new Error("Storage unavailable");
|
|
484
|
+
decision = value;
|
|
485
|
+
choices = { ...value.choices };
|
|
486
|
+
pending = false;
|
|
487
|
+
reconcile();
|
|
488
|
+
emit();
|
|
489
|
+
return true;
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
if (token === generation && !destroyed)
|
|
493
|
+
deny("save_failed");
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
},
|
|
497
|
+
restrict(requested, requestedLocale) {
|
|
498
|
+
if (!validRestrictions(requested))
|
|
499
|
+
return Promise.resolve(false);
|
|
500
|
+
const merged = effectiveRestrictions();
|
|
501
|
+
for (const name of restrictionNames)
|
|
502
|
+
merged[name] ||= requested[name];
|
|
503
|
+
// An opt-out action never renews or reauthorizes an earlier category grant.
|
|
504
|
+
return controller.decide(deniedChoices(), requestedLocale, merged);
|
|
505
|
+
},
|
|
506
|
+
register(serviceID, adapter) {
|
|
507
|
+
if (destroyed ||
|
|
508
|
+
registrations.has(serviceID) ||
|
|
509
|
+
!config.policy.services.some((service) => service.id === serviceID)) {
|
|
510
|
+
throw new Error("Unknown or duplicate consent service");
|
|
511
|
+
}
|
|
512
|
+
const registration = { adapter, started: false };
|
|
513
|
+
registrations.set(serviceID, registration);
|
|
514
|
+
reconcile();
|
|
515
|
+
return () => {
|
|
516
|
+
// A repeated disposer must not detach a later registration from withdrawal.
|
|
517
|
+
if (registrations.get(serviceID) !== registration)
|
|
518
|
+
return;
|
|
519
|
+
stop(serviceID, registration);
|
|
520
|
+
registrations.delete(serviceID);
|
|
521
|
+
};
|
|
522
|
+
},
|
|
523
|
+
async recheck() {
|
|
524
|
+
if (destroyed)
|
|
525
|
+
return false;
|
|
526
|
+
if (checking)
|
|
527
|
+
return checking;
|
|
528
|
+
checking = (async () => {
|
|
529
|
+
if (decision && decision.expires_at <= now())
|
|
530
|
+
deny(null);
|
|
531
|
+
if (!configURL)
|
|
532
|
+
return healthy;
|
|
533
|
+
const token = generation;
|
|
534
|
+
try {
|
|
535
|
+
const fresh = await fetchJSON(configURL, {}, fetcher);
|
|
536
|
+
if (destroyed)
|
|
537
|
+
return false;
|
|
538
|
+
if (!validateConfig(fresh))
|
|
539
|
+
throw new Error("Invalid consent configuration");
|
|
540
|
+
if (fresh.receipt_url)
|
|
541
|
+
sameOriginURL(fresh.receipt_url, origin);
|
|
542
|
+
if (fresh.policy.site !== config.policy.site)
|
|
543
|
+
throw new Error("Consent site changed");
|
|
544
|
+
const changed = JSON.stringify(fresh.policy) !== JSON.stringify(config.policy) ||
|
|
545
|
+
fresh.receipt_url !== config.receipt_url ||
|
|
546
|
+
fresh.region?.selection_id !== config.region?.selection_id;
|
|
547
|
+
if (changed || !fresh.enabled)
|
|
548
|
+
deny(null);
|
|
549
|
+
config = clone(fresh);
|
|
550
|
+
synchronizePrivacy();
|
|
551
|
+
healthy = fresh.enabled;
|
|
552
|
+
if (error === "config_unavailable")
|
|
553
|
+
error = null;
|
|
554
|
+
// Rechecks never replace an in-flight local decision with a stale storage snapshot.
|
|
555
|
+
if (!changed && token === generation && !pending) {
|
|
556
|
+
decision = standing();
|
|
557
|
+
choices = decision ? { ...decision.choices } : deniedChoices();
|
|
558
|
+
}
|
|
559
|
+
lastCheck = now();
|
|
560
|
+
reconcile();
|
|
561
|
+
emit();
|
|
562
|
+
return healthy;
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
if (destroyed)
|
|
566
|
+
return false;
|
|
567
|
+
healthy = false;
|
|
568
|
+
// An outage must not forget a refusal and ask again; a grant needs a fresh choice.
|
|
569
|
+
const current = standing();
|
|
570
|
+
deny("config_unavailable", !current || hasGrant(current.choices));
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
})();
|
|
574
|
+
try {
|
|
575
|
+
return await checking;
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
checking = undefined;
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
destroy() {
|
|
582
|
+
destroyed = true;
|
|
583
|
+
generation++;
|
|
584
|
+
clearInterval(interval);
|
|
585
|
+
for (const timer of retries)
|
|
586
|
+
clearTimeout(timer);
|
|
587
|
+
for (const [id, registration] of registrations)
|
|
588
|
+
stop(id, registration);
|
|
589
|
+
registrations.clear();
|
|
590
|
+
listeners.clear();
|
|
591
|
+
events.removeEventListener("storage", onStorage);
|
|
592
|
+
events.removeEventListener("pageshow", onPageShow);
|
|
593
|
+
events.removeEventListener("focus", onFocus);
|
|
594
|
+
},
|
|
595
|
+
};
|
|
596
|
+
const onStorage = (event) => {
|
|
597
|
+
const storageEvent = event;
|
|
598
|
+
if (storageEvent.key === privacyKey || storageEvent.key === null) {
|
|
599
|
+
// A remote preference update can restrict this tab, but cannot silently lift its opt-outs.
|
|
600
|
+
const remote = readRestrictions();
|
|
601
|
+
for (const name of restrictionNames)
|
|
602
|
+
restrictions[name] ||= remote[name];
|
|
603
|
+
restrictions = effectiveRestrictions();
|
|
604
|
+
cleanDenied(choices);
|
|
605
|
+
reconcile();
|
|
606
|
+
emit();
|
|
607
|
+
if (storageEvent.key === privacyKey)
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (storageEvent.key !== key && storageEvent.key !== null)
|
|
611
|
+
return;
|
|
612
|
+
// Storage events can arrive after a newer local decision. Their payload must still be current.
|
|
613
|
+
if (storage && (typeof storageEvent.newValue === "string" || storageEvent.newValue === null)) {
|
|
614
|
+
try {
|
|
615
|
+
if (storage.getItem(key) !== storageEvent.newValue)
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
catch {
|
|
619
|
+
/* Unavailable storage is handled below as a denial. */
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
generation++;
|
|
623
|
+
pending = false;
|
|
624
|
+
unsaved = null;
|
|
625
|
+
decision = read();
|
|
626
|
+
cleanDenied(decision?.choices ?? deniedChoices());
|
|
627
|
+
// A cross-tab grant requires fresh eligibility before any activation.
|
|
628
|
+
choices = deniedChoices();
|
|
629
|
+
reconcile();
|
|
630
|
+
emit();
|
|
631
|
+
if (configURL)
|
|
632
|
+
void controller.recheck();
|
|
633
|
+
else {
|
|
634
|
+
choices = decision ? { ...decision.choices } : deniedChoices();
|
|
635
|
+
reconcile();
|
|
636
|
+
emit();
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
const onPageShow = (event) => {
|
|
640
|
+
synchronizePrivacy();
|
|
641
|
+
if (!event.persisted)
|
|
642
|
+
return;
|
|
643
|
+
if (configURL) {
|
|
644
|
+
deny(null, false);
|
|
645
|
+
void controller.recheck();
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
// A static page has nothing to revalidate; only storage may have changed while it was cached.
|
|
649
|
+
generation++;
|
|
650
|
+
pending = false;
|
|
651
|
+
const remote = readRestrictions();
|
|
652
|
+
for (const name of restrictionNames)
|
|
653
|
+
restrictions[name] ||= remote[name];
|
|
654
|
+
restore(standing());
|
|
655
|
+
};
|
|
656
|
+
function synchronizePrivacy() {
|
|
657
|
+
const signal = gpc();
|
|
658
|
+
if (signal === lastSignal)
|
|
659
|
+
return;
|
|
660
|
+
lastSignal = signal;
|
|
661
|
+
if (signal) {
|
|
662
|
+
restrictions = effectiveRestrictions();
|
|
663
|
+
saveRestrictions(restrictions);
|
|
664
|
+
generation++;
|
|
665
|
+
pending = false;
|
|
666
|
+
decision = null;
|
|
667
|
+
choices = deniedChoices();
|
|
668
|
+
clearStored();
|
|
669
|
+
cleanDenied(choices);
|
|
670
|
+
reconcile();
|
|
671
|
+
recordSignal();
|
|
672
|
+
}
|
|
673
|
+
else
|
|
674
|
+
deny(null);
|
|
675
|
+
emit();
|
|
676
|
+
}
|
|
677
|
+
function recordSignal() {
|
|
678
|
+
if (destroyed || !gpc())
|
|
679
|
+
return;
|
|
680
|
+
// Record the signal as a denial, never as a refreshed affirmative decision.
|
|
681
|
+
void controller.decide(deniedChoices(), locale, effectiveRestrictions());
|
|
682
|
+
if (decision) {
|
|
683
|
+
decision.source = "privacy_signal";
|
|
684
|
+
save(decision);
|
|
685
|
+
emit();
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
function recordInitialSignal() {
|
|
689
|
+
if (gpc() && !decision?.privacy_signals?.gpc)
|
|
690
|
+
recordSignal();
|
|
691
|
+
}
|
|
692
|
+
const onFocus = () => synchronizePrivacy();
|
|
693
|
+
events.addEventListener("storage", onStorage);
|
|
694
|
+
events.addEventListener("pageshow", onPageShow);
|
|
695
|
+
events.addEventListener("focus", onFocus);
|
|
696
|
+
restrictions = effectiveRestrictions();
|
|
697
|
+
if (gpc())
|
|
698
|
+
saveRestrictions(restrictions);
|
|
699
|
+
decision = read();
|
|
700
|
+
choices = decision ? { ...decision.choices } : deniedChoices();
|
|
701
|
+
cleanDenied(choices);
|
|
702
|
+
const interval = setInterval(() => {
|
|
703
|
+
synchronizePrivacy();
|
|
704
|
+
if (decision && decision.expires_at <= now())
|
|
705
|
+
deny(null);
|
|
706
|
+
if (configURL && now() - lastCheck >= config.recheck_after_seconds * 1000)
|
|
707
|
+
void controller.recheck();
|
|
708
|
+
}, 1000);
|
|
709
|
+
if (configURL)
|
|
710
|
+
void Promise.resolve().then(async () => {
|
|
711
|
+
if (await controller.recheck())
|
|
712
|
+
recordInitialSignal();
|
|
713
|
+
});
|
|
714
|
+
else
|
|
715
|
+
void Promise.resolve().then(recordInitialSignal);
|
|
716
|
+
// Import only a verifiable refusal from the former Kit GA4 runtime. Acceptance never migrates.
|
|
717
|
+
if (!decision) {
|
|
718
|
+
try {
|
|
719
|
+
const raw = storage?.getItem(`rcooler.measurement-consent.v1.${config.policy.site}`) ?? "null";
|
|
720
|
+
const legacy = raw.length <= 16384 ? JSON.parse(raw) : null;
|
|
721
|
+
if (legacy?.allow === false &&
|
|
722
|
+
legacy.epoch === config.policy.epoch &&
|
|
723
|
+
Number.isSafeInteger(legacy.policy) &&
|
|
724
|
+
Number(legacy.policy) > 0 &&
|
|
725
|
+
config.policy.services.some((service) => service.kind === "ga4" && service.measurement_id === legacy.id)) {
|
|
726
|
+
void controller.decide(deniedChoices());
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
/* Invalid legacy storage grants nothing and does not suppress a fresh notice. */
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return controller;
|
|
734
|
+
}
|