@venturetime/consent 0.0.0-stage → 0.2.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/CHANGELOG.md +36 -0
- package/LICENSE +21 -0
- package/README.md +226 -2
- package/dist/index.d.ts +271 -0
- package/dist/index.js +274 -0
- package/dist/react.d.ts +136 -0
- package/dist/react.js +67 -0
- package/package.json +60 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
Hardening after an outside review. Sites should call `consent.start(model)`
|
|
6
|
+
at page start (it replaces `ensureDefault()`, which still works) and wire
|
|
7
|
+
`onError`.
|
|
8
|
+
|
|
9
|
+
- **An older answer cannot come back.** A late server response used to be
|
|
10
|
+
able to put an earlier "yes" back over a "no". The latest answer is now
|
|
11
|
+
also kept in `localStorage`, and corrects the cookie as the response lands
|
|
12
|
+
or on the next page load, before any tag runs. `consent.reconcile()` is
|
|
13
|
+
public for sites that record outside the `record` hook.
|
|
14
|
+
- **A failing hook no longer stops a decision.** `onApply`, subscribers and
|
|
15
|
+
`record` are isolated; failures go to the new `onError(error, step)`.
|
|
16
|
+
- **`consent.start(model)`** runs `onApply` with what applies at page start,
|
|
17
|
+
answered or not. `onApply` now gets a second argument: `'answer'`,
|
|
18
|
+
`'start'` or `'other-tab'`.
|
|
19
|
+
- **Answers from other tabs** are applied at once; `useConsentBanner` closes
|
|
20
|
+
the question when an answer is given elsewhere.
|
|
21
|
+
- **Global Privacy Control wins over a stored yes** in an `opt-out` model.
|
|
22
|
+
New config field `globalPrivacyControl: 'signal-wins' | 'answer-wins'`.
|
|
23
|
+
New `effectiveConsent()` and `consent.effective(model)`.
|
|
24
|
+
- **A record that is refused is reported:** a rejected promise, a thrown
|
|
25
|
+
hook or a response with `ok: false`.
|
|
26
|
+
- **Config is validated** at every entry point (`assertConsentConfig`):
|
|
27
|
+
cookie name, version, lifetime, cookie patterns (no `g` or `y` flag),
|
|
28
|
+
paths.
|
|
29
|
+
- **Cookie cleanup takes paths:** `paths` on an optional cookie.
|
|
30
|
+
- `consentDefaultScript` now needs `maxAgeSeconds` in its config (pass the
|
|
31
|
+
whole config).
|
|
32
|
+
- Real-browser tests (Chromium, WebKit) of the built package.
|
|
33
|
+
|
|
34
|
+
## 0.1.0
|
|
35
|
+
|
|
36
|
+
First release.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Venturetime AS
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,227 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @venturetime/consent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cookie consent without a banner vendor. The rules that are the same on every
|
|
4
|
+
site live here; each site brings its own look, wording and storage.
|
|
5
|
+
|
|
6
|
+
It has no markup, no text, no database and no framework in its core. React is
|
|
7
|
+
needed only for `@venturetime/consent/react`.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @venturetime/consent
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Why not a vendor banner
|
|
14
|
+
|
|
15
|
+
A vendor banner keeps its own copy of the visitor's answer in its own cookie,
|
|
16
|
+
next to whatever the site keeps. Two copies can disagree: a tag that never
|
|
17
|
+
restores the answer on a returning visit, a cookie sweep that deletes the
|
|
18
|
+
site's own cookies. A vendor banner is also licensed per domain, so every new
|
|
19
|
+
market needs setup in someone else's dashboard before it can ask anyone
|
|
20
|
+
anything. Here there is one answer, in one first-party cookie, written by the
|
|
21
|
+
code that reads it.
|
|
22
|
+
|
|
23
|
+
## What is in here
|
|
24
|
+
|
|
25
|
+
| Module | What it does |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| `state` | The answer `{ analytics, marketing }`, its cookie value (`a1m0v1`), the version rule, Google Consent Mode v2 signals, `effectiveConsent` (what applies to a visitor now: the answer, else the model's rule, with Global Privacy Control), the cookie as a server sets it, `assertConsentConfig` |
|
|
28
|
+
| `inline-script` | The `<head>` script: Consent Mode default, then the stored answer, before the tag manager loads |
|
|
29
|
+
| `controller` | `createConsent(config, hooks)`: the one place an answer is applied — Consent Mode update → the site's hooks → cookies of a refused purpose removed → cookie and memory written → subscribers. `start(model)` at page start; answers from other tabs; a failing hook never stops a decision |
|
|
30
|
+
| `cookies` | Which cookies to expire for a refused purpose, on the host and its parent domains |
|
|
31
|
+
| `react` | `useConsentBanner(consent, model)`: when the banner shows, what the switches start as, focus and Escape. No markup |
|
|
32
|
+
|
|
33
|
+
## Use
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// consent.ts — the site's config and controller
|
|
37
|
+
import { createConsent, type ConsentConfig } from '@venturetime/consent';
|
|
38
|
+
|
|
39
|
+
export const CONSENT: ConsentConfig = {
|
|
40
|
+
cookieName: 'site_consent',
|
|
41
|
+
version: 1, // raise it when what you ask changes: everyone is asked again
|
|
42
|
+
maxAgeSeconds: 60 * 60 * 24 * 180,
|
|
43
|
+
optionalCookies: {
|
|
44
|
+
analytics: [{ pattern: /^_ga(?:_.+)?$/, setBy: 'Google Analytics' }],
|
|
45
|
+
marketing: [{ pattern: /^_fbp$/, setBy: 'Meta' }],
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const consent = createConsent(CONSENT, {
|
|
50
|
+
// Other tools that follow consent. Runs on every decision and at page start.
|
|
51
|
+
onApply: (state) => (state.analytics ? analytics.optIn() : analytics.optOut()),
|
|
52
|
+
// Return the fetch promise: a network failure or a response that is not ok goes to onError.
|
|
53
|
+
record: (state, source) =>
|
|
54
|
+
fetch('/api/consent', {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: { 'content-type': 'application/json' },
|
|
57
|
+
body: JSON.stringify({ ...state, source }),
|
|
58
|
+
keepalive: true,
|
|
59
|
+
}),
|
|
60
|
+
// A hook threw, the record was not taken, storage was refused. The answer was applied all the same.
|
|
61
|
+
onError: (error, step) => reportError(error, { step }),
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
// In <head>, before the tag manager's loader
|
|
67
|
+
import { consentDefaultScript } from '@venturetime/consent';
|
|
68
|
+
|
|
69
|
+
<script dangerouslySetInnerHTML={{ __html: consentDefaultScript(CONSENT, 'opt-in') }} />;
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
// The banner: your markup, this hook's behaviour
|
|
74
|
+
'use client';
|
|
75
|
+
import { useConsentBanner } from '@venturetime/consent/react';
|
|
76
|
+
|
|
77
|
+
// Once, before optional SDKs initialise: a Consent Mode default exists, a
|
|
78
|
+
// cookie a late server response got wrong is put right, and onApply runs
|
|
79
|
+
// with what applies to this visitor — answered or not.
|
|
80
|
+
consent.start('opt-in');
|
|
81
|
+
|
|
82
|
+
export function Banner() {
|
|
83
|
+
const b = useConsentBanner(consent, 'opt-in');
|
|
84
|
+
if (b.view === 'hidden') return null;
|
|
85
|
+
return (
|
|
86
|
+
<section ref={b.cardRef} role="dialog" aria-modal="false" tabIndex={-1}>
|
|
87
|
+
{/* b.view === 'choose': one switch per purpose from b.choice / b.setChoice, and b.save */}
|
|
88
|
+
<button onClick={b.rejectAll}>Reject all</button>
|
|
89
|
+
<button onClick={b.acceptAll}>Accept all</button>
|
|
90
|
+
{b.view === 'ask' && <button onClick={b.choose}>Let me choose</button>}
|
|
91
|
+
</section>
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
// POST /api/consent — the record, and the cookie from the server
|
|
98
|
+
import { consentCookie } from '@venturetime/consent';
|
|
99
|
+
|
|
100
|
+
const cookie = consentCookie(state, CONSENT, { secure: true });
|
|
101
|
+
// store one row per answer, then set cookie.name / cookie.value / cookie.options on the response
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## What a site brings
|
|
105
|
+
|
|
106
|
+
1. **Config** (`ConsentConfig`): the cookie's name, the version of what is
|
|
107
|
+
asked, how long an answer stands, and the optional cookies its tags set.
|
|
108
|
+
2. **The model**: `opt-in` (nothing optional before a yes; the banner asks on
|
|
109
|
+
the first visit) or `opt-out` (no banner on arrival; a browser sending
|
|
110
|
+
Global Privacy Control has refused marketing), per site or per market.
|
|
111
|
+
3. **The banner's markup**, in the site's own design, driven by
|
|
112
|
+
`useConsentBanner`. Two rules the markup must keep: "reject all" and
|
|
113
|
+
"accept all" are the same control side by side, and the page behind the
|
|
114
|
+
banner is never blocked.
|
|
115
|
+
4. **The wording**, per language, including the name of each recipient.
|
|
116
|
+
5. **A "Cookie settings" link** on every page that calls
|
|
117
|
+
`consent.openSettings()`.
|
|
118
|
+
6. **A server route** that the `record` hook posts to. It stores one row per
|
|
119
|
+
answer (who, market, language, choices, version, time) and sets the cookie
|
|
120
|
+
again with `consentCookie(...)`: Safari cuts a cookie written by a script
|
|
121
|
+
to seven days, one set by a response keeps its full life. The route must
|
|
122
|
+
refuse a request from another origin — its response sets the cookie that
|
|
123
|
+
says what the visitor agreed to.
|
|
124
|
+
7. **Hooks** for anything else that follows the answer (`onApply`: product
|
|
125
|
+
analytics opt-in and opt-out), and `onError` wired to the site's
|
|
126
|
+
monitoring.
|
|
127
|
+
8. **One call at page start**, `consent.start(model)`, before optional SDKs
|
|
128
|
+
initialise. On the server, read the cookie with
|
|
129
|
+
`effectiveConsent(readConsent(cookie, CONFIG), model, request has Sec-GPC: 1, CONFIG)`.
|
|
130
|
+
|
|
131
|
+
## Moving a site onto it
|
|
132
|
+
|
|
133
|
+
1. List every tag the site runs and every cookie those tags set. Put the
|
|
134
|
+
cookies in `optionalCookies` under their purpose.
|
|
135
|
+
2. Make sure each tag in the tag manager waits for its Consent Mode signal
|
|
136
|
+
(`analytics_storage`, `ad_storage`). A tag that fires without one is not
|
|
137
|
+
stopped by any banner.
|
|
138
|
+
3. Add the config, the controller, the inline script in `<head>` before the
|
|
139
|
+
tag manager, the banner, the settings link, the route and the table.
|
|
140
|
+
4. If the site had a vendor banner whose answers should carry over, read the
|
|
141
|
+
vendor's cookie once in an inline script before `consentDefaultScript`,
|
|
142
|
+
write this cookie, and remove the vendor's. Otherwise visitors are asked
|
|
143
|
+
again.
|
|
144
|
+
5. Check in a browser with third-party requests blocked: default denied and
|
|
145
|
+
no optional cookie before an answer; update after; restored on reload
|
|
146
|
+
before the tag manager loads; a refusal removes the cookies.
|
|
147
|
+
6. On the day it goes live: remove the vendor's tag from the tag manager,
|
|
148
|
+
export the vendor's consent log, update the privacy policy so it lists the
|
|
149
|
+
cookies itself, cancel the vendor.
|
|
150
|
+
|
|
151
|
+
## What it guarantees, and what it does not
|
|
152
|
+
|
|
153
|
+
**An older answer cannot come back.** The server sets the cookie when it has
|
|
154
|
+
recorded an answer, and responses can arrive out of order: a slow "yes"
|
|
155
|
+
landing after a quick "no", in this tab or another. Every answer is also kept
|
|
156
|
+
in `localStorage` under the cookie's name, which no response can write. When
|
|
157
|
+
the two disagree, that memory wins: as the late response lands if the page is
|
|
158
|
+
still open, otherwise in the inline script of the next page load, before any
|
|
159
|
+
tag runs, and the cookie is rewritten so the server reads the right answer
|
|
160
|
+
too. The memory only corrects a cookie that exists — when the cookie ends
|
|
161
|
+
(expired, cleared), so does the answer.
|
|
162
|
+
|
|
163
|
+
**A failing hook cannot stop a decision.** If `onApply`, a subscriber or
|
|
164
|
+
`record` throws, the answer is still stored, cleaned up after, announced and
|
|
165
|
+
recorded. The failure goes to `onError`.
|
|
166
|
+
|
|
167
|
+
**Tabs agree.** An answer in one tab reaches the tags, `onApply` and the
|
|
168
|
+
banner in every other tab of the site at once.
|
|
169
|
+
|
|
170
|
+
**Global Privacy Control**, in an `opt-out` model: marketing is off for as
|
|
171
|
+
long as the browser sends the signal, also over a stored yes
|
|
172
|
+
(`globalPrivacyControl: 'answer-wins'` in the config reverses that; decide it
|
|
173
|
+
per market with whoever owns its privacy policy). In an `opt-in` model the
|
|
174
|
+
signal changes nothing: nothing runs without a yes, and a yes was asked for.
|
|
175
|
+
|
|
176
|
+
**What an answer is valid for:** this browser, this host, this cookie name,
|
|
177
|
+
until the cookie's lifetime ends or `version` is raised. It carries no market
|
|
178
|
+
and no model: a site that serves markets with different rules from one host
|
|
179
|
+
should give each its own `cookieName`. An answer to a higher version than the
|
|
180
|
+
site now runs still counts (a rollback), which assumes a version only adds to
|
|
181
|
+
what was asked.
|
|
182
|
+
|
|
183
|
+
What it does **not** guarantee:
|
|
184
|
+
|
|
185
|
+
- **That a tag has stopped by the time the cleanup runs.** The Consent Mode
|
|
186
|
+
update is a command on the data layer; a tag manager normally acts on it at
|
|
187
|
+
once, but a tag in mid-flight can still write a cookie afterwards. The
|
|
188
|
+
stored answer is the durable part: from the next page load every tag starts
|
|
189
|
+
denied. Check what you rely on against your own container, with nothing
|
|
190
|
+
blocked.
|
|
191
|
+
- **That every trace of a refused purpose is gone.** Cleanup removes cookies
|
|
192
|
+
a script can see, on the host and its parent domains, on the paths you list
|
|
193
|
+
(`/` by default). It cannot reach `HttpOnly` or server-set cookies, cookies
|
|
194
|
+
of another site in an iframe, or what a tag keeps in `localStorage` or
|
|
195
|
+
IndexedDB. Those are the site's to clean up where they exist.
|
|
196
|
+
- **That a tag waits for consent at all.** A tag that does not check its
|
|
197
|
+
Consent Mode signal is not stopped by any banner.
|
|
198
|
+
- **That the record was written.** The answer never waits for the server.
|
|
199
|
+
Wire `onError` to your monitoring, or a failing route goes unseen.
|
|
200
|
+
|
|
201
|
+
## Tests
|
|
202
|
+
|
|
203
|
+
`pnpm test` runs the unit tests. `pnpm test:browser` builds the package and
|
|
204
|
+
runs it in Chromium and WebKit against a small test server
|
|
205
|
+
(`test/browser`): real cookies with real paths and lifetimes, a server
|
|
206
|
+
response that really arrives late, leaving the page before it lands, two
|
|
207
|
+
tabs, Global Privacy Control. They do not run a real tag container; that
|
|
208
|
+
check belongs in each site.
|
|
209
|
+
|
|
210
|
+
## Changing this package
|
|
211
|
+
|
|
212
|
+
- Nothing that only one site needs goes in here: no markup, no text, no
|
|
213
|
+
cookie names, no database.
|
|
214
|
+
- The cookie format and the order inside `apply` are a contract with every
|
|
215
|
+
site's stored answers and tags. Changing either is a breaking change and a
|
|
216
|
+
new major version.
|
|
217
|
+
- The inline script has its own copy of the cookie parser. The tests check it
|
|
218
|
+
against `readConsent`; keep them in step.
|
|
219
|
+
|
|
220
|
+
## Releasing
|
|
221
|
+
|
|
222
|
+
Set the version in `package.json`, merge, then publish a GitHub release whose
|
|
223
|
+
tag is that version with a `v` in front (`v0.2.0`). The release workflow runs
|
|
224
|
+
the checks and publishes to npm. Nothing is published any other way.
|
|
225
|
+
|
|
226
|
+
This is not legal advice: the package keeps the mechanics right, and the
|
|
227
|
+
wording, the purposes and the choice of model are each site's to decide.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/** What a visitor can say yes or no to. Necessary cookies are not a purpose: they are not optional. */
|
|
2
|
+
type Purpose = 'analytics' | 'marketing';
|
|
3
|
+
interface ConsentState {
|
|
4
|
+
/** analytics_storage — measuring how the site is used. */
|
|
5
|
+
analytics: boolean;
|
|
6
|
+
/** ad_storage + ad_user_data + ad_personalization — ad platforms, ad conversions. */
|
|
7
|
+
marketing: boolean;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* How a site (or one market of it) treats a visitor who has not answered:
|
|
11
|
+
* - 'opt-in': nothing optional runs until the visitor says yes; the banner
|
|
12
|
+
* asks on the first visit (UK, EU).
|
|
13
|
+
* - 'opt-out': everything runs until the visitor says no; no banner on
|
|
14
|
+
* arrival, a "Cookie settings" link is where they say no, and a browser
|
|
15
|
+
* that sends Global Privacy Control has already said no to marketing.
|
|
16
|
+
*/
|
|
17
|
+
type ConsentModel = 'opt-in' | 'opt-out';
|
|
18
|
+
/** One optional cookie a tag sets: how to recognise its name, and who sets it. */
|
|
19
|
+
interface OptionalCookie {
|
|
20
|
+
/** Matches the cookie's name. No `g` or `y` flag: those make a pattern remember where it last matched. */
|
|
21
|
+
pattern: RegExp;
|
|
22
|
+
setBy: string;
|
|
23
|
+
/** The paths the cookie may have been set on. A cookie can only be removed
|
|
24
|
+
* by naming its path. Default: `['/']`, where tags set theirs. */
|
|
25
|
+
paths?: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
28
|
+
interface ConsentConfig {
|
|
29
|
+
/** The first-party cookie the answer is stored in, e.g. "pz_consent". */
|
|
30
|
+
cookieName: string;
|
|
31
|
+
/**
|
|
32
|
+
* The version of what the visitor is asked to agree to. Raise it when a
|
|
33
|
+
* purpose is added or changed, or a new kind of recipient joins one (a new
|
|
34
|
+
* ad platform under marketing): every stored answer below it stops
|
|
35
|
+
* counting and the visitor is asked again. Rewording the banner does not
|
|
36
|
+
* need a new version. An answer stored without a version is version 1.
|
|
37
|
+
*/
|
|
38
|
+
version: number;
|
|
39
|
+
/** How long an answer stands before the visitor is asked again, in seconds. */
|
|
40
|
+
maxAgeSeconds: number;
|
|
41
|
+
/**
|
|
42
|
+
* Every optional cookie the site's tags set, by purpose. One list with two
|
|
43
|
+
* jobs: what is removed from the browser when a purpose is refused or
|
|
44
|
+
* withdrawn, and what the site's privacy policy has to name.
|
|
45
|
+
*/
|
|
46
|
+
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
47
|
+
/**
|
|
48
|
+
* In an opt-out model, what decides when the browser sends Global Privacy
|
|
49
|
+
* Control and the visitor has also stored a yes to marketing:
|
|
50
|
+
* - 'signal-wins' (default): the signal. Marketing stays off for as long
|
|
51
|
+
* as the browser sends it, whatever was answered before.
|
|
52
|
+
* - 'answer-wins': the stored answer.
|
|
53
|
+
* Has no effect in an opt-in model, where nothing runs without a yes.
|
|
54
|
+
*/
|
|
55
|
+
globalPrivacyControl?: 'signal-wins' | 'answer-wins';
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Refuses a config that would misbehave somewhere else later: a cookie name
|
|
59
|
+
* that is not a plain name (it is written into cookies, a regular expression
|
|
60
|
+
* and an inline script), a version or lifetime that is not a positive whole
|
|
61
|
+
* number, a cookie pattern that remembers state, a path that is not a path.
|
|
62
|
+
* Checks the fields it is given; every entry point of the package calls it.
|
|
63
|
+
*/
|
|
64
|
+
declare function assertConsentConfig(config: Partial<ConsentConfig>): void;
|
|
65
|
+
type Signal = 'granted' | 'denied';
|
|
66
|
+
interface ConsentModeParams {
|
|
67
|
+
analytics_storage: Signal;
|
|
68
|
+
ad_storage: Signal;
|
|
69
|
+
ad_user_data: Signal;
|
|
70
|
+
ad_personalization: Signal;
|
|
71
|
+
functionality_storage: Signal;
|
|
72
|
+
personalization_storage: Signal;
|
|
73
|
+
}
|
|
74
|
+
/** Compact cookie value: "a1m0v1" = analytics granted, marketing denied,
|
|
75
|
+
* answered under version 1. Short so the inline restore script's parser
|
|
76
|
+
* stays a one-liner. */
|
|
77
|
+
declare function serializeConsent(state: ConsentState, config: Pick<ConsentConfig, 'version'>): string;
|
|
78
|
+
/**
|
|
79
|
+
* The answer in a cookie value, or null when there is none that still counts
|
|
80
|
+
* (no cookie, junk, or an answer to an older version).
|
|
81
|
+
*
|
|
82
|
+
* What an answer is valid for: this browser, on this host, under this cookie
|
|
83
|
+
* name, for six months or whatever the site set, until the version is
|
|
84
|
+
* raised. It carries no market and no model. Sites that serve markets with
|
|
85
|
+
* different rules from one host should give each its own cookie name, or an
|
|
86
|
+
* answer given under one market's wording counts in the other. An answer to
|
|
87
|
+
* a HIGHER version than the site now runs also counts: that is what a
|
|
88
|
+
* rollback looks like, and it assumes a version only ever adds to what was
|
|
89
|
+
* asked. If a version can also take something away, raise it again instead
|
|
90
|
+
* of rolling back.
|
|
91
|
+
*/
|
|
92
|
+
declare function readConsent(value: string | undefined | null, config: Pick<ConsentConfig, 'version'>): ConsentState | null;
|
|
93
|
+
/** What applies to a visitor who has not answered. `gpc` is the browser's
|
|
94
|
+
* Global Privacy Control signal (navigator.globalPrivacyControl, or the
|
|
95
|
+
* `Sec-GPC: 1` request header). */
|
|
96
|
+
declare function unansweredConsent(model: ConsentModel, gpc: boolean): ConsentState;
|
|
97
|
+
/**
|
|
98
|
+
* What applies to a visitor right now: their stored answer, or the model's
|
|
99
|
+
* rule when there is none — and, in an opt-out model, Global Privacy Control
|
|
100
|
+
* on top of either unless the site chose 'answer-wins'. Use this wherever
|
|
101
|
+
* something has to follow consent: an SDK starting up, a server reading the
|
|
102
|
+
* cookie off a request (`gpc` = the `Sec-GPC: 1` header).
|
|
103
|
+
*/
|
|
104
|
+
declare function effectiveConsent(stored: ConsentState | null, model: ConsentModel, gpc: boolean, config?: Pick<ConsentConfig, 'globalPrivacyControl'>): ConsentState;
|
|
105
|
+
/** The Consent Mode signal every optional storage type starts in. */
|
|
106
|
+
declare function defaultSignal(model: ConsentModel): Signal;
|
|
107
|
+
/** A decision as Consent Mode signals. Functionality is always granted (the
|
|
108
|
+
* banner has no switch for it: nothing optional is stored under it);
|
|
109
|
+
* personalization follows analytics. */
|
|
110
|
+
declare function consentModeParams(state: ConsentState): ConsentModeParams;
|
|
111
|
+
/** Global Privacy Control as this browser reports it. */
|
|
112
|
+
declare function browserGpc(): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* The stored value in this browser, or undefined: the cookie, corrected by
|
|
115
|
+
* the browser's own memory of the latest answer when the two disagree.
|
|
116
|
+
*
|
|
117
|
+
* Why there is a second memory: the server sets the cookie again when it has
|
|
118
|
+
* recorded an answer, and its responses can arrive out of order — a slow
|
|
119
|
+
* "yes" landing after a quick "no" would put the yes back. Every answer is
|
|
120
|
+
* therefore also kept in localStorage under the cookie's name, which no
|
|
121
|
+
* response can write. It only ever corrects a cookie that exists: with no
|
|
122
|
+
* cookie (expired, cleared) it counts for nothing, so an answer still ends
|
|
123
|
+
* when its cookie does.
|
|
124
|
+
*/
|
|
125
|
+
declare function storedConsentValue(config: Pick<ConsentConfig, 'cookieName' | 'version'>): string | undefined;
|
|
126
|
+
/** The visitor's stored decision in this browser, or null when undecided. */
|
|
127
|
+
declare function getStoredConsent(config: Pick<ConsentConfig, 'cookieName' | 'version'>): ConsentState | null;
|
|
128
|
+
/**
|
|
129
|
+
* The consent cookie as a server sets it on a response. Set it from the
|
|
130
|
+
* server as well as from the browser: Safari cuts a cookie written by a
|
|
131
|
+
* script to seven days, one set by a response keeps its full life. Readable
|
|
132
|
+
* by scripts on purpose — the inline script restores the answer from it
|
|
133
|
+
* before any tag loads.
|
|
134
|
+
*/
|
|
135
|
+
declare function consentCookie(state: ConsentState, config: ConsentConfig, opts: {
|
|
136
|
+
secure: boolean;
|
|
137
|
+
}): {
|
|
138
|
+
name: string;
|
|
139
|
+
value: string;
|
|
140
|
+
options: {
|
|
141
|
+
path: string;
|
|
142
|
+
maxAge: number;
|
|
143
|
+
sameSite: "lax";
|
|
144
|
+
secure: boolean;
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The `document.cookie` writes that remove every cookie of a refused purpose
|
|
150
|
+
* from this browser. Pure: given the current cookie string and the host. A
|
|
151
|
+
* tag may have set its cookie on the host or on any parent domain, and a
|
|
152
|
+
* cookie can only be removed by naming the domain and path it was set on, so
|
|
153
|
+
* each is expired on all of the domains, on each of its paths (`/` unless
|
|
154
|
+
* the config lists others).
|
|
155
|
+
*
|
|
156
|
+
* What this cannot reach, and a site must handle itself where it applies:
|
|
157
|
+
* cookies a script cannot see (HttpOnly, set by a server), cookies on a path
|
|
158
|
+
* the config does not list, cookies of another site (a third-party iframe),
|
|
159
|
+
* and anything a tag keeps outside cookies (localStorage, IndexedDB).
|
|
160
|
+
*/
|
|
161
|
+
declare function refusedCookieExpiries(cookieString: string, state: ConsentState, hostname: string, optionalCookies: ConsentConfig['optionalCookies']): string[];
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The Consent Mode DEFAULT plus the visitor's stored decision, as the body
|
|
165
|
+
* of an inline <script> for the page's <head>, BEFORE the tag manager's
|
|
166
|
+
* loader. It cannot import anything, so it re-implements the cookie reader
|
|
167
|
+
* (the tests assert the two agree, value by value). When a stored decision
|
|
168
|
+
* exists it is applied synchronously after the default, so tags never
|
|
169
|
+
* observe a denied→granted flip on a returning visit.
|
|
170
|
+
*
|
|
171
|
+
* It reads what `getStoredConsent` reads: the cookie, corrected by the
|
|
172
|
+
* browser's own memory of the latest answer when a late server response has
|
|
173
|
+
* put an older one back (state.ts: storedConsentValue). When it corrects, it
|
|
174
|
+
* also rewrites the cookie, so the server reads the right answer on the next
|
|
175
|
+
* request.
|
|
176
|
+
*
|
|
177
|
+
* The default follows the model: denied for opt-in, granted for opt-out. In
|
|
178
|
+
* an opt-out model a browser sending Global Privacy Control has refused
|
|
179
|
+
* marketing — also over a stored yes, unless the config says 'answer-wins'.
|
|
180
|
+
* security_storage is always granted.
|
|
181
|
+
*
|
|
182
|
+
* `firstPush` is put on the data layer before anything else — what the
|
|
183
|
+
* site's container needs to know from the first event (a market, a currency).
|
|
184
|
+
*/
|
|
185
|
+
declare function consentDefaultScript(config: Pick<ConsentConfig, 'cookieName' | 'version' | 'maxAgeSeconds' | 'globalPrivacyControl'>, model: ConsentModel, firstPush?: Record<string, unknown>): string;
|
|
186
|
+
|
|
187
|
+
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
188
|
+
type ConsentSource = 'banner' | 'settings';
|
|
189
|
+
/**
|
|
190
|
+
* Why `onApply` is running:
|
|
191
|
+
* - 'answer': the visitor just answered here.
|
|
192
|
+
* - 'start': the page is starting up (`start(model)`): what applies to this
|
|
193
|
+
* visitor, whether or not they ever answered.
|
|
194
|
+
* - 'other-tab': the visitor answered in another tab of this site.
|
|
195
|
+
*/
|
|
196
|
+
type ConsentCause = 'answer' | 'start' | 'other-tab';
|
|
197
|
+
/** Which step failed, for `onError`. Nothing here ever stops an answer from being applied. */
|
|
198
|
+
type ConsentErrorStep = 'onApply' | 'subscriber' | 'record' | 'storage';
|
|
199
|
+
/** What a site hangs on an answer, beyond what every site does. */
|
|
200
|
+
interface ConsentHooks {
|
|
201
|
+
/**
|
|
202
|
+
* Other tools that follow consent (product analytics opt-in and opt-out).
|
|
203
|
+
* Runs right after the Consent Mode update on every decision, and once
|
|
204
|
+
* from `start(model)` with what applies at page start. If it throws, the
|
|
205
|
+
* error goes to `onError` and the rest of the decision still happens.
|
|
206
|
+
*/
|
|
207
|
+
onApply?: (state: ConsentState, cause: ConsentCause) => void;
|
|
208
|
+
/**
|
|
209
|
+
* Tell the server a visitor answered, so it can keep the record and set
|
|
210
|
+
* the cookie from its response. Never awaited. Return the `fetch` promise:
|
|
211
|
+
* a rejection, or a response that is not `ok`, goes to `onError`.
|
|
212
|
+
*/
|
|
213
|
+
record?: (state: ConsentState, source: ConsentSource) => void | Promise<unknown>;
|
|
214
|
+
/**
|
|
215
|
+
* Something around a decision failed: a hook threw, the record was not
|
|
216
|
+
* taken, storage was refused. Report it to your monitoring. The decision
|
|
217
|
+
* itself was applied all the same.
|
|
218
|
+
*/
|
|
219
|
+
onError?: (error: unknown, step: ConsentErrorStep) => void;
|
|
220
|
+
}
|
|
221
|
+
interface ConsentController {
|
|
222
|
+
readonly config: ConsentConfig;
|
|
223
|
+
/** The visitor's stored answer in this browser, or null. */
|
|
224
|
+
stored(): ConsentState | null;
|
|
225
|
+
/** What applies to this visitor now: the stored answer, else the model's rule, with Global Privacy Control (state.ts: effectiveConsent). */
|
|
226
|
+
effective(model: ConsentModel): ConsentState;
|
|
227
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie and memory written → subscribers. */
|
|
228
|
+
apply(state: ConsentState): void;
|
|
229
|
+
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
230
|
+
answer(state: ConsentState, source: ConsentSource): void;
|
|
231
|
+
/**
|
|
232
|
+
* Call once when the page starts, before optional SDKs initialise (module
|
|
233
|
+
* evaluation of the banner component is the place): makes sure a Consent
|
|
234
|
+
* Mode default exists, puts right a cookie a late server response got
|
|
235
|
+
* wrong, and runs `onApply` with what applies to this visitor, so every
|
|
236
|
+
* tool starts from the same decision the tags did. Returns that decision.
|
|
237
|
+
*/
|
|
238
|
+
start(model: ConsentModel): ConsentState;
|
|
239
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. `start` does this too. */
|
|
240
|
+
ensureDefault(): void;
|
|
241
|
+
/**
|
|
242
|
+
* Put the cookie back in line with the latest answer this browser
|
|
243
|
+
* remembers, if a late server response replaced it. True when it had to.
|
|
244
|
+
* Runs by itself at start and after every record; call it yourself after
|
|
245
|
+
* any other request whose response may set the consent cookie.
|
|
246
|
+
*/
|
|
247
|
+
reconcile(): boolean;
|
|
248
|
+
/** Hear every applied decision, from this tab or another. Returns the unsubscribe. */
|
|
249
|
+
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
250
|
+
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
251
|
+
openSettings(): void;
|
|
252
|
+
subscribeSettings(listener: () => void): () => void;
|
|
253
|
+
}
|
|
254
|
+
/** `gtag(...)`-shaped push onto window.dataLayer. */
|
|
255
|
+
declare function pushGtagCommand(...args: unknown[]): void;
|
|
256
|
+
/**
|
|
257
|
+
* The one hook every consent decision on a site goes through, so the
|
|
258
|
+
* signals have one author: the Consent Mode update, the site's own hooks,
|
|
259
|
+
* removing the cookies of a refused purpose, and the first-party cookie the
|
|
260
|
+
* inline script reads on the next page load — in this order.
|
|
261
|
+
*
|
|
262
|
+
* About that order: the update is a command on the data layer, and a tag
|
|
263
|
+
* manager acts on it when it processes that command — normally at once, but
|
|
264
|
+
* not provably before the next line here runs. A tag that was mid-flight may
|
|
265
|
+
* still write a cookie after the cleanup. The cookie is the durable part:
|
|
266
|
+
* from the next page load every tag starts denied. Check the behaviour you
|
|
267
|
+
* rely on against your own container.
|
|
268
|
+
*/
|
|
269
|
+
declare function createConsent(config: ConsentConfig, hooks?: ConsentHooks): ConsentController;
|
|
270
|
+
|
|
271
|
+
export { type ConsentCause, type ConsentConfig, type ConsentController, type ConsentErrorStep, type ConsentHooks, type ConsentModeParams, type ConsentModel, type ConsentSource, type ConsentState, type OptionalCookie, type Purpose, type Signal, assertConsentConfig, browserGpc, consentCookie, consentDefaultScript, consentModeParams, createConsent, defaultSignal, effectiveConsent, getStoredConsent, pushGtagCommand, readConsent, refusedCookieExpiries, serializeConsent, storedConsentValue, unansweredConsent };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// src/state.ts
|
|
2
|
+
function assertConsentConfig(config) {
|
|
3
|
+
const fail = (what) => {
|
|
4
|
+
throw new Error(`consent config: ${what}`);
|
|
5
|
+
};
|
|
6
|
+
if ("cookieName" in config && !/^[A-Za-z0-9_-]+$/.test(String(config.cookieName))) fail(`cookie name ${JSON.stringify(config.cookieName)} is not a plain name`);
|
|
7
|
+
if ("version" in config && !(Number.isInteger(config.version) && config.version >= 1)) fail(`version ${config.version} is not a whole number from 1 up`);
|
|
8
|
+
if ("maxAgeSeconds" in config && !(Number.isInteger(config.maxAgeSeconds) && config.maxAgeSeconds > 0)) fail(`maxAgeSeconds ${config.maxAgeSeconds} is not a positive whole number`);
|
|
9
|
+
if (config.globalPrivacyControl !== void 0 && config.globalPrivacyControl !== "signal-wins" && config.globalPrivacyControl !== "answer-wins") fail(`globalPrivacyControl ${JSON.stringify(config.globalPrivacyControl)} is not a known policy`);
|
|
10
|
+
for (const [purpose, cookies] of Object.entries(config.optionalCookies ?? {})) {
|
|
11
|
+
for (const { pattern, paths } of cookies) {
|
|
12
|
+
if (!(pattern instanceof RegExp)) fail(`${purpose}: a cookie pattern is not a RegExp`);
|
|
13
|
+
if (pattern.global || pattern.sticky) fail(`${purpose}: ${pattern} has a g or y flag, which makes it match differently from one call to the next`);
|
|
14
|
+
for (const path of paths ?? []) if (!path.startsWith("/")) fail(`${purpose}: path ${JSON.stringify(path)} does not start with /`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function serializeConsent(state, config) {
|
|
19
|
+
return `a${state.analytics ? 1 : 0}m${state.marketing ? 1 : 0}v${config.version}`;
|
|
20
|
+
}
|
|
21
|
+
function readConsent(value, config) {
|
|
22
|
+
const m = value?.match(/^a([01])m([01])(?:v(\d+))?$/);
|
|
23
|
+
if (!m) return null;
|
|
24
|
+
if (Number(m[3] ?? 1) < config.version) return null;
|
|
25
|
+
return { analytics: m[1] === "1", marketing: m[2] === "1" };
|
|
26
|
+
}
|
|
27
|
+
function unansweredConsent(model, gpc) {
|
|
28
|
+
if (model === "opt-in") return { analytics: false, marketing: false };
|
|
29
|
+
return { analytics: true, marketing: !gpc };
|
|
30
|
+
}
|
|
31
|
+
function effectiveConsent(stored, model, gpc, config = {}) {
|
|
32
|
+
const state = stored ?? unansweredConsent(model, gpc);
|
|
33
|
+
if (model === "opt-out" && gpc && config.globalPrivacyControl !== "answer-wins") return { ...state, marketing: false };
|
|
34
|
+
return state;
|
|
35
|
+
}
|
|
36
|
+
function defaultSignal(model) {
|
|
37
|
+
return model === "opt-in" ? "denied" : "granted";
|
|
38
|
+
}
|
|
39
|
+
function consentModeParams(state) {
|
|
40
|
+
const a = state.analytics ? "granted" : "denied";
|
|
41
|
+
const m = state.marketing ? "granted" : "denied";
|
|
42
|
+
return {
|
|
43
|
+
analytics_storage: a,
|
|
44
|
+
ad_storage: m,
|
|
45
|
+
ad_user_data: m,
|
|
46
|
+
ad_personalization: m,
|
|
47
|
+
functionality_storage: "granted",
|
|
48
|
+
personalization_storage: a
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function browserGpc() {
|
|
52
|
+
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
53
|
+
}
|
|
54
|
+
function cookieValue(cookieName) {
|
|
55
|
+
return document.cookie.match(new RegExp(`(?:^|; )${cookieName}=([^;]*)`))?.[1];
|
|
56
|
+
}
|
|
57
|
+
function storedConsentValue(config) {
|
|
58
|
+
if (typeof document === "undefined") return void 0;
|
|
59
|
+
assertConsentConfig({ cookieName: config.cookieName });
|
|
60
|
+
const cookie = cookieValue(config.cookieName);
|
|
61
|
+
if (cookie === void 0) return void 0;
|
|
62
|
+
try {
|
|
63
|
+
const latest = localStorage.getItem(config.cookieName);
|
|
64
|
+
if (latest && latest !== cookie && readConsent(latest, config)) return latest;
|
|
65
|
+
} catch {
|
|
66
|
+
}
|
|
67
|
+
return cookie;
|
|
68
|
+
}
|
|
69
|
+
function getStoredConsent(config) {
|
|
70
|
+
return readConsent(storedConsentValue(config), config);
|
|
71
|
+
}
|
|
72
|
+
function consentCookie(state, config, opts) {
|
|
73
|
+
assertConsentConfig(config);
|
|
74
|
+
return {
|
|
75
|
+
name: config.cookieName,
|
|
76
|
+
value: serializeConsent(state, config),
|
|
77
|
+
options: { path: "/", maxAge: config.maxAgeSeconds, sameSite: "lax", secure: opts.secure }
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/cookies.ts
|
|
82
|
+
function refusedCookieExpiries(cookieString, state, hostname, optionalCookies) {
|
|
83
|
+
const refused = Object.keys(optionalCookies).filter((purpose) => !state[purpose]).flatMap((purpose) => optionalCookies[purpose]);
|
|
84
|
+
if (refused.length === 0) return [];
|
|
85
|
+
const labels = hostname.split(".");
|
|
86
|
+
const domains = ["", ...labels.slice(0, -1).map((_, i) => `.${labels.slice(i).join(".")}`)];
|
|
87
|
+
const names = cookieString.split("; ").map((part) => part.split("=")[0]).filter(Boolean);
|
|
88
|
+
return names.flatMap((name) => {
|
|
89
|
+
const paths = new Set(refused.filter(({ pattern }) => pattern.test(name)).flatMap(({ paths: paths2 }) => paths2 ?? ["/"]));
|
|
90
|
+
return [...paths].flatMap((path) => domains.map((domain) => `${name}=; path=${path}; max-age=0${domain ? `; domain=${domain}` : ""}`));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/inline-script.ts
|
|
95
|
+
function consentDefaultScript(config, model, firstPush) {
|
|
96
|
+
assertConsentConfig(config);
|
|
97
|
+
const name = config.cookieName;
|
|
98
|
+
const d = JSON.stringify(defaultSignal(model));
|
|
99
|
+
const value = "a([01])m([01])(?:v(\\d+))?";
|
|
100
|
+
const update = (a, m) => `gtag("consent","update",{analytics_storage:${a},ad_storage:${m},ad_user_data:${m},ad_personalization:${m},functionality_storage:"granted",personalization_storage:${a}});`;
|
|
101
|
+
const signalWins = config.globalPrivacyControl !== "answer-wins";
|
|
102
|
+
return [
|
|
103
|
+
"window.dataLayer=window.dataLayer||[];",
|
|
104
|
+
...firstPush ? [`window.dataLayer.push(${JSON.stringify(firstPush).replace(/</g, "\\u003c")});`] : [],
|
|
105
|
+
"function gtag(){dataLayer.push(arguments)}",
|
|
106
|
+
`gtag("consent","default",{ad_personalization:${d},ad_storage:${d},ad_user_data:${d},analytics_storage:${d},functionality_storage:${d},personalization_storage:${d},security_storage:"granted",wait_for_update:500});`,
|
|
107
|
+
`var c=(document.cookie.match(/(?:^|; )${name}=([^;]*)/)||[])[1],r=/^${value}$/;`,
|
|
108
|
+
`try{var l=localStorage.getItem("${name}"),k=l&&l.match(r);if(c!==undefined&&k&&l!==c&&+(k[3]||1)>=${config.version}){c=l;document.cookie="${name}="+l+"; path=/; max-age=${config.maxAgeSeconds}; samesite=lax"}}catch(e){}`,
|
|
109
|
+
`var m=c&&c.match(r);if(m&&+(m[3]||1)<${config.version})m=null;`,
|
|
110
|
+
...model === "opt-out" ? [
|
|
111
|
+
"var g=navigator.globalPrivacyControl===true;",
|
|
112
|
+
`if(m){var a=m[1]==="1"?"granted":"denied",d=m[2]==="1"${signalWins ? "&&!g" : ""}?"granted":"denied";${update("a", "d")}}`,
|
|
113
|
+
`else if(g){${update('"granted"', '"denied"')}}`
|
|
114
|
+
] : [`if(m){var a=m[1]==="1"?"granted":"denied",d=m[2]==="1"?"granted":"denied";${update("a", "d")}}`],
|
|
115
|
+
'gtag("set","ads_data_redaction",true);',
|
|
116
|
+
'gtag("set","url_passthrough",false);'
|
|
117
|
+
].join("");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/controller.ts
|
|
121
|
+
var asArguments = function() {
|
|
122
|
+
return arguments;
|
|
123
|
+
};
|
|
124
|
+
function pushGtagCommand(...args) {
|
|
125
|
+
if (typeof window === "undefined") return;
|
|
126
|
+
const w = window;
|
|
127
|
+
w.dataLayer = w.dataLayer || [];
|
|
128
|
+
w.dataLayer.push(asArguments(...args));
|
|
129
|
+
}
|
|
130
|
+
function createConsent(config, hooks = {}) {
|
|
131
|
+
assertConsentConfig(config);
|
|
132
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
133
|
+
const settingsListeners = /* @__PURE__ */ new Set();
|
|
134
|
+
const report = (error, step) => {
|
|
135
|
+
try {
|
|
136
|
+
hooks.onError?.(error, step);
|
|
137
|
+
} catch {
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const guarded = (step, run) => {
|
|
141
|
+
try {
|
|
142
|
+
run();
|
|
143
|
+
} catch (error) {
|
|
144
|
+
report(error, step);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const cookieLine = (value) => `${config.cookieName}=${value}; path=/; max-age=${config.maxAgeSeconds}; samesite=lax`;
|
|
148
|
+
const rawCookie = () => document.cookie.match(new RegExp(`(?:^|; )${config.cookieName}=([^;]*)`))?.[1];
|
|
149
|
+
function remember(value) {
|
|
150
|
+
try {
|
|
151
|
+
localStorage.setItem(config.cookieName, value);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
try {
|
|
154
|
+
localStorage.removeItem(config.cookieName);
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
report(error, "storage");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function reconcile() {
|
|
161
|
+
if (typeof document === "undefined") return false;
|
|
162
|
+
try {
|
|
163
|
+
const cookie = rawCookie();
|
|
164
|
+
const latest = localStorage.getItem(config.cookieName);
|
|
165
|
+
if (!latest) return false;
|
|
166
|
+
if (cookie === void 0) {
|
|
167
|
+
localStorage.removeItem(config.cookieName);
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (latest === cookie || !readConsent(latest, config)) return false;
|
|
171
|
+
document.cookie = cookieLine(latest);
|
|
172
|
+
return true;
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function decide(state, cause, persist) {
|
|
178
|
+
if (typeof window === "undefined") return;
|
|
179
|
+
pushGtagCommand("consent", "update", consentModeParams(state));
|
|
180
|
+
guarded("onApply", () => hooks.onApply?.(state, cause));
|
|
181
|
+
if (persist) {
|
|
182
|
+
const hostname = window.location?.hostname ?? "";
|
|
183
|
+
for (const expiry of refusedCookieExpiries(document.cookie, state, hostname, config.optionalCookies)) document.cookie = expiry;
|
|
184
|
+
const value = serializeConsent(state, config);
|
|
185
|
+
document.cookie = cookieLine(value);
|
|
186
|
+
remember(value);
|
|
187
|
+
}
|
|
188
|
+
listeners.forEach((listener) => guarded("subscriber", () => listener(state)));
|
|
189
|
+
}
|
|
190
|
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
191
|
+
window.addEventListener("storage", (event) => {
|
|
192
|
+
if (event.key !== config.cookieName || !event.newValue) return;
|
|
193
|
+
const state = readConsent(event.newValue, config);
|
|
194
|
+
if (state) decide(state, "other-tab", false);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function ensureDefault() {
|
|
198
|
+
if (typeof window === "undefined") return;
|
|
199
|
+
reconcile();
|
|
200
|
+
const dl = window.dataLayer ?? [];
|
|
201
|
+
const has = Array.from(dl).some((c) => c != null && typeof c === "object" && c[0] === "consent" && c[1] === "default");
|
|
202
|
+
if (has) return;
|
|
203
|
+
pushGtagCommand("consent", "default", {
|
|
204
|
+
ad_personalization: "denied",
|
|
205
|
+
ad_storage: "denied",
|
|
206
|
+
ad_user_data: "denied",
|
|
207
|
+
analytics_storage: "denied",
|
|
208
|
+
functionality_storage: "denied",
|
|
209
|
+
personalization_storage: "denied",
|
|
210
|
+
security_storage: "granted",
|
|
211
|
+
wait_for_update: 500
|
|
212
|
+
});
|
|
213
|
+
const stored = getStoredConsent(config);
|
|
214
|
+
if (stored) pushGtagCommand("consent", "update", consentModeParams(stored));
|
|
215
|
+
}
|
|
216
|
+
const effective = (model) => effectiveConsent(getStoredConsent(config), model, browserGpc(), config);
|
|
217
|
+
return {
|
|
218
|
+
config,
|
|
219
|
+
stored: () => getStoredConsent(config),
|
|
220
|
+
effective,
|
|
221
|
+
apply: (state) => decide(state, "answer", true),
|
|
222
|
+
answer(state, source) {
|
|
223
|
+
decide(state, "answer", true);
|
|
224
|
+
let sent = void 0;
|
|
225
|
+
try {
|
|
226
|
+
sent = hooks.record?.(state, source);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
report(error, "record");
|
|
229
|
+
}
|
|
230
|
+
void Promise.resolve(sent).then((response) => {
|
|
231
|
+
const r = response;
|
|
232
|
+
if (r && typeof r === "object" && r.ok === false) throw new Error(`consent record was refused${typeof r.status === "number" ? ` (${r.status})` : ""}`);
|
|
233
|
+
}).catch((error) => report(error, "record")).then(() => {
|
|
234
|
+
reconcile();
|
|
235
|
+
});
|
|
236
|
+
},
|
|
237
|
+
start(model) {
|
|
238
|
+
ensureDefault();
|
|
239
|
+
const state = effective(model);
|
|
240
|
+
if (typeof window !== "undefined") guarded("onApply", () => hooks.onApply?.(state, "start"));
|
|
241
|
+
return state;
|
|
242
|
+
},
|
|
243
|
+
ensureDefault,
|
|
244
|
+
reconcile,
|
|
245
|
+
subscribe(listener) {
|
|
246
|
+
listeners.add(listener);
|
|
247
|
+
return () => listeners.delete(listener);
|
|
248
|
+
},
|
|
249
|
+
openSettings() {
|
|
250
|
+
settingsListeners.forEach((l) => l());
|
|
251
|
+
},
|
|
252
|
+
subscribeSettings(listener) {
|
|
253
|
+
settingsListeners.add(listener);
|
|
254
|
+
return () => settingsListeners.delete(listener);
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
export {
|
|
259
|
+
assertConsentConfig,
|
|
260
|
+
browserGpc,
|
|
261
|
+
consentCookie,
|
|
262
|
+
consentDefaultScript,
|
|
263
|
+
consentModeParams,
|
|
264
|
+
createConsent,
|
|
265
|
+
defaultSignal,
|
|
266
|
+
effectiveConsent,
|
|
267
|
+
getStoredConsent,
|
|
268
|
+
pushGtagCommand,
|
|
269
|
+
readConsent,
|
|
270
|
+
refusedCookieExpiries,
|
|
271
|
+
serializeConsent,
|
|
272
|
+
storedConsentValue,
|
|
273
|
+
unansweredConsent
|
|
274
|
+
};
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { RefObject } from 'react';
|
|
2
|
+
|
|
3
|
+
/** What a visitor can say yes or no to. Necessary cookies are not a purpose: they are not optional. */
|
|
4
|
+
type Purpose = 'analytics' | 'marketing';
|
|
5
|
+
interface ConsentState {
|
|
6
|
+
/** analytics_storage — measuring how the site is used. */
|
|
7
|
+
analytics: boolean;
|
|
8
|
+
/** ad_storage + ad_user_data + ad_personalization — ad platforms, ad conversions. */
|
|
9
|
+
marketing: boolean;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* How a site (or one market of it) treats a visitor who has not answered:
|
|
13
|
+
* - 'opt-in': nothing optional runs until the visitor says yes; the banner
|
|
14
|
+
* asks on the first visit (UK, EU).
|
|
15
|
+
* - 'opt-out': everything runs until the visitor says no; no banner on
|
|
16
|
+
* arrival, a "Cookie settings" link is where they say no, and a browser
|
|
17
|
+
* that sends Global Privacy Control has already said no to marketing.
|
|
18
|
+
*/
|
|
19
|
+
type ConsentModel = 'opt-in' | 'opt-out';
|
|
20
|
+
/** One optional cookie a tag sets: how to recognise its name, and who sets it. */
|
|
21
|
+
interface OptionalCookie {
|
|
22
|
+
/** Matches the cookie's name. No `g` or `y` flag: those make a pattern remember where it last matched. */
|
|
23
|
+
pattern: RegExp;
|
|
24
|
+
setBy: string;
|
|
25
|
+
/** The paths the cookie may have been set on. A cookie can only be removed
|
|
26
|
+
* by naming its path. Default: `['/']`, where tags set theirs. */
|
|
27
|
+
paths?: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
30
|
+
interface ConsentConfig {
|
|
31
|
+
/** The first-party cookie the answer is stored in, e.g. "pz_consent". */
|
|
32
|
+
cookieName: string;
|
|
33
|
+
/**
|
|
34
|
+
* The version of what the visitor is asked to agree to. Raise it when a
|
|
35
|
+
* purpose is added or changed, or a new kind of recipient joins one (a new
|
|
36
|
+
* ad platform under marketing): every stored answer below it stops
|
|
37
|
+
* counting and the visitor is asked again. Rewording the banner does not
|
|
38
|
+
* need a new version. An answer stored without a version is version 1.
|
|
39
|
+
*/
|
|
40
|
+
version: number;
|
|
41
|
+
/** How long an answer stands before the visitor is asked again, in seconds. */
|
|
42
|
+
maxAgeSeconds: number;
|
|
43
|
+
/**
|
|
44
|
+
* Every optional cookie the site's tags set, by purpose. One list with two
|
|
45
|
+
* jobs: what is removed from the browser when a purpose is refused or
|
|
46
|
+
* withdrawn, and what the site's privacy policy has to name.
|
|
47
|
+
*/
|
|
48
|
+
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
49
|
+
/**
|
|
50
|
+
* In an opt-out model, what decides when the browser sends Global Privacy
|
|
51
|
+
* Control and the visitor has also stored a yes to marketing:
|
|
52
|
+
* - 'signal-wins' (default): the signal. Marketing stays off for as long
|
|
53
|
+
* as the browser sends it, whatever was answered before.
|
|
54
|
+
* - 'answer-wins': the stored answer.
|
|
55
|
+
* Has no effect in an opt-in model, where nothing runs without a yes.
|
|
56
|
+
*/
|
|
57
|
+
globalPrivacyControl?: 'signal-wins' | 'answer-wins';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
61
|
+
type ConsentSource = 'banner' | 'settings';
|
|
62
|
+
interface ConsentController {
|
|
63
|
+
readonly config: ConsentConfig;
|
|
64
|
+
/** The visitor's stored answer in this browser, or null. */
|
|
65
|
+
stored(): ConsentState | null;
|
|
66
|
+
/** What applies to this visitor now: the stored answer, else the model's rule, with Global Privacy Control (state.ts: effectiveConsent). */
|
|
67
|
+
effective(model: ConsentModel): ConsentState;
|
|
68
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie and memory written → subscribers. */
|
|
69
|
+
apply(state: ConsentState): void;
|
|
70
|
+
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
71
|
+
answer(state: ConsentState, source: ConsentSource): void;
|
|
72
|
+
/**
|
|
73
|
+
* Call once when the page starts, before optional SDKs initialise (module
|
|
74
|
+
* evaluation of the banner component is the place): makes sure a Consent
|
|
75
|
+
* Mode default exists, puts right a cookie a late server response got
|
|
76
|
+
* wrong, and runs `onApply` with what applies to this visitor, so every
|
|
77
|
+
* tool starts from the same decision the tags did. Returns that decision.
|
|
78
|
+
*/
|
|
79
|
+
start(model: ConsentModel): ConsentState;
|
|
80
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. `start` does this too. */
|
|
81
|
+
ensureDefault(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Put the cookie back in line with the latest answer this browser
|
|
84
|
+
* remembers, if a late server response replaced it. True when it had to.
|
|
85
|
+
* Runs by itself at start and after every record; call it yourself after
|
|
86
|
+
* any other request whose response may set the consent cookie.
|
|
87
|
+
*/
|
|
88
|
+
reconcile(): boolean;
|
|
89
|
+
/** Hear every applied decision, from this tab or another. Returns the unsubscribe. */
|
|
90
|
+
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
91
|
+
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
92
|
+
openSettings(): void;
|
|
93
|
+
subscribeSettings(listener: () => void): () => void;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
interface ConsentBanner<T extends HTMLElement> {
|
|
97
|
+
/**
|
|
98
|
+
* What to draw:
|
|
99
|
+
* - 'hidden': nothing.
|
|
100
|
+
* - 'ask': the first-visit question (opt-in only): reject all, accept all, and a way to `choose`.
|
|
101
|
+
* - 'choose': one switch per purpose (`choice`), with reject all, accept all and `save`.
|
|
102
|
+
*/
|
|
103
|
+
view: 'hidden' | 'ask' | 'choose';
|
|
104
|
+
/** The switches in the 'choose' view. */
|
|
105
|
+
choice: ConsentState;
|
|
106
|
+
setChoice: (update: (current: ConsentState) => ConsentState) => void;
|
|
107
|
+
/** Put this on the banner's outer element (give it tabIndex={-1}): focus moves there when "Cookie settings" opens it. */
|
|
108
|
+
cardRef: RefObject<T | null>;
|
|
109
|
+
rejectAll: () => void;
|
|
110
|
+
acceptAll: () => void;
|
|
111
|
+
/** Answer with the switches as they stand. */
|
|
112
|
+
save: () => void;
|
|
113
|
+
/** From 'ask' to 'choose', every switch off. */
|
|
114
|
+
choose: () => void;
|
|
115
|
+
/** Leave 'choose' without answering: back to 'ask' if the question is still open. */
|
|
116
|
+
close: () => void;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The behaviour of a cookie banner, without its markup. The rules it keeps:
|
|
120
|
+
*
|
|
121
|
+
* - An opt-in site asks on the first visit; an opt-out site shows nothing
|
|
122
|
+
* until "Cookie settings" is pressed (controller.openSettings()).
|
|
123
|
+
* - Nothing is pre-ticked in an opt-in site: the switches start off.
|
|
124
|
+
* - Opened from "Cookie settings", the switches show what applies now, focus
|
|
125
|
+
* moves into the banner, Escape closes it and focus goes back to the link.
|
|
126
|
+
* - The banner appears only after hydration (the cookie is read in the
|
|
127
|
+
* browser), and never for a visitor whose answer still counts.
|
|
128
|
+
* - An answer given in another tab closes the question here too.
|
|
129
|
+
*
|
|
130
|
+
* What the markup must do: draw "reject all" and "accept all" as the same
|
|
131
|
+
* control side by side, so no is exactly as easy as yes, and never block the
|
|
132
|
+
* page behind the banner.
|
|
133
|
+
*/
|
|
134
|
+
declare function useConsentBanner<T extends HTMLElement = HTMLDivElement>(consent: ConsentController, model: ConsentModel): ConsentBanner<T>;
|
|
135
|
+
|
|
136
|
+
export { type ConsentBanner, useConsentBanner };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/react.ts
|
|
4
|
+
import { useEffect, useRef, useState } from "react";
|
|
5
|
+
function useConsentBanner(consent, model) {
|
|
6
|
+
const cardRef = useRef(null);
|
|
7
|
+
const opener = useRef(null);
|
|
8
|
+
const [view, setView] = useState("hidden");
|
|
9
|
+
const [fromSettings, setFromSettings] = useState(false);
|
|
10
|
+
const [choice, setChoiceState] = useState({ analytics: false, marketing: false });
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
if (!consent.stored() && model === "opt-in") setView("ask");
|
|
13
|
+
}, [consent, model]);
|
|
14
|
+
useEffect(
|
|
15
|
+
() => consent.subscribeSettings(() => {
|
|
16
|
+
opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
|
17
|
+
setChoiceState(consent.effective(model));
|
|
18
|
+
setFromSettings(true);
|
|
19
|
+
setView("choose");
|
|
20
|
+
}),
|
|
21
|
+
[consent, model]
|
|
22
|
+
);
|
|
23
|
+
useEffect(
|
|
24
|
+
() => consent.subscribe((state) => {
|
|
25
|
+
setChoiceState(state);
|
|
26
|
+
setView((current) => current === "ask" ? "hidden" : current);
|
|
27
|
+
}),
|
|
28
|
+
[consent]
|
|
29
|
+
);
|
|
30
|
+
function dismiss(next) {
|
|
31
|
+
setView(next);
|
|
32
|
+
setFromSettings(false);
|
|
33
|
+
opener.current?.focus();
|
|
34
|
+
opener.current = null;
|
|
35
|
+
}
|
|
36
|
+
const close = () => dismiss(!consent.stored() && model === "opt-in" ? "ask" : "hidden");
|
|
37
|
+
function answer(state) {
|
|
38
|
+
consent.answer(state, fromSettings ? "settings" : "banner");
|
|
39
|
+
dismiss("hidden");
|
|
40
|
+
}
|
|
41
|
+
useEffect(() => {
|
|
42
|
+
if (!fromSettings) return;
|
|
43
|
+
cardRef.current?.focus();
|
|
44
|
+
const onKey = (e) => {
|
|
45
|
+
if (e.key === "Escape") close();
|
|
46
|
+
};
|
|
47
|
+
document.addEventListener("keydown", onKey);
|
|
48
|
+
return () => document.removeEventListener("keydown", onKey);
|
|
49
|
+
}, [fromSettings]);
|
|
50
|
+
return {
|
|
51
|
+
view,
|
|
52
|
+
choice,
|
|
53
|
+
setChoice: setChoiceState,
|
|
54
|
+
cardRef,
|
|
55
|
+
rejectAll: () => answer({ analytics: false, marketing: false }),
|
|
56
|
+
acceptAll: () => answer({ analytics: true, marketing: true }),
|
|
57
|
+
save: () => answer(choice),
|
|
58
|
+
choose: () => {
|
|
59
|
+
setChoiceState({ analytics: false, marketing: false });
|
|
60
|
+
setView("choose");
|
|
61
|
+
},
|
|
62
|
+
close
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export {
|
|
66
|
+
useConsentBanner
|
|
67
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venturetime/consent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Cookie consent without a banner vendor: the answer, its cookie, Google Consent Mode v2 signals and the banner's behaviour. No markup, no text, no database.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Eldarsa/consent.git"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./react": {
|
|
18
|
+
"types": "./dist/react.d.ts",
|
|
19
|
+
"import": "./dist/react.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"CHANGELOG.md"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsup",
|
|
31
|
+
"typecheck": "tsc --noEmit",
|
|
32
|
+
"test": "vitest run",
|
|
33
|
+
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm build",
|
|
34
|
+
"test:browser": "pnpm build && playwright test"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": ">=18"
|
|
38
|
+
},
|
|
39
|
+
"peerDependenciesMeta": {
|
|
40
|
+
"react": {
|
|
41
|
+
"optional": true
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@playwright/test": "1.59.1",
|
|
46
|
+
"@types/react": "^19",
|
|
47
|
+
"@types/react-dom": "^19",
|
|
48
|
+
"jsdom": "^26",
|
|
49
|
+
"react": "^19",
|
|
50
|
+
"react-dom": "^19",
|
|
51
|
+
"tsup": "^8",
|
|
52
|
+
"typescript": "^5",
|
|
53
|
+
"vitest": "^4.1.5"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"packageManager": "pnpm@9.15.0",
|
|
59
|
+
"engines": {
|
|
60
|
+
"node": ">=20"
|
|
61
|
+
}
|
|
62
|
+
}
|