@jini-ai/cookie-consent 0.6.15-rc.1 → 0.6.15
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.d.ts +3 -1
- package/dist/client/dom.js +9 -8
- package/dist/client/index.js +17 -15
- 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 +101 -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 +6 -1
package/dist/client/dom.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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
|
-
import { type Choices, type JiniConsentApi, type Optional, type StoragePrefixes } from '../contract.js';
|
|
3
|
+
import { type Choices, type ConsentState, type JiniConsentApi, type Optional, type StoragePrefixes } from '../contract.js';
|
|
4
4
|
/** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
|
|
5
5
|
export declare function readCookie(doc: Document, name: string): string | null;
|
|
6
6
|
export declare function writeCookie(doc: Document, { name, value, maxAgeS }: {
|
|
@@ -23,6 +23,8 @@ export declare function installOpeners({ api, doc }: {
|
|
|
23
23
|
api: JiniConsentApi;
|
|
24
24
|
doc: Document;
|
|
25
25
|
}): void;
|
|
26
|
+
/** A durable grant that is still waiting for its receipt keeps the banner open with its alert. */
|
|
27
|
+
export declare const waiting: (s: ConsentState) => boolean;
|
|
26
28
|
/** Wire #jini-consent (renderBanner's markup) to the public API. @complexity O(1) per click. */
|
|
27
29
|
export declare function bindBanner({ api, doc }: {
|
|
28
30
|
api: JiniConsentApi;
|
package/dist/client/dom.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
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
4
|
const INERT = 'script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]';
|
|
5
|
-
const SKIP =
|
|
5
|
+
const SKIP = ['type', 'data-src', 'data-type', 'data-consent-category'];
|
|
6
6
|
// Not <html>: the client sets html[data-consent-open] while the banner shows, and every click's closest() would hit it.
|
|
7
7
|
const OPENERS = ':not(html)[data-consent-open],a[href="#privacy-choices"]';
|
|
8
8
|
/** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
|
|
@@ -17,14 +17,15 @@ export function readCookie(doc, name) {
|
|
|
17
17
|
}
|
|
18
18
|
export function writeCookie(doc, { name, value, maxAgeS }, { domain } = {}) {
|
|
19
19
|
const secure = doc.defaultView?.location.protocol === 'https:' ? '; Secure' : '';
|
|
20
|
-
doc.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.floor(maxAgeS)}; SameSite=Lax${secure}
|
|
20
|
+
doc.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.floor(maxAgeS)}; SameSite=Lax${secure}` + (domain ? '; Domain=' + domain : '');
|
|
21
21
|
}
|
|
22
22
|
/** Vendors set cookies on the registrable domain, so expire on the host and each parent domain. */
|
|
23
23
|
function expireEverywhere(doc, name) {
|
|
24
24
|
const parts = (doc.defaultView?.location.hostname ?? '').split('.');
|
|
25
|
-
|
|
25
|
+
const expired = `${name}=; Path=/; Max-Age=0`;
|
|
26
|
+
doc.cookie = expired;
|
|
26
27
|
for (let i = 0; i < parts.length - 1; i++)
|
|
27
|
-
doc.cookie = `${
|
|
28
|
+
doc.cookie = `${expired}; Domain=.${parts.slice(i).join('.')}`;
|
|
28
29
|
}
|
|
29
30
|
/** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. @complexity O(cookies + keys). */
|
|
30
31
|
export function purge(doc, storage) {
|
|
@@ -44,7 +45,7 @@ export function purge(doc, storage) {
|
|
|
44
45
|
catch { /* no storage: nothing to purge */ }
|
|
45
46
|
}
|
|
46
47
|
// MOVED-FROM: @jini-ai/cms consent/html/client.ts template release (ordered, each template consumed once).
|
|
47
|
-
//
|
|
48
|
+
// Follow-up (P4): delete the cms runtime once the consumer inserts this client.
|
|
48
49
|
/** Allowed inert tags become live, in authored order (async=false). Unknown labels stay inert.
|
|
49
50
|
* @complexity O(inert tags). */
|
|
50
51
|
export function activateInert(doc, { allowed, ran }) {
|
|
@@ -63,8 +64,8 @@ export function activateInert(doc, { allowed, ran }) {
|
|
|
63
64
|
}
|
|
64
65
|
function liveScript(doc, inert) {
|
|
65
66
|
const s = doc.createElement('script');
|
|
66
|
-
for (const { name, value } of
|
|
67
|
-
if (!SKIP.
|
|
67
|
+
for (const { name, value } of inert.attributes)
|
|
68
|
+
if (!SKIP.includes(name))
|
|
68
69
|
s.setAttribute(name, value);
|
|
69
70
|
if (inert.nonce)
|
|
70
71
|
s.nonce = inert.nonce; // owner-set CSPs keep working
|
|
@@ -105,7 +106,7 @@ function syncInputs(root, s) {
|
|
|
105
106
|
}
|
|
106
107
|
}
|
|
107
108
|
/** A durable grant that is still waiting for its receipt keeps the banner open with its alert. */
|
|
108
|
-
const waiting = (s) => OPTIONAL.some(c => s.choices[c] && !s.allowed[c]);
|
|
109
|
+
export const waiting = (s) => OPTIONAL.some(c => s.choices[c] && !s.allowed[c]);
|
|
109
110
|
/** Wire #jini-consent (renderBanner's markup) to the public API. @complexity O(1) per click. */
|
|
110
111
|
export function bindBanner({ api, doc }) {
|
|
111
112
|
const root = doc.getElementById('jini-consent');
|
package/dist/client/index.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
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';
|
|
8
|
-
import { activateInert, installOpeners, purge, readCookie, writeCookie } from './dom.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
|
+
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 {
|
|
11
11
|
fn();
|
|
@@ -45,7 +45,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
45
45
|
if (ctl.signal.aborted || anonymous && state.analyticsLevel === 'none')
|
|
46
46
|
return null; // withdrawn first: nothing ran
|
|
47
47
|
return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal }))
|
|
48
|
-
.then(r
|
|
48
|
+
.then((r = {}) => r, () => ({})); // a grant that threw may have run code
|
|
49
49
|
}, () => null); // import failed: nothing ran
|
|
50
50
|
slot.run = { ctl, result };
|
|
51
51
|
}
|
|
@@ -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
|
}
|
|
@@ -118,7 +116,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
118
116
|
persist();
|
|
119
117
|
const now = apply(); // denial is live here, before any network
|
|
120
118
|
const sent = confirm(stored, previousId);
|
|
121
|
-
if (durable &&
|
|
119
|
+
if (durable && waiting(now))
|
|
122
120
|
await within(sent, durable.waitMs ?? 1500);
|
|
123
121
|
return state;
|
|
124
122
|
}
|
|
@@ -154,7 +152,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
154
152
|
// A refused cookie write leaves only this tab's choice; absence cannot supersede it.
|
|
155
153
|
if (!latest && !cookiePersisted)
|
|
156
154
|
return false;
|
|
157
|
-
if (
|
|
155
|
+
if (sameStoredChoice({ latest, stored }))
|
|
158
156
|
return false;
|
|
159
157
|
stored = latest;
|
|
160
158
|
apply();
|
|
@@ -178,6 +176,9 @@ export function createCookieConsent({ config, ports }, options = {}) {
|
|
|
178
176
|
void confirm(stored); // durable retry of an earlier failed receipt
|
|
179
177
|
return api;
|
|
180
178
|
}
|
|
179
|
+
function sameStoredChoice({ latest, stored }) {
|
|
180
|
+
return latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r;
|
|
181
|
+
}
|
|
181
182
|
function durableEvidence({ evidence }, _optional = {}) {
|
|
182
183
|
return evidence?.mode === 'durable' ? evidence : null;
|
|
183
184
|
}
|
|
@@ -201,7 +202,8 @@ function readPage(doc) {
|
|
|
201
202
|
export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
|
|
202
203
|
if (win.jiniConsent)
|
|
203
204
|
return win.jiniConsent;
|
|
204
|
-
const
|
|
205
|
+
const doc = win.document;
|
|
206
|
+
const page = readPage(doc);
|
|
205
207
|
if (!page)
|
|
206
208
|
return undefined;
|
|
207
209
|
const { evidence, ...config } = page;
|
|
@@ -211,10 +213,10 @@ export function boot(win = window, { ports = browserPorts(win), bindBanner } = {
|
|
|
211
213
|
win.jiniConsent = api;
|
|
212
214
|
win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
|
|
213
215
|
win.jiniConsentQueue.push(...queued);
|
|
214
|
-
installOpeners({ api, doc
|
|
216
|
+
installOpeners({ api, doc });
|
|
215
217
|
if (config.banner === 'jini')
|
|
216
|
-
bindBanner?.({ api, doc
|
|
217
|
-
|
|
218
|
+
bindBanner?.({ api, doc });
|
|
219
|
+
doc.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
|
|
218
220
|
return api;
|
|
219
221
|
}
|
|
220
222
|
/** 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",J="jini_region",$="jini:consent",B="jini:consent-ready",O="jini:consent-open",G="jini-consent-config",S=["functional","analytics","marketing"],Te=["necessary",...S],V=["accept","reject","save","do-not-sell","withdraw"];var k="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 W(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 _(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 z(e,{allowed:t,ran:n}){e.querySelectorAll(le).forEach(o=>{let r=o.dataset.consentCategory;if(!(!S.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 Q({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 S){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function N(e,t){for(let n of S){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var D=e=>S.some(t=>e.choices[t]&&!e.allowed[t]);function Y({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=!D(s)),D(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&&!D(s)&&p(s)}}),N(n,e.get()),r(e.get().status==="pending")}var M=864e5,ye=180*M,me=6e4,L=/^[\w-]{16,128}$/,U=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function X({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var E=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function Z({action:e,picked:t={}},n={}){return e==="accept"?E(!0):e==="save"?E(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?E(t.functional!==!1,!1):E(!1)}function Ce({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function ee({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?U:C?.c??E(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?U:e;return{allowed:s,analyticsLevel:o&&!r?"anonymous":s.analytics?"full":"none"}}function he(e){return e.r?"stored":e.q?"pending":"local"}function te({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:E(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&L.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:V.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 Ee=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function ne(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],p=new Set,s=new Set,m=a=>r.filter(l=>l.kind===a).sort((l,c)=>c.priority-l.priority).map(l=>l.value),C=a=>s.forEach(l=>{if(l.kind===a)try{l.fn(m(a))}catch{}});function f(a,l){let c=h=>(n({id:String(a.id),kind:a.kind,reason:h,...l.source?{source:l.source}:{}}),()=>{});if(!Ee.test(String(a.id)))return c("short lowercase id");let A=o.get(a.kind).accept({contribution:a});if(typeof A=="string")return c(A);if(r.some(h=>h.kind===a.kind&&h.id===a.id))return c("duplicate id");let b={kind:a.kind,id:a.id,value:A,priority:l.priority??0};return r.push(b),C(a.kind),()=>{let h=r.indexOf(b);h>=0&&(r.splice(h,1),C(a.kind))}}let v={defineSlot({slot:a}){if(!o.has(a.kind)){o.set(a.kind,a);for(let l of p)l.raw.kind===a.kind&&(p.delete(l),l.dispose=f(l.raw,l.options))}},registerPlugin(a,l={}){if(o.has(a.kind))return f(a,l);let c={raw:a,options:l,dispose:()=>{p.delete(c)}};return p.add(c),()=>c.dispose()},list:({kind:a})=>m(a),subscribe({kind:a,listener:l}){let c={kind:a,fn:l};return s.add(c),()=>{s.delete(c)}}};for(let a of t)v.defineSlot({slot:a});return v}var oe={kind:k,accept({contribution:e}){return S.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var xe=(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??ne({},{slots:[oe]}),p=ke(n),s=new Map,m=new Set,C=new Set,f=e.banner==="off",v=(e.maxAgeDays??180)*M,a=X({configured:e.regionMode,hint:f?null:T(o,J)}),l=()=>f?null:te({raw:T(o,R)}),c=l(),A=!0,b=h();function h(){return ee({stored:c,policy:e.policy,region:a,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!p,anonymous:f})}function j(){let i=JSON.stringify(c);W(o,{name:R,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),A=T(o,R)===i}function q(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(P=>P===void 0?{}:P,()=>({}))),()=>null);i.run={ctl:d,result:u}}async function F(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&&_(o,i.adapter?.storage??i.entry.storage),!y}function re(i){let d=[];for(let u of s.values())(f?i.analyticsLevel==="anonymous":i.allowed[u.entry.category])?u.run||q(u):u.run&&d.push(F(u)),w(()=>u.adapter?.onState?.({state:i}));f||z(o,{allowed:i.allowed,ran:C});let g=S.some(u=>C.has(u)&&!i.allowed[u]);Promise.all(d).then(u=>{(g||u.includes(!0))&&t.reload()})}function x(){let i=b=h(),d=o.documentElement;return d.dataset.consent=i.status,d.dataset.consentRegion=i.region,d.toggleAttribute("data-consent-gpc",i.gpc),re(i),m.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent($,{detail:i})),i}async function K(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;c!==i||I()||typeof y?.id!="string"||!L.test(y.id)||(c={v:1,p:i.p,c:i.c,t:i.t,a:i.a,r:y.id},j(),x())}async function se({action:i},{choices:d={}}={}){if(f)return x();let g=c?.r;c={v:1,p:e.policy,c:Z({action:i,picked:d}),t:t.now(),a:i,...p?{q:1}:{}},j();let u=x(),y=K(c,g);return p&&S.some(P=>u.choices[P]&&!u.allowed[P])&&await xe(y,p.waitMs??1500),b}function ae(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]?q(d):_(o,i.storage),w(()=>d.adapter?.onState?.({state:b}))}function H(i){let d=new Set(i.map(g=>g.id));for(let[g,u]of s)d.has(g)||(s.delete(g),u.run&&F(u).then(y=>{y&&t.reload()}));for(let g of i)s.has(g.id)||ae(g)}function I(){let i=l();return!i&&!A||i?.t===c?.t&&i?.a===c?.a&&i?.r===c?.r?!1:(c=i,x(),!0)}let ce={contract:1,plugins:r,set:se,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:k,listener:H}),H(r.list({kind:k})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),x(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",()=>I()),c?.q&&c.p===e.policy&&K(c),ce}function ke({evidence:e},t={}){return e?.mode==="durable"?e:null}function Re(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 Oe(e){try{return JSON.parse(e.getElementById(G)?.textContent??"")}catch{return null}}function ie(e=window,{ports:t=Re(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=Oe(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),Q({api:s,doc:e.document}),p.banner==="jini"&&n?.({api:s,doc:e.document}),e.document.dispatchEvent(new CustomEvent(B,{detail:s})),s}ie(window,{bindBanner:Y});})();
|
|
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"],Te=["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:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var A=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function Y({action:e,picked:t={}},n={}){return e==="accept"?A(!0):e==="save"?A(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?A(t.functional!==!1,!1):A(!1)}function de({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function U({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:f=le,durable:a=!1,anonymous:d=!1}={}){let m=pe({stored:e,policy:t,nowMs:r,maxAgeMs:f,anonymous:d}),g=de({flags:d?z:m?.c??A(n==="opt-out"),gpc:o}),S={contract:1,policy:t,region:n,gpc:o,choices:g,...fe({choices:g,live:m,durable:a,anonymous:d,gpc:o})};return m?{...S,status:"set",action:m.a,at:m.t,receipt:ge(m)}:{...S,status:"pending",action:null,at:null,receipt:"none"}}function pe({stored:e,policy:t,nowMs:n,maxAgeMs:o,anonymous:r}){return r||!e||e.p!==t?null:e.t<=n+ue&&n-e.t<=o?e:null}function fe({choices:e,live:t,durable:n,anonymous:o,gpc:r},f={}){let a=t&&n&&!t.r,d=o||a?z:e,m=d.analytics?"full":"none";return{allowed:d,analyticsLevel:o&&!r?"anonymous":m}}function ge(e){return e.r?"stored":e.q?"pending":"local"}function X({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!ye(n))return null;let o={v:1,p:n.p,c:A(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&D.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function ye(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:W.includes(e.a)&&Ce(e.c)}function Ce(e){let t=e;return!t||typeof t!="object"?!1:typeof t.functional=="boolean"&&typeof t.analytics=="boolean"&&typeof t.marketing=="boolean"}var me=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],f=new Set,a=new Set,d=s=>r.filter(c=>c.kind===s).sort((c,l)=>l.priority-c.priority).map(c=>c.value),m=s=>a.forEach(c=>{if(c.kind===s)try{c.fn(d(s))}catch{}});function g(s,c){let l=h=>(n({id:String(s.id),kind:s.kind,reason:h,...c.source?{source:c.source}:{}}),()=>{});if(!me.test(String(s.id)))return l("short lowercase id");let x=o.get(s.kind).accept({contribution:s});if(typeof x=="string")return l(x);if(r.some(h=>h.kind===s.kind&&h.id===s.id))return l("duplicate id");let b={kind:s.kind,id:s.id,value:x,priority:c.priority??0};return r.push(b),m(s.kind),()=>{let h=r.indexOf(b);h>=0&&(r.splice(h,1),m(s.kind))}}let S={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let c of f)c.raw.kind===s.kind&&(f.delete(c),c.dispose=g(c.raw,c.options))}},registerPlugin(s,c={}){if(o.has(s.kind))return g(s,c);let l={raw:s,options:c,dispose:()=>{f.delete(l)}};return f.add(l),()=>l.dispose()},list:({kind:s})=>d(s),subscribe({kind:s,listener:c}){let l={kind:s,fn:c};return a.add(l),()=>{a.delete(l)}}};for(let s of t)S.defineSlot({slot:s});return S}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 be='script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]',Se=["type","data-src","data-type","data-consent-category"],he=':not(html)[data-consent-open],a[href="#privacy-choices"]';function w(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 te(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let f=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${f}`+(r?"; Domain="+r:"")}function ve(e,t){let n=(e.defaultView?.location.hostname??"").split("."),o=`${t}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<n.length-1;r++)e.cookie=`${o}; Domain=.${n.slice(r).join(".")}`}function M(e,t){if(t){for(let n of e.cookie.split(/;\s*/)){let o=n.split("=")[0];t.cookies?.some(r=>o.startsWith(r))&&ve(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 ne(e,{allowed:t,ran:n}){e.querySelectorAll(be).forEach(o=>{let r=o.dataset.consentCategory;if(!(!v.includes(r)||!t[r])){if(n.add(r),o.tagName==="IFRAME"){o.setAttribute("src",o.dataset.src),o.removeAttribute("data-src");return}o.replaceWith(xe(e,o))}})}function xe(e,t){let n=e.createElement("script");for(let{name:o,value:r}of t.attributes)Se.includes(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 L({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(he)&&(n.preventDefault(),e.open())})}function Ae(e){let t={};for(let n of v){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function _(e,t){for(let n of v){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var k=e=>v.some(t=>e.choices[t]&&!e.allowed[t]);function j({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),r=a=>{n.hidden=!a,e.setOpen({open:a})},f=a=>{o&&(o.hidden=!k(a)),k(a)||r(!1)};n.addEventListener("click",a=>{let d=a.target.closest?.("[data-consent-action]")?.getAttribute("data-consent-action");d&&(a.preventDefault(),e.set({action:d},{choices:Ae(n)}).then(f))}),n.addEventListener("keydown",a=>{a.key==="Escape"&&e.get().status==="set"&&r(!1)}),t.addEventListener(O,()=>{_(n,e.get()),r(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:a=>{_(n,a),o&&!o.hidden&&!k(a)&&f(a)}}),_(n,e.get()),r(e.get().status==="pending")}var Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),T=e=>{try{e()}catch{}};function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??Z({},{slots:[ee]}),f=Re(n),a=new Map,d=new Set,m=new Set,g=e.banner==="off",S=(e.maxAgeDays??180)*N,s=Q({configured:e.regionMode,hint:g?null:w(o,B)}),c=()=>g?null:X({raw:w(o,R)}),l=c(),x=!0,b=h();function h(){return U({stored:l,policy:e.policy,region:s,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:S,durable:!!f,anonymous:g})}function q(){let i=JSON.stringify(l);te(o,{name:R,value:i,maxAgeS:S/1e3},{domain:e.cookieDomain}),x=w(o,R)===i}function F(i){i.generation++;let p=new AbortController,u=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(C=>i.adapter=C.default)).then(C=>(T(()=>C.onState?.({state:b})),p.signal.aborted||g&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>C.grant({config:i.entry.config??C.config,state:b,signal:p.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:p,result:u}}async function K(i){let p=i.run,y=i.generation;i.run=void 0,p.ctl.abort();let u=await p.result;if(!u)return!1;let C=await Promise.resolve().then(()=>u.revoke?.()).catch(()=>!1);return!g&&i.generation===y&&M(o,i.adapter?.storage??i.entry.storage),!C}function ie(i){let p=[];for(let u of a.values()){let C=g?i.analyticsLevel==="anonymous":i.allowed[u.entry.category];C&&!u.run&&F(u),!C&&u.run&&p.push(K(u)),T(()=>u.adapter?.onState?.({state:i}))}g||ne(o,{allowed:i.allowed,ran:m});let y=v.some(u=>m.has(u)&&!i.allowed[u]);Promise.all(p).then(u=>{(y||u.includes(!0))&&t.reload()})}function E(){let i=b=h(),p=o.documentElement;return p.dataset.consent=i.status,p.dataset.consentRegion=i.region,p.toggleAttribute("data-consent-gpc",i.gpc),ie(i),d.forEach(y=>T(()=>y(i))),o.dispatchEvent(new CustomEvent(G,{detail:i})),i}async function H(i,p){if(!f)return;let y=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:p}),u=await t.fetch(f.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:y}).catch(()=>null),C=u?.ok?await u.json().catch(()=>null):null;l!==i||I()||typeof C?.id!="string"||!D.test(C.id)||(l={v:1,p:i.p,c:i.c,t:i.t,a:i.a,r:C.id},q(),E())}async function re({action:i},{choices:p={}}={}){if(g)return E();let y=l?.r;l={v:1,p:e.policy,c:Y({action:i,picked:p}),t:t.now(),a:i,...f?{q:1}:{}},q();let u=E(),C=H(l,y);return f&&k(u)&&await Ee(C,f.waitMs??1500),b}function se(i){if(g&&(!i.supportsAnonymous||i.category!=="analytics"))return;let p={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};a.set(i.id,p),g||b.allowed[i.category]?F(p):M(o,i.storage),T(()=>p.adapter?.onState?.({state:b}))}function J(i){let p=new Set(i.map(y=>y.id));for(let[y,u]of a)p.has(y)||(a.delete(y),u.run&&K(u).then(C=>{C&&t.reload()}));for(let y of i)a.has(y.id)||se(y)}function I(){let i=c();return!i&&!x||ke({latest:i,stored:l})?!1:(l=i,E(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(d.add(i),()=>{d.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"})),E(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",()=>I()),l?.q&&l.p===e.policy&&H(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 we(e){try{return JSON.parse(e.getElementById($)?.textContent??"")}catch{return null}}function oe(e=window,{ports:t=Oe(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=we(o);if(!r)return;let{evidence:f,...a}=r,d=Pe({config:a,ports:t},{evidence:f}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=d,e.jiniConsentQueue={push:(...g)=>g.forEach(S=>d.plugins.registerPlugin(S,{source:"queue"}))},e.jiniConsentQueue.push(...m),L({api:d,doc:o}),a.banner==="jini"&&n?.({api:d,doc:o}),o.dispatchEvent(new CustomEvent(V,{detail:d})),d}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,101 @@
|
|
|
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
|
+
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
|
+
if (anonymous || !stored || stored.p !== policy)
|
|
52
|
+
return null;
|
|
53
|
+
return stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
|
|
54
|
+
}
|
|
55
|
+
/** Runtime permissions differ from choices for anonymous delivery and unconfirmed durable grants.
|
|
56
|
+
* @complexity O(1). */
|
|
57
|
+
function permissionFor({ choices, live, durable, anonymous, gpc }, _optional = {}) {
|
|
58
|
+
const unconfirmed = live && durable && !live.r;
|
|
59
|
+
const allowed = anonymous || unconfirmed ? DENIED : choices;
|
|
60
|
+
const analyticsLevel = allowed.analytics ? 'full' : 'none';
|
|
61
|
+
return { allowed, analyticsLevel: anonymous && !gpc ? 'anonymous' : analyticsLevel };
|
|
62
|
+
}
|
|
63
|
+
function receiptOf(stored) {
|
|
64
|
+
if (stored.r)
|
|
65
|
+
return 'stored';
|
|
66
|
+
return stored.q ? 'pending' : 'local';
|
|
67
|
+
}
|
|
68
|
+
/** Trust boundary for the cookie: anything malformed is "no choice". Only known fields are copied out.
|
|
69
|
+
* @complexity O(raw length ≤ 1 KiB). */
|
|
70
|
+
export function parseStored({ raw }, _optional = {}) {
|
|
71
|
+
if (!raw || raw.length > 1024)
|
|
72
|
+
return null;
|
|
73
|
+
let s;
|
|
74
|
+
try {
|
|
75
|
+
s = JSON.parse(raw);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (!isStored(s))
|
|
81
|
+
return null;
|
|
82
|
+
const out = { v: 1, p: s.p, c: flags(s.c.functional, s.c.analytics, s.c.marketing), t: s.t, a: s.a };
|
|
83
|
+
if (typeof s.r === 'string' && RECEIPT_ID.test(s.r))
|
|
84
|
+
out.r = s.r;
|
|
85
|
+
if (s.q === 1)
|
|
86
|
+
out.q = 1;
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
function isStored(s) {
|
|
90
|
+
if (!s || s.v !== 1 || typeof s.p !== 'string' || !Number.isFinite(s.t))
|
|
91
|
+
return false;
|
|
92
|
+
return ACTIONS.includes(s.a) && isFlags(s.c);
|
|
93
|
+
}
|
|
94
|
+
/** Own booleans only: truthy strings never count as a grant. @complexity O(1). */
|
|
95
|
+
export function isFlags(c) {
|
|
96
|
+
const f = c;
|
|
97
|
+
if (!f || typeof f !== 'object')
|
|
98
|
+
return false;
|
|
99
|
+
return typeof f.functional === 'boolean' && typeof f.analytics === 'boolean' && typeof f.marketing === 'boolean';
|
|
100
|
+
}
|
|
101
|
+
//# 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.15
|
|
3
|
+
"version": "0.6.15",
|
|
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",
|