@rcooler/consent 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,318 @@
1
+ import { regionalProfiles, regionalRulesVersion, validRestrictions } from "./regional.js";
2
+ const slug = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3
+ const identifier = /^[A-Za-z0-9_-]{1,128}$/;
4
+ const locale = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
5
+ const categories = ["necessary", "preferences", "analytics", "marketing"];
6
+ const kinds = ["ga4", "iframe", "script", "custom"];
7
+ const bytes = (value) => new TextEncoder().encode(value).length;
8
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const keys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
10
+ const control = (value, allowWhitespace = false, rejectDEL = false) => [...value].some((character) => {
11
+ const code = character.charCodeAt(0);
12
+ return ((code < 32 && !(allowWhitespace && (code === 9 || code === 10))) ||
13
+ (rejectDEL && code === 127));
14
+ });
15
+ const text = (value, max) => typeof value === "string" &&
16
+ // NEL is whitespace to Go but not to \s; both validators treat it as blank.
17
+ /[^\s\u0085]/.test(value) &&
18
+ [...value].length <= max &&
19
+ !control(value, true);
20
+ const integer = (value, max) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= max;
21
+ // The same host grammar as ValidURL in policy.go, so that both sides accept the same addresses.
22
+ const authorityPattern = /^(\[[0-9A-Fa-f:.]+\]|[^[\]:]+)(?::([0-9]*))?$/;
23
+ const hostPattern = /^(?:[A-Za-z0-9._~!$&'()*+,;=-]|(?!\p{ASCII})[^\p{Z}\p{C}])+$/u;
24
+ const numericLabelPattern = /^(?:[0-9]+|0[xX][0-9A-Fa-f]*)$/;
25
+ const octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
26
+ const ipv4Pattern = new RegExp(`^(?:${octet}\\.){3}${octet}$`);
27
+ function validAuthority(authority) {
28
+ const match = authorityPattern.exec(authority);
29
+ if (!match)
30
+ return false;
31
+ const [, host = "", port = ""] = match;
32
+ if (Number(port) > 65535)
33
+ return false;
34
+ // The URL parser checks the address inside brackets.
35
+ if (host.startsWith("["))
36
+ return true;
37
+ if (!hostPattern.test(host))
38
+ return false;
39
+ const last = host.replace(/\.$/, "").split(".").pop() ?? "";
40
+ return !numericLabelPattern.test(last) || ipv4Pattern.test(host);
41
+ }
42
+ export function safeURL(value, allowPath = false) {
43
+ if (typeof value !== "string" ||
44
+ value.length < 1 ||
45
+ bytes(value) > 2048 ||
46
+ /[\r\n\t\\]/.test(value) ||
47
+ control(value, false, true) ||
48
+ /%(?![0-9A-Fa-f]{2})/.test(value))
49
+ return false;
50
+ if (allowPath && value.startsWith("/") && !value.startsWith("//") && !value.includes("#"))
51
+ return true;
52
+ try {
53
+ if (!value.startsWith("https://") || !validAuthority(value.slice(8).split(/[/?#]/)[0] ?? ""))
54
+ return false;
55
+ const url = new URL(value);
56
+ return (url.protocol === "https:" && !!url.hostname && !url.username && !url.password && !url.hash);
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ export function validChoices(value) {
63
+ return (object(value) &&
64
+ Object.keys(value).length === 3 &&
65
+ ["preferences", "analytics", "marketing"].every((key) => typeof value[key] === "boolean"));
66
+ }
67
+ export function resolveNoticeLocale(policy, requested) {
68
+ if (Object.hasOwn(policy.notices, requested))
69
+ return requested;
70
+ const base = requested.split("-")[0] ?? "en";
71
+ if (Object.hasOwn(policy.notices, base))
72
+ return base;
73
+ return Object.hasOwn(policy.notices, "en") ? "en" : (Object.keys(policy.notices)[0] ?? "en");
74
+ }
75
+ function validNotice(notice) {
76
+ return (object(notice) &&
77
+ keys(notice, ["title", "description", "privacy_url"]) &&
78
+ text(notice.title, 120) &&
79
+ text(notice.description, 4000) &&
80
+ safeURL(notice.privacy_url, true));
81
+ }
82
+ function profileList(value, maximum) {
83
+ return (Array.isArray(value) &&
84
+ value.length <= maximum &&
85
+ new Set(value).size === value.length &&
86
+ value.every((profile) => typeof profile === "string" && regionalProfiles.includes(profile)));
87
+ }
88
+ export function validRegionalPolicy(value) {
89
+ if (!object(value) ||
90
+ !keys(value, ["rules_version", "applicable_profiles", "notices", "rights"]) ||
91
+ value.rules_version !== regionalRulesVersion ||
92
+ !profileList(value.applicable_profiles, 32))
93
+ return false;
94
+ if (value.notices !== undefined) {
95
+ if (!object(value.notices) || Object.keys(value.notices).length > 32)
96
+ return false;
97
+ for (const [profile, notices] of Object.entries(value.notices)) {
98
+ if (!regionalProfiles.includes(profile) ||
99
+ !object(notices) ||
100
+ Object.keys(notices).length < 1 ||
101
+ Object.keys(notices).length > 20 ||
102
+ !Object.entries(notices).every(([tag, notice]) => locale.test(tag) && validNotice(notice)))
103
+ return false;
104
+ }
105
+ }
106
+ if (value.rights !== undefined) {
107
+ if (!object(value.rights) || Object.keys(value.rights).length > 20)
108
+ return false;
109
+ for (const [tag, links] of Object.entries(value.rights)) {
110
+ if (!locale.test(tag) ||
111
+ !object(links) ||
112
+ !keys(links, ["request_url", "appeal_url"]) ||
113
+ Object.keys(links).length < 1 ||
114
+ !Object.values(links).some((url) => typeof url === "string" && url !== "") ||
115
+ !Object.values(links).every((url) => url === "" || safeURL(url, true)))
116
+ return false;
117
+ }
118
+ }
119
+ return true;
120
+ }
121
+ export function validRegionSelection(value) {
122
+ return (object(value) &&
123
+ keys(value, [
124
+ "country",
125
+ "subdivision",
126
+ "source",
127
+ "profile_id",
128
+ "applicable_profiles",
129
+ "rules_version",
130
+ "selection_id",
131
+ "resolution_version",
132
+ ]) &&
133
+ ["unknown", "host", "trusted_proxy"].includes(String(value.source)) &&
134
+ typeof value.profile_id === "string" &&
135
+ regionalProfiles.includes(value.profile_id) &&
136
+ profileList(value.applicable_profiles, 64) &&
137
+ value.rules_version === regionalRulesVersion &&
138
+ value.applicable_profiles.includes("global-strict") &&
139
+ value.applicable_profiles.includes(value.profile_id) &&
140
+ typeof value.selection_id === "string" &&
141
+ /^[a-f0-9]{64}$/.test(value.selection_id) &&
142
+ (value.country === undefined ||
143
+ value.country === "" ||
144
+ (typeof value.country === "string" && /^[A-Z]{2}$/.test(value.country))) &&
145
+ (value.subdivision === undefined ||
146
+ value.subdivision === "" ||
147
+ (typeof value.country === "string" &&
148
+ typeof value.subdivision === "string" &&
149
+ new RegExp(`^${value.country}-[A-Z0-9]{1,3}$`).test(value.subdivision))) &&
150
+ (value.source !== "unknown" ||
151
+ ((value.country === undefined || value.country === "") &&
152
+ (value.subdivision === undefined || value.subdivision === ""))) &&
153
+ (value.source === "unknown" ||
154
+ (typeof value.country === "string" && /^[A-Z]{2}$/.test(value.country))) &&
155
+ (value.resolution_version === undefined ||
156
+ value.resolution_version === "" ||
157
+ (typeof value.resolution_version === "string" && identifier.test(value.resolution_version))));
158
+ }
159
+ /** Returns a normalized policy. Omitted durations use the shared Go defaults. */
160
+ export function parsePolicy(value) {
161
+ if (!object(value))
162
+ return null;
163
+ const candidate = { expires_after_days: 180, retention_days: 365, ...value };
164
+ return validatePolicy(candidate) ? candidate : null;
165
+ }
166
+ export function validatePolicy(value) {
167
+ if (!object(value) ||
168
+ !keys(value, [
169
+ "schema_version",
170
+ "site",
171
+ "epoch",
172
+ "version",
173
+ "expires_after_days",
174
+ "retention_days",
175
+ "notices",
176
+ "services",
177
+ "regional",
178
+ ]) ||
179
+ value.schema_version !== 1 ||
180
+ typeof value.site !== "string" ||
181
+ !slug.test(value.site) ||
182
+ typeof value.epoch !== "string" ||
183
+ !identifier.test(value.epoch) ||
184
+ !integer(value.version, Number.MAX_SAFE_INTEGER) ||
185
+ !integer(value.expires_after_days, 3650) ||
186
+ !integer(value.retention_days, 3650) ||
187
+ !object(value.notices) ||
188
+ Object.keys(value.notices).length < 1 ||
189
+ Object.keys(value.notices).length > 20 ||
190
+ !Array.isArray(value.services) ||
191
+ value.services.length > 64 ||
192
+ (value.regional !== undefined && !validRegionalPolicy(value.regional)))
193
+ return false;
194
+ for (const [lang, notice] of Object.entries(value.notices)) {
195
+ if (!locale.test(lang) ||
196
+ !object(notice) ||
197
+ !keys(notice, ["title", "description", "privacy_url"]) ||
198
+ !text(notice.title, 120) ||
199
+ !text(notice.description, 4000) ||
200
+ !safeURL(notice.privacy_url, true))
201
+ return false;
202
+ }
203
+ const ids = new Set();
204
+ let ga4Count = 0;
205
+ for (const service of value.services) {
206
+ if (!object(service) ||
207
+ !keys(service, [
208
+ "id",
209
+ "name",
210
+ "description",
211
+ "provider",
212
+ "category",
213
+ "kind",
214
+ "destination",
215
+ "measurement_id",
216
+ "policy_url",
217
+ "storage",
218
+ "processing",
219
+ ]) ||
220
+ typeof service.id !== "string" ||
221
+ !slug.test(service.id) ||
222
+ ids.has(service.id) ||
223
+ !text(service.name, 120) ||
224
+ !text(service.description, 4000) ||
225
+ !text(service.provider, 200) ||
226
+ typeof service.category !== "string" ||
227
+ !categories.includes(service.category) ||
228
+ typeof service.kind !== "string" ||
229
+ !kinds.includes(service.kind) ||
230
+ !safeURL(service.policy_url, true) ||
231
+ (service.destination !== undefined &&
232
+ service.destination !== "" &&
233
+ !safeURL(service.destination)) ||
234
+ !Array.isArray(service.storage) ||
235
+ service.storage.length > 32 ||
236
+ (service.processing !== undefined &&
237
+ (!validRestrictions(service.processing) ||
238
+ (service.category === "necessary" && Object.values(service.processing).some(Boolean)))))
239
+ return false;
240
+ if (service.kind === "ga4" && ++ga4Count > 1)
241
+ return false;
242
+ if (service.kind === "ga4" &&
243
+ (service.category !== "analytics" ||
244
+ typeof service.measurement_id !== "string" ||
245
+ !/^G-[A-Z0-9]{1,32}$/.test(service.measurement_id)))
246
+ return false;
247
+ if (service.kind !== "ga4" &&
248
+ service.measurement_id !== undefined &&
249
+ service.measurement_id !== "")
250
+ return false;
251
+ const scopes = new Set();
252
+ for (const entry of service.storage) {
253
+ if (!object(entry) ||
254
+ !keys(entry, ["name", "type", "domain", "path"]) ||
255
+ !text(entry.name, 128) ||
256
+ typeof entry.type !== "string" ||
257
+ !["cookie", "localStorage"].includes(entry.type) ||
258
+ (entry.domain !== undefined &&
259
+ (typeof entry.domain !== "string" ||
260
+ bytes(entry.domain) > 253 ||
261
+ /[ /\\:@?#\r\n\t]/.test(entry.domain))) ||
262
+ (entry.path !== undefined &&
263
+ (typeof entry.path !== "string" ||
264
+ bytes(entry.path) > 512 ||
265
+ (entry.path !== "" &&
266
+ (!entry.path.startsWith("/") ||
267
+ control(entry.path, false, true) ||
268
+ entry.path.includes(";"))))))
269
+ return false;
270
+ if (entry.type === "localStorage" && (entry.domain || entry.path))
271
+ return false;
272
+ if (entry.type === "cookie" &&
273
+ (!/^[!#$%&'*+.^_`|~A-Za-z0-9-]+$/.test(entry.name) ||
274
+ (typeof entry.domain === "string" &&
275
+ entry.domain !== "" &&
276
+ (!/^\.?[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/.test(entry.domain) ||
277
+ entry.domain.includes(".."))) ||
278
+ (typeof entry.path === "string" &&
279
+ (control(entry.path, false, true) || entry.path.includes(";")))))
280
+ return false;
281
+ const scope = [entry.type, entry.name, entry.domain ?? "", entry.path ?? ""].join("\u0000");
282
+ if (scopes.has(scope))
283
+ return false;
284
+ scopes.add(scope);
285
+ }
286
+ ids.add(service.id);
287
+ }
288
+ return (bytes(JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`)) <= 262144);
289
+ }
290
+ export function validateConfig(value) {
291
+ return (object(value) &&
292
+ keys(value, [
293
+ "enabled",
294
+ "policy",
295
+ "allowed_services",
296
+ "receipt_url",
297
+ "recheck_after_seconds",
298
+ "region",
299
+ "privacy_signals",
300
+ ]) &&
301
+ typeof value.enabled === "boolean" &&
302
+ validatePolicy(value.policy) &&
303
+ Array.isArray(value.allowed_services) &&
304
+ value.allowed_services.length <= 64 &&
305
+ new Set(value.allowed_services).size === value.allowed_services.length &&
306
+ value.allowed_services.every((id) => typeof id === "string" &&
307
+ value.policy.services.some((service) => service.id === id)) &&
308
+ (value.receipt_url === undefined ||
309
+ (typeof value.receipt_url === "string" &&
310
+ value.receipt_url.startsWith("/") &&
311
+ safeURL(value.receipt_url, true))) &&
312
+ integer(value.recheck_after_seconds, 3600) &&
313
+ (value.region === undefined || validRegionSelection(value.region)) &&
314
+ (value.privacy_signals === undefined ||
315
+ (object(value.privacy_signals) &&
316
+ Object.keys(value.privacy_signals).length === 1 &&
317
+ typeof value.privacy_signals.gpc === "boolean")));
318
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@rcooler/consent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Framework-independent consent preferences and explicit service blocking.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": [
8
+ "*.css",
9
+ "./dist/runtime.js"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "@rcooler/source": "./src/index.ts",
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./consent.css": "./dist/consent.css"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "LICENSE"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/RCooLeR/consent.git",
26
+ "directory": "web/packages/consent"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org"
31
+ },
32
+ "scripts": {
33
+ "build": "node ../../node_modules/@typescript/native/bin/tsc -p tsconfig.build.json",
34
+ "typecheck": "node ../../node_modules/@typescript/native/bin/tsc --noEmit -p tsconfig.json"
35
+ }
36
+ }