@jini-ai/cookie-consent 0.7.3-next.2 → 0.7.3-next.3

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.
Files changed (41) hide show
  1. package/dist/client.min.js +1 -1
  2. package/dist/contract.d.ts +2 -78
  3. package/dist/extensions.min.js +1 -1
  4. package/dist/react/ConsentFields.d.ts +4 -1
  5. package/dist/react/ConsentFields.js +11 -5
  6. package/dist/render/css.d.ts +2 -12
  7. package/dist/site/config.d.ts +51 -0
  8. package/dist/site/config.js +75 -0
  9. package/dist/site/cookie-consent.d.ts +53 -0
  10. package/dist/site/cookie-consent.js +47 -0
  11. package/dist/site/document-assets.d.ts +44 -0
  12. package/dist/site/document-assets.js +78 -0
  13. package/dist/site/document-state.d.ts +71 -0
  14. package/dist/site/document-state.js +79 -0
  15. package/dist/site/ensure-privacy-defaults.d.ts +63 -0
  16. package/dist/site/ensure-privacy-defaults.js +44 -0
  17. package/dist/site/http.d.ts +281 -0
  18. package/dist/site/http.js +271 -0
  19. package/dist/site/pre-consent-cache.d.ts +33 -0
  20. package/dist/site/pre-consent-cache.js +43 -0
  21. package/dist/site/privacy-page-template.d.ts +9 -0
  22. package/dist/site/privacy-page-template.js +17 -0
  23. package/dist/site/readiness.d.ts +29 -0
  24. package/dist/site/readiness.js +91 -0
  25. package/dist/site/region-plugins.d.ts +90 -0
  26. package/dist/site/region-plugins.js +73 -0
  27. package/dist/site/request.d.ts +19 -0
  28. package/dist/site/request.js +29 -0
  29. package/dist/site/revisions.d.ts +33 -0
  30. package/dist/site/revisions.js +5 -0
  31. package/dist/site/revisions.repo.d.ts +20 -0
  32. package/dist/site/revisions.repo.js +53 -0
  33. package/dist/site/service.d.ts +204 -0
  34. package/dist/site/service.js +198 -0
  35. package/dist/site/settings.d.ts +54 -0
  36. package/dist/site/settings.js +100 -0
  37. package/dist/site/tool-registrations.d.ts +63 -0
  38. package/dist/site/tool-registrations.js +69 -0
  39. package/dist/site/validation.d.ts +21 -0
  40. package/dist/site/validation.js +77 -0
  41. package/package.json +137 -9
@@ -0,0 +1,271 @@
1
+ import { handleReceipt } from "../server/receipt.js";
2
+ import { resolveRegion } from "../server/region.js";
3
+ import { staticConsentLoaderScript } from "./document-assets.js";
4
+ import { CONSENT_COOKIE, OPTIONAL } from '../contract.js';
5
+ import { DEFAULT_MAX_AGE_MS, parseStored } from '../contracts/policy.js';
6
+ import { readConsent } from '../server/receipt.js';
7
+ import { siteBannerMode } from './cookie-consent.js';
8
+ /** A dot segment or an encoded separator never reaches a plugin handler, whatever the plugin does with paths. */
9
+ const UNSAFE_PLUGIN_PATH = /(?:^|\/)\.\.?(?:\/|$)|%2e|%2f|%5c|\\/i;
10
+ /** The active plugin mounted over this path; none for a path with a dot segment or encoded separator. */
11
+ export function matchConsentPluginHttp({ plugins, full }, _optional = {}) {
12
+ if (UNSAFE_PLUGIN_PATH.test(full))
13
+ return undefined;
14
+ return plugins({}).find((item) => Boolean(item.http && full.startsWith(item.http.path + '/')));
15
+ }
16
+ /** Same-origin/category/rate decision plus the server-owned analytics level. Anonymous delivery needs
17
+ * an adapter declaring support. A category that is not optional (even 'necessary') is read as marketing,
18
+ * the strictest. @complexity O(cookie header) plus one policy read. */
19
+ export async function collectorDecision({ origin, siteOrigin, adapter, readState, rateAllowed }, _optional = {}) {
20
+ const denied = { status: 403, analyticsLevel: 'none' };
21
+ if (origin !== siteOrigin({}))
22
+ return denied;
23
+ const category = OPTIONAL.includes(adapter.category) ? adapter.category : 'marketing';
24
+ const state = await readState({});
25
+ const allowed = category === 'analytics' && state.analyticsLevel === 'anonymous' ? adapter.supportsAnonymous === true : state.allowed[category];
26
+ if (!allowed)
27
+ return denied;
28
+ return { status: await rateAllowed({}) ? null : 429, analyticsLevel: state.analyticsLevel };
29
+ }
30
+ /** The server gate: what this visitor may run right now (GPC/DNT applied, durable rule: an
31
+ * unconfirmed grant is not allowed). A failed policy read allows nothing. @complexity O(cookie header). */
32
+ export async function readVisitorConsent({ readSnapshot, snapshotUnavailable, readPolicy, facts }, _optional = {}) {
33
+ try {
34
+ const snapshot = await readSnapshot({});
35
+ if (snapshotUnavailable({ config: snapshot }))
36
+ return readConsent({ cookieHeader: '', policy: '', regionMode: 'opt-in' });
37
+ if (snapshot && siteBannerMode({ config: snapshot }) === 'off') {
38
+ const { secGpc, dnt, nowMs } = facts({});
39
+ return readConsent({ cookieHeader: '', policy: snapshot.policyVersion, regionMode: 'opt-in' }, { secGpc, dnt, nowMs, anonymous: true });
40
+ }
41
+ const config = snapshot ?? await readPolicy({});
42
+ const { cookieHeader, ...privacy } = facts({});
43
+ return readConsent({ cookieHeader, policy: config.policyVersion, regionMode: config.regionMode === 'opt-in' ? 'opt-in' : 'auto' }, {
44
+ ...privacy, anonymous: siteBannerMode({ config }) === 'off',
45
+ });
46
+ }
47
+ catch {
48
+ return readConsent({ cookieHeader: '', policy: '', regionMode: 'opt-in' });
49
+ }
50
+ }
51
+ /** Detached delivery recheck, the old engine's rule: the receipt is still active (a later choice retires
52
+ * it), names the current policy, grants analytics without GPC and is within the choice lifetime. A forged
53
+ * or withdrawn receipt id never delivers. @complexity O(1): one policy read and one receipt read. */
54
+ export async function receiptAllowsAnalytics({ proof, readSnapshot, snapshotUnavailable, readPolicyVersion, readReceipt, nowMs }, _optional = {}) {
55
+ const snapshot = await readSnapshot({});
56
+ if (snapshotUnavailable({ config: snapshot }))
57
+ return false;
58
+ if (snapshot && siteBannerMode({ config: snapshot }) === 'off')
59
+ return false;
60
+ const policy = snapshot?.policyVersion ?? await readPolicyVersion({});
61
+ if (proof.policyVersion !== policy)
62
+ return false;
63
+ const record = await readReceipt({ id: proof.receiptId });
64
+ return activeAnalyticsRecord({ record, policy, nowMs: nowMs({}) });
65
+ }
66
+ function activeAnalyticsRecord({ record, policy, nowMs }, _optional = {}) {
67
+ if (!record || record.policyVersion !== policy || record.gpc !== false)
68
+ return false;
69
+ return record.choices?.analytics === true && nowMs - Date.parse(String(record.timestamp)) <= DEFAULT_MAX_AGE_MS;
70
+ }
71
+ /** The old engine's analytics proof shape (receipt id + policy), from the new cookie. Undefined unless
72
+ * analytics is allowed and a server receipt exists. @complexity O(cookie header). */
73
+ export function analyticsProof(required, _optional = {}) {
74
+ const { state } = required;
75
+ if (state.analyticsLevel !== 'full')
76
+ return undefined;
77
+ const { cookieHeader } = required;
78
+ const raw = cookieHeader?.match(new RegExp(`(?:^|;\\s*)${CONSENT_COOKIE}=([^;]*)`))?.[1];
79
+ let receiptId;
80
+ try {
81
+ receiptId = parseStored({ raw: raw === undefined ? null : decodeURIComponent(raw) })?.r;
82
+ }
83
+ catch {
84
+ receiptId = undefined;
85
+ }
86
+ return receiptId ? { receiptId, policyVersion: state.policy } : undefined;
87
+ }
88
+ function loadClient(input, _optional = {}) {
89
+ try {
90
+ const body = input.load();
91
+ const hash = input.hash(body).slice(0, 12);
92
+ return { body, src: `${input.endpoint}/client-${hash}.min.js` };
93
+ }
94
+ catch (error) {
95
+ let errorDiagnostic = input.diagnosticUnavailable;
96
+ try {
97
+ errorDiagnostic = input.formatError(error);
98
+ }
99
+ catch { /* Keep the original failure path if diagnostics fail. */ }
100
+ input.warn(errorDiagnostic);
101
+ return undefined;
102
+ }
103
+ }
104
+ function writePluginHttpResponse({ writer, facts, result }) {
105
+ if (result.contentType)
106
+ writer.setHeader('Content-Type', result.contentType);
107
+ writer.setHeader('Cache-Control', facts.method === 'GET' && result.cacheControl ? result.cacheControl : 'private, no-store');
108
+ writer.status(result.status);
109
+ writer.end(result.body);
110
+ }
111
+ async function mountPluginHttp({ pluginBase, facts, plugins, siteOrigin, readState, rateAllowed, writer, next }, _optional = {}) {
112
+ const full = pluginBase + facts.path;
113
+ const plugin = matchConsentPluginHttp({ plugins, full });
114
+ if (!plugin) {
115
+ next();
116
+ return;
117
+ }
118
+ try {
119
+ const decision = facts.method === 'GET' ? undefined : await collectorDecision({ origin: facts.origin, siteOrigin, adapter: plugin.adapter, readState, rateAllowed });
120
+ if (decision?.status) {
121
+ writer.status(decision.status);
122
+ writer.end();
123
+ return;
124
+ }
125
+ const result = await plugin.http.handle({ method: facts.method, path: full.slice(plugin.http.path.length), body: facts.body,
126
+ contentType: facts.contentType ?? 'application/octet-stream', ...(decision && { analyticsLevel: decision.analyticsLevel }) });
127
+ writePluginHttpResponse({ writer, facts, result });
128
+ }
129
+ catch {
130
+ writer.status(502);
131
+ writer.end();
132
+ }
133
+ }
134
+ async function mountReceipts(input, _optional = {}) {
135
+ try {
136
+ const config = await input.readPolicy();
137
+ const response = await handleReceipt({ request: input.request(), ports: {
138
+ store: input.store, policy: () => config.policyVersion, now: input.now,
139
+ // Receipt ids must be unguessable; the site's time-ordered id generator is not.
140
+ ids: input.ids,
141
+ } }, { regionMode: config.regionMode === 'opt-in' ? 'opt-in' : 'auto', allow: input.allow });
142
+ input.write({ status: response.status, headers: Object.fromEntries(response.headers), body: await response.text() });
143
+ }
144
+ catch (error) {
145
+ let errorId;
146
+ try {
147
+ ({ errorId } = input.failure.report(error));
148
+ }
149
+ catch {
150
+ input.failure.diagnosticFailure();
151
+ }
152
+ input.failure.write(errorId);
153
+ }
154
+ }
155
+ async function mountContext(input, _optional = {}) {
156
+ input.setCache('private, no-store');
157
+ try {
158
+ const config = await input.readPolicy();
159
+ if (!config)
160
+ throw input.unavailable();
161
+ const enabled = siteBannerMode({ config }) !== 'off';
162
+ if (enabled) {
163
+ const hint = await resolveRegion({ resolvers: await input.resolvers(), request: input.request });
164
+ input.setRegionCookie(hint);
165
+ input.clearLegacyCookie();
166
+ }
167
+ input.json({ enabled, policy: config.policyVersion, regionMode: config.regionMode === 'opt-in' ? 'opt-in' : 'auto' });
168
+ }
169
+ catch (error) {
170
+ let errorId;
171
+ try {
172
+ ({ errorId } = input.failure.report(error));
173
+ }
174
+ catch {
175
+ input.failure.diagnosticFailure();
176
+ }
177
+ input.failure.write(errorId);
178
+ }
179
+ }
180
+ async function mountStaticThemeLoader(input, _optional = {}) {
181
+ try {
182
+ const theme = input.readThemeId ? input.resolveTheme({ activeThemeId: await input.readThemeId() }) : null;
183
+ const scripts = theme && theme !== input.noThemeId ? theme.manifest.scripts ?? [] : [];
184
+ const assets = await input.assets(scripts);
185
+ input.write(staticConsentLoaderScript({ ...assets, exporting: input.exporting() }));
186
+ }
187
+ catch (error) {
188
+ let errorId;
189
+ try {
190
+ ({ errorId } = input.failure.report(error));
191
+ }
192
+ catch {
193
+ input.failure.diagnosticFailure();
194
+ }
195
+ input.failure.write(errorId);
196
+ }
197
+ }
198
+ function applySiteCookieConsent(input, _optional = {}) {
199
+ const { client } = input.install();
200
+ input.mountReadiness();
201
+ if (client)
202
+ input.mountClient(client);
203
+ try {
204
+ input.mountExtension(input.loadExtension());
205
+ }
206
+ catch (error) {
207
+ let errorDiagnostic = input.extensionFailure.diagnosticUnavailable;
208
+ try {
209
+ errorDiagnostic = input.extensionFailure.formatError(error);
210
+ }
211
+ catch { /* Keep the original failure path if diagnostics fail. */ }
212
+ input.extensionFailure.warn(errorDiagnostic);
213
+ }
214
+ input.mountStaticThemeLoader();
215
+ input.mountDiagnostics();
216
+ input.mountContext();
217
+ const receiptLimiter = input.createReceiptLimiter();
218
+ const store = input.openReceiptStore();
219
+ input.mountReceipts({ store, limiter: receiptLimiter, bodyLimit: input.receiptBodyLimit });
220
+ const collectorLimiter = input.createCollectorLimiter();
221
+ input.mountPluginHttp({ limiter: collectorLimiter, bodyLimit: input.pluginBodyLimit });
222
+ }
223
+ export function createSiteConsentHttp(required, _optional = {}) {
224
+ return {
225
+ readVisitorConsent, receiptAllowsAnalytics, toWebRequest,
226
+ beforeRender: async (input) => {
227
+ // Resolve the cached publication before widget rendering; consent-off pages have no activation runtime.
228
+ await input.readPolicy();
229
+ input.attachAssets();
230
+ input.next();
231
+ },
232
+ setRegionCookie: (input) => setRegionCookie({ ...input, name: required.regionCookieName }),
233
+ clearLegacyCookie: (input) => clearLegacyCookie({ ...input, name: required.legacyCookieName }),
234
+ readAnalyticsProof: async (input) => analyticsProof({ state: await input.readState(), get cookieHeader() { return input.cookieHeader(); } }),
235
+ loadClient: (input) => loadClient({ ...input, endpoint: required.endpoint }),
236
+ pluginHttp: (input) => mountPluginHttp({ ...input, pluginBase: required.pluginBase }),
237
+ diagnostics: async (input) => {
238
+ input.setCache('private, no-store');
239
+ if (!(await input.enabled())) {
240
+ input.missing();
241
+ return;
242
+ }
243
+ input.send();
244
+ },
245
+ receipts: mountReceipts, context: mountContext, staticThemeLoader: mountStaticThemeLoader, applySiteCookieConsent,
246
+ };
247
+ }
248
+ function toWebRequest(required, _optional = {}) {
249
+ const headers = new Headers();
250
+ for (const name of ['origin', 'content-type', 'content-length', 'cookie', 'sec-gpc', 'dnt']) {
251
+ const value = required.header(name);
252
+ if (value !== undefined)
253
+ headers.set(name, value);
254
+ }
255
+ return new Request(new URL(required.originalUrl, required.origin), { method: required.method, headers, body: new Uint8Array(required.body) });
256
+ }
257
+ /** Region persistence is only reached for an enabled consent banner, never anonymous analytics. */
258
+ function setRegionCookie(required, _optional = {}) {
259
+ const current = required.cookieHeader?.match(new RegExp(`(?:^|;\\s*)${required.name}=([^;]*)`))?.[1];
260
+ const secure = required.secure || required.origin.startsWith('https:');
261
+ if (required.hint === 'us' && current !== 'us')
262
+ required.cookie(required.name, 'us', { path: '/', sameSite: 'lax', secure, maxAge: 86_400_000 });
263
+ if (required.hint === 'strict' && current !== undefined)
264
+ required.clearCookie(required.name, { path: '/' });
265
+ }
266
+ /** Only this engine retires the old host-only HttpOnly cookie; its receipt id proves no new categories. */
267
+ function clearLegacyCookie(required, _optional = {}) {
268
+ if (new RegExp(`(?:^|;\\s*)${required.name}=`).test(required.cookieHeader ?? ''))
269
+ required.clearCookie(required.name, { path: '/', httpOnly: true, sameSite: 'lax' });
270
+ }
271
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @file G7-8 (owner decision): a public page rendered BEFORE the visitor made a consent choice, and
3
+ * carrying consent-gated tracking scripts, must never be stored by a shared cache.
4
+ *
5
+ * The consent banner delivers consent-gated scripts inside its JSON page config (`CONFIG_ID`,
6
+ * `@jini-ai/cookie-consent` `renderBanner`); the browser client activates them only after the visitor
7
+ * opts in. A CDN copy of that pre-consent document would keep being replayed after the site's
8
+ * tracking set or consent policy changes, so such responses are `private, no-store` instead.
9
+ */
10
+ export declare const CACHE_CONTROL_PRE_CONSENT_TRACKING = "private, no-store";
11
+ /**
12
+ * True when the page's consent config lists at least one consent-gated script. A config that does
13
+ * not parse counts as gated: failing toward `no-store` costs a cache hit, failing the other way
14
+ * could publish a tracking page to a shared cache.
15
+ * @complexity O(html length).
16
+ */
17
+ export declare function hasConsentGatedScripts({ html, configId }: {
18
+ html: string;
19
+ configId: string;
20
+ }, _optional?: {}): boolean;
21
+ /**
22
+ * The `Cache-Control` to send: the route's own directive, tightened to
23
+ * {@link CACHE_CONTROL_PRE_CONSENT_TRACKING} for a pre-consent request (no parsed consent choice yet)
24
+ * whose page carries consent-gated scripts. Never loosens an already-private directive.
25
+ * @complexity O(html length).
26
+ */
27
+ export declare function preConsentCacheControl({ html, cacheControl, configId, hasConsentChoice }: {
28
+ html: string;
29
+ cacheControl: string;
30
+ configId: string;
31
+ hasConsentChoice: (required: Record<string, never>) => boolean;
32
+ }, _optional?: {}): string;
33
+ //# sourceMappingURL=pre-consent-cache.d.ts.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @file G7-8 (owner decision): a public page rendered BEFORE the visitor made a consent choice, and
3
+ * carrying consent-gated tracking scripts, must never be stored by a shared cache.
4
+ *
5
+ * The consent banner delivers consent-gated scripts inside its JSON page config (`CONFIG_ID`,
6
+ * `@jini-ai/cookie-consent` `renderBanner`); the browser client activates them only after the visitor
7
+ * opts in. A CDN copy of that pre-consent document would keep being replayed after the site's
8
+ * tracking set or consent policy changes, so such responses are `private, no-store` instead.
9
+ */
10
+ export const CACHE_CONTROL_PRE_CONSENT_TRACKING = "private, no-store";
11
+ /**
12
+ * True when the page's consent config lists at least one consent-gated script. A config that does
13
+ * not parse counts as gated: failing toward `no-store` costs a cache hit, failing the other way
14
+ * could publish a tracking page to a shared cache.
15
+ * @complexity O(html length).
16
+ */
17
+ export function hasConsentGatedScripts({ html, configId }, _optional = {}) {
18
+ const escapedConfigId = configId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ const match = new RegExp(`<script type="application/json" id="${escapedConfigId}">([\\s\\S]*?)</script>`).exec(html);
20
+ if (!match)
21
+ return false;
22
+ try {
23
+ const config = JSON.parse(match[1] ?? "");
24
+ return Array.isArray(config.scripts) && config.scripts.length > 0;
25
+ }
26
+ catch {
27
+ return true;
28
+ }
29
+ }
30
+ /**
31
+ * The `Cache-Control` to send: the route's own directive, tightened to
32
+ * {@link CACHE_CONTROL_PRE_CONSENT_TRACKING} for a pre-consent request (no parsed consent choice yet)
33
+ * whose page carries consent-gated scripts. Never loosens an already-private directive.
34
+ * @complexity O(html length).
35
+ */
36
+ export function preConsentCacheControl({ html, cacheControl, configId, hasConsentChoice }, _optional = {}) {
37
+ if (/\b(private|no-store)\b/.test(cacheControl))
38
+ return cacheControl;
39
+ if (hasConsentChoice({}))
40
+ return cacheControl;
41
+ return hasConsentGatedScripts({ html, configId }) ? CACHE_CONTROL_PRE_CONSENT_TRACKING : cacheControl;
42
+ }
43
+ //# sourceMappingURL=pre-consent-cache.js.map
@@ -0,0 +1,9 @@
1
+ /** Initial editable copy only; owner edits are never regenerated. Escapes all interpolated text.
2
+ * @param required Site title and seeded owner's contact, when available.
3
+ * @returns Inner HTML with an editor region and a highlighted missing-contact prompt.
4
+ * @complexity O(n) for n interpolated characters; no I/O. */
5
+ export declare function privacyPageTemplate({ siteTitle, email }: {
6
+ siteTitle: string;
7
+ email?: string;
8
+ }, _options?: {}): string;
9
+ //# sourceMappingURL=privacy-page-template.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { escapeHtml } from '@jini-ai/core/text';
2
+ /** Initial editable copy only; owner edits are never regenerated. Escapes all interpolated text.
3
+ * @param required Site title and seeded owner's contact, when available.
4
+ * @returns Inner HTML with an editor region and a highlighted missing-contact prompt.
5
+ * @complexity O(n) for n interpolated characters; no I/O. */
6
+ export function privacyPageTemplate({ siteTitle, email }, _options = {}) {
7
+ const contact = email?.trim() ? escapeHtml({ text: email }) : '<mark>ADD YOUR CONTACT EMAIL</mark>';
8
+ return `<section data-agent-element="privacy-policy" data-agent-role="region">
9
+ <h1>Privacy Policy</h1>
10
+ <p>${escapeHtml({ text: siteTitle })} uses necessary cookies to operate this website and remember your cookie choices.</p>
11
+ <p>Where present, optional functional cookies support additional features, analytics cookies help measure website use, and marketing cookies support advertising. The cookie banner lets you accept or reject optional categories and change your preferences.</p>
12
+ <p>Necessary cookies remain active. Optional content is controlled by your choices.</p>
13
+ <p>Questions about privacy? Contact ${contact}.</p>
14
+ <p>This page describes this website’s cookie choices. The site owner should edit it to describe any additional collection or use of personal information.</p>
15
+ </section>`;
16
+ }
17
+ //# sourceMappingURL=privacy-page-template.js.map
@@ -0,0 +1,29 @@
1
+ /** Admin-only declaration diagnostics. Sampled HTML is inspected, never converted or returned rewritten. */
2
+ import { type DeclaredScript } from '../contract.js';
3
+ import type { ConsentProblem } from '@jini-ai/core/contracts/site/core-consent-refusal';
4
+ export interface ConsentWarning extends ConsentProblem {
5
+ source?: string | null;
6
+ tag?: string;
7
+ attributes?: string[];
8
+ }
9
+ export interface ConsentDeclarationEvidence {
10
+ scripts: unknown;
11
+ runtimeSlot: boolean;
12
+ problems?: readonly (string | ConsentProblem)[];
13
+ }
14
+ /** Validate declarations and label gaps separately. No allowance simulation or page rewriting.
15
+ * @complexity O(sample bytes + declarations), at most 1 MB and 200 returned diagnostic entries. */
16
+ export declare function consentDeclarationReadiness({ html, scripts, runtimeSlot, problems: evidenceProblems }: {
17
+ html: string;
18
+ } & ConsentDeclarationEvidence, _options?: {}): {
19
+ declarations: DeclaredScript[];
20
+ warnings: ConsentWarning[];
21
+ categories: {
22
+ id: "functional" | "analytics" | "marketing" | "necessary";
23
+ required: boolean;
24
+ editable: boolean;
25
+ }[];
26
+ truncated: boolean;
27
+ problems: ConsentProblem[];
28
+ };
29
+ //# sourceMappingURL=readiness.d.ts.map
@@ -0,0 +1,91 @@
1
+ /** Admin-only declaration diagnostics. Sampled HTML is inspected, never converted or returned rewritten. */
2
+ import { CATEGORIES } from '../contract.js';
3
+ import { validateScripts } from '../contracts/scripts.js';
4
+ import { parse } from 'parse5';
5
+ const LIMIT = 200;
6
+ /** Diagnostics never disclose URL credentials, query values, fragments or inline code. */
7
+ function sourceLabel({ value }, _optional = {}) {
8
+ if (!value)
9
+ return null;
10
+ try {
11
+ const url = new URL(value, 'https://site.invalid');
12
+ return `${url.origin === 'https://site.invalid' ? '' : url.origin}${url.pathname}`.slice(0, 500);
13
+ }
14
+ catch {
15
+ return '[invalid resource URL]';
16
+ }
17
+ }
18
+ function executableScript({ node, attrs }, _optional = {}) {
19
+ if (node.tagName !== 'script' || attrs.has('data-jini-declared-script'))
20
+ return false;
21
+ if (/^\/_consent\/(?:client-[\w-]+\.min\.js|extensions\.min\.js|load\.js)$/.test(attrs.get('src') ?? ''))
22
+ return false;
23
+ return ['', 'module', 'text/javascript', 'application/javascript'].includes((attrs.get('type') ?? '').toLowerCase());
24
+ }
25
+ function unmanaged(node) {
26
+ const attrs = new Map(node.attrs.map(attr => [attr.name, attr.value]));
27
+ const handlers = node.attrs.filter(attr => /^on[a-z]+$/i.test(attr.name)).map(attr => attr.name);
28
+ const resource = liveEmbeddedSource({ tag: node.tagName, attrs });
29
+ if (!executableScript({ node, attrs }) && handlers.length === 0 && resource === undefined)
30
+ return null;
31
+ return { code: 'UNMANAGED_CONTENT', message: 'Executable page content is outside declared-script consent. Review its authoring before moving this site.',
32
+ tag: node.tagName, source: sourceLabel({ value: resource ?? attrs.get('src') }), ...(handlers.length ? { attributes: handlers } : {}) };
33
+ }
34
+ function liveEmbeddedSource({ tag, attrs }, _optional = {}) {
35
+ if (tag === 'object')
36
+ return attrs.get('data');
37
+ return ['iframe', 'embed'].includes(tag) ? attrs.get('src') : undefined;
38
+ }
39
+ /** Templates are inert authored content, not a promise that their future descendants are controlled. */
40
+ function unmanagedWarnings({ html, available }, _optional = {}) {
41
+ const nodes = [...parse(html).childNodes];
42
+ const warnings = [];
43
+ while (nodes.length) {
44
+ const node = nodes.pop();
45
+ if (node === undefined)
46
+ throw new Error('Consent readiness has no node to inspect');
47
+ if (!('tagName' in node))
48
+ continue;
49
+ const warning = unmanaged(node);
50
+ if (appendUnmanagedWarning(warning, warnings, available))
51
+ return { warnings, truncated: true };
52
+ if (node.tagName !== 'template')
53
+ nodes.push(...node.childNodes);
54
+ }
55
+ return { warnings, truncated: false };
56
+ }
57
+ function appendUnmanagedWarning(warning, warnings, available) {
58
+ if (!warning)
59
+ return false;
60
+ if (warnings.length === available)
61
+ return true;
62
+ warnings.push(warning);
63
+ return false;
64
+ }
65
+ const declarationOverflow = ({ scripts, limit }, _optional = {}) => Array.isArray(scripts) && scripts.length > limit;
66
+ /** Validate declarations and label gaps separately. No allowance simulation or page rewriting.
67
+ * @complexity O(sample bytes + declarations), at most 1 MB and 200 returned diagnostic entries. */
68
+ export function consentDeclarationReadiness({ html, scripts, runtimeSlot, problems: evidenceProblems = [] }, _options = {}) {
69
+ const declarationLimit = runtimeSlot ? LIMIT : LIMIT - 1;
70
+ const input = Array.isArray(scripts) ? scripts.slice(0, declarationLimit) : scripts;
71
+ const checked = validateScripts({ scripts: input });
72
+ const declarations = checked.scripts.map(script => {
73
+ const src = sourceLabel({ value: script.src });
74
+ if (src === null)
75
+ throw new Error('Consent readiness has a declaration with no source');
76
+ return { ...script, src };
77
+ });
78
+ const problems = [...evidenceProblems, ...checked.problems].map(problem => typeof problem === 'string' ? { code: 'INVALID_SCRIPT_DECLARATION', message: problem } : problem);
79
+ const categories = CATEGORIES.map(id => ({ id, required: id === 'necessary', editable: false }));
80
+ if (Buffer.byteLength(html, 'utf8') > 1_000_000)
81
+ return { declarations, warnings: [], categories, truncated: true,
82
+ problems: [...problems, { code: 'PAGE_UNAVAILABLE', message: 'The page exceeds the 1 MB audit limit.' }] };
83
+ const inventory = unmanagedWarnings({ html, available: LIMIT - declarations.length - (runtimeSlot ? 0 : 1) });
84
+ if (!runtimeSlot)
85
+ inventory.warnings.unshift({ code: 'MISSING_RUNTIME_SLOT', message: 'This full-document page or theme has no supported runtime loading slot. Review its authoring before moving this site.' });
86
+ const truncated = inventory.truncated || declarationOverflow({ scripts, limit: declarationLimit });
87
+ if (truncated)
88
+ problems.push({ code: 'INVENTORY_TRUNCATED', message: 'More than 200 diagnostic entries. Inspect a smaller page sample.' });
89
+ return { declarations, warnings: inventory.warnings, categories, problems, truncated };
90
+ }
91
+ //# sourceMappingURL=readiness.js.map
@@ -0,0 +1,90 @@
1
+ import type { DeclaredScript, RawContribution, RegionResolver } from '@jini-ai/core/contracts/site/cookie-consent';
2
+ /** The part of a host plugin-contribution definition this file declares: a data file per active plugin,
3
+ * parsed and loaded entry by entry. The host's contribution loader accepts it as is. */
4
+ export interface ConsentContributionDefinition<D, T> {
5
+ readonly filename: string;
6
+ readonly contribution: string;
7
+ readonly kind: 'data';
8
+ readonly parse: (input: {
9
+ readonly raw: string;
10
+ }) => {
11
+ ok: true;
12
+ descriptors: D[];
13
+ } | {
14
+ ok: false;
15
+ reason: string;
16
+ };
17
+ readonly load: (input: {
18
+ readonly plugin: {
19
+ readonly pluginId: string;
20
+ };
21
+ readonly descriptor: D;
22
+ }) => T | string | Promise<T | string>;
23
+ readonly onReadError?: (input: {
24
+ readonly error: unknown;
25
+ }) => readonly string[] | undefined;
26
+ }
27
+ /** The host's plugin-contribution loader (trust, activation and file reads stay with the host). */
28
+ export type LoadConsentContributions = <D, T>(required: {
29
+ readonly workspaceId: string;
30
+ readonly definition: ConsentContributionDefinition<D, T>;
31
+ }, optional: {
32
+ readonly requireActive?: boolean;
33
+ }) => Promise<{
34
+ readonly items: readonly T[];
35
+ readonly refusals: readonly string[];
36
+ }>;
37
+ /** Receives a plain message (no prefix) and the caught error; the host owns the console line and redaction. */
38
+ export type ReportConsentPluginFailure = (required: {
39
+ message: string;
40
+ error: unknown;
41
+ }, optional?: Record<string, never>) => void;
42
+ /** The file a plugin ships at its root to contribute cookie-consent pieces. */
43
+ export declare const CONSENT_CONTRIBUTIONS_FILENAME = "jini-consent.json";
44
+ /** Parse one schema-2 file into region readers and browser bridge declarations. Pure. @complexity O(entries).
45
+ * The rules live in `@jini-ai/cookie-consent/plugins`; this keeps the host's name and signature. */
46
+ export declare function parseConsentContributions({ raw }: {
47
+ raw: string;
48
+ }, _optional?: {}): {
49
+ ok: true;
50
+ descriptors: RawContribution[];
51
+ } | {
52
+ ok: false;
53
+ reason: string;
54
+ };
55
+ /** Turn data entries into resolvers through the package's own trust boundary; refused entries drop.
56
+ * `legacyHeader` absorbs the host's older consent-region-header setting as one more header reader.
57
+ * @complexity O(entries). */
58
+ export declare function toRegionResolvers({ entries }: {
59
+ entries: readonly RawContribution[];
60
+ }, { legacyHeader }?: {
61
+ legacyHeader?: string | undefined;
62
+ }): RegionResolver[];
63
+ /** This site's region readers: the configured ingress plugin's entries (when active), then the legacy
64
+ * header. A plugin fault leaves the site strict; it never fails a page. @complexity O(p) plugins. */
65
+ export declare function loadSiteRegionResolvers({ workspaceId, loadContributions, reportFailure }: {
66
+ workspaceId: string;
67
+ loadContributions: LoadConsentContributions;
68
+ reportFailure: ReportConsentPluginFailure;
69
+ }, { ingress, legacyHeader }?: {
70
+ ingress?: string;
71
+ legacyHeader?: string;
72
+ }): Promise<RegionResolver[]>;
73
+ /** Active plugins may supply a browser consent UI/bridge without becoming trusted region readers.
74
+ * O(active plugin declarations); no browser module executes on the server. A load failure emits no bridge. */
75
+ export declare function loadSiteConsentBridges({ workspaceId, loadContributions, reportFailure }: {
76
+ workspaceId: string;
77
+ loadContributions: LoadConsentContributions;
78
+ reportFailure: ReportConsentPluginFailure;
79
+ }, _optional?: {}): Promise<RawContribution[]>;
80
+ /** Declared assets come from active plugins only. Refusals remain data for readiness/admin diagnostics;
81
+ * a failed load rejects, so the snapshot owner can keep its last good scripts.
82
+ * O(declarations), no module execution or script-body/content reads. */
83
+ export declare function loadSiteConsentScripts({ workspaceId, loadContributions }: {
84
+ workspaceId: string;
85
+ loadContributions: LoadConsentContributions;
86
+ }, _optional?: {}): Promise<{
87
+ scripts: DeclaredScript[];
88
+ problems: readonly string[];
89
+ }>;
90
+ //# sourceMappingURL=region-plugins.d.ts.map
@@ -0,0 +1,73 @@
1
+ /** @file Region readers and browser bridges for cookie consent, contributed as DATA by active plugins in
2
+ * {@link CONSENT_CONTRIBUTIONS_FILENAME} (schema 2: one open `contributions` list of `{ kind, id, … }`).
3
+ * Core names no host. Only the configured ingress plugin may contribute trusted region readers: a
4
+ * country header from anywhere else can be forged by the visitor. No ingress (Fly, Electron, a
5
+ * static export) means no reader, and every visitor gets the strict banner with Reject.
6
+ *
7
+ * Trust: data-only (no plugin code runs) and loaded for ACTIVE plugins only, so switching a host
8
+ * plugin off stops trusting its header. Kinds this file doesn't know are skipped, not refused. */
9
+ import { consentBridgeContribution, declaredScriptsContribution, parseConsentContributions as parseConsentFile } from '../contracts/consent-file.js';
10
+ import { REGION_SLOT } from '../server/region.js';
11
+ /** The file a plugin ships at its root to contribute cookie-consent pieces. */
12
+ export const CONSENT_CONTRIBUTIONS_FILENAME = 'jini-consent.json';
13
+ /** Parse one schema-2 file into region readers and browser bridge declarations. Pure. @complexity O(entries).
14
+ * The rules live in `@jini-ai/cookie-consent/plugins`; this keeps the host's name and signature. */
15
+ export function parseConsentContributions({ raw }, _optional = {}) {
16
+ return parseConsentFile({ raw });
17
+ }
18
+ const regionContribution = {
19
+ filename: CONSENT_CONTRIBUTIONS_FILENAME, contribution: 'cookie consent contributions', kind: 'data',
20
+ parse: parseConsentContributions,
21
+ load: ({ plugin, descriptor }) => descriptor.kind === 'declared-scripts'
22
+ ? declaredScriptsContribution({ pluginId: plugin.pluginId, entry: descriptor }) : { pluginId: plugin.pluginId, entry: descriptor },
23
+ onReadError: ({ error }) => error.code === 'ENOENT' ? [] : undefined,
24
+ };
25
+ /** Turn data entries into resolvers through the package's own trust boundary; refused entries drop.
26
+ * `legacyHeader` absorbs the host's older consent-region-header setting as one more header reader.
27
+ * @complexity O(entries). */
28
+ export function toRegionResolvers({ entries }, { legacyHeader } = {}) {
29
+ const readers = entries.filter(entry => entry.kind === 'region-resolver');
30
+ const all = legacyHeader ? [...readers, { kind: 'region-resolver', id: 'configured-header', header: legacyHeader }] : readers;
31
+ return all.flatMap(contribution => {
32
+ const accepted = REGION_SLOT.accept({ contribution });
33
+ return typeof accepted === 'string' ? [] : [accepted];
34
+ });
35
+ }
36
+ /** This site's region readers: the configured ingress plugin's entries (when active), then the legacy
37
+ * header. A plugin fault leaves the site strict; it never fails a page. @complexity O(p) plugins. */
38
+ export async function loadSiteRegionResolvers({ workspaceId, loadContributions, reportFailure }, { ingress, legacyHeader } = {}) {
39
+ let entries = [];
40
+ if (ingress) {
41
+ try {
42
+ const load = await loadContributions({ workspaceId, definition: regionContribution }, { requireActive: true });
43
+ entries = load.items.flatMap(item => (item.pluginId === ingress ? [item.entry] : []));
44
+ }
45
+ catch (error) {
46
+ reportFailure({ message: 'region readers could not be loaded; visitors get the strict banner', error });
47
+ }
48
+ }
49
+ return toRegionResolvers({ entries }, { legacyHeader });
50
+ }
51
+ /** Active plugins may supply a browser consent UI/bridge without becoming trusted region readers.
52
+ * O(active plugin declarations); no browser module executes on the server. A load failure emits no bridge. */
53
+ export async function loadSiteConsentBridges({ workspaceId, loadContributions, reportFailure }, _optional = {}) {
54
+ try {
55
+ const load = await loadContributions({ workspaceId, definition: regionContribution }, { requireActive: true });
56
+ return load.items.flatMap(({ entry }) => {
57
+ const bridge = consentBridgeContribution({ entry });
58
+ return bridge ? [bridge] : [];
59
+ });
60
+ }
61
+ catch (error) {
62
+ reportFailure({ message: 'browser bridges could not be loaded', error });
63
+ return [];
64
+ }
65
+ }
66
+ /** Declared assets come from active plugins only. Refusals remain data for readiness/admin diagnostics;
67
+ * a failed load rejects, so the snapshot owner can keep its last good scripts.
68
+ * O(declarations), no module execution or script-body/content reads. */
69
+ export async function loadSiteConsentScripts({ workspaceId, loadContributions }, _optional = {}) {
70
+ const loaded = await loadContributions({ workspaceId, definition: regionContribution }, { requireActive: true });
71
+ return { scripts: loaded.items.flatMap(({ entry }) => entry.kind === 'declared-scripts' ? entry.scripts : []), problems: loaded.refusals };
72
+ }
73
+ //# sourceMappingURL=region-plugins.js.map