-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathutils.ts
525 lines (496 loc) · 17.8 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { TCString } from "@iabtechlabtcf/core";
import { extractIds } from "../common-utils";
import { getConsentContext } from "../consent-context";
import {
ConsentMechanism,
FidesCookie,
PrivacyExperience,
PrivacyExperienceMinimal,
PrivacyNoticeWithPreference,
RecordConsentServedRequest,
SaveConsentPreference,
} from "../consent-types";
import { resolveConsentValue } from "../consent-value";
import {
buildCookieConsentFromConsentPreferences,
getFidesConsentCookie,
transformTcfPreferencesToCookieKeys,
} from "../cookie";
import {
DecodedFidesString,
decodeFidesString,
idsFromAcString,
} from "../fides-string";
import {
transformConsentToFidesUserPreference,
transformUserPreferenceToBoolean,
} from "../shared-consent-utils";
import { generateFidesString } from "../tcf";
import { FIDES_SYSTEM_COOKIE_KEY_MAP, TCF_KEY_MAP } from "./constants";
import {
EnabledIds,
GVLTranslationJson,
PrivacyNoticeWithBestTranslation,
TCFFeatureRecord,
TCFFeatureSave,
TcfModels,
TCFPurposeConsentRecord,
TCFPurposeLegitimateInterestsRecord,
TCFPurposeSave,
TcfSavePreferences,
TCFSpecialFeatureSave,
TCFSpecialPurposeSave,
TCFVendorConsentRecord,
TCFVendorLegitimateInterestsRecord,
TCFVendorSave,
} from "./types";
type TcfSave =
| TCFPurposeSave
| TCFSpecialPurposeSave
| TCFFeatureSave
| TCFSpecialFeatureSave
| TCFVendorSave;
/**
* Populates TCF entities with items from both cookie.tcf_consent and cookie.fides_string.
* We must look at both because they contain non-overlapping info that is required for a complete TCFEntities object.
* Returns TCF entities to be assigned to an experience.
*/
export const buildTcfEntitiesFromCookieAndFidesString = (
experience: PrivacyExperience,
cookie: FidesCookie,
) => {
const tcfEntities = {
tcf_purpose_consents: experience.tcf_purpose_consents,
tcf_purpose_legitimate_interests:
experience.tcf_purpose_legitimate_interests,
tcf_special_purposes: experience.tcf_special_purposes,
tcf_features: experience.tcf_features,
tcf_special_features: experience.tcf_special_features,
tcf_vendor_consents: experience.tcf_vendor_consents,
tcf_vendor_legitimate_interests: experience.tcf_vendor_legitimate_interests,
tcf_system_consents: experience.tcf_system_consents,
tcf_system_legitimate_interests: experience.tcf_system_legitimate_interests,
};
// First update tcfEntities based on the `cookie.tcf_consent` obj
FIDES_SYSTEM_COOKIE_KEY_MAP.forEach(({ cookieKey, experienceKey }) => {
const cookieConsent = cookie.tcf_consent[cookieKey] ?? {};
// @ts-ignore the array map should ensure we will get the right record type
tcfEntities[experienceKey] = experience[experienceKey]?.map((item) => {
// Object.keys converts keys to strings, so we coerce id to string here
const preference = Object.keys(cookieConsent).includes(item.id as string)
? transformConsentToFidesUserPreference(
Boolean(cookieConsent[item.id]),
ConsentMechanism.OPT_IN,
)
: item.default_preference;
return { ...item, current_preference: preference };
});
});
// Now update tcfEntities based on the fides string
if (cookie.fides_string) {
const { tc: tcString, ac: acString }: DecodedFidesString =
decodeFidesString(cookie.fides_string);
if (!tcString) {
return tcfEntities;
}
const acStringIds = idsFromAcString(acString);
// Populate every field from tcModel
const tcModel = TCString.decode(tcString);
TCF_KEY_MAP.forEach(({ experienceKey, tcfModelKey }) => {
const isVendorKey =
tcfModelKey === "vendorConsents" ||
tcfModelKey === "vendorLegitimateInterests";
const tcIds = Array.from(tcModel[tcfModelKey])
.filter(([, consented]) => consented)
.map(([id]) => (isVendorKey ? `gvl.${id}` : id));
// @ts-ignore the array map should ensure we will get the right record type
tcfEntities[experienceKey] = experience[experienceKey]?.map((item) => {
let consented = !!tcIds.find((id) => id === item.id);
// Also check the AC string, which only applies to tcf_vendor_consents
if (
experienceKey === "tcf_vendor_consents" &&
acStringIds.find((id) => id === item.id)
) {
consented = true;
}
return {
...item,
current_preference: transformConsentToFidesUserPreference(
consented,
ConsentMechanism.OPT_IN,
),
};
});
});
}
return tcfEntities;
};
/**
* TCF version of updating prefetched experience, based on:
* 1) experience: pre-fetched or client-side experience-based consent configuration
* 2) cookie: cookie containing user preference.
*
* Returns updated experience with user preferences. We have a separate function for notices
* and for TCF so that the bundle trees do not overlap.
*/
export const updateExperienceFromCookieConsentTcf = ({
experience,
cookie,
debug,
}: {
experience: PrivacyExperience;
cookie: FidesCookie;
debug?: boolean;
}): PrivacyExperience => {
// DEFER (PROD-1568) - instead of updating experience here, push this logic into UI
const tcfEntities = buildTcfEntitiesFromCookieAndFidesString(
experience,
cookie,
);
if (debug) {
fidesDebugger(
`Returning updated pre-fetched experience with user consent.`,
experience,
);
}
// If the given TCF experience has no custom notices, return standard TCF entities along with experience
if (!experience.privacy_notices) {
return { ...experience, ...tcfEntities };
}
const noticesWithConsent: PrivacyNoticeWithPreference[] | undefined =
experience.privacy_notices?.map((notice) => {
const preference = Object.keys(cookie.consent).includes(notice.notice_key)
? transformConsentToFidesUserPreference(
Boolean(cookie.consent[notice.notice_key]),
notice.consent_mechanism,
)
: undefined;
return { ...notice, current_preference: preference };
});
return { ...experience, ...tcfEntities, privacy_notices: noticesWithConsent };
};
/**
* Constructs the TCF notices served props based on the privacy experience.
* If the experience is minimal, it will use the minimal TCF fields directly
* which are already in the correct format.
*/
export const constructTCFNoticesServedProps = (
privacyExperience: PrivacyExperience | PrivacyExperienceMinimal,
): Partial<RecordConsentServedRequest> => {
if (!privacyExperience) {
return {};
}
if (!privacyExperience.minimal_tcf) {
const experience = privacyExperience as PrivacyExperience;
return {
tcf_purpose_consents: extractIds(experience.tcf_purpose_consents),
tcf_purpose_legitimate_interests: extractIds(
experience.tcf_purpose_legitimate_interests,
),
tcf_special_purposes: extractIds(experience.tcf_special_purposes),
tcf_vendor_consents: extractIds(experience.tcf_vendor_consents),
tcf_vendor_legitimate_interests: extractIds(
experience.tcf_vendor_legitimate_interests,
),
tcf_features: extractIds(experience.tcf_features),
tcf_special_features: extractIds(experience.tcf_special_features),
tcf_system_consents: extractIds(experience.tcf_system_consents),
tcf_system_legitimate_interests: extractIds(
experience.tcf_system_legitimate_interests,
),
};
}
const minExperience = privacyExperience as PrivacyExperienceMinimal;
return {
tcf_purpose_consents: minExperience.tcf_purpose_consent_ids ?? [],
tcf_purpose_legitimate_interests:
minExperience.tcf_purpose_legitimate_interest_ids ?? [],
tcf_special_purposes: minExperience.tcf_special_purpose_ids ?? [],
tcf_vendor_consents: minExperience.tcf_vendor_consent_ids ?? [],
tcf_vendor_legitimate_interests:
minExperience.tcf_vendor_legitimate_interest_ids ?? [],
tcf_features: minExperience.tcf_feature_ids ?? [],
tcf_special_features: minExperience.tcf_special_feature_ids ?? [],
tcf_system_consents: minExperience.tcf_system_consent_ids ?? [],
tcf_system_legitimate_interests:
minExperience.tcf_system_legitimate_interest_ids ?? [],
};
};
const resolveConsentValueFromTcfModel = (
model:
| TCFPurposeConsentRecord
| TCFPurposeLegitimateInterestsRecord
| TCFFeatureRecord
| TCFVendorConsentRecord
| TCFVendorLegitimateInterestsRecord,
) => {
if (model.current_preference) {
return transformUserPreferenceToBoolean(model.current_preference);
}
return transformUserPreferenceToBoolean(model.default_preference);
};
/**
* Retrieves the enabled IDs from the given TcfModels list. This is used to
* determine which IDs are currently enabled for the user to display in the UI.
*/
export const getEnabledIds = (modelList: TcfModels) => {
if (!modelList) {
return [];
}
return modelList
.map((model) => {
const value = resolveConsentValueFromTcfModel(model);
return { ...model, consentValue: value };
})
.filter((model) => model.consentValue)
.map((model) => `${model.id}`);
};
/**
* Retrieves the enabled IDs from the given Notice list. This is used to
* determine which IDs are currently enabled for the user to display in the UI.
*/
export const getEnabledIdsNotice = (
noticeList: PrivacyNoticeWithPreference[],
) => {
if (!noticeList) {
return [];
}
const parsedCookie: FidesCookie | undefined = getFidesConsentCookie();
const context = getConsentContext();
return noticeList
.map((notice) => {
const value = resolveConsentValue(notice, context, parsedCookie?.consent);
return { ...notice, consentValue: value };
})
.filter((notice) => notice.consentValue)
.map((notice) => `${notice.id}`);
};
const transformTcfModelToTcfSave = ({
modelList,
enabledIds,
}: {
modelList: TcfModels;
enabledIds: string[];
}): TcfSave[] | null => {
if (!modelList) {
return [];
}
return modelList.map((model) => {
const preference = transformConsentToFidesUserPreference(
enabledIds.includes(`${model.id}`),
);
return {
id: model.id,
preference,
};
}) as TcfSave[];
};
const transformTcfIdsToTcfSave = (enabledIds: string[]): TcfSave[] | null => {
if (!enabledIds?.length) {
return [];
}
return enabledIds.map((id) => {
const preference = transformConsentToFidesUserPreference(true);
let updatedId: string | number = id;
if (!Number.isNaN(parseInt(id, 10))) {
updatedId = parseInt(id, 10);
}
return {
id: updatedId,
preference,
};
}) as TcfSave[];
};
interface TcfSavePayloadProps<T> {
experience: T;
enabledIds: EnabledIds;
}
/**
* Creates a TCF save payload based on the user's enabled IDs.
*/
export const createTcfSavePayload = ({
experience,
enabledIds,
}: TcfSavePayloadProps<PrivacyExperience>): TcfSavePreferences => {
// Because systems were combined with vendors to make the UI easier to work with,
// we need to separate them out now (the backend treats them as separate entities).
const enabledConsentSystemIds: string[] = [];
const enabledConsentVendorIds: string[] = [];
const enabledLegintSystemIds: string[] = [];
const enabledLegintVendorIds: string[] = [];
enabledIds.vendorsConsent.forEach((id) => {
if (experience.tcf_system_consents?.map((s) => s.id).includes(id)) {
enabledConsentSystemIds.push(id);
} else {
enabledConsentVendorIds.push(id);
}
});
enabledIds.vendorsLegint.forEach((id) => {
if (
experience.tcf_system_legitimate_interests?.map((s) => s.id).includes(id)
) {
enabledLegintSystemIds.push(id);
} else {
enabledLegintVendorIds.push(id);
}
});
return {
purpose_consent_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_purpose_consents,
enabledIds: enabledIds.purposesConsent,
}) as TCFPurposeSave[],
purpose_legitimate_interests_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_purpose_legitimate_interests,
enabledIds: enabledIds.purposesLegint,
}) as TCFPurposeSave[],
special_feature_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_special_features,
enabledIds: enabledIds.specialFeatures,
}) as TCFSpecialFeatureSave[],
vendor_consent_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_vendor_consents,
enabledIds: enabledConsentVendorIds,
}) as TCFVendorSave[],
vendor_legitimate_interests_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_vendor_legitimate_interests,
enabledIds: enabledLegintVendorIds,
}) as TCFVendorSave[],
system_consent_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_system_consents,
enabledIds: enabledConsentSystemIds,
}) as TCFVendorSave[],
system_legitimate_interests_preferences: transformTcfModelToTcfSave({
modelList: experience.tcf_system_legitimate_interests,
enabledIds: enabledLegintSystemIds,
}) as TCFVendorSave[],
};
};
export const createTcfSavePayloadFromMinExp = ({
experience,
enabledIds,
}: TcfSavePayloadProps<PrivacyExperienceMinimal>) => {
// Because systems were combined with vendors to make the UI easier to work with,
// we need to separate them out now (the backend treats them as separate entities).
const enabledConsentSystemIds: string[] = [];
const enabledConsentVendorIds: string[] = [];
const enabledLegintSystemIds: string[] = [];
const enabledLegintVendorIds: string[] = [];
enabledIds.vendorsConsent.forEach((id) => {
if (experience.tcf_system_consent_ids?.includes(id)) {
enabledConsentSystemIds.push(id);
} else {
enabledConsentVendorIds.push(id);
}
});
enabledIds.vendorsLegint.forEach((id) => {
if (experience.tcf_system_legitimate_interest_ids?.includes(id)) {
enabledLegintSystemIds.push(id);
} else {
enabledLegintVendorIds.push(id);
}
});
return {
purpose_consent_preferences: transformTcfIdsToTcfSave(
enabledIds.purposesConsent,
) as TCFPurposeSave[],
purpose_legitimate_interests_preferences: transformTcfIdsToTcfSave(
enabledIds.purposesLegint,
) as TCFPurposeSave[],
special_feature_preferences: transformTcfIdsToTcfSave(
enabledIds.specialFeatures,
) as TCFSpecialFeatureSave[],
vendor_consent_preferences: transformTcfIdsToTcfSave(
enabledConsentVendorIds,
) as TCFVendorSave[],
vendor_legitimate_interests_preferences: transformTcfIdsToTcfSave(
enabledLegintVendorIds,
) as TCFVendorSave[],
system_consent_preferences: transformTcfIdsToTcfSave(
enabledConsentSystemIds,
) as TCFVendorSave[],
system_legitimate_interests_preferences: transformTcfIdsToTcfSave(
enabledLegintSystemIds,
) as TCFVendorSave[],
};
};
/**
* Updates the Fides cookie with the provided data.
*
* `tcf` and `enabledIds` should represent the same data, where `tcf` is what is
* sent to the backend, and `enabledIds` is what the FE uses. They have diverged
* because the backend has not implemented separate vendor legint/consents yet.
* Therefore, we need both entities right now, but eventually we should be able to
* only use one. In other words, `enabledIds` has a field for `vendorsConsent` and
* `vendorsLegint` but `tcf` only has `vendors`.
*
* @param oldCookie - The old Fides cookie.
* @param tcf - The TCF save preferences representing the data sent to the backend.
* @param enabledIds - The user's enabled IDs. This could include both TCF and custom enabled IDs
* @param experience - The full privacy experience.
* @param consentPreferencesToSave - Any Custom Notice preferences to save.
* @returns A promise that resolves to the updated Fides cookie.
*/
export const updateTCFCookie = async (
oldCookie: FidesCookie,
tcf: TcfSavePreferences,
enabledIds: EnabledIds,
experience: PrivacyExperience | PrivacyExperienceMinimal,
consentPreferencesToSave?: SaveConsentPreference[],
): Promise<FidesCookie> => {
const tcString = await generateFidesString({
tcStringPreferences: enabledIds,
experience,
});
const result = {
...oldCookie,
fides_string: tcString,
tcf_consent: transformTcfPreferencesToCookieKeys(tcf),
tcf_version_hash: experience.meta?.version_hash,
};
if (consentPreferencesToSave) {
result.consent = buildCookieConsentFromConsentPreferences(
consentPreferencesToSave,
);
}
return result;
};
/**
* Retrieves a combined list of GVL Purpose and Special Feature names
* based on the provided GVL translations and locale for use in the
* TCF banner. This list matches the names provided in the minimal TCF
* experience. Changes here should be replicated in the /privacy-experience
* endpoint for minimal_tcf and vice versa. The only difference is that
* the /privacy-experience endpoint sends the purpose types as separate
* arrays, while this function combines them into one. TCFOverlay.tsx combines
* the minimal_tcf experience into one list in a similar way.
*/
export const getGVLPurposeList = (gvlTranslations: Record<string, any>) => {
const purposeTypes = ["purposes", "specialFeatures"];
const GVLPurposeList: string[] = [];
purposeTypes.forEach((type) => {
const purpose = gvlTranslations[type] as GVLTranslationJson["purposes"];
Object.keys(purpose).forEach((key) => {
GVLPurposeList.push(purpose[key].name.trim());
});
});
return GVLPurposeList;
};
export const createTCFConsentPreferencesToSave = (
privacyNoticeList: PrivacyNoticeWithBestTranslation[],
enabledPrivacyNoticeIds: string[],
): SaveConsentPreference[] => {
if (!privacyNoticeList || !enabledPrivacyNoticeIds) {
return [];
}
return privacyNoticeList.map((item) => {
const userPreference = transformConsentToFidesUserPreference(
enabledPrivacyNoticeIds.includes(item.id),
item.consent_mechanism,
);
return new SaveConsentPreference(
item,
userPreference,
item.bestTranslation?.privacy_notice_history_id,
);
});
};