import type { ConsentState } from './categories.js' import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js' /** * Consent persistence in a cookie. Stored with a version so old consents can be * invalidated when the policy changes (Cookie Settings → Policy version in the * panel), a timestamp (GDPR: consent must be dated) and a random id that links * the visitor's choice to the optional server-side consent record. Readable both * client-side (banner) and server-side (script gating, proxy). */ export const CONSENT_COOKIE = 'cookie-consent' /** Default policy version — the panel's Cookie Settings → Policy version overrides it. */ export const CONSENT_VERSION = 1 export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days type StoredConsent = { /** Random id of this decision (no personal data) — matches the consent record. */ id?: string state: ConsentState timestamp: string version: number } /** Random id for a consent decision. */ export function newConsentId(): string { const bytes = new Uint8Array(12) globalThis.crypto.getRandomValues(bytes) return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') } export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string): string { const payload: StoredConsent = { ...(id ? { id } : {}), state, timestamp: new Date().toISOString(), version, } return encodeURIComponent(JSON.stringify(payload)) } /** Full stored record (id, timestamp, version) — null when missing, unreadable or from another policy version. */ export function readConsentRecord(raw: string | undefined, version: number = CONSENT_VERSION): ({ state: ConsentState } & StoredConsent) | null { if (!raw) {return null} try { const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent if (parsed.version !== version) {return null} const state = { ...DEFAULT_CONSENT } for (const cat of CONSENT_CATEGORIES) { if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]} } state.necessary = true return { ...parsed, state } } catch { return null } } export function parseConsent(raw: string | undefined, version: number = CONSENT_VERSION): ConsentState | null { return readConsentRecord(raw, version)?.state ?? null }