@codefast/tracking 0.5.0-canary.5 → 1.0.0-canary.7
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 +220 -0
- package/README.md +176 -126
- package/dist/adapters/tanstack-start.d.ts +80 -0
- package/dist/adapters/tanstack-start.d.ts.map +1 -0
- package/dist/adapters/tanstack-start.js +74 -0
- package/dist/adapters/tanstack-start.js.map +1 -0
- package/dist/client/ad-framework-consent.d.ts +62 -0
- package/dist/client/ad-framework-consent.d.ts.map +1 -0
- package/dist/client/ad-framework-consent.js +40 -0
- package/dist/client/ad-framework-consent.js.map +1 -0
- package/dist/client/browser-cookie.d.ts +9 -0
- package/dist/client/browser-cookie.d.ts.map +1 -0
- package/dist/client/browser-cookie.js +15 -0
- package/dist/client/browser-cookie.js.map +1 -0
- package/dist/client/consent-runtime.d.ts +53 -0
- package/dist/client/consent-runtime.d.ts.map +1 -0
- package/dist/client/consent-runtime.js +33 -0
- package/dist/client/consent-runtime.js.map +1 -0
- package/dist/client/{consent-storage.d.mts → consent-storage.d.ts} +8 -6
- package/dist/client/consent-storage.d.ts.map +1 -0
- package/dist/client/consent-storage.js +109 -0
- package/dist/client/consent-storage.js.map +1 -0
- package/dist/client/consent-withdrawal.d.ts +18 -0
- package/dist/client/consent-withdrawal.d.ts.map +1 -0
- package/dist/client/consent-withdrawal.js +17 -0
- package/dist/client/consent-withdrawal.js.map +1 -0
- package/dist/client/cookie-anonymous-id.d.ts +41 -0
- package/dist/client/cookie-anonymous-id.d.ts.map +1 -0
- package/dist/client/cookie-anonymous-id.js +65 -0
- package/dist/client/cookie-anonymous-id.js.map +1 -0
- package/dist/client/create-client-tracker.d.ts +60 -0
- package/dist/client/create-client-tracker.d.ts.map +1 -0
- package/dist/client/create-client-tracker.js +91 -0
- package/dist/client/create-client-tracker.js.map +1 -0
- package/dist/client/gpc.d.ts +10 -0
- package/dist/client/gpc.d.ts.map +1 -0
- package/dist/client/gpc.js +12 -0
- package/dist/client/gpc.js.map +1 -0
- package/dist/client/initial-consent-store.d.ts +63 -0
- package/dist/client/initial-consent-store.d.ts.map +1 -0
- package/dist/client/initial-consent-store.js +138 -0
- package/dist/client/initial-consent-store.js.map +1 -0
- package/dist/client/is-analytics-allowed.d.ts +26 -0
- package/dist/client/is-analytics-allowed.d.ts.map +1 -0
- package/dist/client/is-analytics-allowed.js +22 -0
- package/dist/client/is-analytics-allowed.js.map +1 -0
- package/dist/client/server-persisted-anonymous-id.d.ts +30 -0
- package/dist/client/server-persisted-anonymous-id.d.ts.map +1 -0
- package/dist/client/server-persisted-anonymous-id.js +72 -0
- package/dist/client/server-persisted-anonymous-id.js.map +1 -0
- package/dist/core/consent-config.d.ts +24 -0
- package/dist/core/consent-config.d.ts.map +1 -0
- package/dist/core/consent-config.js +9 -0
- package/dist/core/consent-config.js.map +1 -0
- package/dist/core/consent-receipt.d.ts +71 -0
- package/dist/core/consent-receipt.d.ts.map +1 -0
- package/dist/core/consent-receipt.js +39 -0
- package/dist/core/consent-receipt.js.map +1 -0
- package/dist/core/consent.d.ts +182 -0
- package/dist/core/consent.d.ts.map +1 -0
- package/dist/core/consent.js +159 -0
- package/dist/core/consent.js.map +1 -0
- package/dist/core/cookie.d.ts +15 -0
- package/dist/core/cookie.d.ts.map +1 -0
- package/dist/core/cookie.js +26 -0
- package/dist/core/cookie.js.map +1 -0
- package/dist/core/destination.d.ts +29 -0
- package/dist/core/destination.d.ts.map +1 -0
- package/dist/core/destination.js +2 -0
- package/dist/core/destination.js.map +1 -0
- package/dist/core/event-catalog.d.ts +35 -0
- package/dist/core/event-catalog.d.ts.map +1 -0
- package/dist/core/event-catalog.js +30 -0
- package/dist/core/event-catalog.js.map +1 -0
- package/dist/core/event-id.d.ts +7 -0
- package/dist/core/event-id.d.ts.map +1 -0
- package/dist/core/event-id.js +9 -0
- package/dist/core/event-id.js.map +1 -0
- package/dist/core/tracked-event.d.ts +15 -0
- package/dist/core/tracked-event.d.ts.map +1 -0
- package/dist/core/tracked-event.js +2 -0
- package/dist/core/tracked-event.js.map +1 -0
- package/dist/destinations/ad-consent.d.ts +23 -0
- package/dist/destinations/ad-consent.d.ts.map +1 -0
- package/dist/destinations/ad-consent.js +12 -0
- package/dist/destinations/ad-consent.js.map +1 -0
- package/dist/destinations/google-analytics.d.ts +148 -0
- package/dist/destinations/google-analytics.d.ts.map +1 -0
- package/dist/destinations/google-analytics.js +156 -0
- package/dist/destinations/google-analytics.js.map +1 -0
- package/dist/destinations/google-consent.d.ts +62 -0
- package/dist/destinations/google-consent.d.ts.map +1 -0
- package/dist/destinations/google-consent.js +109 -0
- package/dist/destinations/google-consent.js.map +1 -0
- package/dist/destinations/meta.d.ts +63 -0
- package/dist/destinations/meta.d.ts.map +1 -0
- package/dist/destinations/meta.js +44 -0
- package/dist/destinations/meta.js.map +1 -0
- package/dist/destinations/microsoft-uet.d.ts +56 -0
- package/dist/destinations/microsoft-uet.d.ts.map +1 -0
- package/dist/destinations/microsoft-uet.js +41 -0
- package/dist/destinations/microsoft-uet.js.map +1 -0
- package/dist/destinations/shared.d.ts +18 -0
- package/dist/destinations/shared.d.ts.map +1 -0
- package/dist/destinations/shared.js +19 -0
- package/dist/destinations/shared.js.map +1 -0
- package/dist/destinations/tiktok.d.ts +55 -0
- package/dist/destinations/tiktok.d.ts.map +1 -0
- package/dist/destinations/tiktok.js +40 -0
- package/dist/destinations/tiktok.js.map +1 -0
- package/dist/destinations/vercel-analytics.d.ts +25 -0
- package/dist/destinations/vercel-analytics.d.ts.map +1 -0
- package/dist/destinations/vercel-analytics.js +23 -0
- package/dist/destinations/vercel-analytics.js.map +1 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +41 -0
- package/dist/index.js.map +1 -0
- package/dist/react/consent-banner.d.ts +155 -0
- package/dist/react/consent-banner.d.ts.map +1 -0
- package/dist/react/consent-banner.js +171 -0
- package/dist/react/consent-banner.js.map +1 -0
- package/dist/react/gtag-consent-bootstrap.d.ts +17 -0
- package/dist/react/gtag-consent-bootstrap.d.ts.map +1 -0
- package/dist/react/gtag-consent-bootstrap.js +22 -0
- package/dist/react/gtag-consent-bootstrap.js.map +1 -0
- package/dist/react/use-consent.d.ts +42 -0
- package/dist/react/use-consent.d.ts.map +1 -0
- package/dist/react/use-consent.js +60 -0
- package/dist/react/use-consent.js.map +1 -0
- package/dist/react/use-google-consent-sync.d.ts +20 -0
- package/dist/react/use-google-consent-sync.d.ts.map +1 -0
- package/dist/react/use-google-consent-sync.js +22 -0
- package/dist/react/use-google-consent-sync.js.map +1 -0
- package/dist/react/use-initial-consent.d.ts +11 -0
- package/dist/react/use-initial-consent.d.ts.map +1 -0
- package/dist/react/use-initial-consent.js +18 -0
- package/dist/react/use-initial-consent.js.map +1 -0
- package/dist/server/anonymous-id-cookie.d.ts +67 -0
- package/dist/server/anonymous-id-cookie.d.ts.map +1 -0
- package/dist/server/anonymous-id-cookie.js +71 -0
- package/dist/server/anonymous-id-cookie.js.map +1 -0
- package/dist/server/consent-receipt-store.d.ts +56 -0
- package/dist/server/consent-receipt-store.d.ts.map +1 -0
- package/dist/server/consent-receipt-store.js +44 -0
- package/dist/server/consent-receipt-store.js.map +1 -0
- package/dist/server/consent-receipt.d.ts +41 -0
- package/dist/server/consent-receipt.d.ts.map +1 -0
- package/dist/server/consent-receipt.js +60 -0
- package/dist/server/consent-receipt.js.map +1 -0
- package/dist/server/initial-consent.d.ts +26 -0
- package/dist/server/initial-consent.d.ts.map +1 -0
- package/dist/server/initial-consent.js +31 -0
- package/dist/server/initial-consent.js.map +1 -0
- package/dist/server/measurement-protocol.d.ts +69 -0
- package/dist/server/measurement-protocol.d.ts.map +1 -0
- package/dist/server/measurement-protocol.js +61 -0
- package/dist/server/measurement-protocol.js.map +1 -0
- package/dist/server/region.d.ts +27 -0
- package/dist/server/region.d.ts.map +1 -0
- package/dist/server/region.js +69 -0
- package/dist/server/region.js.map +1 -0
- package/dist/server/user-deletion.d.ts +64 -0
- package/dist/server/user-deletion.d.ts.map +1 -0
- package/dist/server/user-deletion.js +54 -0
- package/dist/server/user-deletion.js.map +1 -0
- package/dist/tooling/import-protection.d.ts +19 -0
- package/dist/tooling/import-protection.d.ts.map +1 -0
- package/dist/tooling/import-protection.js +23 -0
- package/dist/tooling/import-protection.js.map +1 -0
- package/package.json +203 -108
- package/src/adapters/tanstack-start.ts +135 -0
- package/src/client/ad-framework-consent.ts +86 -0
- package/src/client/browser-cookie.ts +16 -0
- package/src/client/consent-runtime.ts +80 -0
- package/src/client/consent-storage.ts +31 -1
- package/src/client/consent-withdrawal.ts +32 -0
- package/src/client/cookie-anonymous-id.ts +112 -0
- package/src/client/create-client-tracker.ts +128 -86
- package/src/client/gpc.ts +4 -2
- package/src/client/initial-consent-store.ts +218 -0
- package/src/client/is-analytics-allowed.ts +43 -0
- package/src/client/server-persisted-anonymous-id.ts +102 -0
- package/src/core/consent-config.ts +27 -0
- package/src/core/consent-receipt.ts +115 -0
- package/src/core/consent.ts +164 -10
- package/src/core/cookie.ts +29 -0
- package/src/core/destination.ts +17 -8
- package/src/core/event-catalog.ts +29 -15
- package/src/core/event-id.ts +1 -2
- package/src/core/tracked-event.ts +4 -4
- package/src/destinations/ad-consent.ts +29 -0
- package/src/destinations/google-analytics.ts +196 -133
- package/src/destinations/google-consent.ts +164 -0
- package/src/destinations/meta.ts +96 -0
- package/src/destinations/microsoft-uet.ts +86 -0
- package/src/destinations/shared.ts +45 -0
- package/src/destinations/tiktok.ts +85 -0
- package/src/destinations/vercel-analytics.ts +23 -24
- package/src/index.ts +165 -8
- package/src/react/consent-banner.tsx +40 -14
- package/src/react/gtag-consent-bootstrap.tsx +48 -0
- package/src/react/use-consent.ts +53 -45
- package/src/react/use-google-consent-sync.ts +38 -0
- package/src/react/use-initial-consent.ts +22 -0
- package/src/server/anonymous-id-cookie.ts +103 -0
- package/src/server/consent-receipt-store.ts +79 -0
- package/src/server/consent-receipt.ts +89 -0
- package/src/server/initial-consent.ts +46 -0
- package/src/server/measurement-protocol.ts +114 -0
- package/src/server/region.ts +22 -15
- package/src/server/user-deletion.ts +93 -0
- package/src/tooling/import-protection.ts +22 -0
- package/dist/client/consent-storage.mjs +0 -63
- package/dist/client/create-client-tracker.d.mts +0 -37
- package/dist/client/create-client-tracker.mjs +0 -66
- package/dist/client/gpc.d.mts +0 -10
- package/dist/client/gpc.mjs +0 -12
- package/dist/client/index.d.mts +0 -8
- package/dist/client/index.mjs +0 -8
- package/dist/client/lifecycle.d.mts +0 -23
- package/dist/client/lifecycle.mjs +0 -30
- package/dist/client/local-storage.d.mts +0 -13
- package/dist/client/local-storage.mjs +0 -31
- package/dist/client/queue.d.mts +0 -49
- package/dist/client/queue.mjs +0 -71
- package/dist/client/router.d.mts +0 -30
- package/dist/client/router.mjs +0 -17
- package/dist/core/consent.d.mts +0 -89
- package/dist/core/consent.mjs +0 -57
- package/dist/core/destination.d.mts +0 -23
- package/dist/core/destination.mjs +0 -1
- package/dist/core/event-catalog.d.mts +0 -36
- package/dist/core/event-catalog.mjs +0 -12
- package/dist/core/event-id.d.mts +0 -10
- package/dist/core/event-id.mjs +0 -12
- package/dist/core/index.d.mts +0 -6
- package/dist/core/index.mjs +0 -4
- package/dist/core/tracked-event.d.mts +0 -17
- package/dist/core/tracked-event.mjs +0 -1
- package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
- package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
- package/dist/destinations/google-analytics.d.mts +0 -98
- package/dist/destinations/google-analytics.mjs +0 -126
- package/dist/destinations/http-destination.d.mts +0 -20
- package/dist/destinations/http-destination.mjs +0 -25
- package/dist/destinations/index.d.mts +0 -5
- package/dist/destinations/index.mjs +0 -5
- package/dist/destinations/vercel-analytics.d.mts +0 -13
- package/dist/destinations/vercel-analytics.mjs +0 -30
- package/dist/index.d.mts +0 -6
- package/dist/index.mjs +0 -4
- package/dist/react/consent-banner.d.mts +0 -163
- package/dist/react/consent-banner.mjs +0 -209
- package/dist/react/index.d.mts +0 -3
- package/dist/react/index.mjs +0 -3
- package/dist/react/use-consent.d.mts +0 -49
- package/dist/react/use-consent.mjs +0 -54
- package/dist/server/create-server-tracker.d.mts +0 -42
- package/dist/server/create-server-tracker.mjs +0 -67
- package/dist/server/index.d.mts +0 -3
- package/dist/server/index.mjs +0 -3
- package/dist/server/region.d.mts +0 -20
- package/dist/server/region.mjs +0 -56
- package/src/client/index.ts +0 -17
- package/src/client/lifecycle.ts +0 -50
- package/src/client/local-storage.ts +0 -44
- package/src/client/queue.ts +0 -117
- package/src/client/router.ts +0 -37
- package/src/core/index.ts +0 -24
- package/src/destinations/ga4-measurement-protocol.ts +0 -166
- package/src/destinations/http-destination.ts +0 -33
- package/src/destinations/index.ts +0 -20
- package/src/react/index.ts +0 -29
- package/src/server/create-server-tracker.ts +0 -128
- package/src/server/index.ts +0 -4
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
1
3
|
import type { ComponentProps, Dispatch, ReactNode, SetStateAction } from "react";
|
|
2
4
|
import { createContext, useContext, useEffect, useState } from "react";
|
|
3
5
|
|
|
4
6
|
import type { ConsentCategory, ConsentDecision } from "#/core/consent";
|
|
5
|
-
import { CONSENT_CATEGORIES } from "#/core/consent";
|
|
6
7
|
import type { UseConsentResult } from "#/react/use-consent";
|
|
7
8
|
|
|
8
9
|
interface ConsentBannerContextValue {
|
|
@@ -29,16 +30,16 @@ function useConsentBannerContext(part: string): ConsentBannerContextValue {
|
|
|
29
30
|
*/
|
|
30
31
|
export interface ConsentBannerProps extends ComponentProps<"section"> {
|
|
31
32
|
consent: UseConsentResult;
|
|
32
|
-
/** Overrides the default `
|
|
33
|
+
/** Overrides the default `isPromptNeeded` gating — e.g. to reopen the banner as a settings panel. */
|
|
33
34
|
open?: boolean | undefined;
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
|
-
* Non-blocking opt-in prompt for GDPR/
|
|
38
|
+
* Non-blocking opt-in prompt for GDPR/PDPL (VN) regions, as composable parts — the root owns
|
|
38
39
|
* the visibility gating and the preferences-layer state; the `Accept`/`Reject`/`Customize`/
|
|
39
40
|
* `Save` parts wire their own clicks to the consent hook, so any markup (including a
|
|
40
41
|
* design system's button styles via `className`) slots in. Renders nothing once a decision
|
|
41
|
-
* exists or the region defaults to opt-out (`consent.
|
|
42
|
+
* exists or the region defaults to opt-out (`consent.isPromptNeeded`), unless `open` says
|
|
42
43
|
* otherwise. Rendered as a labeled region, not a `<dialog>`: an open non-modal dialog
|
|
43
44
|
* neither traps focus nor blocks the page, so the dialog semantics would over-promise.
|
|
44
45
|
* Unstyled by default — style via `className`/`data-slot` selectors, or import the
|
|
@@ -50,7 +51,7 @@ export interface ConsentBannerProps extends ComponentProps<"section"> {
|
|
|
50
51
|
export function ConsentBanner({ children, consent, open, ...props }: ConsentBannerProps): ReactNode {
|
|
51
52
|
const [pending, setPending] = useState<ConsentDecision | undefined>(undefined);
|
|
52
53
|
|
|
53
|
-
const isVisible = open ?? consent.
|
|
54
|
+
const isVisible = open ?? consent.isPromptNeeded;
|
|
54
55
|
|
|
55
56
|
// Closing must reset the layer — a reopened banner starts at the prompt, not mid-preferences.
|
|
56
57
|
useEffect(() => {
|
|
@@ -125,7 +126,7 @@ export function ConsentBannerActions(props: ConsentBannerActionsProps): ReactNod
|
|
|
125
126
|
export interface ConsentBannerAcceptProps extends Omit<ComponentProps<"button">, "type"> {}
|
|
126
127
|
|
|
127
128
|
/**
|
|
128
|
-
* Grants the categories the app requested (`useConsent`'s `
|
|
129
|
+
* Grants the categories the app requested (`useConsent`'s `requestedCategories`) — never more.
|
|
129
130
|
*
|
|
130
131
|
* @since 0.5.0-canary.5
|
|
131
132
|
*/
|
|
@@ -288,7 +289,7 @@ export function ConsentBannerSave({ onClick, ...props }: ConsentBannerSaveProps)
|
|
|
288
289
|
// the part owns the decision — composed so a consumer onClick still runs
|
|
289
290
|
onClick={(event) => {
|
|
290
291
|
onClick?.(event);
|
|
291
|
-
consent.
|
|
292
|
+
consent.saveDecision(pending);
|
|
292
293
|
setPending(undefined);
|
|
293
294
|
}}
|
|
294
295
|
type="button"
|
|
@@ -300,15 +301,31 @@ export function ConsentBannerSave({ onClick, ...props }: ConsentBannerSaveProps)
|
|
|
300
301
|
* @since 0.5.0-canary.4
|
|
301
302
|
*/
|
|
302
303
|
export interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
|
|
303
|
-
|
|
304
|
+
/**
|
|
305
|
+
* Label shown while the scoped categories are denied — clicking grants them. Defaults
|
|
306
|
+
* to "Allow tracking".
|
|
307
|
+
*/
|
|
308
|
+
allowLabel?: string | undefined;
|
|
304
309
|
consent: UseConsentResult;
|
|
305
|
-
|
|
310
|
+
/**
|
|
311
|
+
* Label shown while any scoped category is granted — clicking denies them. Defaults to
|
|
312
|
+
* CCPA/CPRA "Do Not Sell or Share My Personal Information".
|
|
313
|
+
*/
|
|
314
|
+
denyLabel?: string | undefined;
|
|
315
|
+
/**
|
|
316
|
+
* Purposes this control flips. Defaults to `["ads"]` — CCPA/CPRA "Do Not Sell or Share"
|
|
317
|
+
* mirrors GPC (ads denied, first-party analytics left alone). Pass `["analytics"]` (or
|
|
318
|
+
* both) for a broader opt-out. Distinct from `useConsent`'s `requestedCategories` (what the
|
|
319
|
+
* prompt asks about / `grantAll` grants).
|
|
320
|
+
*/
|
|
321
|
+
toggledCategories?: ReadonlyArray<ConsentCategory> | undefined;
|
|
306
322
|
}
|
|
307
323
|
|
|
308
324
|
/**
|
|
309
325
|
* Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
|
|
310
326
|
* "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
|
|
311
|
-
*
|
|
327
|
+
* By default it only flips `ads` (same scope as a GPC signal); pass `toggledCategories`
|
|
328
|
+
* to include analytics or both.
|
|
312
329
|
*
|
|
313
330
|
* @since 0.5.0-canary.4
|
|
314
331
|
*/
|
|
@@ -316,19 +333,28 @@ export function ConsentToggle({
|
|
|
316
333
|
allowLabel = "Allow tracking",
|
|
317
334
|
consent,
|
|
318
335
|
denyLabel = "Do Not Sell or Share My Personal Information",
|
|
336
|
+
toggledCategories = ["ads"],
|
|
319
337
|
...props
|
|
320
338
|
}: ConsentToggleProps): ReactNode {
|
|
321
|
-
const
|
|
339
|
+
const isAnyCategoryGranted = toggledCategories.some((category) => consent.effectiveConsent[category]);
|
|
322
340
|
|
|
323
341
|
return (
|
|
324
342
|
<button
|
|
325
343
|
data-slot="consent-toggle"
|
|
326
344
|
{...props}
|
|
327
|
-
// the toggle owns its click — flipping the
|
|
328
|
-
onClick={
|
|
345
|
+
// the toggle owns its click — flipping the scoped categories is its whole purpose
|
|
346
|
+
onClick={() => {
|
|
347
|
+
const next = { ...consent.effectiveConsent };
|
|
348
|
+
|
|
349
|
+
for (const category of toggledCategories) {
|
|
350
|
+
next[category] = !isAnyCategoryGranted;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
consent.saveDecision(next);
|
|
354
|
+
}}
|
|
329
355
|
type="button"
|
|
330
356
|
>
|
|
331
|
-
{
|
|
357
|
+
{isAnyCategoryGranted ? denyLabel : allowLabel}
|
|
332
358
|
</button>
|
|
333
359
|
);
|
|
334
360
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ComponentProps, ReactNode } from "react";
|
|
2
|
+
|
|
3
|
+
import type { GtagConsentBootstrapOptions } from "#/destinations/google-analytics";
|
|
4
|
+
import { buildGtagConsentBootstrapScript } from "#/destinations/google-analytics";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @since 1.0.0-canary.6
|
|
8
|
+
*/
|
|
9
|
+
export interface GtagConsentBootstrapProps
|
|
10
|
+
extends
|
|
11
|
+
Omit<ComponentProps<"script">, "children" | "dangerouslySetInnerHTML" | "nonce" | "src" | "type">,
|
|
12
|
+
GtagConsentBootstrapOptions {}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Framework-agnostic inline `<script>` that runs `buildGtagConsentBootstrapScript` before
|
|
16
|
+
* hydration. Pass the same `nonce` here and in `loadGtagScript` for CSP; this component
|
|
17
|
+
* only sets the attribute on the host script — the generated source also stamps it onto
|
|
18
|
+
* the injected gtag.js tag when `nonce` is provided.
|
|
19
|
+
*
|
|
20
|
+
* @since 1.0.0-canary.6
|
|
21
|
+
*/
|
|
22
|
+
export function GtagConsentBootstrap({
|
|
23
|
+
config,
|
|
24
|
+
dataLayerName,
|
|
25
|
+
defaultConsent,
|
|
26
|
+
debugMode,
|
|
27
|
+
gaMeasurementId,
|
|
28
|
+
nonce,
|
|
29
|
+
...props
|
|
30
|
+
}: GtagConsentBootstrapProps): ReactNode {
|
|
31
|
+
const bootstrapOptions: GtagConsentBootstrapOptions = {
|
|
32
|
+
config,
|
|
33
|
+
defaultConsent,
|
|
34
|
+
gaMeasurementId,
|
|
35
|
+
...(dataLayerName === undefined ? {} : { dataLayerName }),
|
|
36
|
+
...(debugMode === undefined ? {} : { debugMode }),
|
|
37
|
+
...(nonce === undefined ? {} : { nonce }),
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
return (
|
|
41
|
+
<script
|
|
42
|
+
{...props}
|
|
43
|
+
dangerouslySetInnerHTML={{ __html: buildGtagConsentBootstrapScript(bootstrapOptions) }}
|
|
44
|
+
{...(nonce === undefined ? {} : { nonce })}
|
|
45
|
+
suppressHydrationWarning
|
|
46
|
+
/>
|
|
47
|
+
);
|
|
48
|
+
}
|
package/src/react/use-consent.ts
CHANGED
|
@@ -1,22 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
"use client";
|
|
2
2
|
|
|
3
|
-
import
|
|
4
|
-
|
|
3
|
+
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
|
|
4
|
+
|
|
5
|
+
import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
|
|
6
|
+
import { CONSENT_CATEGORIES, createConsentDecision, readStoredDecision, resolveDefaultConsent } from "#/core/consent";
|
|
7
|
+
import type { ConsentConfig } from "#/core/consent-config";
|
|
5
8
|
|
|
6
9
|
/**
|
|
7
10
|
* @since 0.5.0-canary.4
|
|
8
11
|
*/
|
|
9
12
|
export interface UseConsentOptions {
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
* Defaults to `["analytics"]`.
|
|
14
|
-
*/
|
|
15
|
-
categories?: ReadonlyArray<ConsentCategory>;
|
|
16
|
-
hasGlobalPrivacyControlSignal?: boolean;
|
|
13
|
+
/** Must be the same object the tracker gate and the tag bootstraps receive — one config, every surface. */
|
|
14
|
+
config: ConsentConfig;
|
|
15
|
+
hasGlobalPrivacyControlSignal?: boolean | undefined;
|
|
17
16
|
mode: ConsentMode;
|
|
18
|
-
onDecision?: (decision: ConsentDecision) => void;
|
|
19
|
-
policyVersion: string;
|
|
17
|
+
onDecision?: ((decision: ConsentDecision) => void) | undefined;
|
|
20
18
|
/** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
|
|
21
19
|
storage: ConsentStorage;
|
|
22
20
|
}
|
|
@@ -32,15 +30,13 @@ export interface UseConsentResult {
|
|
|
32
30
|
effectiveConsent: ConsentDecision;
|
|
33
31
|
grantAll: () => void;
|
|
34
32
|
/** Effective `analytics` consent — gates this package's own tracker pipeline. */
|
|
35
|
-
|
|
33
|
+
isAnalyticsAllowed: boolean;
|
|
36
34
|
/** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
|
|
37
|
-
|
|
35
|
+
isPromptNeeded: boolean;
|
|
38
36
|
/** Persist a granular per-category choice, e.g. from a preferences panel. */
|
|
39
|
-
|
|
37
|
+
saveDecision: (decision: ConsentDecision) => void;
|
|
40
38
|
}
|
|
41
39
|
|
|
42
|
-
const DEFAULT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["analytics"];
|
|
43
|
-
|
|
44
40
|
/**
|
|
45
41
|
* Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
|
|
46
42
|
* `useSyncExternalStore`: the stored record is the single source of truth, hydration is
|
|
@@ -51,8 +47,9 @@ const DEFAULT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["analytics"];
|
|
|
51
47
|
* @since 0.5.0-canary.4
|
|
52
48
|
*/
|
|
53
49
|
export function useConsent(options: UseConsentOptions): UseConsentResult {
|
|
54
|
-
const { storage } = options;
|
|
55
|
-
const
|
|
50
|
+
const { mode, onDecision, storage } = options;
|
|
51
|
+
const { policyVersion, requestedCategories } = options.config;
|
|
52
|
+
const hasGlobalPrivacyControlSignal = options.hasGlobalPrivacyControlSignal ?? false;
|
|
56
53
|
|
|
57
54
|
// useSyncExternalStore needs a referentially stable snapshot, but JSON-backed storages
|
|
58
55
|
// parse a fresh record per load — so the last valid decision is cached by value.
|
|
@@ -61,51 +58,62 @@ export function useConsent(options: UseConsentOptions): UseConsentResult {
|
|
|
61
58
|
const decision = useSyncExternalStore(
|
|
62
59
|
storage.subscribe,
|
|
63
60
|
(): ConsentDecision | undefined => {
|
|
64
|
-
const record = storage.load();
|
|
65
|
-
|
|
66
61
|
// Only a well-formed decision under the current policy version counts — the store
|
|
67
62
|
// is tamperable plain JSON, and a garbage value must re-prompt, not silently deny.
|
|
68
|
-
|
|
63
|
+
const stored = readStoredDecision(storage, policyVersion);
|
|
64
|
+
|
|
65
|
+
if (stored === undefined) {
|
|
69
66
|
cachedDecision.current = undefined;
|
|
70
67
|
|
|
71
68
|
return undefined;
|
|
72
69
|
}
|
|
73
70
|
|
|
74
|
-
const stored = record.decision;
|
|
75
71
|
const cached = cachedDecision.current;
|
|
76
72
|
|
|
77
73
|
if (cached !== undefined && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) {
|
|
78
74
|
return cached;
|
|
79
75
|
}
|
|
80
76
|
|
|
81
|
-
|
|
82
|
-
cachedDecision.current = createConsentDecision(CONSENT_CATEGORIES.filter((category) => stored[category]));
|
|
77
|
+
cachedDecision.current = stored;
|
|
83
78
|
|
|
84
79
|
return cachedDecision.current;
|
|
85
80
|
},
|
|
86
81
|
() => undefined,
|
|
87
82
|
);
|
|
88
83
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
84
|
+
// Kept stable across renders (when their own inputs don't change) so a consumer that
|
|
85
|
+
// passes this hook's result down as a prop/effect-dep doesn't get a fresh identity —
|
|
86
|
+
// and therefore an unnecessary re-render/effect-rerun — every render.
|
|
87
|
+
const saveDecision = useCallback(
|
|
88
|
+
(next: ConsentDecision): void => {
|
|
89
|
+
// No local state — the save notifies the subscription, which re-renders with the new snapshot.
|
|
90
|
+
storage.save({ decision: next, policyVersion, timestamp: Date.now() });
|
|
91
|
+
onDecision?.(next);
|
|
92
|
+
},
|
|
93
|
+
[onDecision, policyVersion, storage],
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
const denyAll = useCallback(() => {
|
|
97
|
+
saveDecision(createConsentDecision([]));
|
|
98
|
+
}, [saveDecision]);
|
|
94
99
|
|
|
95
|
-
const
|
|
96
|
-
|
|
100
|
+
const grantAll = useCallback(() => {
|
|
101
|
+
saveDecision(createConsentDecision(requestedCategories));
|
|
102
|
+
}, [requestedCategories, saveDecision]);
|
|
97
103
|
|
|
98
|
-
|
|
99
|
-
decision,
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
104
|
+
const effectiveConsent =
|
|
105
|
+
decision ?? resolveDefaultConsent({ hasGlobalPrivacyControlSignal, mode, requestedCategories });
|
|
106
|
+
|
|
107
|
+
return useMemo(
|
|
108
|
+
() => ({
|
|
109
|
+
decision,
|
|
110
|
+
denyAll,
|
|
111
|
+
effectiveConsent,
|
|
112
|
+
grantAll,
|
|
113
|
+
isAnalyticsAllowed: effectiveConsent.analytics,
|
|
114
|
+
isPromptNeeded: mode === "opt-in" && decision === undefined,
|
|
115
|
+
saveDecision,
|
|
116
|
+
}),
|
|
117
|
+
[decision, denyAll, effectiveConsent, grantAll, mode, saveDecision],
|
|
118
|
+
);
|
|
111
119
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useEffect } from "react";
|
|
4
|
+
|
|
5
|
+
import { updateGoogleConsent } from "#/destinations/google-analytics";
|
|
6
|
+
import type { UseConsentResult } from "#/react/use-consent";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @since 1.0.0-canary.6
|
|
10
|
+
*/
|
|
11
|
+
export interface UseGoogleConsentSyncOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Idempotent gtag.js load — advanced Consent Mode already injects the tag from a
|
|
14
|
+
* bootstrap; pass a loader as a safety net after a runtime grant.
|
|
15
|
+
*/
|
|
16
|
+
loadGtagScript?: (() => void) | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Keeps Google Consent Mode v2 in sync with `useConsent`: emits `update` when a stored
|
|
21
|
+
* decision exists (including cross-tab / privacy-page saves), and optionally loads gtag
|
|
22
|
+
* when analytics is effective. Mount once on a page-wide surface (e.g. the footer gate).
|
|
23
|
+
*
|
|
24
|
+
* @since 1.0.0-canary.6
|
|
25
|
+
*/
|
|
26
|
+
export function useGoogleConsentSync(consent: UseConsentResult, options: UseGoogleConsentSyncOptions = {}): void {
|
|
27
|
+
const { loadGtagScript } = options;
|
|
28
|
+
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (consent.decision !== undefined) {
|
|
31
|
+
updateGoogleConsent(consent.decision);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (consent.effectiveConsent.analytics) {
|
|
35
|
+
loadGtagScript?.();
|
|
36
|
+
}
|
|
37
|
+
}, [consent.decision, consent.effectiveConsent.analytics, loadGtagScript]);
|
|
38
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useEffect, useSyncExternalStore } from "react";
|
|
4
|
+
|
|
5
|
+
import type { InitialConsentSnapshot, InitialConsentStore } from "#/client/initial-consent-store";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Reactive view of a `createInitialConsentStore` — kicks off resolution on mount (a no-op
|
|
9
|
+
* when the app already did so at router creation) and re-renders once the server lane
|
|
10
|
+
* answers. SSR and the first client render read the strictest snapshot, so hydration can
|
|
11
|
+
* never mismatch on region.
|
|
12
|
+
*
|
|
13
|
+
* @since 1.0.0-canary.6
|
|
14
|
+
*/
|
|
15
|
+
export function useInitialConsent(store: InitialConsentStore): InitialConsentSnapshot {
|
|
16
|
+
// Post-hydration safety net — idempotent with an earlier, pre-hydration kick.
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
store.ensureResolved();
|
|
19
|
+
}, [store]);
|
|
20
|
+
|
|
21
|
+
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
|
|
22
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { ONE_YEAR_IN_SECONDS } from "#/core/cookie";
|
|
2
|
+
|
|
3
|
+
// The only shape the client ever mints (crypto.randomUUID) — anything else is rejected.
|
|
4
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
5
|
+
|
|
6
|
+
// Conservative subset of the RFC 6265 cookie-name token.
|
|
7
|
+
const COOKIE_NAME_PATTERN = /^[\w-]+$/;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Guards the cookie name against anything outside the RFC 6265 token set.
|
|
11
|
+
*
|
|
12
|
+
* @throws Error when `cookieName` is not a valid token.
|
|
13
|
+
*
|
|
14
|
+
* @since 1.0.0-canary.7
|
|
15
|
+
*/
|
|
16
|
+
export function assertValidAnonymousIdCookieName(cookieName: string): void {
|
|
17
|
+
if (!COOKIE_NAME_PATTERN.test(cookieName)) {
|
|
18
|
+
throw new Error(`Invalid anonymous-id cookie name: ${JSON.stringify(cookieName)}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether a value is safe to persist as an anonymous id. The persist endpoint is public and
|
|
24
|
+
* writes its input into a `Set-Cookie`, so only an exactly-UUID-shaped value may pass —
|
|
25
|
+
* anything else is a header-injection attempt or corruption, never a valid id.
|
|
26
|
+
*
|
|
27
|
+
* @since 1.0.0-canary.6
|
|
28
|
+
*/
|
|
29
|
+
export function isValidAnonymousId(value: string): boolean {
|
|
30
|
+
return UUID_PATTERN.test(value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @since 1.0.0-canary.6
|
|
35
|
+
*/
|
|
36
|
+
export interface AnonymousIdCookieOptions {
|
|
37
|
+
/** Cookie name — must match what the client tracker reads. */
|
|
38
|
+
cookieName: string;
|
|
39
|
+
/** The client-minted id to persist — throws unless it is exactly UUID-shaped. */
|
|
40
|
+
id: string;
|
|
41
|
+
/** How long the id survives a return visit. Defaults to one year. */
|
|
42
|
+
maxAgeSeconds?: number | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The validated name/value plus cookie attributes for persisting a client-minted anonymous
|
|
47
|
+
* id from the server — feed straight into the framework's cookie helper (`setCookie`).
|
|
48
|
+
*
|
|
49
|
+
* @remarks
|
|
50
|
+
* Always `Secure` — on a plain-HTTP dev origin a browser may drop it, and the
|
|
51
|
+
* client-written cookie (`createServerPersistedAnonymousId`'s optimistic write) still
|
|
52
|
+
* covers that session. Not `httpOnly`: the client tracker must read the id to stamp it onto
|
|
53
|
+
* events. A server-set cookie escapes Safari ITP's 7-day cap on `document.cookie` writes, so
|
|
54
|
+
* the id actually lives its full max-age. The server only ever re-sets an id the client
|
|
55
|
+
* hands it — minting stays client-side, after consent, by design.
|
|
56
|
+
*
|
|
57
|
+
* @throws Error when `id` is not UUID-shaped or `cookieName` is not a valid token.
|
|
58
|
+
*
|
|
59
|
+
* @since 1.0.0-canary.6
|
|
60
|
+
*/
|
|
61
|
+
export function resolveAnonymousIdCookie(options: AnonymousIdCookieOptions): {
|
|
62
|
+
maxAge: number;
|
|
63
|
+
name: string;
|
|
64
|
+
path: string;
|
|
65
|
+
sameSite: "lax";
|
|
66
|
+
secure: true;
|
|
67
|
+
value: string;
|
|
68
|
+
} {
|
|
69
|
+
assertValidAnonymousIdCookieName(options.cookieName);
|
|
70
|
+
|
|
71
|
+
if (!isValidAnonymousId(options.id)) {
|
|
72
|
+
throw new Error("Invalid anonymous id: expected a UUID-shaped value");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
maxAge: options.maxAgeSeconds ?? ONE_YEAR_IN_SECONDS,
|
|
77
|
+
name: options.cookieName,
|
|
78
|
+
path: "/",
|
|
79
|
+
sameSite: "lax",
|
|
80
|
+
secure: true,
|
|
81
|
+
value: options.id,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Name plus attributes for expiring the anonymous-id cookie — the server half of a consent
|
|
87
|
+
* withdrawal. Attributes must match {@link resolveAnonymousIdCookie} so the browser targets
|
|
88
|
+
* the same cookie. Feed into the framework's `deleteCookie`.
|
|
89
|
+
*
|
|
90
|
+
* @throws Error when `cookieName` is not a valid token.
|
|
91
|
+
*
|
|
92
|
+
* @since 1.0.0-canary.6
|
|
93
|
+
*/
|
|
94
|
+
export function resolveClearAnonymousIdCookie(cookieName: string): {
|
|
95
|
+
name: string;
|
|
96
|
+
path: string;
|
|
97
|
+
sameSite: "lax";
|
|
98
|
+
secure: true;
|
|
99
|
+
} {
|
|
100
|
+
assertValidAnonymousIdCookieName(cookieName);
|
|
101
|
+
|
|
102
|
+
return { name: cookieName, path: "/", sameSite: "lax", secure: true };
|
|
103
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { ConsentReceipt } from "#/core/consent-receipt";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Persistence backend for consent receipts — the durable store is the consumer's to supply
|
|
5
|
+
* (a database, an append-only log). The store is **append-only**: `append` never overwrites,
|
|
6
|
+
* and an update/withdrawal is a new receipt referencing the prior one (spec-consent-receipts §3).
|
|
7
|
+
* May be async so a real backend can await its write.
|
|
8
|
+
*
|
|
9
|
+
* @since 1.0.0-canary.7
|
|
10
|
+
*/
|
|
11
|
+
export interface ReceiptStore {
|
|
12
|
+
append: (receipt: ConsentReceipt) => Promise<void> | void;
|
|
13
|
+
get: (receiptId: string) => ConsentReceipt | undefined | Promise<ConsentReceipt | undefined>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* An in-memory {@link ReceiptStore} for development and tests — **not** durable across a
|
|
18
|
+
* process restart, and not a lawful production store on its own. A real deployment supplies
|
|
19
|
+
* a database-backed implementation; this exists so the endpoint is runnable end-to-end
|
|
20
|
+
* without standing up storage first.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* Append is idempotent-by-id: re-appending the same `receiptId` is ignored, preserving the
|
|
24
|
+
* append-only guarantee even if a client retries.
|
|
25
|
+
*
|
|
26
|
+
* @since 1.0.0-canary.7
|
|
27
|
+
*/
|
|
28
|
+
export function createInMemoryReceiptStore(): ReceiptStore {
|
|
29
|
+
const receipts = new Map<string, ConsentReceipt>();
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
append(receipt: ConsentReceipt): void {
|
|
33
|
+
if (!receipts.has(receipt.receiptId)) {
|
|
34
|
+
receipts.set(receipt.receiptId, receipt);
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
get(receiptId: string): ConsentReceipt | undefined {
|
|
38
|
+
return receipts.get(receiptId);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The minimal id-keyed primitive a durable backend must expose for {@link createDurableReceiptStore}.
|
|
45
|
+
* Keeping it this small lets an integrator back receipts with any store (Vercel KV, Postgres,
|
|
46
|
+
* an append-only log) by implementing two methods rather than the full {@link ReceiptStore}.
|
|
47
|
+
*
|
|
48
|
+
* @since 1.0.0-canary.7
|
|
49
|
+
*/
|
|
50
|
+
export interface ReceiptStoreBackend {
|
|
51
|
+
get: (receiptId: string) => Promise<ConsentReceipt | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* Persist one receipt under its id. MUST be idempotent-by-id and never overwrite — a
|
|
54
|
+
* duplicate `receiptId` is a no-op — so the append-only guarantee holds atomically even
|
|
55
|
+
* under a client retry or concurrent write (e.g. KV set-if-absent, Postgres
|
|
56
|
+
* `INSERT … ON CONFLICT DO NOTHING`). The frame delegates rather than doing a racy
|
|
57
|
+
* get-then-put itself.
|
|
58
|
+
*/
|
|
59
|
+
put: (receiptId: string, receipt: ConsentReceipt) => Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A durable {@link ReceiptStore} over an injected {@link ReceiptStoreBackend} — the package
|
|
64
|
+
* supplies the append-only contract and adaptation, the deployment supplies the backend
|
|
65
|
+
* client (no database dependency is baked in). Pair it with a real backend in production,
|
|
66
|
+
* where {@link createInMemoryReceiptStore} is not a lawful store on its own.
|
|
67
|
+
*
|
|
68
|
+
* @since 1.0.0-canary.7
|
|
69
|
+
*/
|
|
70
|
+
export function createDurableReceiptStore(options: { backend: ReceiptStoreBackend }): ReceiptStore {
|
|
71
|
+
return {
|
|
72
|
+
async append(receipt: ConsentReceipt): Promise<void> {
|
|
73
|
+
await options.backend.put(receipt.receiptId, receipt);
|
|
74
|
+
},
|
|
75
|
+
async get(receiptId: string): Promise<ConsentReceipt | undefined> {
|
|
76
|
+
return options.backend.get(receiptId);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { ConsentReceipt, ConsentReceiptInput } from "#/core/consent-receipt";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The receipt information-structure version this builder emits (ISO/IEC TS 27560-shaped).
|
|
5
|
+
* Bump when the receipt field set changes; stored receipts carry it so a reader can migrate.
|
|
6
|
+
*
|
|
7
|
+
* @since 1.0.0-canary.7
|
|
8
|
+
*/
|
|
9
|
+
export const RECEIPT_SCHEMA_VERSION = "1.0.0";
|
|
10
|
+
|
|
11
|
+
const IPV4_PATTERN = /^(\d{1,3}\.){3}\d{1,3}$/;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Coarsens an IP for storage — a full address MUST never be persisted (spec-consent-receipts
|
|
15
|
+
* §4, R5). IPv4 drops the last two octets; IPv6 keeps only the first two hextets. This mirrors
|
|
16
|
+
* the Cookiebot-style anonymization cited in the spec and is the maximally-private default;
|
|
17
|
+
* a controller may widen it under counsel, but the builder never returns a full address.
|
|
18
|
+
* Returns `undefined` for a missing or malformed input rather than storing a bad value.
|
|
19
|
+
*
|
|
20
|
+
* @since 1.0.0-canary.7
|
|
21
|
+
*/
|
|
22
|
+
export function coarsenIp(ip: string | null | undefined): string | undefined {
|
|
23
|
+
if (!ip) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const trimmed = ip.trim();
|
|
28
|
+
|
|
29
|
+
if (IPV4_PATTERN.test(trimmed)) {
|
|
30
|
+
const octets = trimmed.split(".");
|
|
31
|
+
|
|
32
|
+
// Reject out-of-range octets (e.g. "999.1.1.1") rather than storing a malformed coarse value.
|
|
33
|
+
if (octets.some((octet) => Number(octet) > 255)) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return `${octets[0]}.${octets[1]}.0.0`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (trimmed.includes(":")) {
|
|
41
|
+
const [first, second] = trimmed.split(":");
|
|
42
|
+
|
|
43
|
+
// Require two explicit leading hextets — a compressed-leading address ("::1", "fe80::1")
|
|
44
|
+
// can't be coarsened without full expansion, so degrade to no stored value.
|
|
45
|
+
if (!first || !second) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return `${first}:${second}::`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @remarks
|
|
57
|
+
* `sign` is optional so the package never bakes a crypto secret: supply an HMAC/signature
|
|
58
|
+
* function to stamp an `integrityKey`, letting a client prove its state matches the stored
|
|
59
|
+
* original (spec-consent-receipts §5). Omit it and receipts carry no integrity key.
|
|
60
|
+
*
|
|
61
|
+
* @since 1.0.0-canary.7
|
|
62
|
+
*/
|
|
63
|
+
export interface BuildConsentReceiptOptions {
|
|
64
|
+
input: ConsentReceiptInput;
|
|
65
|
+
/** The connection IP, read server-side — never accepted from the request body. */
|
|
66
|
+
rawIp?: string | null | undefined;
|
|
67
|
+
sign?: ((receipt: Omit<ConsentReceipt, "integrityKey">) => string) | undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Builds a stored consent receipt from caller input plus server-derived fields
|
|
72
|
+
* (`receiptId`, `timestamp`, coarsened IP, optional `integrityKey`). Pure except for the
|
|
73
|
+
* id/clock it stamps — pass those in via a seam if a deterministic build is needed.
|
|
74
|
+
*
|
|
75
|
+
* @since 1.0.0-canary.7
|
|
76
|
+
*/
|
|
77
|
+
export function buildConsentReceipt(options: BuildConsentReceiptOptions): ConsentReceipt {
|
|
78
|
+
const base: Omit<ConsentReceipt, "integrityKey"> = {
|
|
79
|
+
...options.input,
|
|
80
|
+
ipCoarse: coarsenIp(options.rawIp),
|
|
81
|
+
receiptId: crypto.randomUUID(),
|
|
82
|
+
schemaVersion: RECEIPT_SCHEMA_VERSION,
|
|
83
|
+
timestamp: Date.now(),
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const integrityKey = options.sign?.(base);
|
|
87
|
+
|
|
88
|
+
return integrityKey === undefined ? base : { ...base, integrityKey };
|
|
89
|
+
}
|