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

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 +143 -9
@@ -0,0 +1,19 @@
1
+ /** Reject unknown request fields and malformed version tokens before any mutation. O(fields). */
2
+ export declare function readConsentRequest({ body, fields }: {
3
+ body: unknown;
4
+ fields: readonly string[];
5
+ }, _options?: {}): Record<string, unknown>;
6
+ /** Required nullable revision token; omission must never mean permission to overwrite. */
7
+ export declare function consentRevisionToken({ input, key }: {
8
+ input: Record<string, unknown>;
9
+ key: string;
10
+ }, _options?: {}): string | null;
11
+ /** Use the existing local-render path boundary before allocating a loopback server. O(path length).
12
+ * @example consentPagePath({ path: '/privacy' }) */
13
+ export declare function consentPagePath({ path, resolvePath }: {
14
+ path: string;
15
+ resolvePath: (required: {
16
+ raw: string;
17
+ }) => string;
18
+ }, _optional?: {}): string;
19
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1,29 @@
1
+ /** @file Closed request and revision-token contract shared by HTTP and tool transports. */
2
+ import { ToolInputError } from "@jini-ai/core";
3
+ /** Reject unknown request fields and malformed version tokens before any mutation. O(fields). */
4
+ export function readConsentRequest({ body, fields }, _options = {}) {
5
+ if (!body || typeof body !== 'object' || Array.isArray(body))
6
+ throw new ToolInputError({ message: 'Request must be a JSON object.' });
7
+ const input = body;
8
+ if (Object.keys(input).some(key => !fields.includes(key)))
9
+ throw new ToolInputError({ message: 'Unknown consent request field.' });
10
+ return input;
11
+ }
12
+ /** Required nullable revision token; omission must never mean permission to overwrite. */
13
+ export function consentRevisionToken({ input, key }, _options = {}) {
14
+ const value = input[key];
15
+ if (value === null || (typeof value === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(value)))
16
+ return value;
17
+ throw new ToolInputError({ message: `${key} must be a revision id or null.` });
18
+ }
19
+ /** Use the existing local-render path boundary before allocating a loopback server. O(path length).
20
+ * @example consentPagePath({ path: '/privacy' }) */
21
+ export function consentPagePath({ path, resolvePath }, _optional = {}) {
22
+ try {
23
+ return resolvePath({ raw: path });
24
+ }
25
+ catch {
26
+ throw new ToolInputError({ message: 'Choose a local public page path without traversal, API paths, or an external URL.' });
27
+ }
28
+ }
29
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1,33 @@
1
+ /** @file Site policy snapshots; Jini owns enforcement, the host owns site publication state. */
2
+ import type { ConsentConfig } from '../contract.js';
3
+ export interface SiteConsentRevision {
4
+ id: string;
5
+ config: ConsentConfig;
6
+ actorId: string;
7
+ createdAt: string;
8
+ }
9
+ export interface SiteConsentState {
10
+ draft: SiteConsentRevision | null;
11
+ published: SiteConsentRevision | null;
12
+ }
13
+ /** All operations are workspace bound at composition. Conflicting heads must refuse atomically. */
14
+ export interface SiteConsentStore {
15
+ /** Public readers fetch only the publication; drafts stay in the authoring path. */
16
+ readPublished(required: Record<string, never>, optional?: Record<string, never>): Promise<SiteConsentRevision | null>;
17
+ read(required: Record<string, never>, optional?: Record<string, never>): Promise<SiteConsentState>;
18
+ saveDraft(required: {
19
+ revision: SiteConsentRevision;
20
+ expectedDraftId: string | null;
21
+ signal?: AbortSignal | undefined;
22
+ }, optional?: Record<string, never>): Promise<void>;
23
+ publish(required: {
24
+ draftId: string;
25
+ expectedPublishedId: string | null;
26
+ signal?: AbortSignal | undefined;
27
+ }, optional?: Record<string, never>): Promise<void>;
28
+ }
29
+ /** A stale editor or confirmation card cannot overwrite a newer policy. */
30
+ export declare class SiteConsentConflict extends Error {
31
+ constructor();
32
+ }
33
+ //# sourceMappingURL=revisions.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** A stale editor or confirmation card cannot overwrite a newer policy. */
2
+ export class SiteConsentConflict extends Error {
3
+ constructor() { super('Cookie consent changed. Reload and review the current revision before saving or publishing again.'); }
4
+ }
5
+ //# sourceMappingURL=revisions.js.map
@@ -0,0 +1,20 @@
1
+ /** @file Thin SQL adapter for site consent snapshots, using the host's instrumented kernel. */
2
+ import { type RawBuilder } from 'kysely';
3
+ import { type SiteConsentStore } from './revisions.js';
4
+ /** One workspace's immutable policies and CAS publication; no policy/classification logic.
5
+ * @complexity O(1) indexed reads/writes per operation, bounded config JSON (32 KiB).
6
+ * @example createSiteConsentStore({ kernel, workspaceId: 'site-a' }) */
7
+ export declare function createSiteConsentStore({ kernel, workspaceId, tables }: {
8
+ kernel: {
9
+ query<Row>(statement: RawBuilder<Row>): Promise<Row[]>;
10
+ execute(statement: RawBuilder<unknown>): Promise<void>;
11
+ lockKey(key: string): Promise<void>;
12
+ transaction<T>(fn: () => Promise<T>): Promise<T>;
13
+ };
14
+ workspaceId: string;
15
+ tables: {
16
+ revisions: string;
17
+ heads: string;
18
+ };
19
+ }, _options?: {}): SiteConsentStore;
20
+ //# sourceMappingURL=revisions.repo.d.ts.map
@@ -0,0 +1,53 @@
1
+ /** @file Thin SQL adapter for site consent snapshots, using the host's instrumented kernel. */
2
+ import { sql } from 'kysely';
3
+ import { SiteConsentConflict } from './revisions.js';
4
+ /** One workspace's immutable policies and CAS publication; no policy/classification logic.
5
+ * @complexity O(1) indexed reads/writes per operation, bounded config JSON (32 KiB).
6
+ * @example createSiteConsentStore({ kernel, workspaceId: 'site-a' }) */
7
+ export function createSiteConsentStore({ kernel, workspaceId, tables }, _options = {}) {
8
+ /** Keep all row lookups tenant scoped, including pointers read from storage. */
9
+ const revision = async ({ id }, _optional = {}) => {
10
+ if (id === null)
11
+ return null;
12
+ const [row] = await kernel.query(sql `SELECT id, config_json, actor_id, created_at FROM ${sql.table(tables.revisions)} WHERE workspace_id = ${workspaceId} AND id = ${id}`);
13
+ if (!row || row.config_json.length > 32_768)
14
+ throw new Error('Stored consent revision is unavailable.');
15
+ return { id: row.id, config: JSON.parse(row.config_json), actorId: row.actor_id, createdAt: row.created_at };
16
+ };
17
+ /** Read the head once; immutable revision rows keep both pointers consistent across later publications. */
18
+ const read = async (_input = {}, _optional = {}) => {
19
+ const [head] = await kernel.query(sql `SELECT draft_id, published_id FROM ${sql.table(tables.heads)} WHERE workspace_id = ${workspaceId}`);
20
+ return { draft: await revision({ id: head?.draft_id ?? null }), published: await revision({ id: head?.published_id ?? null }) };
21
+ };
22
+ /** Public context needs no authoring data: one head and at most one bounded publication row.
23
+ * Immutable rows keep this pointer safe across concurrent publication. */
24
+ const readPublished = async (_input = {}, _optional = {}) => {
25
+ const [head] = await kernel.query(sql `SELECT published_id FROM ${sql.table(tables.heads)} WHERE workspace_id = ${workspaceId}`);
26
+ return revision({ id: head?.published_id ?? null });
27
+ };
28
+ return {
29
+ read,
30
+ readPublished,
31
+ saveDraft: async ({ revision: next, expectedDraftId, signal }, _optional = {}) => kernel.transaction(async () => {
32
+ await kernel.lockKey(`site-consent:${workspaceId}`);
33
+ const state = await read();
34
+ if ((state.draft?.id ?? null) !== expectedDraftId)
35
+ throw new SiteConsentConflict();
36
+ const config = JSON.stringify(next.config);
37
+ if (config.length > 32_768)
38
+ throw new Error('Consent configuration exceeds 32 KiB.');
39
+ signal?.throwIfAborted();
40
+ await kernel.execute(sql `INSERT INTO ${sql.table(tables.revisions)} (workspace_id, id, config_json, actor_id, created_at) VALUES (${workspaceId}, ${next.id}, ${config}, ${next.actorId}, ${next.createdAt})`);
41
+ await kernel.execute(sql `INSERT INTO ${sql.table(tables.heads)} (workspace_id, draft_id, published_id) VALUES (${workspaceId}, ${next.id}, NULL) ON CONFLICT (workspace_id) DO UPDATE SET draft_id = ${next.id}`);
42
+ }),
43
+ publish: async ({ draftId, expectedPublishedId, signal }, _optional = {}) => kernel.transaction(async () => {
44
+ await kernel.lockKey(`site-consent:${workspaceId}`);
45
+ const state = await read();
46
+ if (state.draft?.id !== draftId || (state.published?.id ?? null) !== expectedPublishedId)
47
+ throw new SiteConsentConflict();
48
+ signal?.throwIfAborted();
49
+ await kernel.execute(sql `UPDATE ${sql.table(tables.heads)} SET published_id = ${draftId} WHERE workspace_id = ${workspaceId}`);
50
+ }),
51
+ };
52
+ }
53
+ //# sourceMappingURL=revisions.repo.js.map
@@ -0,0 +1,204 @@
1
+ /** @file Shared site consent use cases for HTTP and assistant adapters. */
2
+ import type { ConsentConfig } from '@jini-ai/core/contracts/site/cookie-consent';
3
+ import type { ConsentReceiptStorageHealth } from '../node/index.js';
4
+ import type { AuthorizeFn } from '@jini-ai/core/contracts/events';
5
+ import type { SiteConsentStore } from './revisions.js';
6
+ import type { ConsentProblem } from '@jini-ai/core/contracts/site/core-consent-refusal';
7
+ import { type ConsentDeclarationEvidence } from './readiness.js';
8
+ /** The host's publish-refusal envelope: fixed code, wording and fix/rollback choices around the blocking problems.
9
+ * A type alias (not an interface) so it satisfies the deploy route's `Record<string, unknown>` refusal body. */
10
+ export type ConsentDeploymentRefusal = {
11
+ code: string;
12
+ error: string;
13
+ blockingProblems: ConsentProblem[];
14
+ choices: {
15
+ id: string;
16
+ label: string;
17
+ href: string;
18
+ action: string;
19
+ warning?: string;
20
+ }[];
21
+ };
22
+ export interface ConsentServicePorts {
23
+ bannerModeRefusal?: string | undefined;
24
+ workspaceId: string;
25
+ authorize: AuthorizeFn;
26
+ store?: SiteConsentStore;
27
+ ready: Promise<void>;
28
+ clock: {
29
+ nowIso(): string;
30
+ };
31
+ ids: {
32
+ newId(): string;
33
+ };
34
+ trustedRegion: boolean;
35
+ readLegacy(required: Record<string, never>, optional?: Record<string, never>): Promise<ConsentConfig>;
36
+ /** True when no owner on/off choice exists, so `readLegacy().enabled` is only the product default. */
37
+ defaultOnly(required: Record<string, never>, optional?: Record<string, never>): Promise<boolean>;
38
+ privacyPageExists(required: {
39
+ url: string;
40
+ }, optional?: Record<string, never>): Promise<boolean>;
41
+ renderPage(required: {
42
+ path: string;
43
+ }, optional?: Record<string, never>): Promise<{
44
+ html: string;
45
+ ok: boolean;
46
+ truncated: boolean;
47
+ }>;
48
+ /** Inspect the live receipt backend without saving a visitor choice; errors block readiness. */
49
+ receiptStorage(required: Record<string, never>, optional?: Record<string, never>): Promise<ConsentReceiptStorageHealth>;
50
+ /** Admin-only evidence from the active source declarations and document construction capability. */
51
+ declarationEvidence?(required: {
52
+ path: string;
53
+ }, optional?: object): Promise<ConsentDeclarationEvidence>;
54
+ /** Refresh construction-time publication after the durable store has committed. */
55
+ published?(): Promise<void>;
56
+ /** The host's local public page path boundary: returns the local path, throws `ToolInputError` for
57
+ * traversal, API paths or an external URL. Checked before any render is allocated. */
58
+ consentPagePath(required: {
59
+ path: string;
60
+ }, optional?: Record<string, never>): string;
61
+ /** The host's deployment refusal envelope; this package decides only WHEN to refuse. */
62
+ deploymentRefusal(required: {
63
+ problems: ConsentProblem[];
64
+ }, optional?: Record<string, never>): ConsentDeploymentRefusal;
65
+ /** Receives a plain message (no prefix) and the caught error; the host owns the console line and its
66
+ * redaction. Called only on a degraded path that the service already turned into a safe result. */
67
+ reportConsentFailure(required: {
68
+ message: string;
69
+ error: unknown;
70
+ }, optional?: Record<string, never>): void;
71
+ }
72
+ /** Creates one workspace's adapters over the engine and durable policy store.
73
+ * Authorization remains in each operation so direct/tool callers cannot bypass the HTTP guard.
74
+ * @example createSiteConsentService({ ports })
75
+ * @complexity Fixed repository operations; readiness scans receipt filenames and renders one bounded page, never executes JS. */
76
+ export declare function createSiteConsentService({ ports }: {
77
+ ports: ConsentServicePorts;
78
+ }, _options?: {}): {
79
+ read: ({ principalId }: {
80
+ principalId: string;
81
+ }, _optional?: {}) => Promise<{
82
+ draft: {
83
+ config: ConsentConfig;
84
+ id: string;
85
+ actorId: string;
86
+ createdAt: string;
87
+ } | null;
88
+ effective: ConsentConfig;
89
+ categoriesEditable: boolean;
90
+ editor: {
91
+ defaults: {
92
+ customCss: string;
93
+ enabled: boolean;
94
+ regionMode: import("./config.js").SiteConsentRegionMode;
95
+ policyVersion: string;
96
+ privacyPolicyUrl: string;
97
+ secondaryLinkLabel: string;
98
+ secondaryLinkUrl: string;
99
+ title: string;
100
+ message: string;
101
+ acceptLabel: string;
102
+ rejectLabel: string;
103
+ preferencesLabel: string;
104
+ placement: import("./config.js").SiteConsentPlacement;
105
+ };
106
+ placements: ("bottom-bar" | "bottom-left" | "bottom-right" | "top-bar")[];
107
+ textLimits: {
108
+ title: number;
109
+ message: number;
110
+ acceptLabel: number;
111
+ rejectLabel: number;
112
+ preferencesLabel: number;
113
+ secondaryLinkLabel: number;
114
+ };
115
+ maxCssLength: number;
116
+ cssSelectors: string[];
117
+ regionModes: string[];
118
+ bannerModes: ("jini" | "headless" | "off")[];
119
+ categories: {
120
+ id: "functional" | "analytics" | "marketing" | "necessary";
121
+ required: boolean;
122
+ editable: boolean;
123
+ }[];
124
+ rules: {
125
+ gpc: string;
126
+ preferenceMaxAgeMs: number;
127
+ staticReceipts: boolean;
128
+ };
129
+ };
130
+ published: import("./revisions.js").SiteConsentRevision | null;
131
+ }>;
132
+ readiness: ({ principalId, path, config: proposed }: {
133
+ principalId: string;
134
+ path?: string | undefined;
135
+ config?: unknown;
136
+ }, _optional?: {}) => Promise<{
137
+ ready: boolean;
138
+ categories: {
139
+ id: "functional" | "analytics" | "marketing" | "necessary";
140
+ required: boolean;
141
+ editable: boolean;
142
+ }[];
143
+ declarations: import("@jini-ai/core/contracts/site/cookie-consent").DeclaredScript[];
144
+ warnings: import("./readiness.js").ConsentWarning[];
145
+ truncated: boolean;
146
+ limitations: string[];
147
+ receipts: ConsentReceiptStorageHealth;
148
+ enabled: boolean;
149
+ placement: "bottom-bar" | "bottom-left" | "bottom-right" | "top-bar" | undefined;
150
+ regionMode: import("@jini-ai/core/contracts/site/cookie-consent").RegionMode | "auto";
151
+ delivery: string;
152
+ staticSupported: boolean;
153
+ sampledPaths: string[];
154
+ sampleOnly: boolean;
155
+ blockingProblems: ConsentProblem[];
156
+ }>;
157
+ preview: ({ principalId, path, config: proposed }: {
158
+ principalId: string;
159
+ path?: string;
160
+ config?: unknown;
161
+ }, _optional?: {}) => Promise<{
162
+ sandbox: string;
163
+ revisionId: string | null;
164
+ warnings: {
165
+ field: string;
166
+ code: "size" | "syntax" | "selector" | "property" | "value" | "contrast";
167
+ message: string;
168
+ offset?: number;
169
+ selector?: string;
170
+ property?: string;
171
+ }[];
172
+ html: string;
173
+ blockingProblems: ConsentProblem[];
174
+ }>;
175
+ saveDraft: ({ principalId, config: value, expectedDraftId, signal }: {
176
+ principalId: string;
177
+ config: unknown;
178
+ expectedDraftId: string | null;
179
+ signal?: AbortSignal;
180
+ }, _optional?: {}) => Promise<{
181
+ revision: {
182
+ id: string;
183
+ config: ConsentConfig;
184
+ actorId: string;
185
+ createdAt: string;
186
+ };
187
+ blockingProblems: ConsentProblem[];
188
+ }>;
189
+ publish: ({ principalId, draftId, expectedPublishedId, signal }: {
190
+ principalId: string;
191
+ draftId: string;
192
+ expectedPublishedId: string | null;
193
+ signal?: AbortSignal;
194
+ }, _optional?: {}) => Promise<{
195
+ published: boolean;
196
+ revisionId: string;
197
+ }>;
198
+ deploymentCheck: ({ principalId, permission }: {
199
+ principalId: string;
200
+ permission: "system.publish" | "deployments.publish";
201
+ }, _optional?: {}) => Promise<ConsentDeploymentRefusal | null>;
202
+ };
203
+ export type SiteConsentService = ReturnType<typeof createSiteConsentService>;
204
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1,198 @@
1
+ import { adaptLegacyAuthorize, requireToolPermission, ToolInputError } from '@jini-ai/core';
2
+ import { SiteConsentConflict } from './revisions.js';
3
+ import { consentConfigProblems, parseConsentConfig } from './validation.js';
4
+ import { CATEGORIES as CONSENT_CATEGORIES } from '../contract.js';
5
+ import { DEFAULT_MAX_AGE_MS as CONSENT_MAX_AGE_MS } from '../contracts/policy.js';
6
+ import { CONSENT_MAX_CSS_LENGTH } from '../render/css.js';
7
+ import { SITE_CONSENT_BANNER_MODES, SITE_CONSENT_DEFAULT_CSS, SITE_CONSENT_DEFAULTS, SITE_CONSENT_PLACEMENTS, SITE_CONSENT_TEXT_LIMITS, withSiteConsentDefaultCss } from './config.js';
8
+ import { consentDeclarationReadiness } from './readiness.js';
9
+ import { renderSiteConsentPreview } from './cookie-consent.js';
10
+ const CONSENT_CSS_SELECTORS = ['#jini-consent', '.jini-consent', '.jini-consent-reopen'];
11
+ /** Missing declaration collection is failed evidence, never an empty protected source list. */
12
+ async function declarationDiagnostics({ ports, path, html }) {
13
+ if (!ports.declarationEvidence)
14
+ return {
15
+ declarations: [], warnings: [], truncated: false,
16
+ categories: CONSENT_CATEGORIES.map(id => ({ id, required: id === 'necessary', editable: false })),
17
+ problems: [{ code: 'DECLARATIONS_UNAVAILABLE', message: 'Script declarations could not be collected. Readiness cannot be established.' }],
18
+ };
19
+ const evidence = await ports.declarationEvidence({ path });
20
+ return consentDeclarationReadiness({ html, ...evidence });
21
+ }
22
+ /** Unsaved input takes precedence over the draft, then the effective published/legacy policy.
23
+ * An emptied Custom CSS previews the default style, exactly as the public site delivers it. */
24
+ function sampleConsentConfig({ state, proposed, bannerModeRefusal }, _options = {}) {
25
+ return withSiteConsentDefaultCss({ config: parseConsentConfig({ value: proposed === undefined ? state.draft?.config ?? state.effective : proposed, bannerModeRefusal }) });
26
+ }
27
+ /** Readiness requires complete bounded page evidence; banner preview is independent. */
28
+ function isCompleteConsentPage({ page }, _options = {}) {
29
+ return page.ok && !page.truncated;
30
+ }
31
+ /** The legacy ledger allowed empty or longer copy; editor reads must let the owner repair it.
32
+ * Defaults replace only out-of-range text in a copy; published policies and writes stay strict.
33
+ * @complexity O(n) text length across seven bounded legacy fields; no storage writes. */
34
+ function legacyEditorConsentConfig({ config }, _options = {}) {
35
+ const normalized = { ...config };
36
+ const limits = { ...SITE_CONSENT_TEXT_LIMITS, policyVersion: 64 };
37
+ for (const key of Object.keys(limits)) {
38
+ const text = normalized[key];
39
+ if (typeof text !== 'string')
40
+ continue;
41
+ const emptyAllowed = key === 'secondaryLinkLabel' && text.length === 0;
42
+ if (text.length > limits[key] || (!emptyAllowed && !text.trim()))
43
+ normalized[key] = SITE_CONSENT_DEFAULTS[key];
44
+ }
45
+ return normalized;
46
+ }
47
+ function createConsentReader(ports) {
48
+ /** Deny before touching readiness, configuration or rendered content. */
49
+ const authorize = async ({ principalId, write = false }, _optional = {}) => {
50
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: ports.authorize }), principalId, workspaceId: ports.workspaceId, permission: write ? 'settings.workspace.write' : 'settings.read' }, { entityType: 'site-consent' });
51
+ await ports.ready;
52
+ if (!ports.store)
53
+ throw new Error('The durable site consent policy store is unavailable.');
54
+ return ports.store;
55
+ };
56
+ /** Resolve draft and published separately; malformed published data never falls back to OFF. */
57
+ const read = async ({ principalId }, _optional = {}) => {
58
+ const store = await authorize({ principalId });
59
+ const state = await store.read({});
60
+ const legacy = state.published ? null : legacyEditorConsentConfig({ config: await ports.readLegacy({}) });
61
+ // An empty Custom CSS is what the public site fills with the default style, so the editor shows
62
+ // that default in the field for the owner to edit (owner, 2026-10-22).
63
+ const draft = state.draft && { ...state.draft, config: withSiteConsentDefaultCss({ config: state.draft.config }) };
64
+ return { ...state, draft, effective: withSiteConsentDefaultCss({ config: parseConsentConfig({ value: state.published?.config ?? legacy, bannerModeRefusal: ports.bannerModeRefusal }) }), categoriesEditable: false,
65
+ editor: { defaults: { ...SITE_CONSENT_DEFAULTS, customCss: SITE_CONSENT_DEFAULT_CSS }, placements: [...SITE_CONSENT_PLACEMENTS], textLimits: { ...SITE_CONSENT_TEXT_LIMITS },
66
+ maxCssLength: CONSENT_MAX_CSS_LENGTH, cssSelectors: [...CONSENT_CSS_SELECTORS],
67
+ regionModes: ['opt-in', 'auto'], bannerModes: [...SITE_CONSENT_BANNER_MODES],
68
+ categories: CONSENT_CATEGORIES.map(id => ({ id, required: id === 'necessary', editable: false })),
69
+ rules: { gpc: 'always-enforced', preferenceMaxAgeMs: CONSENT_MAX_AGE_MS, staticReceipts: false } } };
70
+ };
71
+ return { authorize, read };
72
+ }
73
+ function createConsentReadiness(ports, read, problems) {
74
+ /** Readiness needs writable proof storage as well as a safe local page sample.
75
+ * Storage errors expose no private paths; render failure/truncation also blocks readiness. */
76
+ const readiness = async ({ principalId, path = '/', config: proposed }, _optional = {}) => {
77
+ const state = await read({ principalId });
78
+ const config = sampleConsentConfig({ state, proposed, bannerModeRefusal: ports.bannerModeRefusal });
79
+ path = ports.consentPagePath({ path });
80
+ const blockingProblems = await problems({ config: { ...config, enabled: true } });
81
+ let receipts;
82
+ try {
83
+ receipts = await ports.receiptStorage({});
84
+ }
85
+ catch {
86
+ receipts = { writable: false, count: null };
87
+ }
88
+ if (!receipts.writable || receipts.count === null)
89
+ blockingProblems.push({ code: 'RECEIPT_STORAGE_UNAVAILABLE', message: 'Consent receipt storage is unavailable or not writable. Visitor choices cannot be saved reliably.' });
90
+ // `config` came through parseConsentConfig, which refuses a config without a string placement,
91
+ // so no default placement is needed here.
92
+ const metadata = { receipts, enabled: state.effective.enabled, placement: config.placement, regionMode: config.regionMode, delivery: 'live', staticSupported: true, sampledPaths: [path], sampleOnly: true, blockingProblems };
93
+ try {
94
+ const page = await ports.renderPage({ path });
95
+ if (!isCompleteConsentPage({ page }))
96
+ blockingProblems.push({ code: 'PAGE_UNAVAILABLE', message: 'The rendered page is unavailable or exceeds the 1 MB audit limit.' });
97
+ const dryRun = await declarationDiagnostics({ ports, path, html: page.html });
98
+ blockingProblems.push(...dryRun.problems);
99
+ return { ...metadata, ready: blockingProblems.length === 0, categories: dryRun.categories, declarations: dryRun.declarations, warnings: dryRun.warnings, truncated: dryRun.truncated || page.truncated,
100
+ limitations: ['One server-rendered page sample; dynamic requests, server cookies and legal compliance require separate review.'] };
101
+ }
102
+ catch (error) {
103
+ ports.reportConsentFailure({ message: 'The page could not be rendered; readiness remains unavailable.', error });
104
+ blockingProblems.push({ code: 'RENDER_FAILED', message: 'The page could not be rendered safely. Readiness cannot be established.' });
105
+ return { ...metadata, ready: false, categories: CONSENT_CATEGORIES.map(id => ({ id, required: id === 'necessary', editable: false })), declarations: [], warnings: [], truncated: false, limitations: ['Rendered evidence unavailable.'] };
106
+ }
107
+ };
108
+ return { readiness };
109
+ }
110
+ function createConsentDeploymentCheck(ports, problems) {
111
+ const staticDeploymentRefusal = async ({ config }, _options = {}) => {
112
+ const blockingProblems = await problems({ config });
113
+ // The cookie-consent banner works on a static host (choices kept in the browser, labelled so).
114
+ return blockingProblems.length ? ports.deploymentRefusal({ problems: blockingProblems }) : null;
115
+ };
116
+ /** Static publication uses browser-local evidence, with the same policy and privacy checks.
117
+ * Unknown configuration remains blocking; explicit OFF remains a readable rollback. */
118
+ const deploymentCheck = async ({ principalId, permission }, _optional = {}) => {
119
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: ports.authorize }), principalId, workspaceId: ports.workspaceId, permission }, { entityType: 'site-publish' });
120
+ try {
121
+ await ports.ready;
122
+ if (!ports.store)
123
+ throw new Error('Consent store unavailable');
124
+ const state = await ports.store.read({});
125
+ // Default-only consent (no owner choice, nothing published) exports without the banner, as the
126
+ // construction slot is empty for that default; the default is off live too (2026-11-02).
127
+ if (!state.published && await ports.defaultOnly({}))
128
+ return null;
129
+ const effective = state.published?.config ?? await ports.readLegacy({});
130
+ // Explicit OFF remains a rollback even when saved legacy copy exceeds today's editor limits.
131
+ if (effective.enabled === false)
132
+ return null;
133
+ const config = parseConsentConfig({ value: effective, bannerModeRefusal: ports.bannerModeRefusal });
134
+ return await staticDeploymentRefusal({ config });
135
+ }
136
+ catch (error) {
137
+ ports.reportConsentFailure({ message: 'The consent policy could not be verified; deployment remains blocked.', error });
138
+ return ports.deploymentRefusal({ problems: [{ code: 'CONSENT_UNAVAILABLE', message: 'The published consent policy could not be verified. Deployment was not started.' }] });
139
+ }
140
+ };
141
+ return { deploymentCheck };
142
+ }
143
+ /** Creates one workspace's adapters over the engine and durable policy store.
144
+ * Authorization remains in each operation so direct/tool callers cannot bypass the HTTP guard.
145
+ * @example createSiteConsentService({ ports })
146
+ * @complexity Fixed repository operations; readiness scans receipt filenames and renders one bounded page, never executes JS. */
147
+ export function createSiteConsentService({ ports }, _options = {}) {
148
+ const { authorize, read } = createConsentReader(ports);
149
+ /** Engine validation plus this site's privacy-page linkage; no HTTP fetch to external policies. */
150
+ const problems = async ({ config }, _optional = {}) => {
151
+ const found = consentConfigProblems({ config, trustedRegion: ports.trustedRegion }, { cssBlocks: false });
152
+ if (config.enabled && config.privacyPolicyUrl && !found.some(problem => problem.field === 'privacyPolicyUrl') && !await ports.privacyPageExists({ url: config.privacyPolicyUrl }))
153
+ found.push({ code: 'PRIVACY_PAGE_MISSING', field: 'privacyPolicyUrl', message: 'Publish the linked privacy page before enabling consent.' });
154
+ return found;
155
+ };
156
+ const { readiness } = createConsentReadiness(ports, read, problems);
157
+ /** A separate scriptless banner preview; no page content is parsed or represented as protected. */
158
+ const preview = async ({ principalId, path = '/', config: proposed }, _optional = {}) => {
159
+ const state = await read({ principalId });
160
+ const config = sampleConsentConfig({ state, proposed, bannerModeRefusal: ports.bannerModeRefusal });
161
+ ports.consentPagePath({ path });
162
+ const rendered = renderSiteConsentPreview({ config, policy: config.policyVersion });
163
+ const html = `<!doctype html><html ${rendered.htmlAttrs}><head><meta charset="utf-8">${rendered.head}</head><body>${rendered.body}</body></html>`;
164
+ const diagnostics = { warnings: rendered.problems.map(problem => ({ ...problem, field: 'appearance' })) };
165
+ return { html, blockingProblems: await problems({ config }), ...diagnostics, sandbox: '', revisionId: state.draft?.id ?? state.published?.id ?? null };
166
+ };
167
+ /** Append an immutable draft; invalid CSS rules are diagnosed and dropped by the preview compiler. */
168
+ const saveDraft = async ({ principalId, config: value, expectedDraftId, signal }, _optional = {}) => {
169
+ const store = await authorize({ principalId, write: true });
170
+ const config = parseConsentConfig({ value, bannerModeRefusal: ports.bannerModeRefusal });
171
+ const blockingProblems = await problems({ config });
172
+ const revision = { id: ports.ids.newId(), config, actorId: principalId, createdAt: ports.clock.nowIso() };
173
+ await store.saveDraft({ revision, expectedDraftId, signal });
174
+ return { revision, blockingProblems };
175
+ };
176
+ /** The stored draft, never caller replacement fields, is what becomes public atomically. */
177
+ const publish = async ({ principalId, draftId, expectedPublishedId, signal }, _optional = {}) => {
178
+ const store = await authorize({ principalId, write: true });
179
+ const state = await store.read({});
180
+ if (state.draft?.id !== draftId)
181
+ throw new SiteConsentConflict();
182
+ const config = parseConsentConfig({ value: state.draft.config, bannerModeRefusal: ports.bannerModeRefusal });
183
+ const blockingProblems = await problems({ config });
184
+ if (blockingProblems.length)
185
+ throw new ToolInputError({ message: blockingProblems.map(problem => problem.message).join(' ') });
186
+ await store.publish({ draftId, expectedPublishedId, signal });
187
+ try {
188
+ await ports.published?.();
189
+ }
190
+ catch (error) {
191
+ ports.reportConsentFailure({ message: 'Cookie preferences were published, but the public preview could not refresh. A later request will try again.', error });
192
+ }
193
+ return { published: true, revisionId: draftId };
194
+ };
195
+ const { deploymentCheck } = createConsentDeploymentCheck(ports, problems);
196
+ return { read, readiness, preview, saveDraft, publish, deploymentCheck };
197
+ }
198
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1,54 @@
1
+ import { type EnsureSettingDefinitionsDeps, type SettingsRepoPort } from '@jini-ai/core/settings';
2
+ import { type SiteConsentSettings } from './config.js';
3
+ /** What a site serves when consent is not on: the default copy with the banner off. */
4
+ export declare const SITE_CONSENT_OFF: SiteConsentSettings;
5
+ /** The shared registrar owns legacy scalar definitions and their ledger revisions.
6
+ * Complete published policies use the site snapshot adapter, avoiding partial field publication.
7
+ * @complexity O(1), thirteen bounded settings definitions. */
8
+ export declare function ensureSiteConsentDefinitions(required: EnsureSettingDefinitionsDeps, { systemPrincipalId }: {
9
+ systemPrincipalId: string;
10
+ }): Promise<void>;
11
+ /** The optional privacy-page repair. Passing the repair makes its failure reporter REQUIRED: the
12
+ * host owns the log channel, line format and redaction, so a failure is never silently dropped. */
13
+ export type SiteConsentPrivacyRepair = {
14
+ ensurePrivacyDefaults?: undefined;
15
+ reportPrivacyDefaultsFailure?: undefined;
16
+ } | {
17
+ ensurePrivacyDefaults: () => Promise<void>;
18
+ reportPrivacyDefaultsFailure: (required: {
19
+ error: unknown;
20
+ }) => void;
21
+ };
22
+ /** Consent owns readiness, without extending WebMCP's failure chain.
23
+ * The shared boot chain serializes ledger writes on the site's single connection.
24
+ * Definition failures block readiness; CMS defaults failures are reported and retried next open.
25
+ * @complexity Registration is O(1); injected CMS defaults inherit their workspace scan cost. */
26
+ export declare function createSiteConsentReadiness({ after, systemPrincipalId, ...required }: EnsureSettingDefinitionsDeps & {
27
+ after: Promise<void>;
28
+ systemPrincipalId: string;
29
+ }, repair?: SiteConsentPrivacyRepair): Promise<void>;
30
+ /** Explicit owner on/off overrides the default for every site. */
31
+ export type SiteConsentActivation = {
32
+ enabled: boolean;
33
+ source: 'owner' | 'default';
34
+ };
35
+ type Deps = {
36
+ settingsRepo: SettingsRepoPort;
37
+ workspaceId: string;
38
+ };
39
+ /** Resolve whether consent applies, honoring an explicit owner choice over the product default.
40
+ * The privacy link is not a precondition for activation; publishing still requires one (validation.ts).
41
+ * @throws Error when the stored flag is not a boolean (never guesses on or off).
42
+ * @complexity O(1), one ledger read. */
43
+ export declare function resolveSiteConsentActivation(deps: Deps, _options?: {}): Promise<SiteConsentActivation>;
44
+ /** Bind workspace settings to the mechanism. Missing definitions use the product default.
45
+ * Malformed values throw rather than bypass an enabled policy. @complexity O(1), thirteen reads. */
46
+ export declare function createSiteConsentConfig({ settingsRepo, workspaceId }: Deps, _options?: {}): {
47
+ get(_input?: Record<string, never>, _optional?: {}): Promise<SiteConsentSettings>;
48
+ };
49
+ /** Authoring reads retain saved copy even while consent is disabled; public rollback still uses get().
50
+ * @example readSiteConsentAuthoringSettings({ settingsRepo, workspaceId })
51
+ * @complexity O(1), one bounded set of existing ledger reads; performs no writes. */
52
+ export declare function readSiteConsentAuthoringSettings(deps: Deps, _options?: {}): Promise<SiteConsentSettings>;
53
+ export {};
54
+ //# sourceMappingURL=settings.d.ts.map