@graffico/legal 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,31 +1,39 @@
1
1
  # @graffico/legal
2
2
 
3
- GDPR compliance per React/Next.js. Banner, modale preferenze, privacy & cookie policy server-rendered, oltre 15 service preset.
4
-
5
- ## Install
3
+ CMP GDPR drop-in per React / Next.js. Banner + modale, policy server-rendered, **tracker terzi che caricano solo dopo consenso**, plugin Next.js per security headers.
6
4
 
7
5
  ```bash
8
6
  pnpm add @graffico/legal
9
7
  ```
10
8
 
11
- ## Setup
9
+ ---
12
10
 
13
- `app/layout.tsx` — server component, **niente `"use client"`**:
11
+ ## 1. Setup minimo
14
12
 
15
- ```tsx
16
- import { LegalProvider } from "@graffico/legal/server";
13
+ `src/config/legal.ts`:
17
14
 
18
- const legalConfig = {
15
+ ```ts
16
+ import type { CompanyConfig } from "@graffico/legal";
17
+
18
+ export const legalConfig: CompanyConfig = {
19
19
  name: "Mia Azienda",
20
20
  domain: "azienda.it",
21
- owners: "Nome Proprietario",
21
+ owners: "Mario Rossi",
22
22
  addresses: "Via Roma 1, Milano",
23
23
  vatNumbers: "01234567890",
24
24
  email: "privacy@azienda.it",
25
- services: ["google-analytics", "facebook-pixel"],
25
+ policyVersion: "2026.05", // cambiarla invalida i consensi vecchi
26
+ services: ["google-analytics", "facebook-pixel", "contact-form"],
26
27
  primaryColor: "#2c5282",
27
28
  language: "it",
28
29
  };
30
+ ```
31
+
32
+ `app/layout.tsx`:
33
+
34
+ ```tsx
35
+ import { LegalProvider } from "@graffico/legal/server";
36
+ import { legalConfig } from "@/config/legal";
29
37
 
30
38
  export default function RootLayout({ children }) {
31
39
  return (
@@ -38,99 +46,165 @@ export default function RootLayout({ children }) {
38
46
  }
39
47
  ```
40
48
 
41
- `<LegalProvider>` monta automaticamente banner, modale preferenze e toggle flottante.
49
+ `<LegalProvider>` monta automaticamente banner + modale + floating toggle.
50
+
51
+ ---
52
+
53
+ ## 2. Tracker — drop-in con consenso integrato
42
54
 
43
- ## Pagine
55
+ Importi il componente Legal, passi le API key. Lo script parte **solo dopo consenso**.
44
56
 
45
57
  ```tsx
46
- // app/privacy-policy/page.tsx
47
- import { PrivacyPolicy } from "@graffico/legal/server";
48
- export default () => <PrivacyPolicy config={legalConfig} />;
58
+ import {
59
+ ConsentModeBoot,
60
+ GoogleAnalyticsLegal,
61
+ GoogleAdsLegal,
62
+ MetaPixelLegal,
63
+ HotjarLegal,
64
+ GTMLegal,
65
+ EmailJSLegal,
66
+ } from "@graffico/legal";
67
+
68
+ <LegalProvider config={legalConfig}>
69
+ <ConsentModeBoot /> {/* Google Consent Mode v2 default = denied */}
70
+ <GoogleAnalyticsLegal gaId="G-XXXX" />
71
+ <GoogleAdsLegal
72
+ conversionId="AW-XXXX"
73
+ conversions={{ formSubmit: { sendTo: "AW-XXXX/abc", value: 1, currency: "EUR" } }}
74
+ />
75
+ <MetaPixelLegal pixelId="123456" events={["Lead", "Contact"]} />
76
+ <HotjarLegal siteId={1234567} />
77
+ <EmailJSLegal
78
+ serviceId={process.env.NEXT_PUBLIC_EMAILJS_SERVICE_ID!}
79
+ templateId={process.env.NEXT_PUBLIC_EMAILJS_TEMPLATE_ID!}
80
+ publicKey={process.env.NEXT_PUBLIC_EMAILJS_USER_ID!}
81
+ />
82
+ {children}
83
+ </LegalProvider>
49
84
  ```
50
85
 
86
+ | Componente | Categoria default | Script gated | Note |
87
+ |---|---|---|---|
88
+ | `ConsentModeBoot` | — | — | Boot gtag stub + Consent Mode v2. **Sempre per primo.** |
89
+ | `GoogleAnalyticsLegal` | `statistical` | `gtag/js?id=G-…` | Anonymize IP on di default. |
90
+ | `GoogleAdsLegal` | `marketing` | `gtag/js?id=AW-…` | Mappa conversioni dichiarativa. |
91
+ | `MetaPixelLegal` | `marketing` | `fbevents.js` | Whitelist `events` opzionale. Su revoca → `fbq('consent','revoke')`. |
92
+ | `HotjarLegal` | `statistical` | `static.hotjar.com/c/hotjar-…` | Session recording + heatmap. |
93
+ | `GTMLegal` | `marketing` | `gtm.js?id=GTM-…` | Lascia ai tag interni la granularità. |
94
+ | `EmailJSLegal` | — (art. 6.1.b) | — | Config holder per `useEmailJS()`. |
95
+
96
+ ---
97
+
98
+ ## 3. Hook trigger eventi
99
+
100
+ Nei tuoi componenti `"use client"`:
101
+
51
102
  ```tsx
52
- // app/cookie-policy/page.tsx
53
- import { CookiePolicy } from "@graffico/legal/server";
54
- export default () => <CookiePolicy config={legalConfig} />;
103
+ import { useGAEvent, useMetaEvent, useAdsConversion, useHotjarEvent } from "@graffico/legal";
104
+
105
+ const trackGA = useGAEvent();
106
+ const trackLead = useMetaEvent("Lead");
107
+ const fireConversion = useAdsConversion("formSubmit");
108
+ const trackHj = useHotjarEvent();
109
+
110
+ // Tutti diventano no-op senza consenso — chiama liberamente
111
+ trackGA("button_click", { id: "hero" });
112
+ trackLead({ value: 99, currency: "EUR" });
113
+ fireConversion();
114
+ trackHj("scroll_to_pricing");
55
115
  ```
56
116
 
57
- ## i18n dinamico (opzionale)
117
+ ---
58
118
 
59
- Se l'app cambia lingua a runtime (es. con i18next), aggiungi un bridge:
119
+ ## 4. Form contatto con consenso
60
120
 
61
121
  ```tsx
62
- // components/legal-i18n-bridge.tsx
63
122
  "use client";
64
- import { useEffect } from "react";
65
- import { setLanguage } from "@graffico/legal";
66
- import i18n from "@/i18n";
67
-
68
- export function LegalI18nBridge() {
69
- useEffect(() => {
70
- const sync = () => setLanguage(i18n.language);
71
- sync();
72
- i18n.on("languageChanged", sync);
73
- return () => i18n.off("languageChanged", sync);
74
- }, []);
75
- return null;
123
+ import { useEmailJS, ConsentCheckbox } from "@graffico/legal";
124
+
125
+ export function ContactForm() {
126
+ const { send, status } = useEmailJS();
127
+
128
+ async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
129
+ e.preventDefault();
130
+ const res = await send(e.currentTarget);
131
+ if (!res.ok) console.warn(res.error); // CONSENT_MISSING | CONFIG_MISSING | SEND_FAILED
132
+ }
133
+
134
+ return (
135
+ <form onSubmit={onSubmit}>
136
+ <input name="name" required />
137
+ <input name="email" type="email" required />
138
+ <textarea name="message" required />
139
+ <ConsentCheckbox /> {/* obbligatorio: blocca submit se non spuntato */}
140
+ <button disabled={status === "loading"}>Invia</button>
141
+ </form>
142
+ );
76
143
  }
77
144
  ```
78
145
 
79
- Inseriscilo come figlio del provider:
146
+ `send()` inietta automaticamente nel payload mail: `_consentId`, `_consentTimestamp`, `_policyVersion` (prova legale art. 7.1).
80
147
 
81
- ```tsx
82
- <LegalProvider config={legalConfig}>
83
- <LegalI18nBridge />
84
- {children}
85
- </LegalProvider>
86
- ```
148
+ ---
87
149
 
88
- ## Service preset
150
+ ## 5. Pagine policy
89
151
 
90
- Inserisci l'id come stringa nell'array `services`:
152
+ Auto-renderizzate dalla config — incluse sezioni Processors / Transfers / Retention / DPO se valorizzati.
91
153
 
92
- | Categoria | Preset disponibili |
93
- |-----------|--------------------|
94
- | Analytics | `google-analytics`, `facebook-pixel`, `linkedin-insight`, `tiktok-pixel`, `microsoft-clarity`, `hotjar`, `google-tag-manager` |
95
- | Pagamenti | `stripe`, `paypal` |
96
- | Contenuti | `youtube`, `google-maps`, `google-fonts` |
97
- | Marketing | `mailchimp`, `newsletter`, `contact-form` |
154
+ ```tsx
155
+ // app/privacy-policy/page.tsx
156
+ import { PrivacyPolicy } from "@graffico/legal/server";
157
+ import { legalConfig } from "@/config/legal";
158
+ export default () => <PrivacyPolicy config={legalConfig} />;
98
159
 
99
- Servizio custom inline:
160
+ // app/cookie-policy/page.tsx
161
+ import { CookiePolicy } from "@graffico/legal/server";
162
+ export default () => <CookiePolicy config={legalConfig} />;
163
+ ```
164
+
165
+ ---
166
+
167
+ ## 6. Gate per embed terzi
100
168
 
101
169
  ```tsx
102
- {
103
- id: "crm",
104
- name: "CRM Interno",
105
- category: "provided", // "automatic" | "provided" | "marketing"
106
- purposes: ["Gestione Clienti"],
107
- dataCollected: ["Email", "Nome"],
108
- }
170
+ import { ConsentGate, useConsentCategory } from "@graffico/legal";
171
+
172
+ <ConsentGate
173
+ category="marketing"
174
+ fallback={<p>Abilita cookie marketing per vedere il video.</p>}
175
+ >
176
+ <iframe src="https://youtube.com/embed/…" />
177
+ </ConsentGate>
109
178
  ```
110
179
 
111
- ## API
180
+ ---
181
+
182
+ ## 7. Next.js plugin — security headers
183
+
184
+ CSP derivata dai `services[]` + `processors[]`. HSTS, X-Frame, Permissions-Policy, COOP, Referrer-Policy.
112
185
 
113
- ### Entry `@graffico/legal/server` (server)
186
+ ```ts
187
+ // next.config.ts
188
+ import { withLegal } from "@graffico/legal/next";
189
+ import { legalConfig } from "@/config/legal";
190
+
191
+ const nextConfig = { /* … */ };
114
192
 
115
- | Export | Tipo |
116
- |--------|------|
117
- | `LegalProvider` | Wrapper root, monta context + banner |
118
- | `PrivacyPolicy` | Pagina privacy policy |
119
- | `CookiePolicy` | Pagina cookie policy |
193
+ export default withLegal(nextConfig, legalConfig, {
194
+ cspReportOnly: process.env.CSP_ENFORCE !== "1", // rollout: 7gg report-only → enforce
195
+ });
196
+ ```
120
197
 
121
- ### Entry `@graffico/legal` (client)
198
+ Per `netlify.toml`:
122
199
 
123
- | Export | Tipo |
124
- |--------|------|
125
- | `useLegalLanguage` | Lingua corrente |
126
- | `useConsent` | Stato consenso (`{ statistical, marketing, ... }`) |
127
- | `useShowBanner`, `useModalOpen`, `useT` | Hook UI |
128
- | `useLegalConfig`, `useLegalConfigOptional` | Config dal context |
129
- | `setLanguage`, `acceptAll`, `declineAll`, `savePreferences`, `resetConsent`, `setModalOpen` | Azioni store |
130
- | `ConsentBanner`, `PreferenceModal`, `FloatingConsentToggle`, `ServiceGrid` | Componenti, già montati dal provider |
131
- | `SERVICE_PRESETS`, `resolveService`, `DEFAULT_PRIMARY_COLOR` | Utility |
200
+ ```ts
201
+ import { emitNetlifyHeaders } from "@graffico/legal/next";
202
+ console.log(emitNetlifyHeaders(legalConfig));
203
+ ```
204
+
205
+ ---
132
206
 
133
- ## Configurazione
207
+ ## 8. `CompanyConfig`
134
208
 
135
209
  ```ts
136
210
  interface CompanyConfig {
@@ -140,19 +214,103 @@ interface CompanyConfig {
140
214
  addresses: string | string[];
141
215
  vatNumbers: string | string[];
142
216
  email: string;
143
- services?: ServiceReference[];
144
- togglePosition?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
145
- lastUpdated?: string;
217
+
218
+ policyVersion?: string; // cambiarla invalida i consensi pregressi
219
+ lastUpdated?: string; // ISO date, default oggi
220
+
221
+ services?: ServiceReference[]; // tracker dichiarati (preset id o oggetto)
222
+ processors?: Processor[]; // destinatari/responsabili esterni
223
+ retention?: RetentionMap; // tempi di conservazione per categoria
224
+ dpo?: DpoInfo; // se nominato (art. 37 GDPR)
225
+
146
226
  theme?: "light" | "dark";
147
227
  primaryColor?: string;
148
228
  language?: "it" | "en";
229
+ togglePosition?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
230
+ }
231
+
232
+ interface Processor {
233
+ name: string;
234
+ purpose: string;
235
+ country: string;
236
+ transferBasis?: string; // "DPF + SCC 2021/914", "SCC", …
237
+ privacyUrl?: string;
238
+ }
239
+
240
+ interface RetentionMap {
241
+ contactForms?: string; // "90d"
242
+ analytics?: string; // "14m"
243
+ marketing?: string; // "2y"
244
+ [k: string]: string | undefined;
245
+ }
246
+
247
+ interface DpoInfo {
248
+ name: string;
249
+ email: string;
250
+ phone?: string;
149
251
  }
150
252
  ```
151
253
 
254
+ ---
255
+
256
+ ## 9. Conformità GDPR / ePrivacy — cosa fa già la lib
257
+
258
+ - **TTL consenso 180 giorni** (`CONSENT_TTL_MS`), allineato al Garante 10/06/2021. Scaduto → re-prompt.
259
+ - **Re-prompt automatico** al cambio `policyVersion`.
260
+ - **Auto-decline su GPC / DNT** (`navigator.globalPrivacyControl`, `Sec-GPC`) senza UI.
261
+ - **Prova legale**: `consentId` UUID + `timestamp` ISO + `policyVersion` + `source` in localStorage e nel payload mail.
262
+ - **Parità grafica reject/accept** nel banner (Garante 10/06/2021 §4).
263
+ - **Categorie indipendenti**: `necessary` / `statistical` / `marketing`. Default OFF.
264
+ - **Niente cookie wall**: il sito resta fruibile senza consenso.
265
+ - **Zero telemetria** della libreria stessa.
266
+
267
+ ---
268
+
269
+ ## 10. Service preset (id stringa per `services[]`)
270
+
271
+ | Categoria | Id |
272
+ |---|---|
273
+ | Analytics | `google-analytics`, `microsoft-clarity`, `hotjar` |
274
+ | Marketing | `facebook-pixel`, `google-ads`, `linkedin-insight`, `tiktok-pixel` |
275
+ | Tag manager | `google-tag-manager` |
276
+ | Pagamenti | `stripe`, `paypal` |
277
+ | Contenuti | `youtube`, `google-maps`, `google-fonts` |
278
+ | Form / mail | `contact-form`, `mailchimp`, `newsletter` |
279
+
280
+ Servizio inline custom:
281
+
282
+ ```ts
283
+ {
284
+ id: "crm",
285
+ name: "CRM Interno",
286
+ category: "provided", // "automatic" | "provided" | "marketing"
287
+ purposes: ["Gestione clienti"],
288
+ dataCollected: ["Email", "Nome"],
289
+ }
290
+ ```
291
+
292
+ ---
293
+
294
+ ## 11. API export
295
+
296
+ **`@graffico/legal/server`** — `LegalProvider`, `PrivacyPolicy`, `CookiePolicy`.
297
+
298
+ **`@graffico/legal`** (client) —
299
+ - Tracker: `ConsentModeBoot`, `GoogleAnalyticsLegal`, `GoogleAdsLegal`, `MetaPixelLegal`, `HotjarLegal`, `GTMLegal`, `EmailJSLegal`
300
+ - Hook: `useConsent`, `useConsentCategory`, `useIsHydrated`, `useGAEvent`, `useAdsConversion`, `useMetaEvent`, `useHotjarEvent`, `useHotjarIdentify`, `useEmailJS`, `useT`, `useLegalLanguage`
301
+ - UI: `ConsentBanner`, `PreferenceModal`, `FloatingConsentToggle`, `ConsentGate`, `ConsentCheckbox`, `ServiceGrid`
302
+ - Azioni: `acceptAll`, `declineAll`, `savePreferences`, `resetConsent`, `setModalOpen`, `setLanguage`
303
+ - Primitive: `subscribeConsent`, `getConsentSnapshot`, `CONSENT_TTL_MS`, `SERVICE_PRESETS`
304
+
305
+ **`@graffico/legal/next`** — `withLegal`, `emitNetlifyHeaders`, `buildLegalHeaders`, `buildCspFromConfig`.
306
+
307
+ ---
308
+
152
309
  ## Requisiti
153
310
 
154
- - React 18+ (Next.js App Router consigliato)
155
- - TailwindCSS opzionale; la lib usa classi Tailwind, integrazione via `content` oppure rimpiazzo con CSS proprio.
311
+ - React ≥ 18 (App Router consigliato)
312
+ - Tailwind opzionale (la UI usa classi Tailwind)
313
+ - `@emailjs/browser` ≥ 4 — peer optional, solo se usi `EmailJSLegal`
156
314
 
157
315
  ---
158
316