@luwiostack/cookie-consent 0.1.0 → 0.3.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
@@ -4,8 +4,8 @@ Cookie consent for React apps. The four categories are fixed: necessary, prefere
4
4
  and marketing. Per category, you list the vendors your site uses there; every cookie a vendor sets
5
5
  carries its category, so a vendor brings only its cookies of the categories you use it in. The
6
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
7
+ year passes. The package also has a gate for embeds, script unblocking, removal of a withdrawn
8
+ category's cookies and ready-made vendor presets. There is no UI: every app
9
9
  builds its own banner and preferences on `useConsent()`.
10
10
 
11
11
  ```bash
@@ -16,14 +16,69 @@ npm i @luwiostack/cookie-consent
16
16
 
17
17
  ```ts
18
18
  // consent.ts
19
- import { createConsent } from '@luwiostack/cookie-consent'
20
- import { googleAds, googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
19
+ import {
20
+ type ConsentTransferDeclaration,
21
+ type ConsentVendorDeclaration,
22
+ createConsent,
23
+ } from '@luwiostack/cookie-consent'
24
+
25
+ const DAY = 24 * 60 * 60 * 1000
26
+
27
+ // Every vendor in full: the same shape your backend sends (see "Config from your backend").
28
+ // A cookie without a domain is first-party; one with a domain is set on the vendor's.
29
+ const googleTransfers: ConsentTransferDeclaration[] = [
30
+ { country: 'GB', safeguards: ['adequacy'] },
31
+ { country: 'JP', safeguards: ['adequacy'] },
32
+ { country: 'US', safeguards: ['dpf', 'scc'] },
33
+ ]
34
+
35
+ const googleAnalytics: ConsentVendorDeclaration = {
36
+ id: 'google_analytics',
37
+ privacy_policy_url: 'https://policies.google.com/privacy',
38
+ transfers: googleTransfers,
39
+ cookies: [
40
+ { name: '_ga', category: 'statistics', max_age: 730 * DAY },
41
+ { name: '_ga_*', category: 'statistics', max_age: 730 * DAY },
42
+ ],
43
+ }
44
+
45
+ const youtube: ConsentVendorDeclaration = {
46
+ id: 'youtube',
47
+ privacy_policy_url: 'https://policies.google.com/privacy',
48
+ transfers: googleTransfers,
49
+ cookies: [
50
+ { name: 'PREF', category: 'preferences', max_age: 240 * DAY, domain: '.youtube.com' },
51
+ { name: 'YSC', category: 'marketing', max_age: 'session', domain: '.youtube.com' },
52
+ { name: 'VISITOR_INFO1_LIVE', category: 'marketing', max_age: 180 * DAY, domain: '.youtube.com' },
53
+ ],
54
+ }
55
+
56
+ const metaPixel: ConsentVendorDeclaration = {
57
+ id: 'meta_pixel',
58
+ privacy_policy_url: 'https://www.facebook.com/privacy/policy/',
59
+ transfers: [{ country: 'US', safeguards: ['dpf'] }],
60
+ cookies: [
61
+ { name: '_fbp', category: 'marketing', max_age: 90 * DAY },
62
+ { name: 'fr', category: 'marketing', max_age: 90 * DAY, domain: '.facebook.com' },
63
+ ],
64
+ }
65
+
66
+ // Your own strictly necessary cookies — always allowed, never asked.
67
+ const mySite: ConsentVendorDeclaration = {
68
+ id: 'my_site',
69
+ cookies: [
70
+ { name: 'session', category: 'necessary', max_age: 'session' },
71
+ { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
72
+ ],
73
+ }
21
74
 
22
75
  export const consent = createConsent({
76
+ // Per category, the vendors your site uses there. A vendor brings only its cookies of that category.
23
77
  categories: {
24
- statistics: [googleAnalytics()],
25
- preferences: [youtube()], // the YouTube embed — without YouTube's marketing cookies
26
- marketing: [googleAds({ cookies: ['_gcl_au', 'IDE'] })],
78
+ necessary: [mySite],
79
+ statistics: [googleAnalytics],
80
+ preferences: [youtube], // the YouTube embed (PREF) — without YouTube's marketing cookies
81
+ marketing: [metaPixel],
27
82
  },
28
83
  policyVersion: 1, // bump when the vendors change → everyone is asked again
29
84
  // maxAge: 365 days by default
@@ -38,21 +93,30 @@ consent.isGranted('marketing', 'youtube') // false — not used there, so no t
38
93
  ```
39
94
 
40
95
  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
96
+ cookies, which are always allowed. So `preferences: [youtube]` is the embed alone (`PREF`). Add
97
+ `youtube` to `marketing` as well to declare YouTube's tracking cookies, and the vendor then needs
43
98
  both categories. Listing a vendor under a category it has no cookies in throws.
44
99
 
100
+ Each listing may also declare the vendor differently, for example a preset narrowed per category
101
+ (`youtube({ cookies: ['PREF'] })` under preferences, `youtube({ cookies: ['YSC'] })` under
102
+ marketing). The vendor then gets the cookies of every listing. Its `privacy_policy_url` and
103
+ `transfers`, and a cookie listed twice, must be declared the same way each time, or it throws.
104
+
105
+ In production the declarations come from your backend, in this same shape: see
106
+ [Config from your backend](#config-from-your-backend).
107
+
45
108
  **Where the decision is kept.** By default in `localStorage` (`luwio.consent`), synced across
46
109
  tabs. A stored decision stops counting when its policy version differs, when it's older than
47
110
  `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.
111
+ tolerated). Where storage is blocked or full, the visitor's choice still applies **for this page** — the
112
+ banner closes, gates open — until the store does change (another tab stores a decision, which then
113
+ wins), and they're asked again on the next page load; `onChange` fires as usual.
51
114
 
52
115
  `consent.categories` is always the four categories, in order (`CONSENT_CATEGORIES`). Each one
53
116
  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.
117
+ always granted and never part of the question. Categories carry no text: like every LuwioStack
118
+ domain object they have a `machine_name`, so render `t(category.machine_name)` (and
119
+ `t(category.description_machine_name)`) from the catalogs below.
56
120
 
57
121
  ## React
58
122
 
@@ -102,6 +166,30 @@ product. `useConsent()` gives you what they need:
102
166
  Keep your preferences' unsaved ticks in your own state, starting from `isGranted`, so nothing is
103
167
  ever pre-ticked. `apps/showcase` (`src/app/CookieBanner.tsx`) is a full example.
104
168
 
169
+ ### Pages without the banner
170
+
171
+ Don't let the banner cover the page that explains it: the privacy and cookie policy, the legal
172
+ notice. Where the banner shows is your app's call, so decide it per route. With
173
+ `@luwiostack/router`, flag the route with `staticData` and read the flag in your banner:
174
+
175
+ ```tsx
176
+ // privacy.route.tsx
177
+ createRoute({ id: 'privacy', staticData: { hideCookieBanner: true }, … })
178
+
179
+ // CookieBanner.tsx
180
+ const { needsDecision, isPreferencesOpen } = useConsent()
181
+ const hideBanner = useRouteStaticData((d) => d.hideCookieBanner === true)
182
+ if (isPreferencesOpen) return <Preferences />
183
+ if (needsDecision && !hideBanner) return <Banner />
184
+ return null
185
+ ```
186
+
187
+ Type the flag once by augmenting `RouteStaticData` (see the router README). Hide only the
188
+ **banner**, not the preferences: a visitor who opens "Cookie settings" on the privacy page gets them.
189
+ Nothing is unblocked meanwhile: the status stays `pending`, so only `necessary` is granted, and the
190
+ banner shows again on the next page. Prefer a route flag over checking the pathname, which breaks
191
+ as soon as the slug is translated.
192
+
105
193
  ## Vendors and their cookies
106
194
 
107
195
  Most cookies come from the same handful of services, so the package ships their declarations at
@@ -119,7 +207,7 @@ metaPixel({ extra: [{ name: 'my_flag', category: 'marketing', max_age: 'session'
119
207
  // Your own site's necessary cookies: never asked about, but they must be declared. List them under
120
208
  // `necessary` — the session, CSRF token and this choice's own storage item.
121
209
  const mySite = {
122
- id: 'my_site', // t('my_site'), t('my_site.session') … in your own catalog
210
+ id: 'my_site', // t('my_site'), t('my_site_session') … in your own catalog
123
211
  cookies: [
124
212
  { name: 'session', category: 'necessary', max_age: 'session' },
125
213
  { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
@@ -133,28 +221,67 @@ const DAY = 24 * 60 * 60 * 1000
133
221
  export const acmeChat = defineVendor({
134
222
  id: 'acme_chat', // t('acme_chat') → the name
135
223
  privacy_policy_url: 'https://acme.example/privacy',
224
+ transfers: [{ country: 'US', safeguards: ['dpf', 'scc'] }], // [] when the data stays in the EEA
136
225
  cookies: [
137
226
  { name: 'acme_id', category: 'preferences', max_age: 365 * DAY }, // type defaults to 'http'
138
227
  { name: 'acme_open', category: 'necessary', type: 'session_storage', max_age: 'session' },
228
+ { name: 'acme_ad', category: 'marketing', max_age: 90 * DAY, domain: '.acme.example' },
139
229
  ],
140
230
  })
141
231
  ```
142
232
 
143
- Each cookie has a `category`, a `max_age` and an optional `type`:
233
+ Each cookie has a `category`, a `max_age` and an optional `type` and `domain`:
144
234
 
145
235
  - `max_age` is milliseconds, `'session'` or `'persistent'`.
146
236
  - `type` is `http` (the default), `local_storage`, `session_storage`, `indexed_db` or `pixel`.
237
+ - `domain` is the vendor's domain a third-party cookie is set on (`.youtube.com`); leave it out for
238
+ one on your own domain. The resolved cookie carries `party`: `first` or `third`.
239
+
240
+ A vendor's `transfers` lists the countries outside the EEA it sends personal data to, each with its
241
+ safeguards: `adequacy` (an EU adequacy decision), `dpf` (EU-US Data Privacy Framework), `scc`
242
+ (standard contractual clauses) or `bcr` (binding corporate rules). `[]` says the data stays in the
243
+ EEA; leaving it out says nothing. Every preset declares it.
147
244
 
148
245
  `ConsentCookieFormatter.formatLocale(cookie, locale)` renders a lifetime as "2 years" or "3
149
- months". It returns `null` for `session` and `persistent`; translate those yourself.
246
+ months". It returns `null` for `session` and `persistent`: translate those with
247
+ `t(cookie.max_age_machine_name)`.
248
+
249
+ Every text has one translation key, a snake_case `machine_name` the consent instance hands out —
250
+ nothing builds a key itself. The text lives in the downloadable catalogs
251
+ (`translations/cookie-consent.<locale>.json`, in en, nl, fr, de and es):
252
+
253
+ | Render | Key | Example |
254
+ | --- | --- | --- |
255
+ | `t(category.machine_name)` | `consent_category_<id>` | `consent_category_statistics` |
256
+ | `t(category.description_machine_name)` | `consent_category_<id>_description` | `consent_category_statistics_description` |
257
+ | `t(vendor.machine_name)` | the vendor id as a machine name | `google_analytics` |
258
+ | `t(cookie.machine_name)` (its purpose) | the vendor's plus the cookie name, `*` as `wildcard` | `google_analytics_ga`, `google_analytics_ga_wildcard` (`_ga_*`) |
259
+ | `t(cookie.type_machine_name)` | `consent_cookie_type_<type>` | `consent_cookie_type_local_storage` |
260
+ | `t(cookie.max_age_machine_name)` | `consent_max_age_<word>` | `consent_max_age_session` |
261
+ | `t(cookie.party_machine_name)` | `consent_cookie_party_<party>` | `consent_cookie_party_third` |
262
+ | `t(key)` for each of `transfer.safeguard_machine_names` | `consent_transfer_safeguard_<safeguard>` | `consent_transfer_safeguard_dpf` |
263
+
264
+ A transfer's `country` is an ISO code: name it with `new Intl.DisplayNames([locale], { type: 'region' })`.
150
265
 
151
- The text lives in the downloadable catalogs (`translations/cookie-consent.<locale>.json`, in en, nl, fr,
152
- de and es):
266
+ ```tsx
267
+ <h3>{t(vendor.machine_name)}</h3>
268
+ {vendor.cookies.map((cookie) => (
269
+ <tr key={cookie.name}>
270
+ <td><code>{cookie.name}</code></td>
271
+ <td>{t(cookie.machine_name)}</td>
272
+ <td>{ConsentCookieFormatter.formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name ?? '')}</td>
273
+ <td>{t(cookie.type_machine_name)}</td>
274
+ </tr>
275
+ ))}
276
+ ```
153
277
 
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.
278
+ You declare vendors (`ConsentVendorDeclaration`: `id` and `cookies`, each a
279
+ `ConsentCookieDeclaration`); the machine names are derived. Every machine name must name one thing:
280
+ two cookie names, two vendor ids, or a vendor and another vendor's cookie (`google` + cookie
281
+ `analytics` against a `google_analytics` vendor) that come out the same throw a `ConsentError`, as does
282
+ a name without letters or digits. A vendor id whose machine name is `consent` or starts with
283
+ `consent_` (`consent_tool`, `Consent Tool`) is reserved for the package's own keys
284
+ (`consent_category_*`, …) and throws too — `consentmanager` is fine — also when they come from your backend.
158
285
 
159
286
  ### Config from your backend
160
287
 
@@ -213,9 +340,8 @@ vendor still brings its own necessary cookies (reCAPTCHA's, say) under the categ
213
340
  ## Outside React
214
341
 
215
342
  ```ts
216
- import { clearRevokedCookies, googleConsentMode, unblockScripts } from '@luwiostack/cookie-consent'
343
+ import { clearRevokedCookies, unblockScripts } from '@luwiostack/cookie-consent'
217
344
 
218
- googleConsentMode(consent) // before gtag.js / GTM loads; standard mapping (ads → marketing, …)
219
345
  unblockScripts(consent) // activates <script type="text/plain" data-consent="statistics">,
220
346
  // plus data-consent-vendor="meta_pixel" to also need that vendor there
221
347
  clearRevokedCookies(consent) // removes the cookies / storage of categories that aren't granted
@@ -223,7 +349,10 @@ clearRevokedCookies(consent) // removes the cookies / storage of categories that
223
349
 
224
350
  `unblockScripts` keeps an activated script's CSP `nonce`, so it works on a site with a nonce-based
225
351
  `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`.
352
+ Scripts run in document order, as the parser would run them: consecutive external scripts download
353
+ in parallel and run in order, and an inline script waits until every external script above it has loaded (or
354
+ failed) — so `lib.js` followed by an inline `lib.init()` just works. An `async` script holds nothing up. Activation is one-way — a withdrawn category can't un-run a script;
355
+ reload from `onChange`.
227
356
 
228
357
  ### Removing what a withdrawn category left
229
358
 
@@ -256,8 +385,7 @@ clearRevokedCookies(consent, {
256
385
  ## Compliance checklist
257
386
 
258
387
  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,
388
+ choice is collected. The package covers prior blocking (`ConsentGate`, `unblockScripts`), removal on withdrawal (`clearRevokedCookies`), the cookie declaration,
261
389
  re-asking (`policyVersion`, `maxAge`) and the data for a consent log (`onChange`). Your app covers
262
390
  the rest:
263
391
 
@@ -271,7 +399,8 @@ the rest:
271
399
  Watch out for: Google-served ads (AdSense, Ad Manager, AdMob) in the EEA / UK need a
272
400
  Google-certified TCF CMP, which this isn't; the CNIL recommends re-asking after about 6 months
273
401
  (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.
402
+ (not read by the package); name the countries and safeguards of each vendor's `transfers` in your
403
+ cookie declaration and privacy policy. Guidance, not legal advice.
275
404
 
276
405
  ## API
277
406
 
@@ -279,12 +408,13 @@ Google-certified TCF CMP, which this isn't; the CNIL recommends re-asking after
279
408
  | --- | --- |
280
409
  | `createConsent({ categories?, policyVersion?, maxAge?, store?, now?, onChange? })` | The consent instance; `categories` maps each fixed category to the vendors used in it. |
281
410
  | `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. |
411
+ | `consent.categories` · `consent.vendors` | The four categories with their vendors (cookies narrowed per category); every vendor in use once. Each with its `machine_name`s. |
412
+ | `ConsentVendorDeclaration` · `ConsentCookieDeclaration` · `ConsentTransferDeclaration` | What you declare: `{ id, privacy_policy_url?, transfers?, cookies }`, `{ name, category, type?, max_age, domain? }`, `{ country, safeguards }`. |
413
+ | `ConsentCategory` · `ConsentVendor` · `ConsentCookie` · `ConsentTransfer` | What you render: the same plus `machine_name` (and `description_machine_name`, `type_machine_name`, `party`, `party_machine_name`, `max_age_machine_name?`, `safeguard_machine_names`). |
283
414
  | `consent.getSnapshot()` | `{ status: 'pending' \| 'decided', decision }`. |
284
415
  | `consent.isGranted(category, vendorId?)` / `isRequired(category)` | `necessary` is always granted. With a vendor, also whether it's used in that category. |
285
416
  | `consent.acceptAll()` / `rejectAll()` / `save(ids)` / `grant(...ids)` / `revoke(...ids)` / `reset()` | Make (or forget) a decision. |
286
417
  | `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
418
  | `unblockScripts(consent, options?)` | Activate blocked scripts / `data-src` embeds. |
289
419
  | `clearRevokedCookies(consent, { onClear? })` | Remove declared first-party cookies and storage of every category that isn't granted. |
290
420
  | `ConsentCookieFormatter.formatLocale(cookie, locale)` | A lifetime as "2 years" / "3 months"; `null` for session / persistent. |