@venturetime/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/LICENSE +21 -0
- package/README.md +155 -2
- package/dist/index.d.ts +157 -0
- package/dist/index.js +160 -0
- package/dist/react.d.ts +105 -0
- package/dist/react.js +71 -0
- package/package.json +57 -4
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,156 @@
|
|
|
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, what applies to a visitor who has not answered (`opt-in` / `opt-out`, Global Privacy Control), the cookie as a server sets it |
|
|
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 written → subscribers |
|
|
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
|
+
record: (state, source) =>
|
|
51
|
+
fetch('/api/consent', {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { 'content-type': 'application/json' },
|
|
54
|
+
body: JSON.stringify({ ...state, source }),
|
|
55
|
+
keepalive: true,
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```tsx
|
|
61
|
+
// In <head>, before the tag manager's loader
|
|
62
|
+
import { consentDefaultScript } from '@venturetime/consent';
|
|
63
|
+
|
|
64
|
+
<script dangerouslySetInnerHTML={{ __html: consentDefaultScript(CONSENT, 'opt-in') }} />;
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
// The banner: your markup, this hook's behaviour
|
|
69
|
+
'use client';
|
|
70
|
+
import { useConsentBanner } from '@venturetime/consent/react';
|
|
71
|
+
|
|
72
|
+
consent.ensureDefault();
|
|
73
|
+
|
|
74
|
+
export function Banner() {
|
|
75
|
+
const b = useConsentBanner(consent, 'opt-in');
|
|
76
|
+
if (b.view === 'hidden') return null;
|
|
77
|
+
return (
|
|
78
|
+
<section ref={b.cardRef} role="dialog" aria-modal="false" tabIndex={-1}>
|
|
79
|
+
{/* b.view === 'choose': one switch per purpose from b.choice / b.setChoice, and b.save */}
|
|
80
|
+
<button onClick={b.rejectAll}>Reject all</button>
|
|
81
|
+
<button onClick={b.acceptAll}>Accept all</button>
|
|
82
|
+
{b.view === 'ask' && <button onClick={b.choose}>Let me choose</button>}
|
|
83
|
+
</section>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// POST /api/consent — the record, and the cookie from the server
|
|
90
|
+
import { consentCookie } from '@venturetime/consent';
|
|
91
|
+
|
|
92
|
+
const cookie = consentCookie(state, CONSENT, { secure: true });
|
|
93
|
+
// store one row per answer, then set cookie.name / cookie.value / cookie.options on the response
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## What a site brings
|
|
97
|
+
|
|
98
|
+
1. **Config** (`ConsentConfig`): the cookie's name, the version of what is
|
|
99
|
+
asked, how long an answer stands, and the optional cookies its tags set.
|
|
100
|
+
2. **The model**: `opt-in` (nothing optional before a yes; the banner asks on
|
|
101
|
+
the first visit) or `opt-out` (no banner on arrival; a browser sending
|
|
102
|
+
Global Privacy Control has refused marketing), per site or per market.
|
|
103
|
+
3. **The banner's markup**, in the site's own design, driven by
|
|
104
|
+
`useConsentBanner`. Two rules the markup must keep: "reject all" and
|
|
105
|
+
"accept all" are the same control side by side, and the page behind the
|
|
106
|
+
banner is never blocked.
|
|
107
|
+
4. **The wording**, per language, including the name of each recipient.
|
|
108
|
+
5. **A "Cookie settings" link** on every page that calls
|
|
109
|
+
`consent.openSettings()`.
|
|
110
|
+
6. **A server route** that the `record` hook posts to. It stores one row per
|
|
111
|
+
answer (who, market, language, choices, version, time) and sets the cookie
|
|
112
|
+
again with `consentCookie(...)`: Safari cuts a cookie written by a script
|
|
113
|
+
to seven days, one set by a response keeps its full life. The route must
|
|
114
|
+
refuse a request from another origin — its response sets the cookie that
|
|
115
|
+
says what the visitor agreed to.
|
|
116
|
+
7. **Hooks** for anything else that follows the answer (`onApply`: product
|
|
117
|
+
analytics opt-in and opt-out).
|
|
118
|
+
|
|
119
|
+
## Moving a site onto it
|
|
120
|
+
|
|
121
|
+
1. List every tag the site runs and every cookie those tags set. Put the
|
|
122
|
+
cookies in `optionalCookies` under their purpose.
|
|
123
|
+
2. Make sure each tag in the tag manager waits for its Consent Mode signal
|
|
124
|
+
(`analytics_storage`, `ad_storage`). A tag that fires without one is not
|
|
125
|
+
stopped by any banner.
|
|
126
|
+
3. Add the config, the controller, the inline script in `<head>` before the
|
|
127
|
+
tag manager, the banner, the settings link, the route and the table.
|
|
128
|
+
4. If the site had a vendor banner whose answers should carry over, read the
|
|
129
|
+
vendor's cookie once in an inline script before `consentDefaultScript`,
|
|
130
|
+
write this cookie, and remove the vendor's. Otherwise visitors are asked
|
|
131
|
+
again.
|
|
132
|
+
5. Check in a browser with third-party requests blocked: default denied and
|
|
133
|
+
no optional cookie before an answer; update after; restored on reload
|
|
134
|
+
before the tag manager loads; a refusal removes the cookies.
|
|
135
|
+
6. On the day it goes live: remove the vendor's tag from the tag manager,
|
|
136
|
+
export the vendor's consent log, update the privacy policy so it lists the
|
|
137
|
+
cookies itself, cancel the vendor.
|
|
138
|
+
|
|
139
|
+
## Changing this package
|
|
140
|
+
|
|
141
|
+
- Nothing that only one site needs goes in here: no markup, no text, no
|
|
142
|
+
cookie names, no database.
|
|
143
|
+
- The cookie format and the order inside `apply` are a contract with every
|
|
144
|
+
site's stored answers and tags. Changing either is a breaking change and a
|
|
145
|
+
new major version.
|
|
146
|
+
- The inline script has its own copy of the cookie parser. The tests check it
|
|
147
|
+
against `readConsent`; keep them in step.
|
|
148
|
+
|
|
149
|
+
## Releasing
|
|
150
|
+
|
|
151
|
+
Set the version in `package.json`, merge, then publish a GitHub release whose
|
|
152
|
+
tag is that version with a `v` in front (`v0.2.0`). The release workflow runs
|
|
153
|
+
the checks and publishes to npm. Nothing is published any other way.
|
|
154
|
+
|
|
155
|
+
This is not legal advice: the package keeps the mechanics right, and the
|
|
156
|
+
wording, the purposes and the choice of model are each site's to decide.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
pattern: RegExp;
|
|
21
|
+
setBy: string;
|
|
22
|
+
}
|
|
23
|
+
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
24
|
+
interface ConsentConfig {
|
|
25
|
+
/** The first-party cookie the answer is stored in, e.g. "pz_consent". */
|
|
26
|
+
cookieName: string;
|
|
27
|
+
/**
|
|
28
|
+
* The version of what the visitor is asked to agree to. Raise it when a
|
|
29
|
+
* purpose is added or changed, or a new kind of recipient joins one (a new
|
|
30
|
+
* ad platform under marketing): every stored answer below it stops
|
|
31
|
+
* counting and the visitor is asked again. Rewording the banner does not
|
|
32
|
+
* need a new version. An answer stored without a version is version 1.
|
|
33
|
+
*/
|
|
34
|
+
version: number;
|
|
35
|
+
/** How long an answer stands before the visitor is asked again, in seconds. */
|
|
36
|
+
maxAgeSeconds: number;
|
|
37
|
+
/**
|
|
38
|
+
* Every optional cookie the site's tags set, by purpose. One list with two
|
|
39
|
+
* jobs: what is removed from the browser when a purpose is refused or
|
|
40
|
+
* withdrawn, and what the site's privacy policy has to name.
|
|
41
|
+
*/
|
|
42
|
+
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
43
|
+
}
|
|
44
|
+
type Signal = 'granted' | 'denied';
|
|
45
|
+
interface ConsentModeParams {
|
|
46
|
+
analytics_storage: Signal;
|
|
47
|
+
ad_storage: Signal;
|
|
48
|
+
ad_user_data: Signal;
|
|
49
|
+
ad_personalization: Signal;
|
|
50
|
+
functionality_storage: Signal;
|
|
51
|
+
personalization_storage: Signal;
|
|
52
|
+
}
|
|
53
|
+
/** Compact cookie value: "a1m0v1" = analytics granted, marketing denied,
|
|
54
|
+
* answered under version 1. Short so the inline restore script's parser
|
|
55
|
+
* stays a one-liner. */
|
|
56
|
+
declare function serializeConsent(state: ConsentState, config: Pick<ConsentConfig, 'version'>): string;
|
|
57
|
+
/** The answer in a cookie value, or null when there is none that still
|
|
58
|
+
* counts (no cookie, junk, or an answer to an older version). */
|
|
59
|
+
declare function readConsent(value: string | undefined | null, config: Pick<ConsentConfig, 'version'>): ConsentState | null;
|
|
60
|
+
/** What applies to a visitor who has not answered. `gpc` is the browser's
|
|
61
|
+
* Global Privacy Control signal (navigator.globalPrivacyControl, or the
|
|
62
|
+
* `Sec-GPC: 1` request header). */
|
|
63
|
+
declare function unansweredConsent(model: ConsentModel, gpc: boolean): ConsentState;
|
|
64
|
+
/** The Consent Mode signal every optional storage type starts in. */
|
|
65
|
+
declare function defaultSignal(model: ConsentModel): Signal;
|
|
66
|
+
/** A decision as Consent Mode signals. Functionality is always granted (the
|
|
67
|
+
* banner has no switch for it: nothing optional is stored under it);
|
|
68
|
+
* personalization follows analytics. */
|
|
69
|
+
declare function consentModeParams(state: ConsentState): ConsentModeParams;
|
|
70
|
+
/** Global Privacy Control as this browser reports it. */
|
|
71
|
+
declare function browserGpc(): boolean;
|
|
72
|
+
/** The visitor's stored decision in this browser, or null when undecided. */
|
|
73
|
+
declare function getStoredConsent(config: Pick<ConsentConfig, 'cookieName' | 'version'>): ConsentState | null;
|
|
74
|
+
/**
|
|
75
|
+
* The consent cookie as a server sets it on a response. Set it from the
|
|
76
|
+
* server as well as from the browser: Safari cuts a cookie written by a
|
|
77
|
+
* script to seven days, one set by a response keeps its full life. Readable
|
|
78
|
+
* by scripts on purpose — the inline script restores the answer from it
|
|
79
|
+
* before any tag loads.
|
|
80
|
+
*/
|
|
81
|
+
declare function consentCookie(state: ConsentState, config: ConsentConfig, opts: {
|
|
82
|
+
secure: boolean;
|
|
83
|
+
}): {
|
|
84
|
+
name: string;
|
|
85
|
+
value: string;
|
|
86
|
+
options: {
|
|
87
|
+
path: string;
|
|
88
|
+
maxAge: number;
|
|
89
|
+
sameSite: "lax";
|
|
90
|
+
secure: boolean;
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The `document.cookie` writes that remove every cookie of a refused purpose
|
|
96
|
+
* from this browser. Pure: given the current cookie string and the host. A
|
|
97
|
+
* tag may have set its cookie on the host or on any parent domain, and a
|
|
98
|
+
* cookie can only be removed by naming the domain it was set on, so each is
|
|
99
|
+
* expired on all of them.
|
|
100
|
+
*/
|
|
101
|
+
declare function refusedCookieExpiries(cookieString: string, state: ConsentState, hostname: string, optionalCookies: ConsentConfig['optionalCookies']): string[];
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The Consent Mode DEFAULT plus the visitor's stored decision, as the body
|
|
105
|
+
* of an inline <script> for the page's <head>, BEFORE the tag manager's
|
|
106
|
+
* loader. It cannot import anything, so it re-implements the cookie parser
|
|
107
|
+
* (the tests assert both parsers agree). When a stored decision exists it is
|
|
108
|
+
* applied synchronously after the default, so tags never observe a
|
|
109
|
+
* denied→granted flip on a returning visit.
|
|
110
|
+
*
|
|
111
|
+
* The default follows the model: denied for opt-in, granted for opt-out. An
|
|
112
|
+
* unanswered visitor in an opt-out market whose browser sends Global Privacy
|
|
113
|
+
* Control has refused marketing. security_storage is always granted.
|
|
114
|
+
*
|
|
115
|
+
* `firstPush` is put on the data layer before anything else — what the
|
|
116
|
+
* site's container needs to know from the first event (a market, a currency).
|
|
117
|
+
*/
|
|
118
|
+
declare function consentDefaultScript(config: Pick<ConsentConfig, 'cookieName' | 'version'>, model: ConsentModel, firstPush?: Record<string, unknown>): string;
|
|
119
|
+
|
|
120
|
+
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
121
|
+
type ConsentSource = 'banner' | 'settings';
|
|
122
|
+
/** What a site hangs on an answer, beyond what every site does. */
|
|
123
|
+
interface ConsentHooks {
|
|
124
|
+
/** Other tools that follow the answer (product analytics opt-in/out). Runs
|
|
125
|
+
* right after the Consent Mode update, on every apply. */
|
|
126
|
+
onApply?: (state: ConsentState) => void;
|
|
127
|
+
/** Tell the server a visitor answered, so it can keep the record and set
|
|
128
|
+
* the cookie from its response. Never awaited; a failure is swallowed. */
|
|
129
|
+
record?: (state: ConsentState, source: ConsentSource) => void | Promise<unknown>;
|
|
130
|
+
}
|
|
131
|
+
interface ConsentController {
|
|
132
|
+
readonly config: ConsentConfig;
|
|
133
|
+
/** The visitor's stored answer in this browser, or null. */
|
|
134
|
+
stored(): ConsentState | null;
|
|
135
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie → subscribers. */
|
|
136
|
+
apply(state: ConsentState): void;
|
|
137
|
+
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
138
|
+
answer(state: ConsentState, source: ConsentSource): void;
|
|
139
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. */
|
|
140
|
+
ensureDefault(): void;
|
|
141
|
+
/** Hear every applied decision. Returns the unsubscribe. */
|
|
142
|
+
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
143
|
+
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
144
|
+
openSettings(): void;
|
|
145
|
+
subscribeSettings(listener: () => void): () => void;
|
|
146
|
+
}
|
|
147
|
+
/** `gtag(...)`-shaped push onto window.dataLayer. */
|
|
148
|
+
declare function pushGtagCommand(...args: unknown[]): void;
|
|
149
|
+
/**
|
|
150
|
+
* The one hook every consent decision on a site goes through, so the
|
|
151
|
+
* signals have one author: the Consent Mode update, the site's own hooks,
|
|
152
|
+
* removing the cookies of a refused purpose, and the first-party cookie the
|
|
153
|
+
* inline script reads on the next page load — in this order.
|
|
154
|
+
*/
|
|
155
|
+
declare function createConsent(config: ConsentConfig, hooks?: ConsentHooks): ConsentController;
|
|
156
|
+
|
|
157
|
+
export { type ConsentConfig, type ConsentController, type ConsentHooks, type ConsentModeParams, type ConsentModel, type ConsentSource, type ConsentState, type OptionalCookie, type Purpose, type Signal, browserGpc, consentCookie, consentDefaultScript, consentModeParams, createConsent, defaultSignal, getStoredConsent, pushGtagCommand, readConsent, refusedCookieExpiries, serializeConsent, unansweredConsent };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// src/state.ts
|
|
2
|
+
function serializeConsent(state, config) {
|
|
3
|
+
return `a${state.analytics ? 1 : 0}m${state.marketing ? 1 : 0}v${config.version}`;
|
|
4
|
+
}
|
|
5
|
+
function readConsent(value, config) {
|
|
6
|
+
const m = value?.match(/^a([01])m([01])(?:v(\d+))?$/);
|
|
7
|
+
if (!m) return null;
|
|
8
|
+
if (Number(m[3] ?? 1) < config.version) return null;
|
|
9
|
+
return { analytics: m[1] === "1", marketing: m[2] === "1" };
|
|
10
|
+
}
|
|
11
|
+
function unansweredConsent(model, gpc) {
|
|
12
|
+
if (model === "opt-in") return { analytics: false, marketing: false };
|
|
13
|
+
return { analytics: true, marketing: !gpc };
|
|
14
|
+
}
|
|
15
|
+
function defaultSignal(model) {
|
|
16
|
+
return model === "opt-in" ? "denied" : "granted";
|
|
17
|
+
}
|
|
18
|
+
function consentModeParams(state) {
|
|
19
|
+
const a = state.analytics ? "granted" : "denied";
|
|
20
|
+
const m = state.marketing ? "granted" : "denied";
|
|
21
|
+
return {
|
|
22
|
+
analytics_storage: a,
|
|
23
|
+
ad_storage: m,
|
|
24
|
+
ad_user_data: m,
|
|
25
|
+
ad_personalization: m,
|
|
26
|
+
functionality_storage: "granted",
|
|
27
|
+
personalization_storage: a
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function browserGpc() {
|
|
31
|
+
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
32
|
+
}
|
|
33
|
+
function getStoredConsent(config) {
|
|
34
|
+
if (typeof document === "undefined") return null;
|
|
35
|
+
const m = document.cookie.match(new RegExp(`(?:^|; )${config.cookieName}=([^;]+)`));
|
|
36
|
+
return readConsent(m?.[1], config);
|
|
37
|
+
}
|
|
38
|
+
function consentCookie(state, config, opts) {
|
|
39
|
+
return {
|
|
40
|
+
name: config.cookieName,
|
|
41
|
+
value: serializeConsent(state, config),
|
|
42
|
+
options: { path: "/", maxAge: config.maxAgeSeconds, sameSite: "lax", secure: opts.secure }
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/cookies.ts
|
|
47
|
+
function refusedCookieExpiries(cookieString, state, hostname, optionalCookies) {
|
|
48
|
+
const refused = Object.keys(optionalCookies).filter((purpose) => !state[purpose]).flatMap((purpose) => optionalCookies[purpose]);
|
|
49
|
+
if (refused.length === 0) return [];
|
|
50
|
+
const labels = hostname.split(".");
|
|
51
|
+
const domains = ["", ...labels.slice(0, -1).map((_, i) => `.${labels.slice(i).join(".")}`)];
|
|
52
|
+
const names = cookieString.split("; ").map((part) => part.split("=")[0]).filter(Boolean);
|
|
53
|
+
return names.filter((name) => refused.some(({ pattern }) => pattern.test(name))).flatMap((name) => domains.map((domain) => `${name}=; path=/; max-age=0${domain ? `; domain=${domain}` : ""}`));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/inline-script.ts
|
|
57
|
+
function consentDefaultScript(config, model, firstPush) {
|
|
58
|
+
if (!/^[\w-]+$/.test(config.cookieName)) throw new Error(`consent cookie name ${config.cookieName} is not a plain name`);
|
|
59
|
+
const d = JSON.stringify(defaultSignal(model));
|
|
60
|
+
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}});`;
|
|
61
|
+
return [
|
|
62
|
+
"window.dataLayer=window.dataLayer||[];",
|
|
63
|
+
...firstPush ? [`window.dataLayer.push(${JSON.stringify(firstPush).replace(/</g, "\\u003c")});`] : [],
|
|
64
|
+
"function gtag(){dataLayer.push(arguments)}",
|
|
65
|
+
`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});`,
|
|
66
|
+
`var m=document.cookie.match(/(?:^|; )${config.cookieName}=a([01])m([01])(?:v(\\d+))?(?:;|$)/);`,
|
|
67
|
+
`if(m&&+(m[3]||1)>=${config.version}){var a=m[1]==="1"?"granted":"denied",d=m[2]==="1"?"granted":"denied";${update("a", "d")}}`,
|
|
68
|
+
...model === "opt-out" ? [`else if(navigator.globalPrivacyControl===true){${update('"granted"', '"denied"')}}`] : [],
|
|
69
|
+
'gtag("set","ads_data_redaction",true);',
|
|
70
|
+
'gtag("set","url_passthrough",false);'
|
|
71
|
+
].join("");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/controller.ts
|
|
75
|
+
var asArguments = function() {
|
|
76
|
+
return arguments;
|
|
77
|
+
};
|
|
78
|
+
function pushGtagCommand(...args) {
|
|
79
|
+
if (typeof window === "undefined") return;
|
|
80
|
+
const w = window;
|
|
81
|
+
w.dataLayer = w.dataLayer || [];
|
|
82
|
+
w.dataLayer.push(asArguments(...args));
|
|
83
|
+
}
|
|
84
|
+
function createConsent(config, hooks = {}) {
|
|
85
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
86
|
+
const settingsListeners = /* @__PURE__ */ new Set();
|
|
87
|
+
function apply(state) {
|
|
88
|
+
if (typeof window === "undefined") return;
|
|
89
|
+
pushGtagCommand("consent", "update", consentModeParams(state));
|
|
90
|
+
hooks.onApply?.(state);
|
|
91
|
+
const hostname = window.location?.hostname ?? "";
|
|
92
|
+
for (const expiry of refusedCookieExpiries(document.cookie, state, hostname, config.optionalCookies)) document.cookie = expiry;
|
|
93
|
+
document.cookie = `${config.cookieName}=${serializeConsent(state, config)}; path=/; max-age=${config.maxAgeSeconds}; samesite=lax`;
|
|
94
|
+
listeners.forEach((l) => l(state));
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
config,
|
|
98
|
+
stored: () => getStoredConsent(config),
|
|
99
|
+
apply,
|
|
100
|
+
answer(state, source) {
|
|
101
|
+
apply(state);
|
|
102
|
+
try {
|
|
103
|
+
void Promise.resolve(hooks.record?.(state, source)).catch(() => {
|
|
104
|
+
});
|
|
105
|
+
} catch {
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
/**
|
|
109
|
+
* Safety net for pages where the inline default script never ran (a
|
|
110
|
+
* framework may omit it from a client-rendered error shell): if the data
|
|
111
|
+
* layer holds no consent default yet, push an all-denied one — the
|
|
112
|
+
* strictest, whatever the model — and the stored answer now. Call it at
|
|
113
|
+
* module evaluation of a client component, before the tag manager's
|
|
114
|
+
* loader runs. Without a default, Google treats consent as granted.
|
|
115
|
+
*/
|
|
116
|
+
ensureDefault() {
|
|
117
|
+
if (typeof window === "undefined") return;
|
|
118
|
+
const dl = window.dataLayer ?? [];
|
|
119
|
+
const has = Array.from(dl).some((c) => c != null && typeof c === "object" && c[0] === "consent" && c[1] === "default");
|
|
120
|
+
if (has) return;
|
|
121
|
+
pushGtagCommand("consent", "default", {
|
|
122
|
+
ad_personalization: "denied",
|
|
123
|
+
ad_storage: "denied",
|
|
124
|
+
ad_user_data: "denied",
|
|
125
|
+
analytics_storage: "denied",
|
|
126
|
+
functionality_storage: "denied",
|
|
127
|
+
personalization_storage: "denied",
|
|
128
|
+
security_storage: "granted",
|
|
129
|
+
wait_for_update: 500
|
|
130
|
+
});
|
|
131
|
+
const stored = getStoredConsent(config);
|
|
132
|
+
if (stored) pushGtagCommand("consent", "update", consentModeParams(stored));
|
|
133
|
+
},
|
|
134
|
+
subscribe(listener) {
|
|
135
|
+
listeners.add(listener);
|
|
136
|
+
return () => listeners.delete(listener);
|
|
137
|
+
},
|
|
138
|
+
openSettings() {
|
|
139
|
+
settingsListeners.forEach((l) => l());
|
|
140
|
+
},
|
|
141
|
+
subscribeSettings(listener) {
|
|
142
|
+
settingsListeners.add(listener);
|
|
143
|
+
return () => settingsListeners.delete(listener);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
export {
|
|
148
|
+
browserGpc,
|
|
149
|
+
consentCookie,
|
|
150
|
+
consentDefaultScript,
|
|
151
|
+
consentModeParams,
|
|
152
|
+
createConsent,
|
|
153
|
+
defaultSignal,
|
|
154
|
+
getStoredConsent,
|
|
155
|
+
pushGtagCommand,
|
|
156
|
+
readConsent,
|
|
157
|
+
refusedCookieExpiries,
|
|
158
|
+
serializeConsent,
|
|
159
|
+
unansweredConsent
|
|
160
|
+
};
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
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
|
+
pattern: RegExp;
|
|
23
|
+
setBy: string;
|
|
24
|
+
}
|
|
25
|
+
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
26
|
+
interface ConsentConfig {
|
|
27
|
+
/** The first-party cookie the answer is stored in, e.g. "pz_consent". */
|
|
28
|
+
cookieName: string;
|
|
29
|
+
/**
|
|
30
|
+
* The version of what the visitor is asked to agree to. Raise it when a
|
|
31
|
+
* purpose is added or changed, or a new kind of recipient joins one (a new
|
|
32
|
+
* ad platform under marketing): every stored answer below it stops
|
|
33
|
+
* counting and the visitor is asked again. Rewording the banner does not
|
|
34
|
+
* need a new version. An answer stored without a version is version 1.
|
|
35
|
+
*/
|
|
36
|
+
version: number;
|
|
37
|
+
/** How long an answer stands before the visitor is asked again, in seconds. */
|
|
38
|
+
maxAgeSeconds: number;
|
|
39
|
+
/**
|
|
40
|
+
* Every optional cookie the site's tags set, by purpose. One list with two
|
|
41
|
+
* jobs: what is removed from the browser when a purpose is refused or
|
|
42
|
+
* withdrawn, and what the site's privacy policy has to name.
|
|
43
|
+
*/
|
|
44
|
+
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
48
|
+
type ConsentSource = 'banner' | 'settings';
|
|
49
|
+
interface ConsentController {
|
|
50
|
+
readonly config: ConsentConfig;
|
|
51
|
+
/** The visitor's stored answer in this browser, or null. */
|
|
52
|
+
stored(): ConsentState | null;
|
|
53
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie → subscribers. */
|
|
54
|
+
apply(state: ConsentState): void;
|
|
55
|
+
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
56
|
+
answer(state: ConsentState, source: ConsentSource): void;
|
|
57
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. */
|
|
58
|
+
ensureDefault(): void;
|
|
59
|
+
/** Hear every applied decision. Returns the unsubscribe. */
|
|
60
|
+
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
61
|
+
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
62
|
+
openSettings(): void;
|
|
63
|
+
subscribeSettings(listener: () => void): () => void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface ConsentBanner<T extends HTMLElement> {
|
|
67
|
+
/**
|
|
68
|
+
* What to draw:
|
|
69
|
+
* - 'hidden': nothing.
|
|
70
|
+
* - 'ask': the first-visit question (opt-in only): reject all, accept all, and a way to `choose`.
|
|
71
|
+
* - 'choose': one switch per purpose (`choice`), with reject all, accept all and `save`.
|
|
72
|
+
*/
|
|
73
|
+
view: 'hidden' | 'ask' | 'choose';
|
|
74
|
+
/** The switches in the 'choose' view. */
|
|
75
|
+
choice: ConsentState;
|
|
76
|
+
setChoice: (update: (current: ConsentState) => ConsentState) => void;
|
|
77
|
+
/** Put this on the banner's outer element (give it tabIndex={-1}): focus moves there when "Cookie settings" opens it. */
|
|
78
|
+
cardRef: RefObject<T | null>;
|
|
79
|
+
rejectAll: () => void;
|
|
80
|
+
acceptAll: () => void;
|
|
81
|
+
/** Answer with the switches as they stand. */
|
|
82
|
+
save: () => void;
|
|
83
|
+
/** From 'ask' to 'choose', every switch off. */
|
|
84
|
+
choose: () => void;
|
|
85
|
+
/** Leave 'choose' without answering: back to 'ask' if the question is still open. */
|
|
86
|
+
close: () => void;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The behaviour of a cookie banner, without its markup. The rules it keeps:
|
|
90
|
+
*
|
|
91
|
+
* - An opt-in site asks on the first visit; an opt-out site shows nothing
|
|
92
|
+
* until "Cookie settings" is pressed (controller.openSettings()).
|
|
93
|
+
* - Nothing is pre-ticked in an opt-in site: the switches start off.
|
|
94
|
+
* - Opened from "Cookie settings", the switches show what applies now, focus
|
|
95
|
+
* moves into the banner, Escape closes it and focus goes back to the link.
|
|
96
|
+
* - The banner appears only after hydration (the cookie is read in the
|
|
97
|
+
* browser), and never for a visitor whose answer still counts.
|
|
98
|
+
*
|
|
99
|
+
* What the markup must do: draw "reject all" and "accept all" as the same
|
|
100
|
+
* control side by side, so no is exactly as easy as yes, and never block the
|
|
101
|
+
* page behind the banner.
|
|
102
|
+
*/
|
|
103
|
+
declare function useConsentBanner<T extends HTMLElement = HTMLDivElement>(consent: ConsentController, model: ConsentModel): ConsentBanner<T>;
|
|
104
|
+
|
|
105
|
+
export { type ConsentBanner, useConsentBanner };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/react.ts
|
|
4
|
+
import { useEffect, useRef, useState } from "react";
|
|
5
|
+
|
|
6
|
+
// src/state.ts
|
|
7
|
+
function unansweredConsent(model, gpc) {
|
|
8
|
+
if (model === "opt-in") return { analytics: false, marketing: false };
|
|
9
|
+
return { analytics: true, marketing: !gpc };
|
|
10
|
+
}
|
|
11
|
+
function browserGpc() {
|
|
12
|
+
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/react.ts
|
|
16
|
+
function useConsentBanner(consent, model) {
|
|
17
|
+
const cardRef = useRef(null);
|
|
18
|
+
const opener = useRef(null);
|
|
19
|
+
const [view, setView] = useState("hidden");
|
|
20
|
+
const [fromSettings, setFromSettings] = useState(false);
|
|
21
|
+
const [choice, setChoiceState] = useState({ analytics: false, marketing: false });
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
if (!consent.stored() && model === "opt-in") setView("ask");
|
|
24
|
+
}, [consent, model]);
|
|
25
|
+
useEffect(
|
|
26
|
+
() => consent.subscribeSettings(() => {
|
|
27
|
+
opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
|
28
|
+
setChoiceState(consent.stored() ?? unansweredConsent(model, browserGpc()));
|
|
29
|
+
setFromSettings(true);
|
|
30
|
+
setView("choose");
|
|
31
|
+
}),
|
|
32
|
+
[consent, model]
|
|
33
|
+
);
|
|
34
|
+
function dismiss(next) {
|
|
35
|
+
setView(next);
|
|
36
|
+
setFromSettings(false);
|
|
37
|
+
opener.current?.focus();
|
|
38
|
+
opener.current = null;
|
|
39
|
+
}
|
|
40
|
+
const close = () => dismiss(!consent.stored() && model === "opt-in" ? "ask" : "hidden");
|
|
41
|
+
function answer(state) {
|
|
42
|
+
consent.answer(state, fromSettings ? "settings" : "banner");
|
|
43
|
+
dismiss("hidden");
|
|
44
|
+
}
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
if (!fromSettings) return;
|
|
47
|
+
cardRef.current?.focus();
|
|
48
|
+
const onKey = (e) => {
|
|
49
|
+
if (e.key === "Escape") close();
|
|
50
|
+
};
|
|
51
|
+
document.addEventListener("keydown", onKey);
|
|
52
|
+
return () => document.removeEventListener("keydown", onKey);
|
|
53
|
+
}, [fromSettings]);
|
|
54
|
+
return {
|
|
55
|
+
view,
|
|
56
|
+
choice,
|
|
57
|
+
setChoice: setChoiceState,
|
|
58
|
+
cardRef,
|
|
59
|
+
rejectAll: () => answer({ analytics: false, marketing: false }),
|
|
60
|
+
acceptAll: () => answer({ analytics: true, marketing: true }),
|
|
61
|
+
save: () => answer(choice),
|
|
62
|
+
choose: () => {
|
|
63
|
+
setChoiceState({ analytics: false, marketing: false });
|
|
64
|
+
setView("choose");
|
|
65
|
+
},
|
|
66
|
+
close
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export {
|
|
70
|
+
useConsentBanner
|
|
71
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venturetime/consent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup",
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"test": "vitest run",
|
|
32
|
+
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm build"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"react": ">=18"
|
|
36
|
+
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"react": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/react": "^19",
|
|
44
|
+
"@types/react-dom": "^19",
|
|
45
|
+
"jsdom": "^26",
|
|
46
|
+
"react": "^19",
|
|
47
|
+
"react-dom": "^19",
|
|
48
|
+
"tsup": "^8",
|
|
49
|
+
"typescript": "^5",
|
|
50
|
+
"vitest": "^4.1.5"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"packageManager": "pnpm@9.15.0",
|
|
56
|
+
"engines": {
|
|
57
|
+
"node": ">=20"
|
|
58
|
+
}
|
|
59
|
+
}
|