@consent-kit/compiler 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 consent-kit contributors
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,17 @@
1
- # Temporary Holding Version
1
+ # @consent-kit/compiler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Compiles a consent-kit registry into the files a site needs: the policy snapshot, the [vanilla-cookieconsent](https://github.com/orestbida/cookieconsent) configuration, the guard manifest, the strict Content-Security-Policy, the registry module, consent-gated `<script>` tags and iframe placeholders.
4
+
5
+ Most projects use it through [`@consent-kit/cli`](https://www.npmjs.com/package/@consent-kit/cli) (`consent-kit build`), which also re-exports the build-script helpers. Install this package directly only to call the compiler from your own tooling:
6
+
7
+ ```sh
8
+ npm install --save-dev @consent-kit/compiler
9
+ ```
10
+
11
+ Exports include `compile`, `policySnapshot`, `guardManifest`, `contentSecurityPolicy`, `describeCspDeviations`, `consentScriptTag` and `consentEmbed`.
12
+
13
+ - [Generated files](https://consent-kit.com/docs/manual/reference/generated-files/)
14
+ - [Content-Security-Policy reference](https://consent-kit.com/docs/manual/reference/content-security-policy/)
15
+ - [Build-script helpers](https://consent-kit.com/docs/manual/reference/runtime-api/#build-script-helpers)
16
+
17
+ MIT licensed.
@@ -0,0 +1,427 @@
1
+ import { Registry, GuardManifest } from '@consent-kit/schema';
2
+ import { CookieConsentConfig, Translation } from 'vanilla-cookieconsent';
3
+
4
+ interface PolicySnapshot {
5
+ /** The registry in canonical form: id-keyed lists sorted by id, set-like lists sorted, keys sorted. */
6
+ policy: Registry;
7
+ /** Lowercase hex SHA-256 of `canonicalJson(policy)`. */
8
+ hash: string;
9
+ }
10
+ /**
11
+ * JSON with recursively sorted object keys and no insignificant whitespace.
12
+ * `undefined` properties are dropped; array order is preserved.
13
+ */
14
+ declare function canonicalJson(value: unknown): string;
15
+ /**
16
+ * The Policy primitive: a canonical, content-hashed snapshot of the registry.
17
+ *
18
+ * Order-independent for everything whose order carries no meaning: the id-keyed
19
+ * lists (purposes, processors, artefacts, collection points), fields within a
20
+ * collection point (keyed by name), and the set-like lists (locales, an
21
+ * artefact's purposes, a purpose's data categories, data subjects and
22
+ * processors). The glossary maps are keyed objects, so their order never
23
+ * counts. Any other change, including
24
+ * a typo fix in a text, changes the hash.
25
+ */
26
+ declare function policySnapshot(registry: Registry): PolicySnapshot;
27
+
28
+ /**
29
+ * What the generated CookieConsent module hands to `installConsentReceipts`
30
+ * (@consent-kit/storage). The same shape as that package's `ReceiptSettings`; declared here
31
+ * so that the compiler does not depend on the browser runtime.
32
+ */
33
+ interface ReceiptSettings {
34
+ /** `receipts.endpoint`, exactly as declared. */
35
+ endpoint: string;
36
+ /** `policySnapshot(registry).hash`: the version the generated documents print. */
37
+ policyHash: string;
38
+ /** CookieConsent's revision of this build. */
39
+ revision: number;
40
+ /** Consent purpose id to its version, sorted by id. */
41
+ purposes: Record<string, number>;
42
+ }
43
+ /** The module the generated config imports the receipt runtime from. */
44
+ declare const RECEIPTS_RUNTIME_MODULE = "@consent-kit/storage";
45
+ /**
46
+ * The receipt settings of a build, or `undefined` when the registry declares no receipt
47
+ * endpoint (it opted out, or it has no consent purpose and no `receipts` section).
48
+ */
49
+ declare function receiptSettings(registry: Registry, options: {
50
+ revision: number;
51
+ }): ReceiptSettings | undefined;
52
+ /**
53
+ * One released policy, as `consent-kit release` appends it to the lock's history: enough to
54
+ * keep accepting the receipts that pages built from it send, after the lock has moved on.
55
+ */
56
+ interface ReleasedPolicy {
57
+ revision: number;
58
+ policyHash: string;
59
+ /** ISO 8601 timestamp of the release. */
60
+ releasedAt: string;
61
+ /** Consent purpose id to its version, sorted by id. */
62
+ consentPurposes: Record<string, number>;
63
+ /** Ids of the purposes with another lawful basis, sorted. */
64
+ otherPurposes: string[];
65
+ /** Whether builds of this release send receipts (the registry declared `receipts.endpoint`). */
66
+ sendsReceipts: boolean;
67
+ }
68
+ /** The history entry for a release of `registry`. */
69
+ declare function releasedPolicy(registry: Registry, release: {
70
+ policyHash: string;
71
+ revision: number;
72
+ releasedAt: string;
73
+ }): ReleasedPolicy;
74
+ /**
75
+ * One policy a receipt endpoint accepts receipts for: what a build's CookieConsent module
76
+ * sends as `policyHash`, `revision` and purposes. The same shape as `ReceiptPolicy` in
77
+ * @consent-kit/server, declared here so that the compiler does not depend on the server.
78
+ */
79
+ interface ReceiptManifestPolicy {
80
+ policyHash: string;
81
+ revision: number;
82
+ /** Consent purpose id to its version, sorted by id: every receipt names each one exactly once. */
83
+ consentPurposes: Record<string, number>;
84
+ /** Ids of the purposes with another lawful basis, sorted: never part of a receipt. */
85
+ otherPurposes: string[];
86
+ /**
87
+ * When a later release replaced this policy (ISO 8601), or `null` while it may still be
88
+ * live: the build's own policy, and the latest release until this build is deployed.
89
+ */
90
+ supersededAt: string | null;
91
+ }
92
+ /** What a receipt endpoint needs to know about the registry: `receipts.manifest.gen.json`. */
93
+ interface ReceiptManifest {
94
+ manifestVersion: 1;
95
+ /** `receipts.endpoint`, exactly as declared. */
96
+ endpoint: string;
97
+ /** The policy of this build first, then every released policy that sent receipts, newest first. */
98
+ policies: ReceiptManifestPolicy[];
99
+ }
100
+ interface ReceiptManifestOptions {
101
+ /** CookieConsent's revision of this build. */
102
+ revision: number;
103
+ /**
104
+ * Every release so far, oldest first (the lock's `history`): pages built from any of them
105
+ * may still be open, or cached, and send their receipts.
106
+ */
107
+ history?: readonly ReleasedPolicy[];
108
+ }
109
+ /**
110
+ * The receipt manifest of a build, or `undefined` when the registry declares no receipt
111
+ * endpoint. A receipt endpoint accepts a receipt only for a policy listed here, with
112
+ * exactly that policy's consent purposes and versions.
113
+ *
114
+ * A policy is its hash at a revision: the same registry released at two revisions is listed
115
+ * twice. A policy released more than once (a change that was later reverted) is listed once,
116
+ * replaced at the time its latest release was.
117
+ */
118
+ declare function receiptManifest(registry: Registry, options: ReceiptManifestOptions): ReceiptManifest | undefined;
119
+ /** The origin receipts are sent to, or `null` for a site-relative endpoint (or none). */
120
+ declare function receiptOrigin(registry: Registry): string | null;
121
+ /**
122
+ * One line on where consent receipts go, for `consent-kit check` and the audit report.
123
+ * `undefined` for a registry without a `receipts` section (it has no consent purpose).
124
+ */
125
+ declare function describeReceipts(registry: Registry): string | undefined;
126
+
127
+ /** Id of the generated read-only category. A consent purpose may not use this id. */
128
+ declare const NECESSARY_CATEGORY = "necessary";
129
+ /** CookieConsent's own consent cookie (its default `cookie.name`) and default lifetime. */
130
+ declare const CONSENT_COOKIE_NAME = "cc_cookie";
131
+ interface CookieConsentOptions {
132
+ /**
133
+ * CookieConsent's single, global revision number. Bump it whenever any
134
+ * consent purpose's version bumps; everyone is then asked again.
135
+ */
136
+ revision: number;
137
+ }
138
+ /** The generated config: a `CookieConsentConfig` whose translations are always inline objects. */
139
+ interface GeneratedCookieConsentConfig extends CookieConsentConfig {
140
+ revision: number;
141
+ language: {
142
+ default: string;
143
+ translations: Record<string, Translation>;
144
+ };
145
+ }
146
+ /**
147
+ * Compile the registry into a CookieConsent v3 config.
148
+ *
149
+ * - One category per consent purpose (off by default), plus one read-only,
150
+ * enabled `necessary` category. Non-consent purposes never get a toggle.
151
+ * - Inside each category, one service per processor with an artefact there, keyed
152
+ * by processor id, each with its own toggle (artefacts of every kind count,
153
+ * not only cookies). `guardManifest` and `consentScriptTag` use the same key.
154
+ * - An artefact bound to several consent purposes appears under EACH of them
155
+ * (service, autoClear, cookie table); `guardManifest` requires all of them,
156
+ * and the artefact's service in all of them.
157
+ * An artefact with at least one consent purpose is never listed as necessary.
158
+ * - `autoClear` and service `cookies` hold cookie artefacts only: CookieConsent
159
+ * cannot erase localStorage/sessionStorage/IndexedDB. Storage artefacts are
160
+ * listed in the cookie tables for information, with their declared `duration`
161
+ * when they have one.
162
+ */
163
+ declare function cookieConsentConfig(registry: Registry, options: CookieConsentOptions): GeneratedCookieConsentConfig;
164
+ interface RenderModuleOptions {
165
+ /** Emit TypeScript (type import + annotation). Set to false for a plain ES module. Default true. */
166
+ typescript?: boolean;
167
+ /**
168
+ * Consent receipts (`receiptSettings`). When given, the module imports
169
+ * `installConsentReceipts` from @consent-kit/storage and calls it on import, so every
170
+ * decision CookieConsent reports is POSTed to the endpoint, whatever callbacks the
171
+ * site passes to `CookieConsent.run`. The settings are exported as `consentReceipts`.
172
+ */
173
+ receipts?: ReceiptSettings;
174
+ }
175
+ /**
176
+ * Source of an ES/TypeScript module exporting the config. Unlike JSON, this keeps
177
+ * RegExp values (autoClear patterns) as RegExp literals. Throws on values that
178
+ * cannot be written as a literal (functions, class instances).
179
+ */
180
+ declare function renderCookieConsentModule(config: CookieConsentConfig, options?: RenderModuleOptions): string;
181
+
182
+ /**
183
+ * Built-in banner and preferences-modal strings. EN and DE only; other registry
184
+ * locales fall back to their base language ("de-AT" → "de") and then to English.
185
+ * These are drafts pending the legal review of the phrase library (spec section 8).
186
+ */
187
+ interface UiStrings {
188
+ consentModal: {
189
+ title: string;
190
+ description: string;
191
+ acceptAllBtn: string;
192
+ acceptNecessaryBtn: string;
193
+ showPreferencesBtn: string;
194
+ };
195
+ preferencesModal: {
196
+ title: string;
197
+ acceptAllBtn: string;
198
+ acceptNecessaryBtn: string;
199
+ savePreferencesBtn: string;
200
+ closeIconLabel: string;
201
+ serviceCounterLabel: string;
202
+ };
203
+ necessary: {
204
+ title: string;
205
+ description: string;
206
+ };
207
+ table: {
208
+ name: string;
209
+ provider: string;
210
+ duration: string;
211
+ purpose: string;
212
+ };
213
+ duration: {
214
+ session: string;
215
+ persistent: string;
216
+ day: string;
217
+ days: string;
218
+ };
219
+ /** Purpose text for CookieConsent's own consent cookie. */
220
+ consentCookiePurpose: string;
221
+ }
222
+ declare const UI_STRINGS: Readonly<Record<'en' | 'de', UiStrings>>;
223
+ declare function uiStringsFor(locale: string): UiStrings;
224
+
225
+ /**
226
+ * What the runtime guard needs: every declared cookie, storage key, IndexedDB
227
+ * database, script/iframe origin and endpoint/pixel origin, with the consent
228
+ * categories that must ALL be accepted before it may be used (empty = always
229
+ * allowed).
230
+ *
231
+ * An entry that requires consent and whose artefact has a processor also carries
232
+ * `service`, the processor id: `cookieConsentConfig` emits a toggle under that
233
+ * key in each of the entry's categories, and the guard requires it in all of them.
234
+ *
235
+ * Entries are sorted by artefact id. Script, iframe, endpoint and pixel entries
236
+ * carry the declared URL as a prefix, origin + path without query and hash (see
237
+ * the matching contract on `GuardManifest`; the longest matching prefix wins):
238
+ * - a script's `src` names one file, so its entry is that file's full path;
239
+ * - an iframe's `src` and an endpoint's or pixel's `url` are prefixes as
240
+ * declared, so two endpoints on one origin keep their own consent
241
+ * requirements, and a path nothing declares is undeclared even on a declared
242
+ * origin. A bare origin stays a bare origin and covers every path on it;
243
+ * - a site-relative path stays site-relative.
244
+ * - stylesheets, fonts and media files are listed with the endpoints, as declared
245
+ * network destinations. The guard does not police them: it has no hook for a
246
+ * `<link>`, a CSS `url()` or a `<video>`, and they are never consent-gated. The
247
+ * entries are there so that the audit, which matches against this manifest,
248
+ * knows a declared load from an undeclared one. Stopping an undeclared one is
249
+ * the Content-Security-Policy's job.
250
+ * (The Content-Security-Policy, by contrast, stays origin-level: see `csp.ts`.)
251
+ * CookieConsent's own `cc_cookie` is added as always-allowed unless the registry
252
+ * declares a cookie with that exact name.
253
+ */
254
+ declare function guardManifest(registry: Registry): GuardManifest;
255
+
256
+ /** The fetch directives the policy spells out, in header order. */
257
+ declare const CSP_FETCH_DIRECTIVES: readonly ["script-src", "style-src", "font-src", "img-src", "connect-src", "frame-src", "media-src", "worker-src", "manifest-src"];
258
+ type CspFetchDirective = (typeof CSP_FETCH_DIRECTIVES)[number];
259
+ type CspDirective = 'default-src' | CspFetchDirective | 'object-src' | 'base-uri' | 'form-action' | 'frame-ancestors' | 'upgrade-insecure-requests' | 'report-uri' | 'report-to';
260
+ interface ContentSecurityPolicyOptions {
261
+ /**
262
+ * Adds `'nonce-<placeholder>'` to `script-src`, for the server or adapter to
263
+ * replace per response (e.g. "{{CSP_NONCE}}"). Letters, digits and `{}_-.` only.
264
+ */
265
+ noncePlaceholder?: string;
266
+ /**
267
+ * Base64 SHA-256 digests of inline scripts to allow in `script-src`, e.g. the
268
+ * inline guard. Each must be the digest of the script element's exact text.
269
+ */
270
+ inlineScriptHashes?: string[];
271
+ /**
272
+ * Base64 SHA-256 digests of inline `<style>` elements to allow in `style-src`.
273
+ * (Hashes do not cover `style="…"` attributes; nothing consent-kit generates uses those.)
274
+ */
275
+ inlineStyleHashes?: string[];
276
+ }
277
+ /** One way in which the policy is weaker than the strict default, and why. */
278
+ interface CspDeviation {
279
+ /** The directive concerned, or "policy" for report-only. */
280
+ directive: string;
281
+ /**
282
+ * `sources-added`: the registry's `csp.allow` added sources. `report-only`: the policy is
283
+ * not enforced. `directive-omitted`: a hardening directive was left out.
284
+ */
285
+ kind: 'sources-added' | 'report-only' | 'directive-omitted';
286
+ /** For `sources-added`. */
287
+ sources?: string[];
288
+ reason: string;
289
+ /** `registry`: written in the `csp` section. `automatic`: decided by the compiler from other declarations. */
290
+ origin: 'registry' | 'automatic';
291
+ }
292
+ interface ContentSecurityPolicy {
293
+ /** `strict`: exactly the default. `loosened`: see `deviations`. */
294
+ level: 'strict' | 'loosened';
295
+ /** Every deviation from the strict policy. Empty for `strict`. */
296
+ deviations: CspDeviation[];
297
+ /** Directive to its values, in header order. A directive without values (`upgrade-insecure-requests`) has `[]`. */
298
+ directives: Partial<Record<CspDirective, string[]>>;
299
+ /** `Content-Security-Policy`, or `Content-Security-Policy-Report-Only` when the registry asks for report-only. */
300
+ headerName: 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only';
301
+ /** The header value. */
302
+ header: string;
303
+ /**
304
+ * The value for `<meta http-equiv="Content-Security-Policy">`, for hosts that cannot set
305
+ * headers: the same policy without `frame-ancestors`, `report-uri` and `report-to`, which
306
+ * browsers ignore in a meta element. Prefer the header: only it protects against framing.
307
+ * `null` for a report-only policy, which cannot be delivered by meta at all.
308
+ */
309
+ meta: string | null;
310
+ /** Value of the `Reporting-Endpoints` header that defines the `report-to` group, when both `reportUri` and `reportTo` are set. */
311
+ reportingEndpoints?: string;
312
+ }
313
+ /**
314
+ * The strictest Content-Security-Policy the registry allows, loosened only where the
315
+ * registry's `csp` section says so.
316
+ *
317
+ * Strict means:
318
+ * - `default-src 'none'`: whatever no directive below admits is refused.
319
+ * - Every fetch directive is spelled out as `'self'` plus the sorted origins of the
320
+ * artefacts declared for it: `script-src` (scripts), `style-src` (stylesheets),
321
+ * `font-src` (fonts), `img-src` (pixels), `connect-src` (endpoints and the consent-receipt
322
+ * endpoint), `frame-src`
323
+ * (iframes), `media-src` (media), and `worker-src` and `manifest-src`, which no
324
+ * artefact kind feeds. `'self'` is the deliberate baseline for all of them, including
325
+ * those with nothing declared: first-party files are never declared in the registry,
326
+ * so the compiler cannot know which kinds a site serves itself, and `'self'` admits
327
+ * nothing that the site's own origin does not already control through `script-src`.
328
+ * - No `'unsafe-inline'`, no `'unsafe-eval'`, no wildcard, no `data:` or `blob:`. Inline
329
+ * scripts run only by nonce or hash (`options`); inline styles only by hash.
330
+ * - `object-src 'none'`, `base-uri 'self'`, `form-action 'self'` (the registry does not
331
+ * record where a form posts to, so a third-party form target is a `csp.allow` entry),
332
+ * `frame-ancestors 'none'`, and `upgrade-insecure-requests`.
333
+ * - `upgrade-insecure-requests` is left out, and reported as an automatic deviation,
334
+ * when the registry declares an `http:` URL (it would turn that declared load into a
335
+ * failing https request), or when `csp.upgradeInsecureRequests` is `false`.
336
+ *
337
+ * The policy is the outer boundary (declared vs. undeclared), regardless of consent;
338
+ * per-consent switching is the gates' job. It is origin-level on purpose, unlike the
339
+ * guard manifest, which keeps the declared paths: CSP path matching is unreliable as a
340
+ * boundary (it is ignored after a redirect, and a path source without a trailing slash
341
+ * matches one exact file), and vendors move files within their origin. So a path nothing
342
+ * declares on a declared origin passes the CSP; the guard and the audit report it.
343
+ *
344
+ * Throws on anything that could inject into the header. A validated registry never does.
345
+ */
346
+ declare function contentSecurityPolicy(registry: Registry, options?: ContentSecurityPolicyOptions): ContentSecurityPolicy;
347
+ /** One line per deviation from the strict policy, for `consent-kit check` and the audit report. Empty when strict. */
348
+ declare function describeCspDeviations(deviations: readonly CspDeviation[]): string[];
349
+
350
+ /**
351
+ * Source of `registry.gen.ts`: for each id space a string-literal union type
352
+ * (`PurposeId`) and a const object mapping each id to itself (`purposeIds`), so
353
+ * `gate('plausbile')` is a type error and ids can be enumerated at runtime.
354
+ * Ids are sorted; an empty id space yields `never` and `{}`.
355
+ *
356
+ * Emitted: PurposeId, ConsentPurposeId, ProcessorId, ArtefactId,
357
+ * {Script,Cookie,Storage,Iframe,Pixel,Endpoint,Stylesheet,Font,Media}Id, CollectionPointId.
358
+ */
359
+ declare function renderRegistryModule(registry: Registry): string;
360
+
361
+ /**
362
+ * The HTML for a declared script artefact, per CookieConsent's scripts management.
363
+ *
364
+ * - Bound to one consent purpose: an inert tag CookieConsent activates on consent,
365
+ * `<script type="text/plain" data-category data-service data-src>`.
366
+ * `data-service` is the processor id (the service key in the generated config
367
+ * and `GuardEntry.service` in the guard manifest) and is omitted when the
368
+ * artefact has no processor. CookieConsent then activates the tag only while
369
+ * that service is enabled in that category.
370
+ * - No consent purposes: a normal executable `<script src>`.
371
+ * - Several consent purposes: throws. CookieConsent's `data-category` holds a
372
+ * single category, so it cannot express "all of these"; emitting one of them
373
+ * would run the script without the others' consent.
374
+ *
375
+ * Throws when the id is unknown or not a script artefact.
376
+ */
377
+ declare function consentScriptTag(registry: Registry, artefactId: string): string;
378
+
379
+ interface ConsentEmbedOptions {
380
+ /** Accessible name of the iframe (`title`). Carried as `data-title` until the embed is activated. */
381
+ title?: string;
382
+ /**
383
+ * The concrete URL to embed, when the artefact's `src` is an origin or a URL
384
+ * prefix (e.g. a player URL with a video id). Must be under the declared `src`.
385
+ * Default: the declared `src` itself.
386
+ */
387
+ src?: string;
388
+ /**
389
+ * HTML shown inside the placeholder until the embed is activated (a notice, an
390
+ * "allow" button). Inserted as given: it is the caller's markup, not escaped.
391
+ */
392
+ placeholder?: string;
393
+ }
394
+ /**
395
+ * The HTML for a declared iframe artefact: the iframe counterpart of `consentScriptTag`.
396
+ *
397
+ * - Bound to one consent purpose: an inert placeholder,
398
+ * `<div data-ck-embed data-category data-service data-src [data-title]>`.
399
+ * Nothing loads until `syncEmbeds` from `@consent-kit/storage` swaps in the
400
+ * iframe, once the category (and the service, the processor id) is accepted.
401
+ * CookieConsent v3 itself has no convention for embeds (it only manages
402
+ * `script[data-category]`), so `data-ck-embed` is consent-kit's own marker;
403
+ * `data-category`, `data-service` and `data-src` mean what they mean on a
404
+ * CookieConsent-managed script tag.
405
+ * - No consent purposes: a normal `<iframe src>`.
406
+ * - Several consent purposes: throws, like `consentScriptTag`.
407
+ *
408
+ * Throws when the id is unknown or not an iframe artefact, and when `options.src`
409
+ * is not under the artefact's declared `src`.
410
+ */
411
+ declare function consentEmbed(registry: Registry, artefactId: string, options?: ConsentEmbedOptions): string;
412
+
413
+ interface CompileOptions extends CookieConsentOptions, ContentSecurityPolicyOptions {
414
+ }
415
+ declare const OUTPUT_FILES: {
416
+ readonly registryModule: "registry.gen.ts";
417
+ readonly policy: "policy.json";
418
+ readonly cookieConsentModule: "cookieconsent.config.gen.ts";
419
+ readonly guardManifest: "guard-manifest.json";
420
+ readonly csp: "csp.json";
421
+ };
422
+ type OutputFileName = (typeof OUTPUT_FILES)[keyof typeof OUTPUT_FILES];
423
+ /** Every build output as filename → contents. Performs no I/O; writing the files is the caller's job. */
424
+ declare function compile(registry: Registry, options: CompileOptions): Record<OutputFileName, string>;
425
+
426
+ export { CONSENT_COOKIE_NAME, CSP_FETCH_DIRECTIVES, NECESSARY_CATEGORY, OUTPUT_FILES, RECEIPTS_RUNTIME_MODULE, UI_STRINGS, canonicalJson, compile, consentEmbed, consentScriptTag, contentSecurityPolicy, cookieConsentConfig, describeCspDeviations, describeReceipts, guardManifest, policySnapshot, receiptManifest, receiptOrigin, receiptSettings, releasedPolicy, renderCookieConsentModule, renderRegistryModule, uiStringsFor };
427
+ export type { CompileOptions, ConsentEmbedOptions, ContentSecurityPolicy, ContentSecurityPolicyOptions, CookieConsentOptions, CspDeviation, CspDirective, CspFetchDirective, GeneratedCookieConsentConfig, OutputFileName, PolicySnapshot, ReceiptManifest, ReceiptManifestOptions, ReceiptManifestPolicy, ReceiptSettings, ReleasedPolicy, RenderModuleOptions, UiStrings };
package/dist/index.js ADDED
@@ -0,0 +1,714 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { locateUrl, pathCovers } from '@consent-kit/schema';
3
+
4
+ // src/policy.ts
5
+ function compareStrings(a, b) {
6
+ return a < b ? -1 : a > b ? 1 : 0;
7
+ }
8
+ function sortedUnique(values) {
9
+ return [...new Set(values)].sort(compareStrings);
10
+ }
11
+ function sortById(items) {
12
+ return [...items].sort((a, b) => compareStrings(a.id, b.id));
13
+ }
14
+ function consentPurposeIds(registry) {
15
+ return new Set(registry.purposes.filter((p) => p.basis === "consent").map((p) => p.id));
16
+ }
17
+ function consentCategoriesOf(artefact, consentIds) {
18
+ return sortedUnique(artefact.purposes.filter((id) => consentIds.has(id)));
19
+ }
20
+ function consentServiceOf(artefact, categories) {
21
+ return categories.length > 0 ? artefact.processor : void 0;
22
+ }
23
+ function originOf(url) {
24
+ const location = locateUrl(url);
25
+ if (location.where === "invalid") throw new Error(`consent-kit: "${url}" is not a valid URL: ${location.problem}`);
26
+ if (location.where === "site") return null;
27
+ if (location.url.origin === "null") {
28
+ throw new Error(`consent-kit: "${url}" has no network origin; only http(s) and ws(s) URLs can be declared`);
29
+ }
30
+ return location.url.origin;
31
+ }
32
+ function urlPrefixOf(url) {
33
+ const origin = originOf(url);
34
+ if (origin === null) return url.replace(/[?#].*$/s, "");
35
+ const location = locateUrl(url);
36
+ const pathname = location.where === "remote" ? location.url.pathname : "/";
37
+ return pathname === "/" ? origin : origin + pathname;
38
+ }
39
+ function localize(text, locale, defaultLocale) {
40
+ if (!text) return void 0;
41
+ return text[locale] ?? text[defaultLocale] ?? Object.values(text)[0];
42
+ }
43
+ function escapeHtml(value) {
44
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
45
+ }
46
+
47
+ // src/policy.ts
48
+ function canonicalJson(value) {
49
+ return JSON.stringify(sortKeys(value));
50
+ }
51
+ function sortKeys(value) {
52
+ if (Array.isArray(value)) return value.map(sortKeys);
53
+ if (value !== null && typeof value === "object") {
54
+ const source = value;
55
+ const out = {};
56
+ for (const key of Object.keys(source).sort(compareStrings)) {
57
+ if (source[key] !== void 0) out[key] = sortKeys(source[key]);
58
+ }
59
+ return out;
60
+ }
61
+ return value;
62
+ }
63
+ function policySnapshot(registry) {
64
+ const normalised = {
65
+ ...registry,
66
+ locales: sortedUnique(registry.locales),
67
+ purposes: sortById(registry.purposes).map((p) => ({
68
+ ...p,
69
+ dataCategories: sortedUnique(p.dataCategories),
70
+ ...p.dataSubjects === void 0 ? {} : { dataSubjects: sortedUnique(p.dataSubjects) },
71
+ ...p.processors === void 0 ? {} : { processors: sortedUnique(p.processors) }
72
+ })),
73
+ processors: sortById(registry.processors),
74
+ artefacts: sortById(registry.artefacts).map((a) => ({ ...a, purposes: sortedUnique(a.purposes) })),
75
+ collectionPoints: sortById(registry.collectionPoints).map((c) => ({
76
+ ...c,
77
+ fields: [...c.fields].sort((a, b) => compareStrings(a.name, b.name))
78
+ }))
79
+ };
80
+ const json = canonicalJson(normalised);
81
+ return {
82
+ policy: JSON.parse(json),
83
+ hash: createHash("sha256").update(json, "utf8").digest("hex")
84
+ };
85
+ }
86
+
87
+ // src/receipts.ts
88
+ var RECEIPTS_RUNTIME_MODULE = "@consent-kit/storage";
89
+ function receiptSettings(registry, options) {
90
+ const receipts = registry.receipts;
91
+ if (receipts === void 0 || !("endpoint" in receipts)) return void 0;
92
+ const consentIds = consentPurposeIds(registry);
93
+ const purposes = {};
94
+ for (const purpose of sortById(registry.purposes)) {
95
+ if (consentIds.has(purpose.id)) purposes[purpose.id] = purpose.version;
96
+ }
97
+ return { endpoint: receipts.endpoint, policyHash: policySnapshot(registry).hash, revision: options.revision, purposes };
98
+ }
99
+ function releasedPolicy(registry, release) {
100
+ return {
101
+ revision: release.revision,
102
+ policyHash: release.policyHash,
103
+ releasedAt: release.releasedAt,
104
+ ...manifestPolicy(registry),
105
+ sendsReceipts: receiptSettings(registry, release) !== void 0
106
+ };
107
+ }
108
+ function receiptManifest(registry, options) {
109
+ const settings = receiptSettings(registry, options);
110
+ if (settings === void 0) return void 0;
111
+ const policies = /* @__PURE__ */ new Map();
112
+ const add = (policy) => {
113
+ const key = `${policy.policyHash}:${policy.revision}`;
114
+ const known = policies.get(key);
115
+ if (known === void 0) policies.set(key, policy);
116
+ else known.supersededAt = later(known.supersededAt, policy.supersededAt);
117
+ };
118
+ add({ policyHash: settings.policyHash, revision: settings.revision, ...manifestPolicy(registry), supersededAt: null });
119
+ const history = options.history ?? [];
120
+ for (let index = history.length - 1; index >= 0; index--) {
121
+ const release = history[index];
122
+ if (!release.sendsReceipts) continue;
123
+ add({
124
+ policyHash: release.policyHash,
125
+ revision: release.revision,
126
+ consentPurposes: { ...release.consentPurposes },
127
+ otherPurposes: [...release.otherPurposes],
128
+ supersededAt: history[index + 1]?.releasedAt ?? null
129
+ });
130
+ }
131
+ return { manifestVersion: 1, endpoint: settings.endpoint, policies: [...policies.values()] };
132
+ }
133
+ function later(a, b) {
134
+ return a === null || b === null ? null : a > b ? a : b;
135
+ }
136
+ function manifestPolicy(registry) {
137
+ const consentIds = consentPurposeIds(registry);
138
+ const consentPurposes = {};
139
+ const otherPurposes = [];
140
+ for (const purpose of sortById(registry.purposes)) {
141
+ if (consentIds.has(purpose.id)) consentPurposes[purpose.id] = purpose.version;
142
+ else otherPurposes.push(purpose.id);
143
+ }
144
+ return { consentPurposes, otherPurposes };
145
+ }
146
+ function receiptOrigin(registry) {
147
+ const receipts = registry.receipts;
148
+ return receipts !== void 0 && "endpoint" in receipts ? originOf(receipts.endpoint) : null;
149
+ }
150
+ function describeReceipts(registry) {
151
+ const receipts = registry.receipts;
152
+ if (receipts === void 0) return void 0;
153
+ if ("endpoint" in receipts) return `Consent receipts: one per decision, POSTed to ${receipts.endpoint}.`;
154
+ return `Consent receipts: NOT KEPT. The registry opts out, so no decision of a visitor is recorded beyond the consent cookie in their browser. Reason given: ${receipts.optOut.reason}`;
155
+ }
156
+
157
+ // src/strings.ts
158
+ var en = {
159
+ consentModal: {
160
+ title: "Your privacy choices",
161
+ description: "We only use optional cookies and similar technologies if you agree. You can change your choice at any time.",
162
+ acceptAllBtn: "Accept all",
163
+ acceptNecessaryBtn: "Reject all",
164
+ showPreferencesBtn: "Manage preferences"
165
+ },
166
+ preferencesModal: {
167
+ title: "Privacy preferences",
168
+ acceptAllBtn: "Accept all",
169
+ acceptNecessaryBtn: "Reject all",
170
+ savePreferencesBtn: "Save my choices",
171
+ closeIconLabel: "Close",
172
+ serviceCounterLabel: "Service|Services"
173
+ },
174
+ necessary: {
175
+ title: "Strictly necessary",
176
+ description: "Needed for the site to work. These are always on and do not require consent."
177
+ },
178
+ table: { name: "Name", provider: "Provider", duration: "Duration", purpose: "Purpose" },
179
+ duration: { session: "Session", persistent: "Until deleted", day: "day", days: "days" },
180
+ consentCookiePurpose: "Stores your privacy choices."
181
+ };
182
+ var de = {
183
+ consentModal: {
184
+ title: "Ihre Datenschutz-Einstellungen",
185
+ description: "Optionale Cookies und \xE4hnliche Technologien verwenden wir nur mit Ihrer Einwilligung. Sie k\xF6nnen Ihre Auswahl jederzeit \xE4ndern.",
186
+ acceptAllBtn: "Alle akzeptieren",
187
+ acceptNecessaryBtn: "Alle ablehnen",
188
+ showPreferencesBtn: "Einstellungen verwalten"
189
+ },
190
+ preferencesModal: {
191
+ title: "Datenschutz-Einstellungen",
192
+ acceptAllBtn: "Alle akzeptieren",
193
+ acceptNecessaryBtn: "Alle ablehnen",
194
+ savePreferencesBtn: "Auswahl speichern",
195
+ closeIconLabel: "Schlie\xDFen",
196
+ serviceCounterLabel: "Dienst|Dienste"
197
+ },
198
+ necessary: {
199
+ title: "Unbedingt erforderlich",
200
+ description: "F\xFCr den Betrieb der Website notwendig. Diese sind immer aktiv und erfordern keine Einwilligung."
201
+ },
202
+ table: { name: "Name", provider: "Anbieter", duration: "Dauer", purpose: "Zweck" },
203
+ duration: { session: "Sitzung", persistent: "Bis zur L\xF6schung", day: "Tag", days: "Tage" },
204
+ consentCookiePurpose: "Speichert Ihre Datenschutz-Einstellungen."
205
+ };
206
+ var UI_STRINGS = { en, de };
207
+ function uiStringsFor(locale) {
208
+ const base = locale.toLowerCase().split(/[-_]/)[0];
209
+ return base === "de" ? de : en;
210
+ }
211
+
212
+ // src/cookieconsent.ts
213
+ var NECESSARY_CATEGORY = "necessary";
214
+ var CONSENT_COOKIE_NAME = "cc_cookie";
215
+ var CONSENT_COOKIE_DAYS = 182;
216
+ function cookieConsentConfig(registry, options) {
217
+ const { revision } = options;
218
+ if (!Number.isInteger(revision) || revision < 0) {
219
+ throw new Error(`consent-kit: revision must be a non-negative integer, got ${String(revision)}`);
220
+ }
221
+ const consentIds = consentPurposeIds(registry);
222
+ if (consentIds.has(NECESSARY_CATEGORY)) {
223
+ throw new Error(
224
+ `consent-kit: a consent purpose cannot use the id "${NECESSARY_CATEGORY}"; it is reserved for the read-only category`
225
+ );
226
+ }
227
+ const consentPurposes = registry.purposes.filter((p) => consentIds.has(p.id));
228
+ const processors = new Map(registry.processors.map((p) => [p.id, p]));
229
+ const artefactsByCategory = new Map(consentPurposes.map((p) => [p.id, []]));
230
+ const necessaryArtefacts = [];
231
+ for (const artefact of registry.artefacts) {
232
+ const categories2 = consentCategoriesOf(artefact, consentIds);
233
+ if (categories2.length === 0) necessaryArtefacts.push(artefact);
234
+ for (const category2 of categories2) artefactsByCategory.get(category2)?.push(artefact);
235
+ }
236
+ const categories = {
237
+ [NECESSARY_CATEGORY]: { enabled: true, readOnly: true }
238
+ };
239
+ for (const purpose of consentPurposes) {
240
+ categories[purpose.id] = category(purpose.id, artefactsByCategory.get(purpose.id) ?? [], processors);
241
+ }
242
+ const translations = {};
243
+ for (const locale of registry.locales) {
244
+ translations[locale] = translation(registry, locale, consentPurposes, artefactsByCategory, necessaryArtefacts, processors);
245
+ }
246
+ return {
247
+ mode: "opt-in",
248
+ revision,
249
+ respectGpc: true,
250
+ autoClearCookies: true,
251
+ manageScriptTags: true,
252
+ guiOptions: {
253
+ consentModal: { layout: "box", equalWeightButtons: true, flipButtons: false },
254
+ preferencesModal: { layout: "box", equalWeightButtons: true, flipButtons: false }
255
+ },
256
+ categories,
257
+ language: { default: registry.defaultLocale, translations }
258
+ };
259
+ }
260
+ function cookieItem(cookie) {
261
+ const item = {
262
+ name: cookie.pattern !== void 0 ? new RegExp(cookie.pattern) : cookie.name ?? ""
263
+ };
264
+ if (cookie.domain !== void 0) item.domain = cookie.domain;
265
+ return item;
266
+ }
267
+ function isCookie(artefact) {
268
+ return artefact.kind === "cookie";
269
+ }
270
+ function category(categoryId, artefacts, processors) {
271
+ const out = { enabled: false, readOnly: false };
272
+ const serviceOf = (a) => consentServiceOf(a, [categoryId]);
273
+ const processorIds = [...new Set(artefacts.flatMap((a) => serviceOf(a) ?? []))].sort(compareStrings);
274
+ if (processorIds.length > 0) {
275
+ const services = {};
276
+ for (const id of processorIds) {
277
+ const service = { label: escapeHtml(processors.get(id)?.name ?? id) };
278
+ const cookies2 = artefacts.filter((a) => serviceOf(a) === id).filter(isCookie).map(cookieItem);
279
+ if (cookies2.length > 0) service.cookies = cookies2;
280
+ services[id] = service;
281
+ }
282
+ out.services = services;
283
+ }
284
+ const cookies = artefacts.filter(isCookie).map(cookieItem);
285
+ if (cookies.length > 0) out.autoClear = { cookies };
286
+ return out;
287
+ }
288
+ function translation(registry, locale, consentPurposes, artefactsByCategory, necessaryArtefacts, processors) {
289
+ const strings = uiStringsFor(locale);
290
+ const purposes = new Map(registry.purposes.map((p) => [p.id, p]));
291
+ const text = (purpose, field) => localize(purpose[field], locale, registry.defaultLocale) ?? purpose.id;
292
+ const row = (artefact) => ({
293
+ name: escapeHtml(displayName(artefact)),
294
+ provider: escapeHtml(
295
+ (artefact.processor !== void 0 ? processors.get(artefact.processor)?.name : void 0) ?? registry.controller.name
296
+ ),
297
+ duration: escapeHtml(displayDuration(artefact, strings)),
298
+ purpose: localize(artefact.description, locale, registry.defaultLocale) ?? artefact.purposes.map((id) => {
299
+ const p = purposes.get(id);
300
+ return p ? text(p, "title") : id;
301
+ }).join(", ")
302
+ });
303
+ const table = (rows) => rows.length > 0 ? { headers: { ...strings.table }, body: rows } : void 0;
304
+ const tableArtefacts = (artefacts) => artefacts.filter((a) => a.kind === "cookie" || a.kind === "storage");
305
+ const necessaryRows = tableArtefacts(necessaryArtefacts).map(row);
306
+ const declaresConsentCookie = registry.artefacts.some((a) => a.kind === "cookie" && a.name === CONSENT_COOKIE_NAME);
307
+ if (!declaresConsentCookie) {
308
+ necessaryRows.push({
309
+ name: CONSENT_COOKIE_NAME,
310
+ provider: escapeHtml(registry.controller.name),
311
+ duration: `${CONSENT_COOKIE_DAYS} ${strings.duration.days}`,
312
+ purpose: strings.consentCookiePurpose
313
+ });
314
+ }
315
+ const sections = [
316
+ section(strings.necessary.title, strings.necessary.description, NECESSARY_CATEGORY, table(necessaryRows)),
317
+ ...consentPurposes.map(
318
+ (purpose) => section(
319
+ text(purpose, "title"),
320
+ text(purpose, "description"),
321
+ purpose.id,
322
+ table(tableArtefacts(artefactsByCategory.get(purpose.id) ?? []).map(row))
323
+ )
324
+ )
325
+ ];
326
+ return {
327
+ consentModal: { ...strings.consentModal },
328
+ preferencesModal: { ...strings.preferencesModal, sections }
329
+ };
330
+ }
331
+ function section(title, description, linkedCategory, cookieTable) {
332
+ const out = { title, description, linkedCategory };
333
+ if (cookieTable) out.cookieTable = cookieTable;
334
+ return out;
335
+ }
336
+ var STORAGE_AREA_LABEL = { local: "localStorage", session: "sessionStorage", indexeddb: "IndexedDB" };
337
+ function displayName(artefact) {
338
+ if (artefact.kind === "cookie") return artefact.name ?? artefact.pattern ?? artefact.id;
339
+ return `${artefact.key ?? artefact.pattern ?? artefact.id} (${STORAGE_AREA_LABEL[artefact.area]})`;
340
+ }
341
+ function displayDuration(artefact, strings) {
342
+ if (artefact.kind === "storage" && (artefact.duration === void 0 || artefact.duration === "persistent")) {
343
+ return artefact.duration === void 0 && artefact.area === "session" ? strings.duration.session : strings.duration.persistent;
344
+ }
345
+ if (artefact.duration === "session") return strings.duration.session;
346
+ const days = /^(\d+)d$/.exec(artefact.duration ?? "");
347
+ if (days) return `${days[1]} ${days[1] === "1" ? strings.duration.day : strings.duration.days}`;
348
+ return artefact.duration ?? "";
349
+ }
350
+ function renderCookieConsentModule(config, options = {}) {
351
+ const typescript = options.typescript ?? true;
352
+ const { receipts } = options;
353
+ const lines = ["// Generated by consent-kit from privacy.registry.yaml. Do not edit."];
354
+ if (typescript) lines.push("import type { CookieConsentConfig } from 'vanilla-cookieconsent';");
355
+ if (receipts !== void 0) {
356
+ lines.push(
357
+ `import { installConsentReceipts } from '${RECEIPTS_RUNTIME_MODULE}';`,
358
+ "",
359
+ "/**",
360
+ ' * Consent receipts (registry "receipts"): one JSON POST to `endpoint` per decision, on',
361
+ " * CookieConsent's first-consent and change events. Installed when this module is imported.",
362
+ " */",
363
+ `export const consentReceipts = ${literal(receipts, "", "receipts")};`,
364
+ "",
365
+ "installConsentReceipts(consentReceipts);"
366
+ );
367
+ }
368
+ lines.push(
369
+ "",
370
+ `export const cookieConsentConfig${typescript ? ": CookieConsentConfig" : ""} = ${literal(config, "", "config")};`,
371
+ "",
372
+ "export default cookieConsentConfig;",
373
+ ""
374
+ );
375
+ return lines.join("\n");
376
+ }
377
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
378
+ function stringLiteral(value) {
379
+ return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
380
+ }
381
+ function literal(value, indent, path) {
382
+ if (value === null) return "null";
383
+ switch (typeof value) {
384
+ case "string":
385
+ return stringLiteral(value);
386
+ case "boolean":
387
+ return String(value);
388
+ case "number":
389
+ if (!Number.isFinite(value)) break;
390
+ return String(value);
391
+ case "object": {
392
+ const inner = `${indent} `;
393
+ if (value instanceof RegExp) return String(value);
394
+ if (Array.isArray(value)) {
395
+ if (value.length === 0) return "[]";
396
+ return `[
397
+ ${value.map((v, i) => `${inner}${literal(v, inner, `${path}[${i}]`)},
398
+ `).join("")}${indent}]`;
399
+ }
400
+ const proto = Object.getPrototypeOf(value);
401
+ if (proto !== Object.prototype && proto !== null) break;
402
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
403
+ if (entries.length === 0) return "{}";
404
+ return `{
405
+ ${entries.map(([k, v]) => `${inner}${IDENTIFIER.test(k) ? k : stringLiteral(k)}: ${literal(v, inner, `${path}.${k}`)},
406
+ `).join("")}${indent}}`;
407
+ }
408
+ }
409
+ throw new Error(`consent-kit: cannot render ${path} (${typeof value}) as a module literal`);
410
+ }
411
+
412
+ // src/guard.ts
413
+ function guardManifest(registry) {
414
+ const consentIds = consentPurposeIds(registry);
415
+ const manifest = {
416
+ cookies: [],
417
+ localStorage: [],
418
+ sessionStorage: [],
419
+ indexedDB: [],
420
+ scripts: [],
421
+ iframes: [],
422
+ endpoints: []
423
+ };
424
+ const storageList = { local: manifest.localStorage, session: manifest.sessionStorage, indexeddb: manifest.indexedDB };
425
+ for (const artefact of sortById(registry.artefacts)) {
426
+ const categories = consentCategoriesOf(artefact, consentIds);
427
+ const service = consentServiceOf(artefact, categories);
428
+ const matcher = (name, pattern) => {
429
+ const entry = pattern !== void 0 && name === void 0 ? { id: artefact.id, pattern, categories } : { id: artefact.id, name: name ?? "", categories };
430
+ if (service !== void 0) entry.service = service;
431
+ return entry;
432
+ };
433
+ switch (artefact.kind) {
434
+ case "cookie":
435
+ manifest.cookies.push(matcher(artefact.name, artefact.pattern));
436
+ break;
437
+ case "storage":
438
+ storageList[artefact.area].push(matcher(artefact.key, artefact.pattern));
439
+ break;
440
+ case "script":
441
+ manifest.scripts.push(matcher(urlPrefixOf(artefact.src), void 0));
442
+ break;
443
+ case "iframe":
444
+ manifest.iframes.push(matcher(urlPrefixOf(artefact.src), void 0));
445
+ break;
446
+ case "pixel":
447
+ case "endpoint":
448
+ manifest.endpoints.push(matcher(urlPrefixOf(artefact.url), void 0));
449
+ break;
450
+ case "stylesheet":
451
+ case "font":
452
+ case "media":
453
+ manifest.endpoints.push(matcher(urlPrefixOf(artefact.src), void 0));
454
+ break;
455
+ }
456
+ }
457
+ if (!manifest.cookies.some((entry) => entry.name === CONSENT_COOKIE_NAME)) {
458
+ manifest.cookies.push({ id: CONSENT_COOKIE_NAME, name: CONSENT_COOKIE_NAME, categories: [] });
459
+ manifest.cookies.sort((a, b) => compareStrings(a.id, b.id));
460
+ }
461
+ return manifest;
462
+ }
463
+
464
+ // src/csp.ts
465
+ var CSP_FETCH_DIRECTIVES = [
466
+ "script-src",
467
+ "style-src",
468
+ "font-src",
469
+ "img-src",
470
+ "connect-src",
471
+ "frame-src",
472
+ "media-src",
473
+ "worker-src",
474
+ "manifest-src"
475
+ ];
476
+ var DIRECTIVE_BY_KIND = {
477
+ script: "script-src",
478
+ stylesheet: "style-src",
479
+ font: "font-src",
480
+ pixel: "img-src",
481
+ endpoint: "connect-src",
482
+ iframe: "frame-src",
483
+ media: "media-src"
484
+ };
485
+ function targetOf(artefact) {
486
+ switch (artefact.kind) {
487
+ case "cookie":
488
+ case "storage":
489
+ return void 0;
490
+ case "pixel":
491
+ case "endpoint":
492
+ return artefact.url;
493
+ default:
494
+ return artefact.src;
495
+ }
496
+ }
497
+ function contentSecurityPolicy(registry, options = {}) {
498
+ const config = registry.csp ?? {};
499
+ const origins = new Map(CSP_FETCH_DIRECTIVES.map((directive) => [directive, /* @__PURE__ */ new Set()]));
500
+ const insecure = [];
501
+ for (const artefact of registry.artefacts) {
502
+ const directive = DIRECTIVE_BY_KIND[artefact.kind];
503
+ const target = targetOf(artefact);
504
+ if (directive === void 0 || target === void 0) continue;
505
+ const origin = originOf(target);
506
+ if (origin === null) continue;
507
+ origins.get(directive)?.add(origin);
508
+ if (origin.startsWith("http:")) insecure.push(origin);
509
+ }
510
+ const receiptsTo = receiptOrigin(registry);
511
+ if (receiptsTo !== null) origins.get("connect-src")?.add(receiptsTo);
512
+ const { noncePlaceholder } = options;
513
+ if (noncePlaceholder !== void 0 && !/^[A-Za-z0-9{}_.-]+$/.test(noncePlaceholder)) {
514
+ throw new Error(`consent-kit: invalid CSP nonce placeholder "${noncePlaceholder}"`);
515
+ }
516
+ const hashSources = (hashes, what) => {
517
+ for (const hash of hashes ?? []) {
518
+ if (!/^[A-Za-z0-9+/]{43}=$/.test(hash)) throw new Error(`consent-kit: invalid SHA-256 ${what} hash "${hash}"`);
519
+ }
520
+ return [...hashes ?? []].sort(compareStrings).map((hash) => `'sha256-${hash}'`);
521
+ };
522
+ const scriptHashes = hashSources(options.inlineScriptHashes, "script");
523
+ const styleHashes = hashSources(options.inlineStyleHashes, "style");
524
+ const directives = { "default-src": ["'none'"] };
525
+ for (const directive of CSP_FETCH_DIRECTIVES) {
526
+ const sources = ["'self'"];
527
+ if (directive === "script-src" && noncePlaceholder !== void 0) sources.push(`'nonce-${noncePlaceholder}'`);
528
+ if (directive === "script-src") sources.push(...scriptHashes);
529
+ if (directive === "style-src") sources.push(...styleHashes);
530
+ sources.push(...[...origins.get(directive) ?? []].sort(compareStrings));
531
+ directives[directive] = sources;
532
+ }
533
+ directives["object-src"] = ["'none'"];
534
+ directives["base-uri"] = ["'self'"];
535
+ directives["form-action"] = ["'self'"];
536
+ directives["frame-ancestors"] = ["'none'"];
537
+ const deviations = [];
538
+ for (const entry of config.allow ?? []) {
539
+ const current = directives[entry.directive];
540
+ if (current === void 0 || entry.directive === "upgrade-insecure-requests" || entry.directive === "report-uri" || entry.directive === "report-to") {
541
+ throw new Error(`consent-kit: csp.allow names "${entry.directive}", which is not a directive that can be loosened`);
542
+ }
543
+ for (const source of entry.sources) {
544
+ if (/[\s;,]/.test(source) || source === "") throw new Error(`consent-kit: csp.allow source ${JSON.stringify(source)} is not a CSP source expression`);
545
+ }
546
+ const kept = current.filter((source) => source !== "'none'");
547
+ const added = entry.sources.filter((source) => !kept.includes(source));
548
+ directives[entry.directive] = [...kept, ...added];
549
+ deviations.push({ directive: entry.directive, kind: "sources-added", sources: [...entry.sources], reason: entry.reason, origin: "registry" });
550
+ }
551
+ if (config.upgradeInsecureRequests === false) {
552
+ deviations.push({
553
+ directive: "upgrade-insecure-requests",
554
+ kind: "directive-omitted",
555
+ reason: "csp.upgradeInsecureRequests is false in the registry.",
556
+ origin: "registry"
557
+ });
558
+ } else if (insecure.length > 0) {
559
+ deviations.push({
560
+ directive: "upgrade-insecure-requests",
561
+ kind: "directive-omitted",
562
+ reason: `The registry declares http: URLs (${[...new Set(insecure)].sort(compareStrings).join(", ")}); upgrading them to https would break those declared loads. Declare https: URLs to get the directive back.`,
563
+ origin: "automatic"
564
+ });
565
+ } else {
566
+ directives["upgrade-insecure-requests"] = [];
567
+ }
568
+ const { reportUri, reportTo } = config;
569
+ if (reportUri !== void 0) {
570
+ if (/[\s;,"]/.test(reportUri)) throw new Error(`consent-kit: csp.reportUri ${JSON.stringify(reportUri)} cannot be written into a header`);
571
+ directives["report-uri"] = [reportUri];
572
+ }
573
+ if (reportTo !== void 0) {
574
+ if (!/^[A-Za-z0-9_-]+$/.test(reportTo)) throw new Error(`consent-kit: csp.reportTo ${JSON.stringify(reportTo)} is not a group name`);
575
+ directives["report-to"] = [reportTo];
576
+ }
577
+ if (config.reportOnly === true) {
578
+ deviations.push({
579
+ directive: "policy",
580
+ kind: "report-only",
581
+ reason: "csp.reportOnly is true in the registry: violations are reported, nothing is blocked.",
582
+ origin: "registry"
583
+ });
584
+ }
585
+ const render = (skip = []) => Object.entries(directives).filter(([directive]) => !skip.includes(directive)).map(([directive, sources]) => [directive, ...sources].join(" ")).join("; ");
586
+ const policy = {
587
+ level: deviations.length === 0 ? "strict" : "loosened",
588
+ deviations,
589
+ directives,
590
+ headerName: config.reportOnly === true ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy",
591
+ header: render(),
592
+ meta: config.reportOnly === true ? null : render(["frame-ancestors", "report-uri", "report-to"])
593
+ };
594
+ if (reportUri !== void 0 && reportTo !== void 0) policy.reportingEndpoints = `${reportTo}="${reportUri}"`;
595
+ return policy;
596
+ }
597
+ function describeCspDeviations(deviations) {
598
+ return deviations.map((deviation) => {
599
+ const what = deviation.kind === "sources-added" ? `${deviation.directive} also allows ${(deviation.sources ?? []).join(" ")}` : deviation.kind === "report-only" ? "the policy is report-only and blocks nothing" : `${deviation.directive} is left out`;
600
+ return `${what}${deviation.origin === "automatic" ? " (automatic)" : ""}: ${deviation.reason}`;
601
+ });
602
+ }
603
+
604
+ // src/registry-module.ts
605
+ var KINDS = [
606
+ { kind: "script", name: "Script" },
607
+ { kind: "cookie", name: "Cookie" },
608
+ { kind: "storage", name: "Storage" },
609
+ { kind: "iframe", name: "Iframe" },
610
+ { kind: "pixel", name: "Pixel" },
611
+ { kind: "endpoint", name: "Endpoint" },
612
+ { kind: "stylesheet", name: "Stylesheet" },
613
+ { kind: "font", name: "Font" },
614
+ { kind: "media", name: "Media" }
615
+ ];
616
+ function renderRegistryModule(registry) {
617
+ const blocks = [
618
+ block("PurposeId", registry.purposes.map((p) => p.id)),
619
+ block("ConsentPurposeId", registry.purposes.filter((p) => p.basis === "consent").map((p) => p.id)),
620
+ block("ProcessorId", registry.processors.map((p) => p.id)),
621
+ block("ArtefactId", registry.artefacts.map((a) => a.id)),
622
+ ...KINDS.map(({ kind, name }) => block(`${name}Id`, registry.artefacts.filter((a) => a.kind === kind).map((a) => a.id))),
623
+ block("CollectionPointId", registry.collectionPoints.map((c) => c.id))
624
+ ];
625
+ return ["// Generated by consent-kit from privacy.registry.yaml. Do not edit.", ...blocks].join("\n\n") + "\n";
626
+ }
627
+ function block(typeName, ids) {
628
+ const sorted = sortedUnique(ids);
629
+ const constName = typeName.charAt(0).toLowerCase() + typeName.slice(1) + "s";
630
+ const union = sorted.length > 0 ? sorted.map((id) => JSON.stringify(id)).join(" | ") : "never";
631
+ const object = sorted.length > 0 ? `{
632
+ ${sorted.map((id) => ` ${JSON.stringify(id)}: ${JSON.stringify(id)},
633
+ `).join("")}}` : "{}";
634
+ return `export type ${typeName} = ${union};
635
+ export const ${constName}: { readonly [Id in ${typeName}]: Id } = ${object};`;
636
+ }
637
+
638
+ // src/script-tag.ts
639
+ function consentScriptTag(registry, artefactId) {
640
+ const artefact = registry.artefacts.find((a) => a.id === artefactId);
641
+ if (!artefact) throw new Error(`consent-kit: no artefact with id "${artefactId}"`);
642
+ if (artefact.kind !== "script") {
643
+ throw new Error(`consent-kit: artefact "${artefactId}" is a ${artefact.kind}, not a script`);
644
+ }
645
+ const categories = consentCategoriesOf(artefact, consentPurposeIds(registry));
646
+ const [category2] = categories;
647
+ if (category2 === void 0) return `<script src="${escapeHtml(artefact.src)}"></script>`;
648
+ if (categories.length > 1) {
649
+ throw new Error(
650
+ `consent-kit: script "${artefactId}" is bound to several consent purposes (${categories.join(", ")}); CookieConsent's data-category takes exactly one. Bind the script to a single consent purpose.`
651
+ );
652
+ }
653
+ const attributes = ['type="text/plain"', `data-category="${escapeHtml(category2)}"`];
654
+ const service = consentServiceOf(artefact, categories);
655
+ if (service !== void 0) attributes.push(`data-service="${escapeHtml(service)}"`);
656
+ attributes.push(`data-src="${escapeHtml(artefact.src)}"`);
657
+ return `<script ${attributes.join(" ")}></script>`;
658
+ }
659
+ function consentEmbed(registry, artefactId, options = {}) {
660
+ const artefact = registry.artefacts.find((a) => a.id === artefactId);
661
+ if (!artefact) throw new Error(`consent-kit: no artefact with id "${artefactId}"`);
662
+ if (artefact.kind !== "iframe") {
663
+ throw new Error(`consent-kit: artefact "${artefactId}" is a ${artefact.kind}, not an iframe`);
664
+ }
665
+ const src = options.src ?? artefact.src;
666
+ if (!isUnder(src, artefact.src)) {
667
+ throw new Error(`consent-kit: "${src}" is not under the declared src of iframe "${artefactId}" (${artefact.src})`);
668
+ }
669
+ const categories = consentCategoriesOf(artefact, consentPurposeIds(registry));
670
+ const [category2] = categories;
671
+ const title = options.title !== void 0 ? ` title="${escapeHtml(options.title)}"` : "";
672
+ if (category2 === void 0) return `<iframe src="${escapeHtml(src)}"${title}></iframe>`;
673
+ if (categories.length > 1) {
674
+ throw new Error(
675
+ `consent-kit: iframe "${artefactId}" is bound to several consent purposes (${categories.join(", ")}); an embed placeholder takes exactly one category. Bind the iframe to a single consent purpose.`
676
+ );
677
+ }
678
+ const attributes = ["data-ck-embed", `data-category="${escapeHtml(category2)}"`];
679
+ const service = consentServiceOf(artefact, categories);
680
+ if (service !== void 0) attributes.push(`data-service="${escapeHtml(service)}"`);
681
+ attributes.push(`data-src="${escapeHtml(src)}"`);
682
+ if (options.title !== void 0) attributes.push(`data-title="${escapeHtml(options.title)}"`);
683
+ return `<div ${attributes.join(" ")}>${options.placeholder ?? ""}</div>`;
684
+ }
685
+ function isUnder(url, declared) {
686
+ const a = locateUrl(url);
687
+ const b = locateUrl(declared);
688
+ if (a.where === "site" && b.where === "site") return pathCovers(b.pathname, a.pathname);
689
+ if (a.where !== "remote" || b.where !== "remote") return false;
690
+ return a.url.origin !== "null" && a.url.origin === b.url.origin && pathCovers(b.url.pathname, a.url.pathname);
691
+ }
692
+
693
+ // src/compile.ts
694
+ var OUTPUT_FILES = {
695
+ registryModule: "registry.gen.ts",
696
+ policy: "policy.json",
697
+ cookieConsentModule: "cookieconsent.config.gen.ts",
698
+ guardManifest: "guard-manifest.json",
699
+ csp: "csp.json"
700
+ };
701
+ function compile(registry, options) {
702
+ const json = (value) => `${JSON.stringify(value, null, 2)}
703
+ `;
704
+ const { policy, hash } = policySnapshot(registry);
705
+ return {
706
+ [OUTPUT_FILES.registryModule]: renderRegistryModule(registry),
707
+ [OUTPUT_FILES.policy]: json({ hash, policy }),
708
+ [OUTPUT_FILES.cookieConsentModule]: renderCookieConsentModule(cookieConsentConfig(registry, options), { receipts: receiptSettings(registry, options) }),
709
+ [OUTPUT_FILES.guardManifest]: json(guardManifest(registry)),
710
+ [OUTPUT_FILES.csp]: json(contentSecurityPolicy(registry, options))
711
+ };
712
+ }
713
+
714
+ export { CONSENT_COOKIE_NAME, CSP_FETCH_DIRECTIVES, NECESSARY_CATEGORY, OUTPUT_FILES, RECEIPTS_RUNTIME_MODULE, UI_STRINGS, canonicalJson, compile, consentEmbed, consentScriptTag, contentSecurityPolicy, cookieConsentConfig, describeCspDeviations, describeReceipts, guardManifest, policySnapshot, receiptManifest, receiptOrigin, receiptSettings, releasedPolicy, renderCookieConsentModule, renderRegistryModule, uiStringsFor };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@consent-kit/compiler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Compiles a consent-kit registry into a policy snapshot, CookieConsent config, guard manifest and Content-Security-Policy.",
5
+ "keywords": [
6
+ "consent-kit",
7
+ "consent",
8
+ "privacy",
9
+ "gdpr",
10
+ "eprivacy",
11
+ "cookie-consent",
12
+ "cookieconsent",
13
+ "content-security-policy",
14
+ "compiler"
15
+ ],
16
+ "homepage": "https://consent-kit.com",
17
+ "bugs": {
18
+ "url": "https://github.com/pavelpascari/consent-kit/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/pavelpascari/consent-kit.git",
23
+ "directory": "packages/compiler"
24
+ },
25
+ "license": "MIT",
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "import": "./dist/index.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "dependencies": {
47
+ "vanilla-cookieconsent": "^3.3.0",
48
+ "@consent-kit/schema": "0.1.0"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup"
52
+ },
53
+ "main": "./dist/index.js",
54
+ "types": "./dist/index.d.ts"
6
55
  }