-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
consentManagementGpp.js
381 lines (342 loc) · 12.7 KB
/
consentManagementGpp.js
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
/**
* This module adds GPP consentManagement support to prebid.js. It interacts with
* supported CMPs (Consent Management Platforms) to grab the user's consent information
* and make it available for any GPP supported adapters to read/pass this information to
* their system and for various other features/modules in Prebid.js.
*/
import {deepSetValue, isEmpty, isNumber, isPlainObject, isStr, logError, logInfo, logWarn} from '../src/utils.js';
import {config} from '../src/config.js';
import {gppDataHandler} from '../src/adapterManager.js';
import {timedAuctionHook} from '../src/utils/perfMetrics.js';
import {enrichFPD} from '../src/fpd/enrichment.js';
import {getGlobal} from '../src/prebidGlobal.js';
import {cmpClient, MODE_CALLBACK} from '../libraries/cmp/cmpClient.js';
import {GreedyPromise} from '../src/utils/promise.js';
import {buildActivityParams} from '../src/activities/params.js';
const DEFAULT_CMP = 'iab';
const DEFAULT_CONSENT_TIMEOUT = 10000;
export let userCMP;
export let consentTimeout;
let staticConsentData;
let consentData;
let addedConsentHook = false;
function pipeCallbacks(fn, {onSuccess, onError}) {
new GreedyPromise((resolve) => resolve(fn())).then(onSuccess, (err) => {
if (err instanceof GPPError) {
onError(err.message, ...err.args);
} else {
onError(`GPP error:`, err);
}
});
}
function lookupStaticConsentData(callbacks) {
return pipeCallbacks(() => processCmpData(staticConsentData), callbacks);
}
class GPPError {
constructor(message, arg) {
this.message = message;
this.args = arg == null ? [] : [arg];
}
}
export class GPPClient {
apiVersion = '1.1';
static INST;
static get(mkCmp = cmpClient) {
if (this.INST == null) {
const cmp = mkCmp({
apiName: '__gpp',
apiArgs: ['command', 'callback', 'parameter'], // do not pass version - not clear what it's for (or what we should use),
mode: MODE_CALLBACK
});
if (cmp == null) {
throw new GPPError('GPP CMP not found');
}
this.INST = new this(cmp);
}
return this.INST;
}
#resolve;
#reject;
#pending = [];
initialized = false;
constructor(cmp) {
this.cmp = cmp;
[this.#resolve, this.#reject] = [0, 1].map(slot => (result) => {
while (this.#pending.length) {
this.#pending.pop()[slot](result);
}
});
}
/**
* initialize this client - update consent data if already available,
* and set up event listeners to also update on CMP changes
*
* @param pingData
* @returns {Promise<{}>} a promise to GPP consent data
*/
init(pingData) {
const ready = this.updateWhenReady(pingData);
if (!this.initialized) {
if (pingData.gppVersion !== this.apiVersion) {
logWarn(`Unrecognized GPP CMP version: ${pingData.apiVersion}. Continuing using GPP API version ${this.apiVersion}...`);
}
this.initialized = true;
this.cmp({
command: 'addEventListener',
callback: (event, success) => {
if (success != null && !success) {
this.#reject(new GPPError('Received error response from CMP', event));
} else if (event?.pingData?.cmpStatus === 'error') {
this.#reject(new GPPError('CMP status is "error"; please check CMP setup', event));
} else if (this.isCMPReady(event?.pingData || {}) && ['sectionChange', 'signalStatus'].includes(event?.eventName)) {
this.#resolve(this.updateConsent(event.pingData));
}
}
});
}
return ready;
}
refresh() {
return this.cmp({command: 'ping'}).then(this.init.bind(this));
}
/**
* Retrieve and store GPP consent data.
*
* @param pingData
* @returns {Promise<{}>} a promise to GPP consent data
*/
updateConsent(pingData) {
return new GreedyPromise(resolve => {
if (pingData == null || isEmpty(pingData)) {
throw new GPPError('Received empty response from CMP', pingData);
}
const consentData = processCmpData(pingData);
logInfo('Retrieved GPP consent from CMP:', consentData);
resolve(consentData);
})
}
/**
* Return a promise to GPP consent data, to be retrieved the next time the CMP signals it's ready.
*
* @returns {Promise<{}>}
*/
nextUpdate() {
return new GreedyPromise((resolve, reject) => {
this.#pending.push([resolve, reject]);
});
}
/**
* Return a promise to GPP consent data, to be retrieved immediately if the CMP is ready according to `pingData`,
* or as soon as it signals that it's ready otherwise.
*
* @param pingData
* @returns {Promise<{}>}
*/
updateWhenReady(pingData) {
return this.isCMPReady(pingData) ? this.updateConsent(pingData) : this.nextUpdate();
}
isCMPReady(pingData) {
return pingData.signalStatus === 'ready';
}
}
/**
* This function handles interacting with an IAB compliant CMP to obtain the consent information of the user.
* Given the async nature of the CMP's API, we pass in acting success/error callback functions to exit this function
* based on the appropriate result.
* @param {Object} options - An object containing the callbacks.
* @param {function(Object): void} options.onSuccess - Acts as a success callback when CMP returns a value; pass along consentObject from CMP.
* @param {function(string, ...Object?): void} options.onError - Acts as an error callback while interacting with CMP; pass along an error message (string) and any extra error arguments (purely for logging).
* @param {function(): Object} [mkCmp=cmpClient] - A function to create the CMP client. Defaults to `cmpClient`.
*/
export function lookupIabConsent({onSuccess, onError}, mkCmp = cmpClient) {
pipeCallbacks(() => GPPClient.get(mkCmp).refresh(), {onSuccess, onError});
}
// add new CMPs here, with their dedicated lookup function
const cmpCallMap = {
'iab': lookupIabConsent,
'static': lookupStaticConsentData
};
/**
* Look up consent data and store it in the `consentData` global as well as `adapterManager.js`' gdprDataHandler.
*
* @param cb A callback that takes: a boolean that is true if the auction should be canceled; an error message and extra
* error arguments that will be undefined if there's no error.
*/
function loadConsentData(cb) {
let isDone = false;
let timer = null;
function done(consentData, shouldCancelAuction, errMsg, ...extraArgs) {
if (timer != null) {
clearTimeout(timer);
}
isDone = true;
gppDataHandler.setConsentData(consentData);
if (typeof cb === 'function') {
cb(shouldCancelAuction, errMsg, ...extraArgs);
}
}
if (!cmpCallMap.hasOwnProperty(userCMP)) {
done(null, false, `GPP CMP framework (${userCMP}) is not a supported framework. Aborting consentManagement module and resuming auction.`);
return;
}
const callbacks = {
onSuccess: (data) => done(data, false),
onError: function (msg, ...extraArgs) {
done(null, true, msg, ...extraArgs);
}
};
cmpCallMap[userCMP](callbacks);
if (!isDone) {
const onTimeout = () => {
const continueToAuction = (data) => {
done(data, false, 'GPP CMP did not load, continuing auction...');
};
pipeCallbacks(() => processCmpData(consentData), {
onSuccess: continueToAuction,
onError: () => continueToAuction(storeConsentData())
});
};
if (consentTimeout === 0) {
onTimeout();
} else {
timer = setTimeout(onTimeout, consentTimeout);
}
}
}
/**
* Like `loadConsentData`, but cache and re-use previously loaded data.
* @param cb
*/
function loadIfMissing(cb) {
if (consentData) {
logInfo('User consent information already known. Pulling internally stored information...');
// eslint-disable-next-line standard/no-callback-literal
cb(false);
} else {
loadConsentData(cb);
}
}
/**
* If consentManagement module is enabled (ie included in setConfig), this hook function will attempt to fetch the
* user's encoded consent string from the supported CMP. Once obtained, the module will store this
* data as part of a gppConsent object which gets transferred to adapterManager's gppDataHandler object.
* This information is later added into the bidRequest object for any supported adapters to read/pass along to their system.
* @param {object} reqBidsConfigObj required; This is the same param that's used in pbjs.requestBids.
* @param {function} fn required; The next function in the chain, used by hook.js
*/
export const requestBidsHook = timedAuctionHook('gpp', function requestBidsHook(fn, reqBidsConfigObj) {
loadIfMissing(function (shouldCancelAuction, errMsg, ...extraArgs) {
if (errMsg) {
let log = logWarn;
if (shouldCancelAuction) {
log = logError;
errMsg = `${errMsg} Canceling auction as per consentManagement config.`;
}
log(errMsg, ...extraArgs);
}
if (shouldCancelAuction) {
fn.stopTiming();
if (typeof reqBidsConfigObj.bidsBackHandler === 'function') {
reqBidsConfigObj.bidsBackHandler();
} else {
logError('Error executing bidsBackHandler');
}
} else {
fn.call(this, reqBidsConfigObj);
}
});
});
function processCmpData(consentData) {
if (
(consentData?.applicableSections != null && !Array.isArray(consentData.applicableSections)) ||
(consentData?.gppString != null && !isStr(consentData.gppString)) ||
(consentData?.parsedSections != null && !isPlainObject(consentData.parsedSections))
) {
throw new GPPError('CMP returned unexpected value during lookup process.', consentData);
}
['usnatv1', 'uscav1'].forEach(section => {
if (consentData?.parsedSections?.[section]) {
logWarn(`Received invalid section from cmp: '${section}'. Some functionality may not work as expected`, consentData);
}
});
return storeConsentData(consentData);
}
/**
* Stores CMP data locally in module to make information available in adaptermanager.js for later in the auction
* @param {{}} gppData the result of calling a CMP's `getGPPData` (or equivalent)
*/
export function storeConsentData(gppData = {}) {
consentData = {
gppString: gppData?.gppString,
applicableSections: gppData?.applicableSections || [],
parsedSections: gppData?.parsedSections || {},
gppData: gppData
};
gppDataHandler.setConsentData(gppData);
return consentData;
}
/**
* Simply resets the module's consentData variable back to undefined, mainly for testing purposes
*/
export function resetConsentData() {
consentData = undefined;
userCMP = undefined;
consentTimeout = undefined;
gppDataHandler.reset();
GPPClient.INST = null;
}
/**
* A configuration function that initializes some module variables, as well as add a hook into the requestBids function
* @param {{cmp:string, timeout:number, defaultGdprScope:boolean}} config required; consentManagement module config settings; cmp (string), timeout (int))
*/
export function setConsentConfig(config) {
config = config && config.gpp;
if (!config || typeof config !== 'object') {
logWarn('consentManagement.gpp config not defined, exiting consent manager module');
return;
}
if (isStr(config.cmpApi)) {
userCMP = config.cmpApi;
} else {
userCMP = DEFAULT_CMP;
logInfo(`consentManagement.gpp config did not specify cmp. Using system default setting (${DEFAULT_CMP}).`);
}
if (isNumber(config.timeout)) {
consentTimeout = config.timeout;
} else {
consentTimeout = DEFAULT_CONSENT_TIMEOUT;
logInfo(`consentManagement.gpp config did not specify timeout. Using system default setting (${DEFAULT_CONSENT_TIMEOUT}).`);
}
if (userCMP === 'static') {
if (isPlainObject(config.consentData)) {
staticConsentData = config.consentData;
consentTimeout = 0;
} else {
logError(`consentManagement.gpp config with cmpApi: 'static' did not specify consentData. No consents will be available to adapters.`);
}
}
logInfo('consentManagement.gpp module has been activated...');
if (!addedConsentHook) {
getGlobal().requestBids.before(requestBidsHook, 50);
buildActivityParams.before((next, params) => {
return next(Object.assign({gppConsent: gppDataHandler.getConsentData()}, params));
});
}
addedConsentHook = true;
gppDataHandler.enable();
loadConsentData(); // immediately look up consent data to make it available without requiring an auction
}
config.getConfig('consentManagement', config => setConsentConfig(config.consentManagement));
export function enrichFPDHook(next, fpd) {
return next(fpd.then(ortb2 => {
const consent = gppDataHandler.getConsentData();
if (consent) {
if (Array.isArray(consent.applicableSections)) {
deepSetValue(ortb2, 'regs.gpp_sid', consent.applicableSections);
}
deepSetValue(ortb2, 'regs.gpp', consent.gppString);
}
return ortb2;
}));
}
enrichFPD.before(enrichFPDHook);