@luwiostack/cookie-consent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,293 @@
1
- # Temporary Holding Version
1
+ # @luwiostack/cookie-consent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cookie consent for React apps. The four categories are fixed: necessary, preferences, statistics
4
+ and marketing. Per category, you list the vendors your site uses there; every cookie a vendor sets
5
+ carries its category, so a vendor brings only its cookies of the categories you use it in. The
6
+ decision is kept in `localStorage`, and the visitor is asked again when the policy changes or a
7
+ year passes. The package also has a gate for embeds, Google Consent Mode v2, script unblocking,
8
+ removal of a withdrawn category's cookies and ready-made vendor presets. There is no UI: every app
9
+ builds its own banner and preferences on `useConsent()`.
10
+
11
+ ```bash
12
+ npm i @luwiostack/cookie-consent
13
+ ```
14
+
15
+ ## Create the instance
16
+
17
+ ```ts
18
+ // consent.ts
19
+ import { createConsent } from '@luwiostack/cookie-consent'
20
+ import { googleAds, googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
21
+
22
+ export const consent = createConsent({
23
+ categories: {
24
+ statistics: [googleAnalytics()],
25
+ preferences: [youtube()], // the YouTube embed — without YouTube's marketing cookies
26
+ marketing: [googleAds({ cookies: ['_gcl_au', 'IDE'] })],
27
+ },
28
+ policyVersion: 1, // bump when the vendors change → everyone is asked again
29
+ // maxAge: 365 days by default
30
+ onChange: (next, previous) => {
31
+ // log the decision server-side: next?.consent_id, next?.granted(), next?.decided_at
32
+ },
33
+ })
34
+
35
+ consent.isGranted('statistics') // a category ('stats' is a type error)
36
+ consent.isGranted('preferences', 'youtube') // + YouTube is used in preferences: the embed
37
+ consent.isGranted('marketing', 'youtube') // false — not used there, so no tracking
38
+ ```
39
+
40
+ A vendor listed under a category brings only its cookies of that category, plus its necessary
41
+ cookies, which are always allowed. So `preferences: [youtube()]` is the embed alone (`PREF`). Add
42
+ `youtube()` to `marketing` as well to declare YouTube's tracking cookies, and the vendor then needs
43
+ both categories. Listing a vendor under a category it has no cookies in throws.
44
+
45
+ **Where the decision is kept.** By default in `localStorage` (`luwio.consent`), synced across
46
+ tabs. A stored decision stops counting when its policy version differs, when it's older than
47
+ `maxAge`, or when it's dated in the future (it could never expire; a few minutes of clock drift are
48
+ tolerated). Where storage is blocked or full, the visitor's choice still applies **for the rest of
49
+ the page's life** — the banner closes, gates open — and they're asked again on the next page load;
50
+ `onChange` fires as usual.
51
+
52
+ `consent.categories` is always the four categories, in order (`CONSENT_CATEGORIES`). Each one
53
+ carries the vendors used in it, and only those cookies. `necessary` is required: it is
54
+ always granted and never part of the question. Categories carry no text, so render
55
+ `` t(`category.${id}`) `` from the catalogs below.
56
+
57
+ ## React
58
+
59
+ ```tsx
60
+ import { Consent, ConsentGate, useConsent } from '@luwiostack/cookie-consent/react'
61
+
62
+ <Consent consent={consent}>
63
+ <App />
64
+ <CookieBanner />
65
+ </Consent>
66
+
67
+ // Your own banner — the package ships no UI, only the state and actions.
68
+ function CookieBanner() {
69
+ const { needsDecision, isPreferencesOpen, acceptAll, rejectAll, openPreferences } = useConsent()
70
+ if (!needsDecision || isPreferencesOpen) return null
71
+ return (
72
+ <section aria-label="Cookies" className="cookie-banner">
73
+ <h2>We use cookies</h2>
74
+ <button type="button" onClick={rejectAll}>Reject all</button>
75
+ <button type="button" onClick={openPreferences}>Customize</button>
76
+ <button type="button" onClick={acceptAll}>Accept all</button>
77
+ </section>
78
+ )
79
+ }
80
+
81
+ // Hold an embed back until its category is granted — and, with a vendor, only while that vendor is
82
+ // used in the category (it renders nothing when YouTube isn't used in preferences):
83
+ <ConsentGate
84
+ category="preferences"
85
+ vendor="youtube"
86
+ fallback={(gate) => <button onClick={gate.grant}>Load video</button>}
87
+ >
88
+ <iframe src="https://www.youtube-nocookie.com/embed/…" />
89
+ </ConsentGate>
90
+ ```
91
+
92
+ The package ships **no UI**. Every app builds its own banner and preferences, so they match the
93
+ product. `useConsent()` gives you what they need:
94
+
95
+ - `needsDecision`
96
+ - `categories`, each with its vendors and cookies
97
+ - `isGranted(category, vendor?)`
98
+ - `acceptAll`, `rejectAll` and `save`
99
+ - `isPreferencesOpen`, `openPreferences` and `closePreferences`: shared state, so a link anywhere
100
+ can open your preferences. The three decision actions close them.
101
+
102
+ Keep your preferences' unsaved ticks in your own state, starting from `isGranted`, so nothing is
103
+ ever pre-ticked. `apps/showcase` (`src/app/CookieBanner.tsx`) is a full example.
104
+
105
+ ## Vendors and their cookies
106
+
107
+ Most cookies come from the same handful of services, so the package ships their declarations at
108
+ `@luwiostack/cookie-consent/vendors`. They are data only, like a country's `machine_name`, and every
109
+ cookie is already tagged with its category; you choose which categories you use a vendor in. Each preset is a separate export, so your bundle only
110
+ holds the ones you import. Call a preset as is, keep only the cookies your setup sets, or add your
111
+ own:
112
+
113
+ ```ts
114
+ import { defineVendor, googleAds, metaPixel } from '@luwiostack/cookie-consent/vendors'
115
+
116
+ googleAds({ cookies: ['_gcl_au', 'IDE'] }) // only these
117
+ metaPixel({ extra: [{ name: 'my_flag', category: 'marketing', max_age: 'session' }] }) // plus yours
118
+
119
+ // Your own site's necessary cookies: never asked about, but they must be declared. List them under
120
+ // `necessary` — the session, CSRF token and this choice's own storage item.
121
+ const mySite = {
122
+ id: 'my_site', // t('my_site'), t('my_site.session') … in your own catalog
123
+ cookies: [
124
+ { name: 'session', category: 'necessary', max_age: 'session' },
125
+ { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
126
+ ],
127
+ } as const
128
+ // createConsent({ categories: { necessary: [mySite], … } })
129
+
130
+ // A service without a preset — declare it, or package it with defineVendor to reuse it, then list
131
+ // it under the categories you use it in:
132
+ const DAY = 24 * 60 * 60 * 1000
133
+ export const acmeChat = defineVendor({
134
+ id: 'acme_chat', // t('acme_chat') → the name
135
+ privacy_policy_url: 'https://acme.example/privacy',
136
+ cookies: [
137
+ { name: 'acme_id', category: 'preferences', max_age: 365 * DAY }, // type defaults to 'http'
138
+ { name: 'acme_open', category: 'necessary', type: 'session_storage', max_age: 'session' },
139
+ ],
140
+ })
141
+ ```
142
+
143
+ Each cookie has a `category`, a `max_age` and an optional `type`:
144
+
145
+ - `max_age` is milliseconds, `'session'` or `'persistent'`.
146
+ - `type` is `http` (the default), `local_storage`, `session_storage`, `indexed_db` or `pixel`.
147
+
148
+ `ConsentCookieFormatter.formatLocale(cookie, locale)` renders a lifetime as "2 years" or "3
149
+ months". It returns `null` for `session` and `persistent`; translate those yourself.
150
+
151
+ The text lives in the downloadable catalogs (`translations/cookie-consent.<locale>.json`, in en, nl, fr,
152
+ de and es):
153
+
154
+ - `category.<id>` and `category.<id>.description` name and describe the four categories.
155
+ - `t(vendor.id)` is a vendor's name.
156
+ - `` t(`${vendor.id}.${cookie.name}`) `` is a cookie's purpose.
157
+ - `cookie_type.<type>`, `max_age.session` and `max_age.persistent` cover the rest.
158
+
159
+ ### Config from your backend
160
+
161
+ When a back office decides which integrations are on, the config is data. The backend sends JSON
162
+ (`ConsentConfigData`): per category, the vendors used in it (preset ids or full declarations), and
163
+ a policy version.
164
+ `consentConfigFromData` turns it into `createConsent` options:
165
+
166
+ ```ts
167
+ import { consentConfigFromData } from '@luwiostack/cookie-consent/vendors'
168
+
169
+ // config.consent from your startup config:
170
+ // { "policy_version": 7, "categories": {
171
+ // "statistics": ["google_analytics"],
172
+ // "preferences": ["youtube"],
173
+ // "marketing": [
174
+ // { "preset": "google_ads", "cookies": ["_gcl_au"] },
175
+ // { "id": "acme_chat", "cookies": [{ "name": "acme_id", "category": "marketing", "max_age": 31536000000 }] }
176
+ // ]
177
+ // } }
178
+ const consent = createConsent({ ...consentConfigFromData(config.consent), onChange: logConsent })
179
+ ```
180
+
181
+ **Strictly necessary cookies stay in the app.** The backend decides the optional categories; the
182
+ app declares its own `necessary` vendors in code and passes them as `necessary`. They come first,
183
+ followed by the data's categories; `policy_version` and `max_age` still come from the data:
184
+
185
+ ```ts
186
+ // The app's own strictly necessary cookies — never configured in the back office.
187
+ const mySite = {
188
+ id: 'my_site',
189
+ cookies: [
190
+ { name: 'session', category: 'necessary', max_age: 'session' },
191
+ { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
192
+ ],
193
+ } as const
194
+
195
+ const consent = createConsent({
196
+ ...consentConfigFromData(config.consent, { necessary: [mySite] }), // + preferences, statistics, marketing
197
+ onChange: logConsent,
198
+ })
199
+ ```
200
+
201
+ Once the app passes `necessary`, data that lists a `necessary` category is refused with
202
+ `ConsentError`: strictly necessary cookies are the app's to declare, never the backend's. A backend
203
+ vendor still brings its own necessary cookies (reCAPTCHA's, say) under the category it's listed in.
204
+
205
+ - **Preset lookup:** presets resolve through `vendorPresets`, the id → preset map. It bundles every
206
+ preset, since the backend picks at runtime.
207
+ - **Policy version:** bump `policy_version` on the backend whenever the vendor list changes, so
208
+ visitors are asked again.
209
+ - **Errors:** an unknown category, preset or cookie throws `ConsentError`, and so does a vendor
210
+ listed under a category it has no cookies in, or a `necessary` category in the data when the app
211
+ passes its own.
212
+
213
+ ## Outside React
214
+
215
+ ```ts
216
+ import { clearRevokedCookies, googleConsentMode, unblockScripts } from '@luwiostack/cookie-consent'
217
+
218
+ googleConsentMode(consent) // before gtag.js / GTM loads; standard mapping (ads → marketing, …)
219
+ unblockScripts(consent) // activates <script type="text/plain" data-consent="statistics">,
220
+ // plus data-consent-vendor="meta_pixel" to also need that vendor there
221
+ clearRevokedCookies(consent) // removes the cookies / storage of categories that aren't granted
222
+ ```
223
+
224
+ `unblockScripts` keeps an activated script's CSP `nonce`, so it works on a site with a nonce-based
225
+ `Content-Security-Policy`: put the nonce on the blocked `<script type="text/plain">` as usual.
226
+ Activation is one-way — a withdrawn category can't un-run a script; reload from `onChange`.
227
+
228
+ ### Removing what a withdrawn category left
229
+
230
+ Withdrawing consent should stop the tracking *and* remove what it stored. `clearRevokedCookies`
231
+ does the second: at start and on every change, it deletes the declared cookies and storage items of
232
+ every category that isn't granted — after "withdraw statistics", `_ga` and every `_ga_*` are gone.
233
+
234
+ ```ts
235
+ import { clearRevokedCookies } from '@luwiostack/cookie-consent'
236
+
237
+ clearRevokedCookies(consent, {
238
+ // optional: per item removed — log it, or reload so scripts that already run stop
239
+ onClear: (cookie, actualName) => console.info('removed', actualName),
240
+ })
241
+ ```
242
+
243
+ - **Declared items only**, matched by the declared name (`*` is a wildcard: `_ga_*` matches
244
+ `_ga_ABC123`). Undeclared cookies are never touched, and neither is `necessary`.
245
+ - **Shared names are kept**: if a granted category also declares a name, it stays.
246
+ - Per `type`: `http` cookies are expired — tried with every parent domain and path, since tags set
247
+ them broadly (GA sets `_ga` on your registrable domain); `local_storage` / `session_storage`
248
+ items are removed; `indexed_db` databases are deleted; a `pixel` stores nothing to remove.
249
+ - **First-party only.** A third-party cookie (`IDE` on doubleclick.net, YouTube's on youtube.com)
250
+ lives on another site — a page can't remove it. `HttpOnly` cookies only your server can.
251
+ - It removes data, it doesn't stop scripts that are already running: reload the page after a
252
+ withdrawal (e.g. from `onClear`) for that.
253
+ - `onClear` reports only what's really gone: a cookie no domain/path variant could reach isn't
254
+ reported, nor an IndexedDB database in a browser that can't list them (it's deleted by exact name).
255
+
256
+ ## Compliance checklist
257
+
258
+ The four categories are granular enough for GDPR / ePrivacy; what regulators check is how the
259
+ choice is collected. The package covers prior blocking (`ConsentGate`, `unblockScripts`, Consent
260
+ Mode's denied default), removal on withdrawal (`clearRevokedCookies`), the cookie declaration,
261
+ re-asking (`policyVersion`, `maxAge`) and the data for a consent log (`onChange`). Your app covers
262
+ the rest:
263
+
264
+ - Reject all next to Accept all on the first layer, with the same weight.
265
+ - No pre-ticked boxes: start the preferences from `isGranted`.
266
+ - A "Cookie settings" link on every page, and a reload when something is withdrawn.
267
+ - Store each decision server-side (`consent_id`, version, time, granted categories).
268
+ - Declare what your setup really sets, checked against a cookie scan; only truly necessary cookies
269
+ under `necessary`. Bump `policyVersion` whenever a vendor is added or moved.
270
+
271
+ Watch out for: Google-served ads (AdSense, Ad Manager, AdMob) in the EEA / UK need a
272
+ Google-certified TCF CMP, which this isn't; the CNIL recommends re-asking after about 6 months
273
+ (set `maxAge`); California expects a Global Privacy Control signal to count as refusing marketing
274
+ (not read by the package); name US vendors in your privacy policy. Guidance, not legal advice.
275
+
276
+ ## API
277
+
278
+ | | |
279
+ | --- | --- |
280
+ | `createConsent({ categories?, policyVersion?, maxAge?, store?, now?, onChange? })` | The consent instance; `categories` maps each fixed category to the vendors used in it. |
281
+ | `CONSENT_CATEGORIES` · `ConsentCategoryId` | `necessary`, `preferences`, `statistics`, `marketing`. |
282
+ | `consent.categories` · `consent.vendors` | The four categories with their vendors (cookies narrowed per category); every vendor in use once. |
283
+ | `consent.getSnapshot()` | `{ status: 'pending' \| 'decided', decision }`. |
284
+ | `consent.isGranted(category, vendorId?)` / `isRequired(category)` | `necessary` is always granted. With a vendor, also whether it's used in that category. |
285
+ | `consent.acceptAll()` / `rejectAll()` / `save(ids)` / `grant(...ids)` / `revoke(...ids)` / `reset()` | Make (or forget) a decision. |
286
+ | `ConsentDecision` | `consent_id`, `policy_version`, `decided_at`, `granted()`, `isGranted(id)`, `toJSON()`. |
287
+ | `googleConsentMode(consent, { mapping?, region?, waitForUpdate?, adsDataRedaction?, urlPassthrough?, gtag? })` | Google Consent Mode v2 default + updates; `DEFAULT_GOOGLE_CONSENT_MAPPING` unless you pass one. |
288
+ | `unblockScripts(consent, options?)` | Activate blocked scripts / `data-src` embeds. |
289
+ | `clearRevokedCookies(consent, { onClear? })` | Remove declared first-party cookies and storage of every category that isn't granted. |
290
+ | `ConsentCookieFormatter.formatLocale(cookie, locale)` | A lifetime as "2 years" / "3 months"; `null` for session / persistent. |
291
+ | `@luwiostack/cookie-consent/vendors` | 10 presets, `defineVendor`, `vendorPresets`, `consentConfigFromData(data, { necessary? })`. |
292
+ | `<Consent consent>` · `useConsent()` | Provider and reactive hook. |
293
+ | `<ConsentGate category vendor? fallback>` | Children only once granted; `fallback(api)` gets `missing`, `grant()`, `openPreferences()`. With a vendor, renders nothing when it isn't used in the category. |
@@ -0,0 +1,55 @@
1
+ //#region src/categories.ts
2
+ /**
3
+ * The fixed consent categories, in display order — the same four every consent tool (and Google
4
+ * Consent Mode) works with. `necessary` is always granted. Each id is also the translation key of
5
+ * the category's name (`category.<id>`) and description (`category.<id>.description`) in the
6
+ * package catalogs.
7
+ */
8
+ const CONSENT_CATEGORIES = [
9
+ "necessary",
10
+ "preferences",
11
+ "statistics",
12
+ "marketing"
13
+ ];
14
+ /** The category that is always granted and can't be refused. */
15
+ const REQUIRED_CATEGORY = "necessary";
16
+ /** Whether a value is one of the fixed category ids. */
17
+ function isConsentCategoryId(value) {
18
+ return CONSENT_CATEGORIES.includes(value);
19
+ }
20
+ //#endregion
21
+ //#region src/errors.ts
22
+ /** Thrown for an invalid consent configuration or an invalid stored decision. */
23
+ var ConsentError = class extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "ConsentError";
27
+ }
28
+ };
29
+ //#endregion
30
+ Object.defineProperty(exports, "CONSENT_CATEGORIES", {
31
+ enumerable: true,
32
+ get: function() {
33
+ return CONSENT_CATEGORIES;
34
+ }
35
+ });
36
+ Object.defineProperty(exports, "ConsentError", {
37
+ enumerable: true,
38
+ get: function() {
39
+ return ConsentError;
40
+ }
41
+ });
42
+ Object.defineProperty(exports, "REQUIRED_CATEGORY", {
43
+ enumerable: true,
44
+ get: function() {
45
+ return REQUIRED_CATEGORY;
46
+ }
47
+ });
48
+ Object.defineProperty(exports, "isConsentCategoryId", {
49
+ enumerable: true,
50
+ get: function() {
51
+ return isConsentCategoryId;
52
+ }
53
+ });
54
+
55
+ //# sourceMappingURL=errors-BqpghFQf.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-BqpghFQf.cjs","names":[],"sources":["../src/categories.ts","../src/errors.ts"],"sourcesContent":["/**\n * The fixed consent categories, in display order — the same four every consent tool (and Google\n * Consent Mode) works with. `necessary` is always granted. Each id is also the translation key of\n * the category's name (`category.<id>`) and description (`category.<id>.description`) in the\n * package catalogs.\n */\nexport const CONSENT_CATEGORIES = ['necessary', 'preferences', 'statistics', 'marketing'] as const\n\n/** `'necessary' | 'preferences' | 'statistics' | 'marketing'` */\nexport type ConsentCategoryId = (typeof CONSENT_CATEGORIES)[number]\n\n/** The category that is always granted and can't be refused. */\nexport const REQUIRED_CATEGORY = 'necessary' satisfies ConsentCategoryId\n\n/** Whether a value is one of the fixed category ids. */\nexport function isConsentCategoryId(value: unknown): value is ConsentCategoryId {\n return (CONSENT_CATEGORIES as readonly unknown[]).includes(value)\n}\n","/** Thrown for an invalid consent configuration or an invalid stored decision. */\nexport class ConsentError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConsentError'\n }\n}\n"],"mappings":";;;;;;;AAMA,MAAa,qBAAqB;CAAC;CAAa;CAAe;CAAc;AAAW;;AAMxF,MAAa,oBAAoB;;AAGjC,SAAgB,oBAAoB,OAA4C;CAC9E,OAAQ,mBAA0C,SAAS,KAAK;AAClE;;;;AChBA,IAAa,eAAb,cAAkC,MAAM;CACtC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
@@ -0,0 +1,32 @@
1
+ //#region src/categories.ts
2
+ /**
3
+ * The fixed consent categories, in display order — the same four every consent tool (and Google
4
+ * Consent Mode) works with. `necessary` is always granted. Each id is also the translation key of
5
+ * the category's name (`category.<id>`) and description (`category.<id>.description`) in the
6
+ * package catalogs.
7
+ */
8
+ const CONSENT_CATEGORIES = [
9
+ "necessary",
10
+ "preferences",
11
+ "statistics",
12
+ "marketing"
13
+ ];
14
+ /** The category that is always granted and can't be refused. */
15
+ const REQUIRED_CATEGORY = "necessary";
16
+ /** Whether a value is one of the fixed category ids. */
17
+ function isConsentCategoryId(value) {
18
+ return CONSENT_CATEGORIES.includes(value);
19
+ }
20
+ //#endregion
21
+ //#region src/errors.ts
22
+ /** Thrown for an invalid consent configuration or an invalid stored decision. */
23
+ var ConsentError = class extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "ConsentError";
27
+ }
28
+ };
29
+ //#endregion
30
+ export { isConsentCategoryId as i, CONSENT_CATEGORIES as n, REQUIRED_CATEGORY as r, ConsentError as t };
31
+
32
+ //# sourceMappingURL=errors-D2ZIcEYK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-D2ZIcEYK.mjs","names":[],"sources":["../src/categories.ts","../src/errors.ts"],"sourcesContent":["/**\n * The fixed consent categories, in display order — the same four every consent tool (and Google\n * Consent Mode) works with. `necessary` is always granted. Each id is also the translation key of\n * the category's name (`category.<id>`) and description (`category.<id>.description`) in the\n * package catalogs.\n */\nexport const CONSENT_CATEGORIES = ['necessary', 'preferences', 'statistics', 'marketing'] as const\n\n/** `'necessary' | 'preferences' | 'statistics' | 'marketing'` */\nexport type ConsentCategoryId = (typeof CONSENT_CATEGORIES)[number]\n\n/** The category that is always granted and can't be refused. */\nexport const REQUIRED_CATEGORY = 'necessary' satisfies ConsentCategoryId\n\n/** Whether a value is one of the fixed category ids. */\nexport function isConsentCategoryId(value: unknown): value is ConsentCategoryId {\n return (CONSENT_CATEGORIES as readonly unknown[]).includes(value)\n}\n","/** Thrown for an invalid consent configuration or an invalid stored decision. */\nexport class ConsentError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConsentError'\n }\n}\n"],"mappings":";;;;;;;AAMA,MAAa,qBAAqB;CAAC;CAAa;CAAe;CAAc;AAAW;;AAMxF,MAAa,oBAAoB;;AAGjC,SAAgB,oBAAoB,OAA4C;CAC9E,OAAQ,mBAA0C,SAAS,KAAK;AAClE;;;;AChBA,IAAa,eAAb,cAAkC,MAAM;CACtC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}