@jini-ai/cookie-consent 0.6.15-rc.2 → 0.6.16
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/client/dom.js +19 -15
- package/dist/client/index.js +19 -24
- package/dist/client.min.d.ts +2 -0
- package/dist/client.min.js +1 -1
- package/dist/contracts/plugins.d.ts +15 -0
- package/dist/contracts/plugins.js +78 -0
- package/dist/contracts/policy.d.ts +47 -0
- package/dist/contracts/policy.js +96 -0
- package/dist/node/index.js +2 -2
- package/dist/plugins.d.ts +2 -14
- package/dist/plugins.js +2 -77
- package/dist/policy.d.ts +2 -46
- package/dist/policy.js +2 -94
- package/dist/render/banner.js +1 -1
- package/dist/render/base-css.js +1 -1
- package/dist/render/css-parser.js +6 -10
- package/dist/render/css.js +8 -4
- package/dist/server/receipt.js +3 -5
- package/package.json +8 -2
package/dist/client/dom.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/** @file DOM helpers for the browser client: cookies, storage purge, inert tags and the Jini banner binding.
|
|
2
2
|
* The Jini banner is a client of the public API, exactly like an owner's own ("My own") banner. */
|
|
3
3
|
import { OPEN_EVENT, OPTIONAL } from '../contract.js';
|
|
4
|
-
const
|
|
5
|
-
const SKIP = new Set(['type', 'data-src', 'data-type', 'data-consent-category']);
|
|
4
|
+
const SKIP = ['type', 'data-src', 'data-type', 'data-consent-category'];
|
|
6
5
|
// Not <html>: the client sets html[data-consent-open] while the banner shows, and every click's closest() would hit it.
|
|
7
6
|
const OPENERS = ':not(html)[data-consent-open],a[href="#privacy-choices"]';
|
|
8
7
|
/** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
|
|
@@ -17,14 +16,15 @@ export function readCookie(doc, name) {
|
|
|
17
16
|
}
|
|
18
17
|
export function writeCookie(doc, { name, value, maxAgeS }, { domain } = {}) {
|
|
19
18
|
const secure = doc.defaultView?.location.protocol === 'https:' ? '; Secure' : '';
|
|
20
|
-
doc.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.floor(maxAgeS)}; SameSite=Lax${secure}
|
|
19
|
+
doc.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.floor(maxAgeS)}; SameSite=Lax${secure}` + (domain ? '; Domain=' + domain : '');
|
|
21
20
|
}
|
|
22
21
|
/** Vendors set cookies on the registrable domain, so expire on the host and each parent domain. */
|
|
23
22
|
function expireEverywhere(doc, name) {
|
|
24
23
|
const parts = (doc.defaultView?.location.hostname ?? '').split('.');
|
|
25
|
-
|
|
24
|
+
const expired = `${name}=; Path=/; Max-Age=0`;
|
|
25
|
+
doc.cookie = expired;
|
|
26
26
|
for (let i = 0; i < parts.length - 1; i++)
|
|
27
|
-
doc.cookie = `${
|
|
27
|
+
doc.cookie = `${expired}; Domain=.${parts.slice(i).join('.')}`;
|
|
28
28
|
}
|
|
29
29
|
/** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. @complexity O(cookies + keys). */
|
|
30
30
|
export function purge(doc, storage) {
|
|
@@ -43,28 +43,32 @@ export function purge(doc, storage) {
|
|
|
43
43
|
}
|
|
44
44
|
catch { /* no storage: nothing to purge */ }
|
|
45
45
|
}
|
|
46
|
-
//
|
|
47
|
-
//
|
|
46
|
+
// Resource templates are owned by the CMS gate; consume its output rather than re-encoding subtrees.
|
|
47
|
+
// Follow-up (P4): delete the cms runtime once the consumer inserts this client.
|
|
48
48
|
/** Allowed inert tags become live, in authored order (async=false). Unknown labels stay inert.
|
|
49
49
|
* @complexity O(inert tags). */
|
|
50
50
|
export function activateInert(doc, { allowed, ran }) {
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
// One category guard handles legacy tags and CMS templates, including unlabelled resources.
|
|
52
|
+
doc.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(node => {
|
|
53
|
+
const content = node.content;
|
|
54
|
+
const category = (content ? node.dataset.category : node.dataset.consentCategory);
|
|
53
55
|
if (!OPTIONAL.includes(category) || !allowed[category])
|
|
54
56
|
return;
|
|
55
57
|
ran.add(category);
|
|
56
58
|
if (node.tagName === 'IFRAME') {
|
|
57
|
-
node.
|
|
59
|
+
node.src = node.dataset.src;
|
|
58
60
|
node.removeAttribute('data-src');
|
|
59
|
-
return;
|
|
60
61
|
}
|
|
61
|
-
|
|
62
|
+
else {
|
|
63
|
+
// Moving the fragment consumes the wrapper once and preserves the gate's markup and position.
|
|
64
|
+
node.replaceWith(content ?? liveScript(doc, node));
|
|
65
|
+
}
|
|
62
66
|
});
|
|
63
67
|
}
|
|
64
68
|
function liveScript(doc, inert) {
|
|
65
69
|
const s = doc.createElement('script');
|
|
66
|
-
for (const { name, value } of
|
|
67
|
-
if (!SKIP.
|
|
70
|
+
for (const { name, value } of inert.attributes)
|
|
71
|
+
if (!SKIP.includes(name))
|
|
68
72
|
s.setAttribute(name, value);
|
|
69
73
|
if (inert.nonce)
|
|
70
74
|
s.nonce = inert.nonce; // owner-set CSPs keep working
|
|
@@ -120,7 +124,7 @@ export function bindBanner({ api, doc }) {
|
|
|
120
124
|
show(false);
|
|
121
125
|
};
|
|
122
126
|
root.addEventListener('click', event => {
|
|
123
|
-
const action = event.target.closest?.('[data-consent-action]')?.
|
|
127
|
+
const action = event.target.closest?.('[data-consent-action]')?.dataset.consentAction;
|
|
124
128
|
if (!action)
|
|
125
129
|
return;
|
|
126
130
|
event.preventDefault();
|
package/dist/client/index.js
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
|
|
4
4
|
* unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
|
|
5
5
|
import { ADAPTER_KIND, CONFIG_ID, CONSENT_COOKIE, OPEN_EVENT, OPTIONAL, READY_EVENT, REGION_COOKIE, STATE_EVENT } from '../contract.js';
|
|
6
|
-
import { choicesFor, DAY_MS, effective, parseStored, RECEIPT_ID, regionFrom } from '../policy.js';
|
|
7
|
-
import { ADAPTER_SLOT, createPluginRegistry } from '../plugins.js';
|
|
6
|
+
import { choicesFor, DAY_MS, effective, parseStored, RECEIPT_ID, regionFrom } from '../contracts/policy.js';
|
|
7
|
+
import { ADAPTER_SLOT, createPluginRegistry } from '../contracts/plugins.js';
|
|
8
8
|
import { activateInert, installOpeners, purge, readCookie, waiting, writeCookie } from './dom.js';
|
|
9
9
|
const within = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);
|
|
10
10
|
const quiet = (fn) => { try {
|
|
@@ -15,7 +15,7 @@ catch { /* a broken plugin or listener never blocks consent */ } };
|
|
|
15
15
|
export function createCookieConsent({ config, ports }, options = {}) {
|
|
16
16
|
const { doc } = ports;
|
|
17
17
|
const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
|
|
18
|
-
const durable =
|
|
18
|
+
const durable = options.evidence?.mode === 'durable' ? options.evidence : null;
|
|
19
19
|
const slots = new Map();
|
|
20
20
|
const listeners = new Set();
|
|
21
21
|
const ran = new Set(); // categories whose raw inert tags executed
|
|
@@ -68,11 +68,9 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
68
68
|
const stops = [];
|
|
69
69
|
for (const slot of slots.values()) {
|
|
70
70
|
const allowed = anonymous ? next.analyticsLevel === 'anonymous' : next.allowed[slot.entry.category];
|
|
71
|
-
if (allowed)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
else if (slot.run)
|
|
71
|
+
if (allowed && !slot.run)
|
|
72
|
+
start(slot);
|
|
73
|
+
if (!allowed && slot.run)
|
|
76
74
|
stops.push(stop(slot));
|
|
77
75
|
quiet(() => slot.adapter?.onState?.({ state: next }));
|
|
78
76
|
}
|
|
@@ -106,7 +104,9 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
106
104
|
return;
|
|
107
105
|
if (typeof out?.id !== 'string' || !RECEIPT_ID.test(out.id))
|
|
108
106
|
return; // failed: q stays, retried at the next boot
|
|
109
|
-
|
|
107
|
+
// Keep the choice intact, replacing its pending marker with the confirmed receipt.
|
|
108
|
+
stored = { ...choice, r: out.id };
|
|
109
|
+
delete stored.q;
|
|
110
110
|
persist();
|
|
111
111
|
apply(); // the receipt is what lets durable grants run
|
|
112
112
|
}
|
|
@@ -154,7 +154,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
154
154
|
// A refused cookie write leaves only this tab's choice; absence cannot supersede it.
|
|
155
155
|
if (!latest && !cookiePersisted)
|
|
156
156
|
return false;
|
|
157
|
-
if (
|
|
157
|
+
if (latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r)
|
|
158
158
|
return false;
|
|
159
159
|
stored = latest;
|
|
160
160
|
apply();
|
|
@@ -173,17 +173,11 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
173
173
|
apply();
|
|
174
174
|
doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible')
|
|
175
175
|
adopt(); });
|
|
176
|
-
doc.defaultView?.addEventListener('pageshow',
|
|
176
|
+
doc.defaultView?.addEventListener('pageshow', adopt);
|
|
177
177
|
if (stored?.q && stored.p === config.policy)
|
|
178
178
|
void confirm(stored); // durable retry of an earlier failed receipt
|
|
179
179
|
return api;
|
|
180
180
|
}
|
|
181
|
-
function sameStoredChoice({ latest, stored }) {
|
|
182
|
-
return latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r;
|
|
183
|
-
}
|
|
184
|
-
function durableEvidence({ evidence }, _optional = {}) {
|
|
185
|
-
return evidence?.mode === 'durable' ? evidence : null;
|
|
186
|
-
}
|
|
187
181
|
export function browserPorts(win) {
|
|
188
182
|
return {
|
|
189
183
|
doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
|
|
@@ -204,20 +198,21 @@ function readPage(doc) {
|
|
|
204
198
|
export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
|
|
205
199
|
if (win.jiniConsent)
|
|
206
200
|
return win.jiniConsent;
|
|
207
|
-
const
|
|
201
|
+
const doc = win.document;
|
|
202
|
+
const page = readPage(doc);
|
|
208
203
|
if (!page)
|
|
209
204
|
return undefined;
|
|
210
|
-
|
|
211
|
-
const api = createCookieConsent({ config, ports }, { evidence });
|
|
205
|
+
// The parsed page already satisfies ClientConfig; avoid copying it just to omit evidence.
|
|
206
|
+
const api = createCookieConsent({ config: page, ports }, { evidence: page.evidence });
|
|
212
207
|
// Before boot the queue is a plain array; an already-replaced queue object has nothing left to drain.
|
|
213
208
|
const queued = Array.isArray(win.jiniConsentQueue) ? win.jiniConsentQueue : [];
|
|
214
209
|
win.jiniConsent = api;
|
|
215
210
|
win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
|
|
216
211
|
win.jiniConsentQueue.push(...queued);
|
|
217
|
-
installOpeners({ api, doc
|
|
218
|
-
if (
|
|
219
|
-
bindBanner?.({ api, doc
|
|
220
|
-
|
|
212
|
+
installOpeners({ api, doc });
|
|
213
|
+
if (page.banner === 'jini')
|
|
214
|
+
bindBanner?.({ api, doc });
|
|
215
|
+
doc.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
|
|
221
216
|
return api;
|
|
222
217
|
}
|
|
223
218
|
/** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
|
package/dist/client.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var R="jini_choices",H="jini_region",J="jini:consent",$="jini:consent-ready",O="jini:consent-open",B="jini-consent-config",h=["functional","analytics","marketing"],we=["necessary",...h],G=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var le='script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]',ue=new Set(["type","data-src","data-type","data-consent-category"]),de=':not(html)[data-consent-open],a[href="#privacy-choices"]';function T(e,t){let n=e.cookie.split(/;\s*/).find(o=>o.startsWith(t+"="));try{return n?decodeURIComponent(n.slice(t.length+1)):null}catch{return null}}function V(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let p=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${p}${r?`; Domain=${r}`:""}`}function pe(e,t){let n=(e.defaultView?.location.hostname??"").split(".");e.cookie=`${t}=; Path=/; Max-Age=0`;for(let o=0;o<n.length-1;o++)e.cookie=`${t}=; Path=/; Max-Age=0; Domain=.${n.slice(o).join(".")}`}function D(e,t){if(t){for(let n of e.cookie.split(/;\s*/)){let o=n.split("=")[0];t.cookies?.some(r=>o.startsWith(r))&&pe(e,o)}try{let n=e.defaultView.localStorage;for(let o of Object.keys(n))t.local?.some(r=>o.startsWith(r))&&n.removeItem(o)}catch{}}}function W(e,{allowed:t,ran:n}){e.querySelectorAll(le).forEach(o=>{let r=o.dataset.consentCategory;if(!(!h.includes(r)||!t[r])){if(n.add(r),o.tagName==="IFRAME"){o.setAttribute("src",o.dataset.src),o.removeAttribute("data-src");return}o.replaceWith(fe(e,o))}})}function fe(e,t){let n=e.createElement("script");for(let{name:o,value:r}of Array.from(t.attributes))ue.has(o)||n.setAttribute(o,r);return t.nonce&&(n.nonce=t.nonce),t.dataset.type&&(n.type=t.dataset.type),t.dataset.src?n.src=t.dataset.src:n.text=t.text,n.async=!1,n}function z({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(de)&&(n.preventDefault(),e.open())})}function ge(e){let t={};for(let n of h){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function N(e,t){for(let n of h){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var k=e=>h.some(t=>e.choices[t]&&!e.allowed[t]);function Q({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),r=s=>{n.hidden=!s,e.setOpen({open:s})},p=s=>{o&&(o.hidden=!k(s)),k(s)||r(!1)};n.addEventListener("click",s=>{let m=s.target.closest?.("[data-consent-action]")?.getAttribute("data-consent-action");m&&(s.preventDefault(),e.set({action:m},{choices:ge(n)}).then(p))}),n.addEventListener("keydown",s=>{s.key==="Escape"&&e.get().status==="set"&&r(!1)}),t.addEventListener(O,()=>{N(n,e.get()),r(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:s=>{N(n,s),o&&!o.hidden&&!k(s)&&p(s)}}),N(n,e.get()),r(e.get().status==="pending")}var _=864e5,ye=180*_,me=6e4,M=/^[\w-]{16,128}$/,Y=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function U({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var x=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function X({action:e,picked:t={}},n={}){return e==="accept"?x(!0):e==="save"?x(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?x(t.functional!==!1,!1):x(!1)}function Ce({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function Z({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:p=ye,durable:s=!1,anonymous:m=!1}={}){let C=be({stored:e,policy:t,nowMs:r,maxAgeMs:p,anonymous:m}),f=Ce({flags:m?Y:C?.c??x(n==="opt-out"),gpc:o}),v={contract:1,policy:t,region:n,gpc:o,choices:f,...Se({choices:f,live:C,durable:s,anonymous:m,gpc:o})};return C?{...v,status:"set",action:C.a,at:C.t,receipt:he(C)}:{...v,status:"pending",action:null,at:null,receipt:"none"}}function be({stored:e,policy:t,nowMs:n,maxAgeMs:o,anonymous:r}){return!r&&e&&e.p===t&&e.t<=n+me&&n-e.t<=o?e:null}function Se({choices:e,live:t,durable:n,anonymous:o,gpc:r},p={}){let s=o||t&&n&&!t.r?Y:e;return{allowed:s,analyticsLevel:o&&!r?"anonymous":s.analytics?"full":"none"}}function he(e){return e.r?"stored":e.q?"pending":"local"}function ee({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!ve(n))return null;let o={v:1,p:n.p,c:x(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&M.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function ve(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:G.includes(e.a)&&Ae(e.c)}function Ae(e){let t=e;return!!t&&typeof t=="object"&&typeof t.functional=="boolean"&&typeof t.analytics=="boolean"&&typeof t.marketing=="boolean"}var xe=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function te(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],p=new Set,s=new Set,m=a=>r.filter(c=>c.kind===a).sort((c,l)=>l.priority-c.priority).map(c=>c.value),C=a=>s.forEach(c=>{if(c.kind===a)try{c.fn(m(a))}catch{}});function f(a,c){let l=S=>(n({id:String(a.id),kind:a.kind,reason:S,...c.source?{source:c.source}:{}}),()=>{});if(!xe.test(String(a.id)))return l("short lowercase id");let A=o.get(a.kind).accept({contribution:a});if(typeof A=="string")return l(A);if(r.some(S=>S.kind===a.kind&&S.id===a.id))return l("duplicate id");let b={kind:a.kind,id:a.id,value:A,priority:c.priority??0};return r.push(b),C(a.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),C(a.kind))}}let v={defineSlot({slot:a}){if(!o.has(a.kind)){o.set(a.kind,a);for(let c of p)c.raw.kind===a.kind&&(p.delete(c),c.dispose=f(c.raw,c.options))}},registerPlugin(a,c={}){if(o.has(a.kind))return f(a,c);let l={raw:a,options:c,dispose:()=>{p.delete(l)}};return p.add(l),()=>l.dispose()},list:({kind:a})=>m(a),subscribe({kind:a,listener:c}){let l={kind:a,fn:c};return s.add(l),()=>{s.delete(l)}}};for(let a of t)v.defineSlot({slot:a});return v}var ne={kind:P,accept({contribution:e}){return h.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),w=e=>{try{e()}catch{}};function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??te({},{slots:[ne]}),p=Re(n),s=new Map,m=new Set,C=new Set,f=e.banner==="off",v=(e.maxAgeDays??180)*_,a=U({configured:e.regionMode,hint:f?null:T(o,H)}),c=()=>f?null:ee({raw:T(o,R)}),l=c(),A=!0,b=S();function S(){return Z({stored:l,policy:e.policy,region:a,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!p,anonymous:f})}function L(){let i=JSON.stringify(l);V(o,{name:R,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),A=T(o,R)===i}function j(i){i.generation++;let d=new AbortController,u=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(y=>i.adapter=y.default)).then(y=>(w(()=>y.onState?.({state:b})),d.signal.aborted||f&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>y.grant({config:i.entry.config??y.config,state:b,signal:d.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:d,result:u}}async function q(i){let d=i.run,g=i.generation;i.run=void 0,d.ctl.abort();let u=await d.result;if(!u)return!1;let y=await Promise.resolve().then(()=>u.revoke?.()).catch(()=>!1);return!f&&i.generation===g&&D(o,i.adapter?.storage??i.entry.storage),!y}function ie(i){let d=[];for(let u of s.values())(f?i.analyticsLevel==="anonymous":i.allowed[u.entry.category])?u.run||j(u):u.run&&d.push(q(u)),w(()=>u.adapter?.onState?.({state:i}));f||W(o,{allowed:i.allowed,ran:C});let g=h.some(u=>C.has(u)&&!i.allowed[u]);Promise.all(d).then(u=>{(g||u.includes(!0))&&t.reload()})}function E(){let i=b=S(),d=o.documentElement;return d.dataset.consent=i.status,d.dataset.consentRegion=i.region,d.toggleAttribute("data-consent-gpc",i.gpc),ie(i),m.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent(J,{detail:i})),i}async function F(i,d){if(!p)return;let g=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:d}),u=await t.fetch(p.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:g}).catch(()=>null),y=u?.ok?await u.json().catch(()=>null):null;l!==i||I()||typeof y?.id!="string"||!M.test(y.id)||(l={v:1,p:i.p,c:i.c,t:i.t,a:i.a,r:y.id},L(),E())}async function re({action:i},{choices:d={}}={}){if(f)return E();let g=l?.r;l={v:1,p:e.policy,c:X({action:i,picked:d}),t:t.now(),a:i,...p?{q:1}:{}},L();let u=E(),y=F(l,g);return p&&k(u)&&await Ee(y,p.waitMs??1500),b}function se(i){if(f&&(!i.supportsAnonymous||i.category!=="analytics"))return;let d={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};s.set(i.id,d),f||b.allowed[i.category]?j(d):D(o,i.storage),w(()=>d.adapter?.onState?.({state:b}))}function K(i){let d=new Set(i.map(g=>g.id));for(let[g,u]of s)d.has(g)||(s.delete(g),u.run&&q(u).then(y=>{y&&t.reload()}));for(let g of i)s.has(g.id)||se(g)}function I(){let i=c();return!i&&!A||ke({latest:i,stored:l})?!1:(l=i,E(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(m.add(i),()=>{m.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:K}),K(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),E(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",()=>I()),l?.q&&l.p===e.policy&&F(l),ae}function ke({latest:e,stored:t}){return e?.t===t?.t&&e?.a===t?.a&&e?.r===t?.r}function Re({evidence:e},t={}){return e?.mode==="durable"?e:null}function Oe(e){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:t=>import(t)}}function Te(e){try{return JSON.parse(e.getElementById(B)?.textContent??"")}catch{return null}}function oe(e=window,{ports:t=Oe(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=Te(e.document);if(!o)return;let{evidence:r,...p}=o,s=Pe({config:p,ports:t},{evidence:r}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=s,e.jiniConsentQueue={push:(...C)=>C.forEach(f=>s.plugins.registerPlugin(f,{source:"queue"}))},e.jiniConsentQueue.push(...m),z({api:s,doc:e.document}),p.banner==="jini"&&n?.({api:s,doc:e.document}),e.document.dispatchEvent(new CustomEvent($,{detail:s})),s}oe(window,{bindBanner:Q});})();
|
|
1
|
+
"use strict";(()=>{var R="jini_choices",B="jini_region",G="jini:consent",V="jini:consent-ready",O="jini:consent-open",$="jini-consent-config",v=["functional","analytics","marketing"],ke=["necessary",...v],W=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var N=864e5,le=180*N,ue=6e4,D=/^[\w-]{16,128}$/,z=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function Q({configured:e,hint:n},t={}){return e!=="auto"?e:n==="us"?"opt-out":"opt-in"}var x=(e,n=e,t=n)=>({functional:e,analytics:n,marketing:t});function Y({action:e,picked:n={}},t={}){return e==="accept"?x(!0):e==="save"?x(n.functional===!0,n.analytics===!0,n.marketing===!0):e==="do-not-sell"?x(n.functional!==!1,!1):x(!1)}function de({flags:e,gpc:n},t={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!n,marketing:e.marketing&&!n}}function U({stored:e,policy:n,region:t,gpc:o,nowMs:r},{maxAgeMs:a=le,durable:c=!1,anonymous:f=!1}={}){let m=!f&&e&&e.p===n&&e.t<=r+ue&&r-e.t<=a?e:null,C=de({flags:f?z:m?.c??x(t==="opt-out"),gpc:o}),h={contract:1,policy:n,region:t,gpc:o,choices:C,...pe({choices:C,live:m,durable:c,anonymous:f,gpc:o})};return m?{...h,status:"set",action:m.a,at:m.t,receipt:fe(m)}:{...h,status:"pending",action:null,at:null,receipt:"none"}}function pe({choices:e,live:n,durable:t,anonymous:o,gpc:r},a={}){let c=n&&t&&!n.r,f=o||c?z:e,m=f.analytics?"full":"none";return{allowed:f,analyticsLevel:o&&!r?"anonymous":m}}function fe(e){return e.r?"stored":e.q?"pending":"local"}function X({raw:e},n={}){if(!e||e.length>1024)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!ge(t))return null;let o={v:1,p:t.p,c:x(t.c.functional,t.c.analytics,t.c.marketing),t:t.t,a:t.a};return typeof t.r=="string"&&D.test(t.r)&&(o.r=t.r),t.q===1&&(o.q=1),o}function ge(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:W.includes(e.a)&&ye(e.c)}function ye(e){let n=e;return!n||typeof n!="object"?!1:["functional","analytics","marketing"].every(t=>Object.hasOwn(n,t)&&typeof n[t]=="boolean")}var me=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:n=[],onProblem:t=()=>{}}={}){let o=new Map,r=[],a=new Set,c=new Set,f=s=>r.filter(u=>u.kind===s).sort((u,l)=>l.priority-u.priority).map(u=>u.value),m=s=>c.forEach(u=>{if(u.kind===s)try{u.fn(f(s))}catch{}});function C(s,u){let l=S=>(t({id:String(s.id),kind:s.kind,reason:S,...u.source?{source:u.source}:{}}),()=>{});if(!me.test(String(s.id)))return l("short lowercase id");let E=o.get(s.kind).accept({contribution:s});if(typeof E=="string")return l(E);if(r.some(S=>S.kind===s.kind&&S.id===s.id))return l("duplicate id");let b={kind:s.kind,id:s.id,value:E,priority:u.priority??0};return r.push(b),m(s.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),m(s.kind))}}let h={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let u of a)u.raw.kind===s.kind&&(a.delete(u),u.dispose=C(u.raw,u.options))}},registerPlugin(s,u={}){if(o.has(s.kind))return C(s,u);let l={raw:s,options:u,dispose:()=>{a.delete(l)}};return a.add(l),()=>l.dispose()},list:({kind:s})=>f(s),subscribe({kind:s,listener:u}){let l={kind:s,fn:u};return c.add(l),()=>{c.delete(l)}}};for(let s of n)h.defineSlot({slot:s});return h}var ee={kind:P,accept({contribution:e}){return v.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var Ce=["type","data-src","data-type","data-consent-category"],be=':not(html)[data-consent-open],a[href="#privacy-choices"]';function T(e,n){let t=e.cookie.split(/;\s*/).find(o=>o.startsWith(n+"="));try{return t?decodeURIComponent(t.slice(n.length+1)):null}catch{return null}}function te(e,{name:n,value:t,maxAgeS:o},{domain:r}={}){let a=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${n}=${encodeURIComponent(t)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${a}`+(r?"; Domain="+r:"")}function Se(e,n){let t=(e.defaultView?.location.hostname??"").split("."),o=`${n}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<t.length-1;r++)e.cookie=`${o}; Domain=.${t.slice(r).join(".")}`}function M(e,n){if(n){for(let t of e.cookie.split(/;\s*/)){let o=t.split("=")[0];n.cookies?.some(r=>o.startsWith(r))&&Se(e,o)}try{let t=e.defaultView.localStorage;for(let o of Object.keys(t))n.local?.some(r=>o.startsWith(r))&&t.removeItem(o)}catch{}}}function ne(e,{allowed:n,ran:t}){e.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(o=>{let r=o.content,a=r?o.dataset.category:o.dataset.consentCategory;!v.includes(a)||!n[a]||(t.add(a),o.tagName==="IFRAME"?(o.src=o.dataset.src,o.removeAttribute("data-src")):o.replaceWith(r??ve(e,o)))})}function ve(e,n){let t=e.createElement("script");for(let{name:o,value:r}of n.attributes)Ce.includes(o)||t.setAttribute(o,r);return n.nonce&&(t.nonce=n.nonce),n.dataset.type&&(t.type=n.dataset.type),n.dataset.src?t.src=n.dataset.src:t.text=n.text,t.async=!1,t}function L({api:e,doc:n}){n.addEventListener("click",t=>{t.target.closest?.(be)&&(t.preventDefault(),e.open())})}function he(e){let n={};for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(n[t]=o.checked)}return n}function _(e,n){for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(o.checked=n.choices[t],o.disabled=n.gpc&&t!=="functional")}}var k=e=>v.some(n=>e.choices[n]&&!e.allowed[n]);function j({api:e,doc:n}){let t=n.getElementById("jini-consent");if(!t)return;let o=t.querySelector("[data-consent-error]"),r=c=>{t.hidden=!c,e.setOpen({open:c})},a=c=>{o&&(o.hidden=!k(c)),k(c)||r(!1)};t.addEventListener("click",c=>{let f=c.target.closest?.("[data-consent-action]")?.dataset.consentAction;f&&(c.preventDefault(),e.set({action:f},{choices:he(t)}).then(a))}),t.addEventListener("keydown",c=>{c.key==="Escape"&&e.get().status==="set"&&r(!1)}),n.addEventListener(O,()=>{_(t,e.get()),r(!0),t.querySelector("button")?.focus()}),e.subscribe({listener:c=>{_(t,c),o&&!o.hidden&&!k(c)&&a(c)}}),_(t,e.get()),r(e.get().status==="pending")}var Ee=(e,n)=>Promise.race([e,new Promise(t=>setTimeout(t,n))]),w=e=>{try{e()}catch{}};function xe({config:e,ports:n},t={}){let{doc:o}=n,r=t.plugins??Z({},{slots:[ee]}),a=t.evidence?.mode==="durable"?t.evidence:null,c=new Map,f=new Set,m=new Set,C=e.banner==="off",h=(e.maxAgeDays??180)*N,s=Q({configured:e.regionMode,hint:C?null:T(o,B)}),u=()=>C?null:X({raw:T(o,R)}),l=u(),E=!0,b=S();function S(){return U({stored:l,policy:e.policy,region:s,gpc:n.gpc(),nowMs:n.now()},{maxAgeMs:h,durable:!!a,anonymous:C})}function q(){let i=JSON.stringify(l);te(o,{name:R,value:i,maxAgeS:h/1e3},{domain:e.cookieDomain}),E=T(o,R)===i}function F(i){i.generation++;let p=new AbortController,d=Promise.resolve(i.adapter??n.importModule(i.entry.src).then(y=>i.adapter=y.default)).then(y=>(w(()=>y.onState?.({state:b})),p.signal.aborted||C&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>y.grant({config:i.entry.config??y.config,state:b,signal:p.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:p,result:d}}async function K(i){let p=i.run,g=i.generation;i.run=void 0,p.ctl.abort();let d=await p.result;if(!d)return!1;let y=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!C&&i.generation===g&&M(o,i.adapter?.storage??i.entry.storage),!y}function ie(i){let p=[];for(let d of c.values()){let y=C?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];y&&!d.run&&F(d),!y&&d.run&&p.push(K(d)),w(()=>d.adapter?.onState?.({state:i}))}C||ne(o,{allowed:i.allowed,ran:m});let g=v.some(d=>m.has(d)&&!i.allowed[d]);Promise.all(p).then(d=>{(g||d.includes(!0))&&n.reload()})}function A(){let i=b=S(),p=o.documentElement;return p.dataset.consent=i.status,p.dataset.consentRegion=i.region,p.toggleAttribute("data-consent-gpc",i.gpc),ie(i),f.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent(G,{detail:i})),i}async function H(i,p){if(!a)return;let g=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:n.gpc(),previousId:p}),d=await n.fetch(a.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:g}).catch(()=>null),y=d?.ok?await d.json().catch(()=>null):null;l!==i||I()||typeof y?.id!="string"||!D.test(y.id)||(l={...i,r:y.id},delete l.q,q(),A())}async function re({action:i},{choices:p={}}={}){if(C)return A();let g=l?.r;l={v:1,p:e.policy,c:Y({action:i,picked:p}),t:n.now(),a:i,...a?{q:1}:{}},q();let d=A(),y=H(l,g);return a&&k(d)&&await Ee(y,a.waitMs??1500),b}function se(i){if(C&&(!i.supportsAnonymous||i.category!=="analytics"))return;let p={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};c.set(i.id,p),C||b.allowed[i.category]?F(p):M(o,i.storage),w(()=>p.adapter?.onState?.({state:b}))}function J(i){let p=new Set(i.map(g=>g.id));for(let[g,d]of c)p.has(g)||(c.delete(g),d.run&&K(d).then(y=>{y&&n.reload()}));for(let g of i)c.has(g.id)||se(g)}function I(){let i=u();return!i&&!E||i?.t===l?.t&&i?.a===l?.a&&i?.r===l?.r?!1:(l=i,A(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(f.add(i),()=>{f.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:J}),J(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),A(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",I),l?.q&&l.p===e.policy&&H(l),ae}function Ae(e){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:n=>import(n)}}function Pe(e){try{return JSON.parse(e.getElementById($)?.textContent??"")}catch{return null}}function oe(e=window,{ports:n=Ae(e),bindBanner:t}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=Pe(o);if(!r)return;let a=xe({config:r,ports:n},{evidence:r.evidence}),c=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=a,e.jiniConsentQueue={push:(...f)=>f.forEach(m=>a.plugins.registerPlugin(m,{source:"queue"}))},e.jiniConsentQueue.push(...c),L({api:a,doc:o}),r.banner==="jini"&&t?.({api:a,doc:o}),o.dispatchEvent(new CustomEvent(V,{detail:a})),a}oe(window,{bindBanner:j});})();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** @file Generic plugin registry: universal, no DOM, no Node. Any package can add a slot kind with
|
|
2
|
+
* defineSlot(); contributions to kinds this build doesn't know wait instead of failing, so a new kind
|
|
3
|
+
* (a tracker signature, a consent log sink, ...) never needs a change here. */
|
|
4
|
+
import { type AdapterContribution, type PluginRegistry, type SlotKind, type SlotProblem } from '../contract.js';
|
|
5
|
+
type RegistryOptions = {
|
|
6
|
+
slots?: readonly SlotKind[];
|
|
7
|
+
onProblem?: (problem: SlotProblem) => void;
|
|
8
|
+
};
|
|
9
|
+
/** @example createPluginRegistry({}, { slots: [ADAPTER_SLOT], onProblem: report })
|
|
10
|
+
* @complexity O(n log n) per list(); O(parked) per defineSlot(). Registries hold a handful of entries. */
|
|
11
|
+
export declare function createPluginRegistry(_required?: object, { slots, onProblem }?: RegistryOptions): PluginRegistry;
|
|
12
|
+
/** The browser consent-adapter slot: a live adapter (grant()) or a lazy one (module src). */
|
|
13
|
+
export declare const ADAPTER_SLOT: SlotKind<AdapterContribution>;
|
|
14
|
+
export {};
|
|
15
|
+
//# sourceMappingURL=plugins.d.ts.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** @file Generic plugin registry: universal, no DOM, no Node. Any package can add a slot kind with
|
|
2
|
+
* defineSlot(); contributions to kinds this build doesn't know wait instead of failing, so a new kind
|
|
3
|
+
* (a tracker signature, a consent log sink, ...) never needs a change here. */
|
|
4
|
+
import { ADAPTER_KIND, OPTIONAL } from '../contract.js';
|
|
5
|
+
const ID = /^[a-z0-9][a-z0-9._:-]{0,63}$/;
|
|
6
|
+
/** @example createPluginRegistry({}, { slots: [ADAPTER_SLOT], onProblem: report })
|
|
7
|
+
* @complexity O(n log n) per list(); O(parked) per defineSlot(). Registries hold a handful of entries. */
|
|
8
|
+
export function createPluginRegistry(_required = {}, { slots = [], onProblem = () => undefined } = {}) {
|
|
9
|
+
const kinds = new Map();
|
|
10
|
+
const held = [];
|
|
11
|
+
const parked = new Set();
|
|
12
|
+
const listeners = new Set();
|
|
13
|
+
const list = (kind) => held.filter(h => h.kind === kind).sort((a, b) => b.priority - a.priority).map(h => h.value);
|
|
14
|
+
const emit = (kind) => listeners.forEach(l => { if (l.kind === kind)
|
|
15
|
+
try {
|
|
16
|
+
l.fn(list(kind));
|
|
17
|
+
}
|
|
18
|
+
catch { /* isolate */ } });
|
|
19
|
+
/** Duplicate ids are refused, never guessed (same rule as the host's contribution loaders). */
|
|
20
|
+
function admit(raw, options) {
|
|
21
|
+
const refuse = (reason) => { onProblem({ id: String(raw.id), kind: raw.kind, reason, ...(options.source ? { source: options.source } : {}) }); return () => undefined; };
|
|
22
|
+
if (!ID.test(String(raw.id)))
|
|
23
|
+
return refuse('short lowercase id');
|
|
24
|
+
const value = kinds.get(raw.kind).accept({ contribution: raw });
|
|
25
|
+
if (typeof value === 'string')
|
|
26
|
+
return refuse(value);
|
|
27
|
+
if (held.some(h => h.kind === raw.kind && h.id === raw.id))
|
|
28
|
+
return refuse('duplicate id');
|
|
29
|
+
const entry = { kind: raw.kind, id: raw.id, value, priority: options.priority ?? 0 };
|
|
30
|
+
held.push(entry);
|
|
31
|
+
emit(raw.kind);
|
|
32
|
+
return () => { const at = held.indexOf(entry); if (at >= 0) {
|
|
33
|
+
held.splice(at, 1);
|
|
34
|
+
emit(raw.kind);
|
|
35
|
+
} };
|
|
36
|
+
}
|
|
37
|
+
const registry = {
|
|
38
|
+
defineSlot({ slot }) {
|
|
39
|
+
if (kinds.has(slot.kind))
|
|
40
|
+
return;
|
|
41
|
+
kinds.set(slot.kind, slot);
|
|
42
|
+
for (const item of parked) {
|
|
43
|
+
if (item.raw.kind !== slot.kind)
|
|
44
|
+
continue;
|
|
45
|
+
parked.delete(item);
|
|
46
|
+
item.dispose = admit(item.raw, item.options); // the caller's disposer now removes the admitted entry
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
registerPlugin(raw, options = {}) {
|
|
50
|
+
if (kinds.has(raw.kind))
|
|
51
|
+
return admit(raw, options);
|
|
52
|
+
const item = { raw, options, dispose: () => { parked.delete(item); } };
|
|
53
|
+
parked.add(item);
|
|
54
|
+
return () => item.dispose();
|
|
55
|
+
},
|
|
56
|
+
list: ({ kind }) => list(kind),
|
|
57
|
+
subscribe({ kind, listener }) {
|
|
58
|
+
const entry = { kind, fn: listener };
|
|
59
|
+
listeners.add(entry);
|
|
60
|
+
return () => { listeners.delete(entry); };
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
for (const slot of slots)
|
|
64
|
+
registry.defineSlot({ slot });
|
|
65
|
+
return registry;
|
|
66
|
+
}
|
|
67
|
+
/** The browser consent-adapter slot: a live adapter (grant()) or a lazy one (module src). */
|
|
68
|
+
export const ADAPTER_SLOT = {
|
|
69
|
+
kind: ADAPTER_KIND,
|
|
70
|
+
accept({ contribution: c }) {
|
|
71
|
+
if (!OPTIONAL.includes(c.category))
|
|
72
|
+
return 'category must be functional, analytics or marketing';
|
|
73
|
+
if (typeof c.grant === 'function' || typeof c.src === 'string')
|
|
74
|
+
return c;
|
|
75
|
+
return 'grant() or src needed';
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
//# sourceMappingURL=plugins.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** @file The one consent rule, shared by the browser client and the server so they can never disagree.
|
|
2
|
+
* Pure functions: no DOM, no Node. */
|
|
3
|
+
import { type Choices, type ConsentAction, type ConsentState, type Flags, type RegionMode, type StoredChoice } from '../contract.js';
|
|
4
|
+
export declare const DAY_MS = 86400000;
|
|
5
|
+
export declare const DEFAULT_MAX_AGE_MS: number;
|
|
6
|
+
/** Receipt ids keep the cms receipt-file rule, so ids can never navigate out of a receipt directory. */
|
|
7
|
+
export declare const RECEIPT_ID: RegExp;
|
|
8
|
+
export declare const DENIED: Choices;
|
|
9
|
+
/** Only the literal hint 'us' loosens; anything else, including absence, is strict. @complexity O(1). */
|
|
10
|
+
export declare function regionFrom({ configured, hint }: {
|
|
11
|
+
configured: 'auto' | RegionMode;
|
|
12
|
+
hint: string | null | undefined;
|
|
13
|
+
}, _optional?: {}): RegionMode;
|
|
14
|
+
/** What a button press means. Unknown picks are false. @complexity O(1). */
|
|
15
|
+
export declare function choicesFor({ action, picked }: {
|
|
16
|
+
action: ConsentAction;
|
|
17
|
+
picked?: Partial<Flags>;
|
|
18
|
+
}, _optional?: {}): Flags;
|
|
19
|
+
/** GPC wins over stored or new grants for every category that can share data; nothing can lift it. @complexity O(1). */
|
|
20
|
+
export declare function clamp({ flags, gpc }: {
|
|
21
|
+
flags: Flags;
|
|
22
|
+
gpc: boolean;
|
|
23
|
+
}, _optional?: {}): Choices;
|
|
24
|
+
/** Region default, policy-version + age expiry, GPC clamp, and (durable mode) no grant without a receipt.
|
|
25
|
+
* A region default with no stored choice (the opt-out model) is never "waiting", so it runs as configured.
|
|
26
|
+
* Anonymous delivery ignores stored grants; its level permits only anonymous-capable adapters, subject to the privacy signal.
|
|
27
|
+
* @example effective({ stored, policy: '2026-10-26', region: 'opt-in', gpc: false, nowMs: Date.now() }, { durable: true })
|
|
28
|
+
* @complexity O(1). */
|
|
29
|
+
export declare function effective({ stored, policy, region, gpc, nowMs }: {
|
|
30
|
+
stored: StoredChoice | null;
|
|
31
|
+
policy: string;
|
|
32
|
+
region: RegionMode;
|
|
33
|
+
gpc: boolean;
|
|
34
|
+
nowMs: number;
|
|
35
|
+
}, { maxAgeMs, durable, anonymous }?: {
|
|
36
|
+
maxAgeMs?: number;
|
|
37
|
+
durable?: boolean;
|
|
38
|
+
anonymous?: boolean;
|
|
39
|
+
}): ConsentState;
|
|
40
|
+
/** Trust boundary for the cookie: anything malformed is "no choice". Only known fields are copied out.
|
|
41
|
+
* @complexity O(raw length ≤ 1 KiB). */
|
|
42
|
+
export declare function parseStored({ raw }: {
|
|
43
|
+
raw: string | null | undefined;
|
|
44
|
+
}, _optional?: {}): StoredChoice | null;
|
|
45
|
+
/** Own booleans only: truthy strings never count as a grant. @complexity O(1). */
|
|
46
|
+
export declare function isFlags(c: unknown): c is Flags;
|
|
47
|
+
//# sourceMappingURL=policy.d.ts.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** @file The one consent rule, shared by the browser client and the server so they can never disagree.
|
|
2
|
+
* Pure functions: no DOM, no Node. */
|
|
3
|
+
// MOVED-FROM: @jini-ai/cms consent/policy.ts (resolveConsentRegion, resolveConsentChoices, readConsentRecord,
|
|
4
|
+
// createConsentRecord). Follow-up (P4): delete the cms copies once the consumer reads this package.
|
|
5
|
+
import { ACTIONS } from '../contract.js';
|
|
6
|
+
export const DAY_MS = 86_400_000;
|
|
7
|
+
export const DEFAULT_MAX_AGE_MS = 180 * DAY_MS;
|
|
8
|
+
/** A receipt time comes from the server clock and is compared with the client clock; allow a minute. */
|
|
9
|
+
const SKEW_MS = 60_000;
|
|
10
|
+
/** Receipt ids keep the cms receipt-file rule, so ids can never navigate out of a receipt directory. */
|
|
11
|
+
export const RECEIPT_ID = /^[\w-]{16,128}$/;
|
|
12
|
+
export const DENIED = Object.freeze({ necessary: true, functional: false, analytics: false, marketing: false });
|
|
13
|
+
/** Only the literal hint 'us' loosens; anything else, including absence, is strict. @complexity O(1). */
|
|
14
|
+
export function regionFrom({ configured, hint }, _optional = {}) {
|
|
15
|
+
if (configured !== 'auto')
|
|
16
|
+
return configured;
|
|
17
|
+
return hint === 'us' ? 'opt-out' : 'opt-in';
|
|
18
|
+
}
|
|
19
|
+
const flags = (functional, analytics = functional, marketing = analytics) => ({ functional, analytics, marketing });
|
|
20
|
+
/** What a button press means. Unknown picks are false. @complexity O(1). */
|
|
21
|
+
export function choicesFor({ action, picked = {} }, _optional = {}) {
|
|
22
|
+
if (action === 'accept')
|
|
23
|
+
return flags(true);
|
|
24
|
+
if (action === 'save')
|
|
25
|
+
return flags(picked.functional === true, picked.analytics === true, picked.marketing === true);
|
|
26
|
+
// Do-not-sell keeps functional unless explicitly unticked: it is a sale/share refusal, not a reject.
|
|
27
|
+
if (action === 'do-not-sell')
|
|
28
|
+
return flags(picked.functional !== false, false);
|
|
29
|
+
return flags(false); // reject, withdraw
|
|
30
|
+
}
|
|
31
|
+
/** GPC wins over stored or new grants for every category that can share data; nothing can lift it. @complexity O(1). */
|
|
32
|
+
export function clamp({ flags, gpc }, _optional = {}) {
|
|
33
|
+
return { necessary: true, functional: flags.functional, analytics: flags.analytics && !gpc, marketing: flags.marketing && !gpc };
|
|
34
|
+
}
|
|
35
|
+
/** Region default, policy-version + age expiry, GPC clamp, and (durable mode) no grant without a receipt.
|
|
36
|
+
* A region default with no stored choice (the opt-out model) is never "waiting", so it runs as configured.
|
|
37
|
+
* Anonymous delivery ignores stored grants; its level permits only anonymous-capable adapters, subject to the privacy signal.
|
|
38
|
+
* @example effective({ stored, policy: '2026-10-26', region: 'opt-in', gpc: false, nowMs: Date.now() }, { durable: true })
|
|
39
|
+
* @complexity O(1). */
|
|
40
|
+
export function effective({ stored, policy, region, gpc, nowMs }, { maxAgeMs = DEFAULT_MAX_AGE_MS, durable = false, anonymous = false } = {}) {
|
|
41
|
+
// Banner-off never revives an old identity or consent grant, even in an opt-out region.
|
|
42
|
+
// Policy mismatch, future (beyond skew) and expired choices are all stale.
|
|
43
|
+
const live = !anonymous && stored && stored.p === policy && stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
|
|
44
|
+
const choices = clamp({ flags: anonymous ? DENIED : live?.c ?? flags(region === 'opt-out'), gpc });
|
|
45
|
+
const base = { contract: 1, policy, region, gpc, choices, ...permissionFor({ choices, live, durable, anonymous, gpc }) };
|
|
46
|
+
if (!live)
|
|
47
|
+
return { ...base, status: 'pending', action: null, at: null, receipt: 'none' };
|
|
48
|
+
return { ...base, status: 'set', action: live.a, at: live.t, receipt: receiptOf(live) };
|
|
49
|
+
}
|
|
50
|
+
/** Runtime permissions differ from choices for anonymous delivery and unconfirmed durable grants.
|
|
51
|
+
* @complexity O(1). */
|
|
52
|
+
function permissionFor({ choices, live, durable, anonymous, gpc }, _optional = {}) {
|
|
53
|
+
const unconfirmed = live && durable && !live.r;
|
|
54
|
+
const allowed = anonymous || unconfirmed ? DENIED : choices;
|
|
55
|
+
const analyticsLevel = allowed.analytics ? 'full' : 'none';
|
|
56
|
+
return { allowed, analyticsLevel: anonymous && !gpc ? 'anonymous' : analyticsLevel };
|
|
57
|
+
}
|
|
58
|
+
function receiptOf(stored) {
|
|
59
|
+
if (stored.r)
|
|
60
|
+
return 'stored';
|
|
61
|
+
return stored.q ? 'pending' : 'local';
|
|
62
|
+
}
|
|
63
|
+
/** Trust boundary for the cookie: anything malformed is "no choice". Only known fields are copied out.
|
|
64
|
+
* @complexity O(raw length ≤ 1 KiB). */
|
|
65
|
+
export function parseStored({ raw }, _optional = {}) {
|
|
66
|
+
if (!raw || raw.length > 1024)
|
|
67
|
+
return null;
|
|
68
|
+
let s;
|
|
69
|
+
try {
|
|
70
|
+
s = JSON.parse(raw);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if (!isStored(s))
|
|
76
|
+
return null;
|
|
77
|
+
const out = { v: 1, p: s.p, c: flags(s.c.functional, s.c.analytics, s.c.marketing), t: s.t, a: s.a };
|
|
78
|
+
if (typeof s.r === 'string' && RECEIPT_ID.test(s.r))
|
|
79
|
+
out.r = s.r;
|
|
80
|
+
if (s.q === 1)
|
|
81
|
+
out.q = 1;
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function isStored(s) {
|
|
85
|
+
if (!s || s.v !== 1 || typeof s.p !== 'string' || !Number.isFinite(s.t))
|
|
86
|
+
return false;
|
|
87
|
+
return ACTIONS.includes(s.a) && isFlags(s.c);
|
|
88
|
+
}
|
|
89
|
+
/** Own booleans only: truthy strings never count as a grant. @complexity O(1). */
|
|
90
|
+
export function isFlags(c) {
|
|
91
|
+
const f = c;
|
|
92
|
+
if (!f || typeof f !== 'object')
|
|
93
|
+
return false;
|
|
94
|
+
return ['functional', 'analytics', 'marketing'].every(key => Object.hasOwn(f, key) && typeof f[key] === 'boolean');
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=policy.js.map
|
package/dist/node/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// MOVED-FROM: @jini-ai/cms consent/node/index.ts, unchanged except the record types now come from ../server.
|
|
2
|
-
//
|
|
2
|
+
// Follow-up (P4): delete the cms copy once the consumer reads this package.
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import * as fs from 'node:fs/promises';
|
|
5
5
|
import { isIP } from 'node:net';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
|
-
import { DEFAULT_MAX_AGE_MS as CONSENT_MAX_AGE_MS } from '../policy.js';
|
|
7
|
+
import { DEFAULT_MAX_AGE_MS as CONSENT_MAX_AGE_MS } from '../contracts/policy.js';
|
|
8
8
|
const RECEIPT_FILENAME = /^[a-zA-Z0-9_-]{16,128}\.json$/;
|
|
9
9
|
/** Prepare the same private directory used by receipt writes, check write/search access and count
|
|
10
10
|
* receipt files without reading visitor proof. Filesystem errors propagate to the host's readiness check.
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,15 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
* (a tracker signature, a consent log sink, ...) never needs a change here. */
|
|
4
|
-
import { type AdapterContribution, type PluginRegistry, type SlotKind, type SlotProblem } from './contract.js';
|
|
5
|
-
type RegistryOptions = {
|
|
6
|
-
slots?: readonly SlotKind[];
|
|
7
|
-
onProblem?: (problem: SlotProblem) => void;
|
|
8
|
-
};
|
|
9
|
-
/** @example createPluginRegistry({}, { slots: [ADAPTER_SLOT], onProblem: report })
|
|
10
|
-
* @complexity O(n log n) per list(); O(parked) per defineSlot(). Registries hold a handful of entries. */
|
|
11
|
-
export declare function createPluginRegistry(_required?: object, { slots, onProblem }?: RegistryOptions): PluginRegistry;
|
|
12
|
-
/** The browser consent-adapter slot: a live adapter (grant()) or a lazy one (module src). */
|
|
13
|
-
export declare const ADAPTER_SLOT: SlotKind<AdapterContribution>;
|
|
14
|
-
export {};
|
|
1
|
+
/** Compatibility entry; the shared implementation serves browser and server consumers. */
|
|
2
|
+
export * from './contracts/plugins.js';
|
|
15
3
|
//# sourceMappingURL=plugins.d.ts.map
|
package/dist/plugins.js
CHANGED
|
@@ -1,78 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
* (a tracker signature, a consent log sink, ...) never needs a change here. */
|
|
4
|
-
import { ADAPTER_KIND, OPTIONAL } from './contract.js';
|
|
5
|
-
const ID = /^[a-z0-9][a-z0-9._:-]{0,63}$/;
|
|
6
|
-
/** @example createPluginRegistry({}, { slots: [ADAPTER_SLOT], onProblem: report })
|
|
7
|
-
* @complexity O(n log n) per list(); O(parked) per defineSlot(). Registries hold a handful of entries. */
|
|
8
|
-
export function createPluginRegistry(_required = {}, { slots = [], onProblem = () => undefined } = {}) {
|
|
9
|
-
const kinds = new Map();
|
|
10
|
-
const held = [];
|
|
11
|
-
const parked = new Set();
|
|
12
|
-
const listeners = new Set();
|
|
13
|
-
const list = (kind) => held.filter(h => h.kind === kind).sort((a, b) => b.priority - a.priority).map(h => h.value);
|
|
14
|
-
const emit = (kind) => listeners.forEach(l => { if (l.kind === kind)
|
|
15
|
-
try {
|
|
16
|
-
l.fn(list(kind));
|
|
17
|
-
}
|
|
18
|
-
catch { /* isolate */ } });
|
|
19
|
-
/** Duplicate ids are refused, never guessed (same rule as the host's contribution loaders). */
|
|
20
|
-
function admit(raw, options) {
|
|
21
|
-
const refuse = (reason) => { onProblem({ id: String(raw.id), kind: raw.kind, reason, ...(options.source ? { source: options.source } : {}) }); return () => undefined; };
|
|
22
|
-
if (!ID.test(String(raw.id)))
|
|
23
|
-
return refuse('short lowercase id');
|
|
24
|
-
const value = kinds.get(raw.kind).accept({ contribution: raw });
|
|
25
|
-
if (typeof value === 'string')
|
|
26
|
-
return refuse(value);
|
|
27
|
-
if (held.some(h => h.kind === raw.kind && h.id === raw.id))
|
|
28
|
-
return refuse('duplicate id');
|
|
29
|
-
const entry = { kind: raw.kind, id: raw.id, value, priority: options.priority ?? 0 };
|
|
30
|
-
held.push(entry);
|
|
31
|
-
emit(raw.kind);
|
|
32
|
-
return () => { const at = held.indexOf(entry); if (at >= 0) {
|
|
33
|
-
held.splice(at, 1);
|
|
34
|
-
emit(raw.kind);
|
|
35
|
-
} };
|
|
36
|
-
}
|
|
37
|
-
const registry = {
|
|
38
|
-
defineSlot({ slot }) {
|
|
39
|
-
if (kinds.has(slot.kind))
|
|
40
|
-
return;
|
|
41
|
-
kinds.set(slot.kind, slot);
|
|
42
|
-
for (const item of parked) {
|
|
43
|
-
if (item.raw.kind !== slot.kind)
|
|
44
|
-
continue;
|
|
45
|
-
parked.delete(item);
|
|
46
|
-
item.dispose = admit(item.raw, item.options); // the caller's disposer now removes the admitted entry
|
|
47
|
-
}
|
|
48
|
-
},
|
|
49
|
-
registerPlugin(raw, options = {}) {
|
|
50
|
-
if (kinds.has(raw.kind))
|
|
51
|
-
return admit(raw, options);
|
|
52
|
-
const item = { raw, options, dispose: () => { parked.delete(item); } };
|
|
53
|
-
parked.add(item);
|
|
54
|
-
return () => item.dispose();
|
|
55
|
-
},
|
|
56
|
-
list: ({ kind }) => list(kind),
|
|
57
|
-
subscribe({ kind, listener }) {
|
|
58
|
-
const entry = { kind, fn: listener };
|
|
59
|
-
listeners.add(entry);
|
|
60
|
-
return () => { listeners.delete(entry); };
|
|
61
|
-
},
|
|
62
|
-
};
|
|
63
|
-
for (const slot of slots)
|
|
64
|
-
registry.defineSlot({ slot });
|
|
65
|
-
return registry;
|
|
66
|
-
}
|
|
67
|
-
/** The browser consent-adapter slot: a live adapter (grant()) or a lazy one (module src). */
|
|
68
|
-
export const ADAPTER_SLOT = {
|
|
69
|
-
kind: ADAPTER_KIND,
|
|
70
|
-
accept({ contribution: c }) {
|
|
71
|
-
if (!OPTIONAL.includes(c.category))
|
|
72
|
-
return 'category must be functional, analytics or marketing';
|
|
73
|
-
if (typeof c.grant === 'function' || typeof c.src === 'string')
|
|
74
|
-
return c;
|
|
75
|
-
return 'grant() or src needed';
|
|
76
|
-
},
|
|
77
|
-
};
|
|
1
|
+
/** Compatibility entry; the shared implementation serves browser and server consumers. */
|
|
2
|
+
export * from './contracts/plugins.js';
|
|
78
3
|
//# sourceMappingURL=plugins.js.map
|
package/dist/policy.d.ts
CHANGED
|
@@ -1,47 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
import { type Choices, type ConsentAction, type ConsentState, type Flags, type RegionMode, type StoredChoice } from './contract.js';
|
|
4
|
-
export declare const DAY_MS = 86400000;
|
|
5
|
-
export declare const DEFAULT_MAX_AGE_MS: number;
|
|
6
|
-
/** Receipt ids keep the cms receipt-file rule, so ids can never navigate out of a receipt directory. */
|
|
7
|
-
export declare const RECEIPT_ID: RegExp;
|
|
8
|
-
export declare const DENIED: Choices;
|
|
9
|
-
/** Only the literal hint 'us' loosens; anything else, including absence, is strict. @complexity O(1). */
|
|
10
|
-
export declare function regionFrom({ configured, hint }: {
|
|
11
|
-
configured: 'auto' | RegionMode;
|
|
12
|
-
hint: string | null | undefined;
|
|
13
|
-
}, _optional?: {}): RegionMode;
|
|
14
|
-
/** What a button press means. Unknown picks are false. @complexity O(1). */
|
|
15
|
-
export declare function choicesFor({ action, picked }: {
|
|
16
|
-
action: ConsentAction;
|
|
17
|
-
picked?: Partial<Flags>;
|
|
18
|
-
}, _optional?: {}): Flags;
|
|
19
|
-
/** GPC wins over stored or new grants for every category that can share data; nothing can lift it. @complexity O(1). */
|
|
20
|
-
export declare function clamp({ flags, gpc }: {
|
|
21
|
-
flags: Flags;
|
|
22
|
-
gpc: boolean;
|
|
23
|
-
}, _optional?: {}): Choices;
|
|
24
|
-
/** Region default, policy-version + age expiry, GPC clamp, and (durable mode) no grant without a receipt.
|
|
25
|
-
* A region default with no stored choice (the opt-out model) is never "waiting", so it runs as configured.
|
|
26
|
-
* Anonymous delivery ignores stored grants; its level permits only anonymous-capable adapters, subject to the privacy signal.
|
|
27
|
-
* @example effective({ stored, policy: '2026-10-26', region: 'opt-in', gpc: false, nowMs: Date.now() }, { durable: true })
|
|
28
|
-
* @complexity O(1). */
|
|
29
|
-
export declare function effective({ stored, policy, region, gpc, nowMs }: {
|
|
30
|
-
stored: StoredChoice | null;
|
|
31
|
-
policy: string;
|
|
32
|
-
region: RegionMode;
|
|
33
|
-
gpc: boolean;
|
|
34
|
-
nowMs: number;
|
|
35
|
-
}, { maxAgeMs, durable, anonymous }?: {
|
|
36
|
-
maxAgeMs?: number;
|
|
37
|
-
durable?: boolean;
|
|
38
|
-
anonymous?: boolean;
|
|
39
|
-
}): ConsentState;
|
|
40
|
-
/** Trust boundary for the cookie: anything malformed is "no choice". Only known fields are copied out.
|
|
41
|
-
* @complexity O(raw length ≤ 1 KiB). */
|
|
42
|
-
export declare function parseStored({ raw }: {
|
|
43
|
-
raw: string | null | undefined;
|
|
44
|
-
}, _optional?: {}): StoredChoice | null;
|
|
45
|
-
/** Own booleans only: truthy strings never count as a grant. @complexity O(1). */
|
|
46
|
-
export declare function isFlags(c: unknown): c is Flags;
|
|
1
|
+
/** Compatibility entry; the shared implementation serves browser and server consumers. */
|
|
2
|
+
export * from './contracts/policy.js';
|
|
47
3
|
//# sourceMappingURL=policy.d.ts.map
|
package/dist/policy.js
CHANGED
|
@@ -1,95 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
// MOVED-FROM: @jini-ai/cms consent/policy.ts (resolveConsentRegion, resolveConsentChoices, readConsentRecord,
|
|
4
|
-
// createConsentRecord). TODO(P4): delete the cms copies once the consumer reads this package.
|
|
5
|
-
import { ACTIONS } from './contract.js';
|
|
6
|
-
export const DAY_MS = 86_400_000;
|
|
7
|
-
export const DEFAULT_MAX_AGE_MS = 180 * DAY_MS;
|
|
8
|
-
/** A receipt time comes from the server clock and is compared with the client clock; allow a minute. */
|
|
9
|
-
const SKEW_MS = 60_000;
|
|
10
|
-
/** Receipt ids keep the cms receipt-file rule, so ids can never navigate out of a receipt directory. */
|
|
11
|
-
export const RECEIPT_ID = /^[\w-]{16,128}$/;
|
|
12
|
-
export const DENIED = Object.freeze({ necessary: true, functional: false, analytics: false, marketing: false });
|
|
13
|
-
/** Only the literal hint 'us' loosens; anything else, including absence, is strict. @complexity O(1). */
|
|
14
|
-
export function regionFrom({ configured, hint }, _optional = {}) {
|
|
15
|
-
if (configured !== 'auto')
|
|
16
|
-
return configured;
|
|
17
|
-
return hint === 'us' ? 'opt-out' : 'opt-in';
|
|
18
|
-
}
|
|
19
|
-
const flags = (functional, analytics = functional, marketing = analytics) => ({ functional, analytics, marketing });
|
|
20
|
-
/** What a button press means. Unknown picks are false. @complexity O(1). */
|
|
21
|
-
export function choicesFor({ action, picked = {} }, _optional = {}) {
|
|
22
|
-
if (action === 'accept')
|
|
23
|
-
return flags(true);
|
|
24
|
-
if (action === 'save')
|
|
25
|
-
return flags(picked.functional === true, picked.analytics === true, picked.marketing === true);
|
|
26
|
-
// Do-not-sell keeps functional unless explicitly unticked: it is a sale/share refusal, not a reject.
|
|
27
|
-
if (action === 'do-not-sell')
|
|
28
|
-
return flags(picked.functional !== false, false);
|
|
29
|
-
return flags(false); // reject, withdraw
|
|
30
|
-
}
|
|
31
|
-
/** GPC wins over stored or new grants for every category that can share data; nothing can lift it. @complexity O(1). */
|
|
32
|
-
export function clamp({ flags, gpc }, _optional = {}) {
|
|
33
|
-
return { necessary: true, functional: flags.functional, analytics: flags.analytics && !gpc, marketing: flags.marketing && !gpc };
|
|
34
|
-
}
|
|
35
|
-
/** Region default, policy-version + age expiry, GPC clamp, and (durable mode) no grant without a receipt.
|
|
36
|
-
* A region default with no stored choice (the opt-out model) is never "waiting", so it runs as configured.
|
|
37
|
-
* Anonymous delivery ignores stored grants; its level permits only anonymous-capable adapters, subject to the privacy signal.
|
|
38
|
-
* @example effective({ stored, policy: '2026-10-26', region: 'opt-in', gpc: false, nowMs: Date.now() }, { durable: true })
|
|
39
|
-
* @complexity O(1). */
|
|
40
|
-
export function effective({ stored, policy, region, gpc, nowMs }, { maxAgeMs = DEFAULT_MAX_AGE_MS, durable = false, anonymous = false } = {}) {
|
|
41
|
-
// Banner-off never revives an old identity or consent grant, even in an opt-out region.
|
|
42
|
-
const live = current({ stored, policy, nowMs, maxAgeMs, anonymous });
|
|
43
|
-
const choices = clamp({ flags: anonymous ? DENIED : live?.c ?? flags(region === 'opt-out'), gpc });
|
|
44
|
-
const base = { contract: 1, policy, region, gpc, choices, ...permissionFor({ choices, live, durable, anonymous, gpc }) };
|
|
45
|
-
if (!live)
|
|
46
|
-
return { ...base, status: 'pending', action: null, at: null, receipt: 'none' };
|
|
47
|
-
return { ...base, status: 'set', action: live.a, at: live.t, receipt: receiptOf(live) };
|
|
48
|
-
}
|
|
49
|
-
/** Unparseable, future (beyond skew) and expired choices are all stale. @complexity O(1). */
|
|
50
|
-
function current({ stored, policy, nowMs, maxAgeMs, anonymous }) {
|
|
51
|
-
return !anonymous && stored && stored.p === policy && stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
|
|
52
|
-
}
|
|
53
|
-
/** Runtime permissions differ from choices for anonymous delivery and unconfirmed durable grants.
|
|
54
|
-
* @complexity O(1). */
|
|
55
|
-
function permissionFor({ choices, live, durable, anonymous, gpc }, _optional = {}) {
|
|
56
|
-
const allowed = anonymous || live && durable && !live.r ? DENIED : choices;
|
|
57
|
-
return { allowed, analyticsLevel: anonymous && !gpc ? 'anonymous' : allowed.analytics ? 'full' : 'none' };
|
|
58
|
-
}
|
|
59
|
-
function receiptOf(stored) {
|
|
60
|
-
if (stored.r)
|
|
61
|
-
return 'stored';
|
|
62
|
-
return stored.q ? 'pending' : 'local';
|
|
63
|
-
}
|
|
64
|
-
/** Trust boundary for the cookie: anything malformed is "no choice". Only known fields are copied out.
|
|
65
|
-
* @complexity O(raw length ≤ 1 KiB). */
|
|
66
|
-
export function parseStored({ raw }, _optional = {}) {
|
|
67
|
-
if (!raw || raw.length > 1024)
|
|
68
|
-
return null;
|
|
69
|
-
let s;
|
|
70
|
-
try {
|
|
71
|
-
s = JSON.parse(raw);
|
|
72
|
-
}
|
|
73
|
-
catch {
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
if (!isStored(s))
|
|
77
|
-
return null;
|
|
78
|
-
const out = { v: 1, p: s.p, c: flags(s.c.functional, s.c.analytics, s.c.marketing), t: s.t, a: s.a };
|
|
79
|
-
if (typeof s.r === 'string' && RECEIPT_ID.test(s.r))
|
|
80
|
-
out.r = s.r;
|
|
81
|
-
if (s.q === 1)
|
|
82
|
-
out.q = 1;
|
|
83
|
-
return out;
|
|
84
|
-
}
|
|
85
|
-
function isStored(s) {
|
|
86
|
-
if (!s || s.v !== 1 || typeof s.p !== 'string' || !Number.isFinite(s.t))
|
|
87
|
-
return false;
|
|
88
|
-
return ACTIONS.includes(s.a) && isFlags(s.c);
|
|
89
|
-
}
|
|
90
|
-
/** Own booleans only: truthy strings never count as a grant. @complexity O(1). */
|
|
91
|
-
export function isFlags(c) {
|
|
92
|
-
const f = c;
|
|
93
|
-
return !!f && typeof f === 'object' && typeof f.functional === 'boolean' && typeof f.analytics === 'boolean' && typeof f.marketing === 'boolean';
|
|
94
|
-
}
|
|
1
|
+
/** Compatibility entry; the shared implementation serves browser and server consumers. */
|
|
2
|
+
export * from './contracts/policy.js';
|
|
95
3
|
//# sourceMappingURL=policy.js.map
|
package/dist/render/banner.js
CHANGED
|
@@ -18,7 +18,7 @@ const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''
|
|
|
18
18
|
const esc = (s) => String(s).replace(/[&<>"']/g, ch => ESC[ch]);
|
|
19
19
|
const json = (v) => JSON.stringify(v).replace(/</g, '\\u003c');
|
|
20
20
|
const EMPTY = Object.freeze({ head: '', body: '', htmlAttrs: '', problems: [] });
|
|
21
|
-
// MOVED-FROM: @jini-ai/cms consent/html/render.ts consentPolicyHref.
|
|
21
|
+
// MOVED-FROM: @jini-ai/cms consent/html/render.ts consentPolicyHref. Follow-up (P4): delete the cms copy.
|
|
22
22
|
/** Refuse executable/data/protocol-relative links; local pages are the common case. @complexity O(url length). */
|
|
23
23
|
export function safeHref(url) {
|
|
24
24
|
if (!url)
|
package/dist/render/base-css.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// MOVED-FROM: @jini-ai/cms consent/html/styles.ts (CONSENT_CSS). Changed: scoped to the new visitor-independent
|
|
2
|
-
// markup (no data-has-record states, no form).
|
|
2
|
+
// markup (no data-has-record states, no form). Follow-up (P4): delete the cms copy once the consumer reads this package.
|
|
3
3
|
/** Compact defaults for the Jini banner. Theme tokens (--jini-surface, --jini-text, ...) are honoured when the
|
|
4
4
|
* host page defines them; owner tokens/CSS from compileConsentCss() follow, then the engine parity block. */
|
|
5
5
|
// Auto-fit keeps actions equally sized in one row when they fit, without growing the text controls.
|
|
@@ -81,7 +81,7 @@ function takeUntil({ tokens, state, delimiters }) {
|
|
|
81
81
|
function declarations({ tokens, state }) {
|
|
82
82
|
const result = [];
|
|
83
83
|
while (state.cursor < tokens.length) {
|
|
84
|
-
if (tokens[state.cursor].kind === 'space') {
|
|
84
|
+
if (tokens[state.cursor].kind === 'space' || tokens[state.cursor].value === ';') {
|
|
85
85
|
state.cursor++;
|
|
86
86
|
continue;
|
|
87
87
|
}
|
|
@@ -89,10 +89,6 @@ function declarations({ tokens, state }) {
|
|
|
89
89
|
state.cursor++;
|
|
90
90
|
return result;
|
|
91
91
|
}
|
|
92
|
-
if (tokens[state.cursor].value === ';') {
|
|
93
|
-
state.cursor++;
|
|
94
|
-
continue;
|
|
95
|
-
}
|
|
96
92
|
result.push(declaration({ tokens, state }));
|
|
97
93
|
}
|
|
98
94
|
// Only entered after the rule's `{` was consumed, so `cursor - 1` is always a real token.
|
|
@@ -130,7 +126,8 @@ function mediaRules({ tokens, state, media }, _options = {}) {
|
|
|
130
126
|
throw new ConsentCssSyntaxError('Nested media queries are not supported.', offset);
|
|
131
127
|
state.cursor++;
|
|
132
128
|
const header = takeUntil({ tokens, state, delimiters: '{};@' });
|
|
133
|
-
const
|
|
129
|
+
const width = String.raw `\((?:min|max)-width:\s*\d{1,4}(?:\.\d+)?px\)`;
|
|
130
|
+
const match = new RegExp(String.raw `^media\s*((?:screen\s+and\s+)?${width}(?:\s+and\s+${width})?)$`).exec(header);
|
|
134
131
|
if (!match || tokens[state.cursor]?.value !== '{')
|
|
135
132
|
throw new ConsentCssSyntaxError('Only width @media queries are supported.', offset);
|
|
136
133
|
state.cursor++;
|
|
@@ -151,11 +148,10 @@ function ruleList(input, _options = {}) {
|
|
|
151
148
|
state.cursor++;
|
|
152
149
|
return rules;
|
|
153
150
|
}
|
|
154
|
-
if (token.value === '@')
|
|
151
|
+
if (token.value === '@')
|
|
155
152
|
rules.push(...mediaRules(input));
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
rules.push(qualifiedRule(input));
|
|
153
|
+
else
|
|
154
|
+
rules.push(qualifiedRule(input));
|
|
159
155
|
}
|
|
160
156
|
if (media !== undefined)
|
|
161
157
|
throw new ConsentCssSyntaxError('Unclosed media query.', tokens[state.cursor - 1].offset);
|
package/dist/render/css.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Reject-parity block always apply. No DOM, no I/O. */
|
|
5
5
|
// MOVED-FROM: @jini-ai/cms consent/css.ts (value rules, contrast check, parity block). Changed: the selector
|
|
6
6
|
// gate is "anything under the scope" instead of a fixed surface list, and problems drop one rule instead
|
|
7
|
-
// of the whole customization.
|
|
7
|
+
// of the whole customization. Follow-up (P4): delete the cms copy once the consumer reads this package.
|
|
8
8
|
import { ConsentCssSyntaxError, parseConsentCss } from './css-parser.js';
|
|
9
9
|
export const CONSENT_CSS_SCOPE = '#jini-consent';
|
|
10
10
|
export const CONSENT_MAX_CSS_LENGTH = 16_384;
|
|
@@ -36,7 +36,9 @@ function lengthList({ value, min = 0, max = 32, count = 4 }) {
|
|
|
36
36
|
function shadowColor(value) {
|
|
37
37
|
if (isColor(value))
|
|
38
38
|
return true;
|
|
39
|
-
const
|
|
39
|
+
const channel = String.raw `\s*(\d{1,3})\s*,`;
|
|
40
|
+
const alpha = String.raw `\s*(0(?:\.\d+)?|1(?:\.0+)?|\.\d+)\s*`;
|
|
41
|
+
const match = new RegExp(String.raw `^rgba\(${channel}${channel}${channel}${alpha}\)$`).exec(value);
|
|
40
42
|
return match !== null && match.slice(1, 4).every(channel => Number(channel) <= 255);
|
|
41
43
|
}
|
|
42
44
|
/** A bounded shadow cannot cover the page or disguise the banner with a huge spread. @complexity O(value length). */
|
|
@@ -104,7 +106,7 @@ const COMPOUND = /^(?:[a-z][a-z0-9-]*|\*)?(?:[.#][a-z][\w-]*)*(?::(?:hover|focus
|
|
|
104
106
|
const ROOTS = /^(?:#jini-consent|\.jini-consent|\.jini-consent-reopen)(?=$|[\s>:])/;
|
|
105
107
|
/** Normalized selector, or null when it leaves the banner scope or could break Reject parity. @complexity O(selector length). */
|
|
106
108
|
export function scopedSelector(selector) {
|
|
107
|
-
const normalized = selector.trim().
|
|
109
|
+
const normalized = selector.trim().split('>').map(part => part.trim()).join(' > ').replace(/\s+/g, ' ');
|
|
108
110
|
if (!ROOTS.test(normalized))
|
|
109
111
|
return null;
|
|
110
112
|
const compounds = normalized.split(' ').filter(part => part !== '>');
|
|
@@ -229,7 +231,9 @@ function withoutRootColors(rules) {
|
|
|
229
231
|
}
|
|
230
232
|
/** Emit only validated selectors/declarations, retaining their optional width condition. @complexity O(rule bytes). */
|
|
231
233
|
function emitRule(rule) {
|
|
232
|
-
const
|
|
234
|
+
const selectors = rule.selector.split(',').map(s => scopedSelector(s)).join(',');
|
|
235
|
+
const declarations = rule.declarations.map(({ property, value }) => `${property}:${value}`).join(';');
|
|
236
|
+
const css = `${selectors}{${declarations}}`;
|
|
233
237
|
return rule.media === undefined ? css : `@media ${rule.media}{${css}}`;
|
|
234
238
|
}
|
|
235
239
|
/** Validate/compile the banner appearance for both the admin preview and delivery. Tokens render first, then
|
package/dist/server/receipt.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* same function. The response never sets a cookie: the browser client owns the cookie, so a slow Accept
|
|
3
3
|
* response can't overwrite a newer Reject. */
|
|
4
4
|
// MOVED-FROM: @jini-ai/cms consent/policy.ts createConsentRecord/readConsentRecord and consent/express receipt
|
|
5
|
-
// handling (origin check, policy race, no IP/user-agent in evidence).
|
|
5
|
+
// handling (origin check, policy race, no IP/user-agent in evidence). Follow-up (P4): delete the cms copies.
|
|
6
6
|
import { ACTIONS, CONSENT_COOKIE, REGION_COOKIE } from '../contract.js';
|
|
7
|
-
import { choicesFor, clamp, DEFAULT_MAX_AGE_MS, effective, isFlags, parseStored, RECEIPT_ID, regionFrom } from '../policy.js';
|
|
7
|
+
import { choicesFor, clamp, DEFAULT_MAX_AGE_MS, effective, isFlags, parseStored, RECEIPT_ID, regionFrom } from '../contracts/policy.js';
|
|
8
8
|
const problem = (status, message) => new Response(JSON.stringify({ error: message }), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
|
|
9
9
|
/** POST <endpoint>. The host builds `request.url` from its PUBLIC origin so the origin check is meaningful.
|
|
10
10
|
* @example app.post('/_consent', async (req, res) => send(res, await handleReceipt({ request: toRequest(req), ports })))
|
|
@@ -69,9 +69,7 @@ async function readJson({ request, maxBytes }) {
|
|
|
69
69
|
function cookie(header, name) {
|
|
70
70
|
for (const part of (header ?? '').split(/;\s*/)) {
|
|
71
71
|
const at = part.indexOf('=');
|
|
72
|
-
if (at < 1)
|
|
73
|
-
continue;
|
|
74
|
-
if (part.slice(0, at) !== name)
|
|
72
|
+
if (at < 1 || part.slice(0, at) !== name)
|
|
75
73
|
continue;
|
|
76
74
|
try {
|
|
77
75
|
return decodeURIComponent(part.slice(at + 1));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/cookie-consent",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.16",
|
|
4
4
|
"description": "Standalone, vendor-free cookie consent: a consent-state contract any banner can drive, a ~3 KB browser client, a pure-string banner renderer with owner CSS, web-standard receipts and open plugin slots.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
"domain": "capability",
|
|
13
13
|
"kind": "consent",
|
|
14
14
|
"runtime": "universal",
|
|
15
|
+
"isolation": {
|
|
16
|
+
"entries": {
|
|
17
|
+
"./client.min.js": "client"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
15
20
|
"entries": {
|
|
16
21
|
".": "universal",
|
|
17
22
|
"./policy": "universal",
|
|
@@ -87,7 +92,8 @@
|
|
|
87
92
|
"esbuild": "^0.28.1",
|
|
88
93
|
"jsdom": "^25.0.1",
|
|
89
94
|
"typescript": "^5.6.0",
|
|
90
|
-
"vitest": "^2.1.0"
|
|
95
|
+
"vitest": "^2.1.0",
|
|
96
|
+
"@jini-ai/cms": "^0.6.16"
|
|
91
97
|
},
|
|
92
98
|
"scripts": {
|
|
93
99
|
"build": "tsc -p tsconfig.json && node scripts/build-client.mjs",
|