Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prebid core: add utility to retrieve user agent client hints #8826

Merged
merged 5 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions libraries/fpd/sua.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {isEmptyStr, isStr, isEmpty} from '../../src/utils.js';
import {GreedyPromise} from '../../src/utils/promise.js';

export const SUA_SOURCE_UNKNOWN = 0;
export const SUA_SOURCE_LOW_ENTROPY = 1;
export const SUA_SOURCE_HIGH_ENTROPY = 2;
export const SUA_SOURCE_UA_HEADER = 3;

// "high entropy" (i.e. privacy-sensitive) fields that can be requested from the navigator.
export const HIGH_ENTROPY_HINTS = [
'architecture',
'bitness',
'model',
'platformVersion',
'fullVersionList'
]

/**
* Returns low entropy UA client hints encoded as an ortb2.6 device.sua object; or null if no UA client hints are available.
*/
export const getLowEntropySUA = lowEntropySUAAccessor();

/**
* Returns a promise to high entropy UA client hints encoded as an ortb2.6 device.sua object, or null if no UA client hints are available.
*
* Note that the return value is a promise because the underlying browser API returns a promise; this
* seems to plan for additional controls (such as alerts / permission request prompts to the user); it's unclear
* at the moment if this means that asking for more hints would result in slower / more expensive calls.
*
* @param {Array[String]} hints hints to request, defaults to all (HIGH_ENTROPY_HINTS).
*/
export const getHighEntropySUA = highEntropySUAAccessor();

export function lowEntropySUAAccessor(uaData = window.navigator?.userAgentData) {
const sua = isEmpty(uaData) ? null : Object.freeze(uaDataToSUA(SUA_SOURCE_LOW_ENTROPY, uaData));
return function () {
return sua;
}
}

export function highEntropySUAAccessor(uaData = window.navigator?.userAgentData) {
const cache = {};
const keys = new WeakMap();
return function (hints = HIGH_ENTROPY_HINTS) {
if (!keys.has(hints)) {
const sorted = Array.from(hints);
sorted.sort();
keys.set(hints, sorted.join('|'));
}
const key = keys.get(hints);
if (!cache.hasOwnProperty(key)) {
try {
cache[key] = uaData.getHighEntropyValues(hints).then(result => {
return isEmpty(result) ? null : Object.freeze(uaDataToSUA(SUA_SOURCE_HIGH_ENTROPY, result))
}).catch(() => null);
} catch (e) {
cache[key] = GreedyPromise.resolve(null);
}
}
return cache[key];
}
}

/**
* Convert a User Agent client hints object to an ORTB 2.6 device.sua fragment
* https://iabtechlab.com/wp-content/uploads/2022/04/OpenRTB-2-6_FINAL.pdf
*
* @param source source of the UAData object (0 to 3)
* @param uaData https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/
* @return {{}}
*/
export function uaDataToSUA(source, uaData) {
function toBrandVersion(brand, version) {
const bv = {brand};
if (isStr(version) && !isEmptyStr(version)) {
bv.version = version.split('.');
}
return bv;
}

const sua = {source};
if (uaData.platform) {
sua.platform = toBrandVersion(uaData.platform, uaData.platformVersion);
}
if (uaData.fullVersionList || uaData.brands) {
sua.browsers = (uaData.fullVersionList || uaData.brands).map(({brand, version}) => toBrandVersion(brand, version));
}
if (uaData.hasOwnProperty('mobile')) {
sua.mobile = uaData.mobile ? 1 : 0;
}
['model', 'bitness', 'architecture'].forEach(prop => {
const value = uaData[prop];
if (isStr(value)) {
sua[prop] = value;
}
})
return sua;
}
47 changes: 33 additions & 14 deletions modules/enrichmentFpdModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ import { timestamp, mergeDeep } from '../src/utils.js';
import { submodule } from '../src/hook.js';
import {getRefererInfo, parseDomain} from '../src/refererDetection.js';
import { getCoreStorageManager } from '../src/storageManager.js';
import {GreedyPromise} from '../src/utils/promise.js';
import {getHighEntropySUA, getLowEntropySUA} from '../libraries/fpd/sua.js';

let ortb2 = {};
let ortb2;
let win = (window === window.top) ? window : window.top;
export const coreStorage = getCoreStorageManager('enrichmentFpd');

export const sua = {he: getHighEntropySUA, le: getLowEntropySUA};

/**
* Find the root domain
* @param {string|undefined} fullDomain
Expand Down Expand Up @@ -124,6 +128,17 @@ function setKeywords() {
if (keywords && keywords.content) mergeDeep(ortb2, { site: { keywords: keywords.content.replace(/\s/g, '') } });
}

function setDeviceSua(hints) {
let data = Array.isArray(hints) && hints.length === 0
? GreedyPromise.resolve(sua.le())
: sua.he(hints);
return data.then((sua) => {
if (sua != null) {
mergeDeep(ortb2, {device: {sua}});
}
})
}

/**
* Checks the Global Privacy Control status, and if exists and is true, merges into regs.ext.gpc
*/
Expand All @@ -137,30 +152,34 @@ function setGpc() {
/**
* Resets modules global ortb2 data
*/
const resetOrtb2 = () => { ortb2 = {} };
export const resetEnrichments = () => { ortb2 = null };

function runEnrichments() {
function runEnrichments(fpdConf) {
setReferer();
setPage();
setDomain();
setDimensions();
setKeywords();
setGpc();

return ortb2;
return setDeviceSua(fpdConf.uaHints).then(() => ortb2);
}

/**
* Sets default values to ortb2 if exists and adds currency and ortb2 setConfig callbacks on init
*/
export function processFpd(fpdConf, {global}) {
resetOrtb2();

return {
global: (!fpdConf.skipEnrichments) ? mergeDeep(runEnrichments(), global) : global
};
if (fpdConf.skipEnrichments) {
return {global};
} else {
let ready;
if (ortb2 == null) {
ortb2 = {};
ready = runEnrichments(fpdConf);
} else {
ready = GreedyPromise.resolve();
}
return ready.then(() => ({
global: mergeDeep({}, ortb2, global)
}))
}
}

/** @type {firstPartyDataSubmodule} */
export const enrichmentsSubmodule = {
name: 'enrichments',
Expand Down
Loading