forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
criteoBidAdapter.js
636 lines (546 loc) · 20.2 KB
/
criteoBidAdapter.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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import {deepAccess, deepSetValue, isArray, logError, logWarn, parseUrl} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js';
import {getStorageManager} from '../src/storageManager.js';
import {getRefererInfo} from '../src/refererDetection.js';
import {hasPurpose1Consent} from '../src/utils/gdpr.js';
import {Renderer} from '../src/Renderer.js';
import {OUTSTREAM} from '../src/video.js';
import {ajax} from '../src/ajax.js';
import {ortbConverter} from '../libraries/ortbConverter/converter.js';
import {ortb25Translator} from '../libraries/ortb2.5Translator/translator.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
* @typedef {import('../src/adapters/bidderFactory.js').Bid} Bid
* @typedef {import('../src/adapters/bidderFactory.js').ServerRequest} ServerRequest
* @typedef {import('../src/adapters/bidderFactory.js').BidderSpec} BidderSpec
* @typedef {import('../src/adapters/bidderFactory.js').TimedOutBid} TimedOutBid
*/
const GVLID = 91;
export const ADAPTER_VERSION = 37;
const BIDDER_CODE = 'criteo';
const CDB_ENDPOINT = 'https://grid-bidder.criteo.com/openrtb_2_5/pbjs/auction/request';
const PROFILE_ID_INLINE = 207;
export const storage = getStorageManager({ bidderCode: BIDDER_CODE });
const LOG_PREFIX = 'Criteo: ';
const TRANSLATOR = ortb25Translator();
const PUBLISHER_TAG_OUTSTREAM_SRC = 'https://static.criteo.net/js/ld/publishertag.renderer.js'
const OPTOUT_COOKIE_NAME = 'cto_optout';
const BUNDLE_COOKIE_NAME = 'cto_bundle';
const GUID_RETENTION_TIME_HOUR = 24 * 30 * 13; // 13 months
const OPTOUT_RETENTION_TIME_HOUR = 5 * 12 * 30 * 24; // 5 years
/**
* Defines the generic oRTB converter and all customization functions.
*/
const CONVERTER = ortbConverter({
context: {
netRevenue: true,
ttl: 60
},
imp,
request,
bidResponse,
response
});
/**
* Builds an impression object for the ORTB 2.5 request.
*
* @param {function} buildImp - The function for building an imp object.
* @param {Object} bidRequest - The bid request object.
* @param {Object} context - The context object.
* @returns {Object} The ORTB 2.5 imp object.
*/
function imp(buildImp, bidRequest, context) {
let imp = buildImp(bidRequest, context);
const params = bidRequest.params;
imp.tagid = bidRequest.adUnitCode;
deepSetValue(imp, 'ext', {
...bidRequest.params.ext,
...imp.ext,
rwdd: imp.rwdd,
floors: getFloors(bidRequest),
bidder: {
publishersubid: params?.publisherSubId,
zoneid: params?.zoneId,
uid: params?.uid,
},
});
delete imp.rwdd // oRTB 2.6 field moved to ext
if (!context.fledgeEnabled && imp.ext.igs?.ae) {
delete imp.ext.igs.ae;
}
if (hasVideoMediaType(bidRequest)) {
const paramsVideo = bidRequest.params.video;
if (paramsVideo !== undefined) {
deepSetValue(imp, 'video', {
...imp.video,
skip: imp.video.skip || paramsVideo.skip || 0,
placement: imp.video.placement || paramsVideo.placement,
minduration: imp.video.minduration || paramsVideo.minduration,
playbackmethod: imp.video.playbackmethod || paramsVideo.playbackmethod,
startdelay: imp.video.startdelay || paramsVideo.startdelay || 0,
})
}
deepSetValue(imp, 'video.ext', {
context: bidRequest.mediaTypes.video.context,
playersizes: parseSizes(deepAccess(bidRequest, 'mediaTypes.video.playerSize'), parseSize),
plcmt: bidRequest.mediaTypes.video.plcmt,
poddur: bidRequest.mediaTypes.video.adPodDurationSec,
rqddurs: bidRequest.mediaTypes.video.durationRangeSec,
})
}
if (imp.native && typeof imp.native.request !== 'undefined') {
let requestNative = JSON.parse(imp.native.request);
// We remove the native asset requirements if we used the bypass to generate the imp
const hasAssetRequirements = requestNative.assets &&
(requestNative.assets.length !== 1 || Object.keys(requestNative.assets[0]).length);
if (!hasAssetRequirements) {
delete requestNative.assets;
}
deepSetValue(imp, 'native.request_native', requestNative);
delete imp.native.request;
}
return imp;
}
/**
* Builds a request object for the ORTB 2.5 request.
*
* @param {function} buildRequest - The function for building a request object.
* @param {Array} imps - An array of ORTB 2.5 impression objects.
* @param {Object} bidderRequest - The bidder request object.
* @param {Object} context - The context object.
* @returns {Object} The ORTB 2.5 request object.
*/
function request(buildRequest, imps, bidderRequest, context) {
let request = buildRequest(imps, bidderRequest, context);
// params.pubid should override publisher id
if (typeof context.publisherId !== 'undefined') {
if (typeof request.app !== 'undefined') {
deepSetValue(request, 'app.publisher.id', context.publisherId);
} else {
deepSetValue(request, 'site.publisher.id', context.publisherId);
}
}
if (bidderRequest && bidderRequest.gdprConsent) {
deepSetValue(request, 'regs.ext.gdprversion', bidderRequest.gdprConsent.apiVersion);
}
// Translate 2.6 OpenRTB request into 2.5 OpenRTB request
request = TRANSLATOR(request);
return request;
}
/**
* Build bid from oRTB 2.5 bid.
*
* @param buildBidResponse
* @param bid
* @param context
* @returns {*}
*/
function bidResponse(buildBidResponse, bid, context) {
context.mediaType = deepAccess(bid, 'ext.mediatype');
if (context.mediaType === NATIVE && typeof bid.adm_native !== 'undefined') {
bid.adm = bid.adm_native;
delete bid.adm_native;
}
let bidResponse = buildBidResponse(bid, context);
const {bidRequest} = context;
bidResponse.currency = deepAccess(bid, 'ext.cur')
if (typeof deepAccess(bid, 'ext.meta') !== 'undefined') {
deepSetValue(bidResponse, 'meta', {
...bidResponse.meta,
...bid.ext.meta
});
}
if (typeof deepAccess(bid, 'ext.paf.content_id') !== 'undefined') {
deepSetValue(bidResponse, 'meta.paf.content_id', bid.ext.paf.content_id)
}
if (bidResponse.mediaType === VIDEO) {
bidResponse.vastUrl = bid.ext?.displayurl;
// if outstream video, add a default render for it.
if (deepAccess(bidRequest, 'mediaTypes.video.context') === OUTSTREAM) {
bidResponse.renderer = createOutstreamVideoRenderer(bid);
}
}
return bidResponse;
}
/**
* Builds bid response from the oRTB 2.5 bid response.
*
* @param buildResponse
* @param bidResponses
* @param ortbResponse
* @param context
* @returns *
*/
function response(buildResponse, bidResponses, ortbResponse, context) {
let response = buildResponse(bidResponses, ortbResponse, context);
const pafTransmission = deepAccess(ortbResponse, 'ext.paf.transmission');
response.bids.forEach(bid => {
if (typeof pafTransmission !== 'undefined' && typeof deepAccess(bid, 'meta.paf.content_id') !== 'undefined') {
deepSetValue(bid, 'meta.paf.transmission', pafTransmission);
} else {
delete bid.meta.paf;
}
});
return response;
}
/** @type {BidderSpec} */
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
getUserSyncs: function (syncOptions, _, gdprConsent, uspConsent, gppConsent = {}) {
let { gppString = '', applicableSections = [] } = gppConsent;
const refererInfo = getRefererInfo();
const origin = 'criteoPrebidAdapter';
if (syncOptions.iframeEnabled && hasPurpose1Consent(gdprConsent)) {
const queryParams = [];
queryParams.push(`origin=${origin}`);
queryParams.push(`topUrl=${refererInfo.domain}`);
if (gdprConsent) {
if (gdprConsent.gdprApplies) {
queryParams.push(`gdpr=${gdprConsent.gdprApplies == true ? 1 : 0}`);
}
if (gdprConsent.consentString) {
queryParams.push(`gdpr_consent=${gdprConsent.consentString}`);
}
}
if (uspConsent) {
queryParams.push(`us_privacy=${uspConsent}`);
}
queryParams.push(`gpp=${gppString}`);
if (Array.isArray(applicableSections)) {
for (const applicableSection of applicableSections) {
queryParams.push(`gpp_sid=${applicableSection}`);
}
}
const requestId = Math.random().toString();
const jsonHash = {
bundle: readFromAllStorages(BUNDLE_COOKIE_NAME),
cw: storage.cookiesAreEnabled(),
lsw: storage.localStorageIsEnabled(),
optoutCookie: readFromAllStorages(OPTOUT_COOKIE_NAME),
origin: origin,
requestId: requestId,
tld: refererInfo.domain,
topUrl: refererInfo.domain,
version: '$prebid.version$'.replace(/\./g, '_'),
};
window.addEventListener('message', function handler(event) {
if (!event.data || event.origin != 'https://gum.criteo.com') {
return;
}
if (event.data.requestId !== requestId) {
return;
}
this.removeEventListener('message', handler);
event.stopImmediatePropagation();
const response = event.data;
if (response.optout) {
deleteFromAllStorages(BUNDLE_COOKIE_NAME);
saveOnAllStorages(OPTOUT_COOKIE_NAME, true, OPTOUT_RETENTION_TIME_HOUR);
} else {
if (response.bundle) {
saveOnAllStorages(BUNDLE_COOKIE_NAME, response.bundle, GUID_RETENTION_TIME_HOUR);
}
}
}, true);
const jsonHashSerialized = JSON.stringify(jsonHash).replace(/"/g, '%22');
return [{
type: 'iframe',
url: `https://gum.criteo.com/syncframe?${queryParams.join('&')}#${jsonHashSerialized}`
}];
} else if (syncOptions.pixelEnabled && hasPurpose1Consent(gdprConsent)) {
const queryParams = [];
queryParams.push(`profile=207`);
if (gdprConsent) {
if (gdprConsent.gdprApplies === true) {
queryParams.push(`gdprapplies=true`);
}
if (gdprConsent.consentString) {
queryParams.push(`gdpr=${gdprConsent.consentString}`);
}
}
if (uspConsent) {
queryParams.push(`ccpa=${uspConsent}`);
}
queryParams.push(`gpp=${gppString}`);
if (Array.isArray(applicableSections)) {
for (const applicableSection of applicableSections) {
queryParams.push(`gpp_sid=${applicableSection}`);
}
}
// gpp
// gpp_sid
return [{
type: 'image',
url: `https://ssp-sync.criteo.com/user-sync/redirect?${queryParams.join('&')}`
}];
}
return [];
},
/**
* f
* @param {object} bid
* @return {boolean}
*/
isBidRequestValid: (bid) => {
// either one of zoneId or networkId should be set
if (!(bid && bid.params && (bid.params.zoneId || bid.params.networkId))) {
return false;
}
// video media types requires some mandatory params
if (hasVideoMediaType(bid)) {
if (!hasValidVideoMediaType(bid)) {
return false;
}
}
return true;
},
/**
* @param {BidRequest[]} bidRequests
* @param {*} bidderRequest
* @return {ServerRequest}
*/
buildRequests: (bidRequests, bidderRequest) => {
bidRequests.forEach(bidRequest => {
if (hasNativeMediaType(bidRequest)) {
if (!checkNativeSendId(bidRequest)) {
logWarn(LOG_PREFIX + 'all native assets containing URL should be sent as placeholders with sendId(icon, image, clickUrl, displayUrl, privacyLink, privacyIcon)');
}
// We support native request without assets requirements because we can fill them later on.
// This is a trick to fool oRTB converter isOpenRTBBidRequestValid(ortb) fn because it needs
// nativeOrtbRequest.assets to be non-empty.
if (deepAccess(bidRequest, 'nativeOrtbRequest.assets') == null) {
logWarn(LOG_PREFIX + 'native asset requirements are missing');
deepSetValue(bidRequest, 'nativeOrtbRequest.assets', [{}]);
}
}
});
const context = buildContext(bidRequests, bidderRequest);
const url = buildCdbUrl(context);
const data = CONVERTER.toORTB({bidderRequest, bidRequests, context});
if (data) {
return { method: 'POST', url, data, bidRequests };
}
},
/**
* @param {*} response
* @param {ServerRequest} request
* @return {Bid[] | {bids: Bid[], fledgeAuctionConfigs: object[]}}
*/
interpretResponse: (response, request) => {
if (typeof response?.body == 'undefined') {
return []; // no bid
}
const interpretedResponse = CONVERTER.fromORTB({response: response.body, request: request.data});
const bids = interpretedResponse.bids || [];
const fledgeAuctionConfigs = deepAccess(response.body, 'ext.igi')?.filter(igi => isArray(igi?.igs))
.flatMap(igi => igi.igs);
if (fledgeAuctionConfigs?.length) {
return {
bids,
paapi: fledgeAuctionConfigs,
};
}
return bids;
},
/**
* @param {BidRequest[]} bidRequests
*/
onDataDeletionRequest: (bidRequests) => {
const id = readFromAllStorages(BUNDLE_COOKIE_NAME);
if (id) {
deleteFromAllStorages(BUNDLE_COOKIE_NAME);
ajax('https://privacy.criteo.com/api/privacy/datadeletionrequest',
null,
JSON.stringify({ publisherUserId: id }),
{
contentType: 'application/json',
method: 'POST'
});
}
}
};
function readFromAllStorages(name) {
const fromCookie = storage.getCookie(name);
const fromLocalStorage = storage.getDataFromLocalStorage(name);
return fromCookie || fromLocalStorage || undefined;
}
function saveOnAllStorages(name, value, expirationTimeHours) {
const date = new Date();
date.setTime(date.getTime() + (expirationTimeHours * 60 * 60 * 1000));
const expires = `expires=${date.toUTCString()}`;
storage.setCookie(name, value, expires);
storage.setDataInLocalStorage(name, value);
}
function deleteFromAllStorages(name) {
storage.setCookie(name, '', 0);
storage.removeDataFromLocalStorage(name);
}
/**
* @param {BidRequest[]} bidRequests
* @param bidderRequest
*/
function buildContext(bidRequests, bidderRequest) {
const queryString = parseUrl(bidderRequest?.refererInfo?.topmostLocation).search;
return {
url: bidderRequest?.refererInfo?.page || '',
debug: queryString['pbt_debug'] === '1',
noLog: queryString['pbt_nolog'] === '1',
fledgeEnabled: bidderRequest.paapi?.enabled,
amp: bidRequests.some(bidRequest => bidRequest.params.integrationMode === 'amp'),
networkId: bidRequests.find(bidRequest => bidRequest.params?.networkId)?.params.networkId,
publisherId: bidRequests.find(bidRequest => bidRequest.params?.pubid)?.params.pubid,
};
}
/**
* @param {Object} context
* @return {string}
*/
function buildCdbUrl(context) {
let url = CDB_ENDPOINT;
url += '?profileId=' + PROFILE_ID_INLINE;
url += '&av=' + String(ADAPTER_VERSION);
url += '&wv=' + encodeURIComponent('$prebid.version$');
url += '&cb=' + String(Math.floor(Math.random() * 99999999999));
if (storage.localStorageIsEnabled()) {
url += '&lsavail=1';
} else {
url += '&lsavail=0';
}
if (context.amp) {
url += '&im=1';
}
if (context.debug) {
url += '&debug=1';
}
if (context.noLog) {
url += '&nolog=1';
}
const bundle = readFromAllStorages(BUNDLE_COOKIE_NAME);
if (bundle) {
url += `&bundle=${bundle}`;
}
const optout = readFromAllStorages(OPTOUT_COOKIE_NAME);
if (optout) {
url += `&optout=1`;
}
if (context.networkId) {
url += `&networkId=` + context.networkId;
}
return url;
}
function checkNativeSendId(bidRequest) {
return !(bidRequest.nativeParams &&
(
(bidRequest.nativeParams.image && ((bidRequest.nativeParams.image.sendId !== true || bidRequest.nativeParams.image.sendTargetingKeys === true))) ||
(bidRequest.nativeParams.icon && ((bidRequest.nativeParams.icon.sendId !== true || bidRequest.nativeParams.icon.sendTargetingKeys === true))) ||
(bidRequest.nativeParams.clickUrl && ((bidRequest.nativeParams.clickUrl.sendId !== true || bidRequest.nativeParams.clickUrl.sendTargetingKeys === true))) ||
(bidRequest.nativeParams.displayUrl && ((bidRequest.nativeParams.displayUrl.sendId !== true || bidRequest.nativeParams.displayUrl.sendTargetingKeys === true))) ||
(bidRequest.nativeParams.privacyLink && ((bidRequest.nativeParams.privacyLink.sendId !== true || bidRequest.nativeParams.privacyLink.sendTargetingKeys === true))) ||
(bidRequest.nativeParams.privacyIcon && ((bidRequest.nativeParams.privacyIcon.sendId !== true || bidRequest.nativeParams.privacyIcon.sendTargetingKeys === true)))
));
}
function parseSizes(sizes, parser = s => s) {
if (sizes == undefined) {
return [];
}
if (Array.isArray(sizes[0])) { // is there several sizes ? (ie. [[728,90],[200,300]])
return sizes.map(size => parser(size));
}
return [parser(sizes)]; // or a single one ? (ie. [728,90])
}
function parseSize(size) {
return size[0] + 'x' + size[1];
}
function hasVideoMediaType(bidRequest) {
return deepAccess(bidRequest, 'mediaTypes.video') !== undefined;
}
function hasNativeMediaType(bidRequest) {
return deepAccess(bidRequest, 'mediaTypes.native') !== undefined;
}
function hasValidVideoMediaType(bidRequest) {
let isValid = true;
var requiredMediaTypesParams = ['mimes', 'playerSize', 'maxduration', 'protocols', 'api', 'skip', 'placement', 'playbackmethod'];
requiredMediaTypesParams.forEach(function (param) {
if (param === 'placement') {
if (deepAccess(bidRequest, 'mediaTypes.video.' + param) === undefined && deepAccess(bidRequest, 'params.video.' + param) === undefined && deepAccess(bidRequest, 'mediaTypes.video.plcmt') === undefined && deepAccess(bidRequest, 'params.video.plcmt') === undefined) {
isValid = false;
logError('Criteo Bid Adapter: mediaTypes.video.' + param + ' or mediaTypes.video.plcmt is required');
}
} else {
if (deepAccess(bidRequest, 'mediaTypes.video.' + param) === undefined && deepAccess(bidRequest, 'params.video.' + param) === undefined) {
isValid = false;
logError('Criteo Bid Adapter: mediaTypes.video.' + param + ' is required');
}
}
});
return isValid;
}
function pickAvailableGetFloorFunc(bidRequest) {
if (bidRequest.getFloor) {
return bidRequest.getFloor;
}
if (bidRequest.params.bidFloor && bidRequest.params.bidFloorCur) {
try {
const floor = parseFloat(bidRequest.params.bidFloor);
return () => {
return {
currency: bidRequest.params.bidFloorCur,
floor: floor
};
};
} catch { }
}
return undefined;
}
function getFloors(bidRequest) {
try {
const floors = {};
const getFloor = pickAvailableGetFloorFunc(bidRequest);
if (getFloor) {
if (bidRequest.mediaTypes?.banner) {
floors.banner = {};
const bannerSizes = parseSizes(deepAccess(bidRequest, 'mediaTypes.banner.sizes'))
bannerSizes.forEach(bannerSize => floors.banner[parseSize(bannerSize).toString()] = getFloor.call(bidRequest, { size: bannerSize, mediaType: BANNER }));
}
if (bidRequest.mediaTypes?.video) {
floors.video = {};
const videoSizes = parseSizes(deepAccess(bidRequest, 'mediaTypes.video.playerSize'))
videoSizes.forEach(videoSize => floors.video[parseSize(videoSize).toString()] = getFloor.call(bidRequest, { size: videoSize, mediaType: VIDEO }));
}
if (bidRequest.mediaTypes?.native) {
floors.native = {};
floors.native['*'] = getFloor.call(bidRequest, { size: '*', mediaType: NATIVE });
}
return floors;
}
} catch (e) {
logError('Could not parse floors from Prebid: ' + e);
}
}
function createOutstreamVideoRenderer(bid) {
if (bid.ext?.videoPlayerConfig === undefined || bid.ext?.videoPlayerType === undefined) {
return undefined;
}
const config = {
documentResolver: (_, sourceDocument, renderDocument) => {
return renderDocument ?? sourceDocument;
}
}
const render = (_, renderDocument) => {
let payload = {
slotid: bid.id,
vastUrl: bid.ext?.displayurl,
vastXml: bid.adm,
documentContext: renderDocument,
};
let outstreamConfig = bid.ext.videoPlayerConfig;
window.CriteoOutStream[bid.ext.videoPlayerType].play(payload, outstreamConfig)
};
const renderer = Renderer.install({ url: PUBLISHER_TAG_OUTSTREAM_SRC, config: config });
renderer.setRender(render);
return renderer;
}
registerBidder(spec);