@sumsub/fisherman
Version:
The Sumsub Fisherman is a powerful tool that helps developers integrate fraud detection capabilities into their applications. With Fisherman, you can easily identify and prevent fraudulent activities within your system, providing a safer and more secure e
904 lines (903 loc) • 27.1 kB
JavaScript
import C from "fingerprintjs2";
import $e from "detectincognitojs";
function pe() {
return Date.now();
}
function Ke() {
return (/* @__PURE__ */ new Date()).toISOString();
}
const Ve = "crypto" in window && "randomUUID" in window.crypto;
function je() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
const t = Math.random() * 16 | 0;
return (e === "x" ? t : t & 3 | 8).toString(16);
});
}
function Ge() {
return Ve ? crypto.randomUUID() : je();
}
const He = {
type: "InvalidToken",
message: "Token is invalid, make sure you generate a new one each time, because the old ones are invalidated upon usage"
}, ge = {
type: "NoToken",
message: "Authentication token is required to send requests"
}, Ce = {
type: "UpdateTokenRetriesLimitReached",
message: "Token renewal failed after multiple attempts (limit reached). Request aborted to prevent infinite retry loop."
}, We = {
type: "NetworkError",
message: "Failed to connect to the server. Possible network or CORS configuration issue."
}, le = {
type: "FpDisabled",
message: "You are trying to use FP, which is not enabled for you."
}, Xe = {
type: "FpClientTimeout",
message: "Device visitorId calc timeout"
}, Ye = {
type: "FpRateLimit",
message: "FP request rate limit is exceeded"
}, V = 0;
async function W({ payload: e, token: t, url: n, onload: i }) {
try {
const r = await fetch(n, {
method: "POST",
body: JSON.stringify(e),
headers: {
"Content-Type": "application/json",
"X-Client-Id": "fisherman",
...t ? { "X-Access-Token": t } : {}
}
});
return i(r.status, e), r.status;
} catch {
return i(V, e), V;
}
}
const Je = 2e3, ze = 3, Qe = atob("aHR0cHM6Ly9jb2NrcGl0LnN1bXN1Yi5jb20="), Ze = Math.random().toString(36).substring(0, 8), ve = `/resources/bhv/evts/${Ze}`, Ee = "/resources/di/req";
let R, Y, Re, O, m, K, j, ne = ve, re = Ee, L = 0, ie = "info";
function et(e) {
R = e, q(R.token);
}
function tt(e) {
e && (ne = e);
}
function nt(e) {
e && (re = e);
}
function rt(e) {
ie = e ?? "info";
}
function it() {
ye(), Re = void 0, q(void 0), Y = void 0, ne = ve, re = Ee, L = 0, K = !1, ie = "info";
}
async function B(e, t) {
return await at(
ot(
e,
{
fpRequestId: t == null ? void 0 : t.fpRequestId,
fpVisitorId: t == null ? void 0 : t.fpVisitorId,
fpSimulation: t == null ? void 0 : t.fpSimulation
},
t == null ? void 0 : t.behavioralDataEnabled
)
);
}
function ot(e, t = {}, n = !0) {
e.capturedAt = Ke();
const i = Ge(), r = "deviceFingerprint" in e || !n, o = {
id: i,
predecessorEventId: Y,
deviceSessionId: Re,
...t,
[r ? "initData" : "interactionData"]: e
};
return Y = i, o;
}
async function at(e, t) {
m === void 0 && (m = []), !K && e.initData ? (K = !0, m.unshift(e)) : m.push(e), K && (j || (j = setTimeout(ct, Je)));
}
function ye() {
clearTimeout(j), m = void 0, j = void 0;
}
async function ct() {
if (m != null && m.length && O) {
const e = [...m];
ye(), await we(e);
}
}
function M() {
return R.baseUrl !== void 0 ? R.baseUrl : Qe;
}
async function st() {
if (R.accessTokenUpdateHandler) {
const e = await R.accessTokenUpdateHandler();
q(e);
}
}
async function we(e) {
O ? await W({
payload: e,
token: O,
url: `${M()}${ne}`,
onload: (t, n) => he(t, () => we(n))
}) : v(ge);
}
async function G(e) {
O ? await W({
payload: e,
token: O,
url: `${M()}${re}`,
onload: (t, n) => he(t, () => G(n))
}) : v(ge);
}
async function he(e, t) {
if (e === 401 || e === V) {
let n = L >= ze;
!n && R.accessTokenUpdateHandler ? (L++, S("TokenRefreshRetry", `attempt=${L}`), await st(), await t()) : q(void 0);
let i;
e === V ? i = We : n ? i = Ce : i = He, v(i);
} else e === 200 && (L = 0);
}
function S(e, t) {
ie !== "debug" || !R || R.disabledErrorLogging || W({
payload: { errorType: "fishermanDebug", errorName: e, message: t },
token: O,
url: `${M()}/resources/serviceLogger/warn`,
onload: () => {
}
});
}
function v(e) {
const t = {
errorType: "fishermanError",
errorName: e.type,
message: e.message
};
R.disabledErrorLogging || W({
payload: t,
token: O,
url: `${M()}/resources/serviceLogger/warn`,
onload: () => {
}
}), R.onError && R.onError(e);
}
function q(e) {
O = e;
}
const me = "focus";
let P, J = 0;
function ut() {
P = () => {
J++, B({
event: "focus",
count: J
});
}, window.addEventListener(me, P);
}
function lt() {
P && (window.removeEventListener(me, P), P = void 0), J = 0;
}
function dt(e) {
if (e.target instanceof Element) {
const t = e.target, n = t.getAttribute("type"), i = n ? `[${n}]` : "", r = t.id ? `#${t.id}` : "";
return `${t.tagName}${i}${r}`;
}
}
const ft = [
// Modifier keys
"Alt",
"Control",
"Meta",
"Shift",
// Whitespace keys
"Enter",
"Tab",
// Navigation keys
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"End",
"Home",
// Editing keys
"Backspace",
"Delete",
// UI keys
"Escape"
];
function pt(e) {
if (ft.includes(e))
return e;
}
function Ie(e) {
return e instanceof Element;
}
const gt = typeof window.WeakMap == "function", A = gt ? /* @__PURE__ */ new WeakMap() : void 0;
function vt(e) {
return A == null ? void 0 : A.get(e);
}
function Et(e, t) {
A == null || A.set(e, t);
}
const Rt = ["type", "autocomplete", "autofocus", "placeholder", "aria-label"];
function yt(e) {
const t = e.parentNode, n = e.tagName;
if (t) {
const i = Array.from(t.childNodes).filter(
(r) => Ie(r) && n === r.tagName
);
if (i.length > 1) {
const r = i.indexOf(e);
if (r > -1)
return `:nth-of-type(${r + 1})`;
}
}
return "";
}
function wt(e) {
const t = e.id ? `#${e.id}` : "", n = yt(e), i = Rt.map((r) => {
if (e.hasAttribute(r)) {
const o = e.getAttribute(r);
return `[${o ? `${r}="${o}"` : r}]`;
}
}).filter(Boolean).join("");
return (
// INPUT
e.tagName + // #id
t + // :nth-of-type(2)
n + // [type="email"][autocomplete="email"][autofocus][aria-label="Email or username"]
i
);
}
function ht(e) {
const t = [e];
let n = e;
for (; n.parentElement; ) {
const r = n.parentElement;
t.push(r), n = r;
}
const i = t.reverse().map(wt).join(" > ");
return C.x64hash128(i, 31);
}
function mt(e) {
if (Ie(e.target)) {
const t = e.target;
let n = vt(t);
return n || (n = ht(t), Et(t, n)), n;
}
}
const Oe = ["keydown", "keyup"], Te = ["mousemove", "mousedown"], be = ["paste", "focusin", "change", ...Te, ...Oe];
let y, w;
function _e() {
y = /* @__PURE__ */ new Map(), w = [];
}
function It(e) {
let t;
return e.type === "change" && (w && (w == null ? void 0 : w.length) > 0 && (t = w), _e()), t;
}
function Ot({ key: e }) {
y && y.get(e) === void 0 && y.set(e, pe());
}
function Tt({ key: e }) {
const t = y == null ? void 0 : y.get(e);
if (y && t) {
w === void 0 && (w = []), y.delete(e);
const n = { start: t, end: pe() }, i = pt(e);
i && (n.key = i), w.push(n);
}
}
function oe(e) {
const t = e.type;
if (t === "keydown" ? Ot(e) : t === "keyup" && Tt(e), !Oe.includes(t)) {
const n = {
event: t,
trusted: e.isTrusted,
el: dt(e),
elUid: mt(e),
cadence: It(e)
};
B(n);
}
Te.includes(t) && document.removeEventListener(t, oe);
}
function bt() {
_e(), be.forEach((e) => document.addEventListener(e, oe));
}
function _t() {
be.forEach((e) => document.removeEventListener(e, oe)), y = void 0, w = void 0;
}
const Se = "deviceorientation";
let D;
function St(e) {
const t = e.alpha !== null ? e.alpha : 0, n = e.beta !== null ? e.beta : 0, i = e.gamma !== null ? e.gamma : 0, r = Math.abs(n) > Math.abs(i) ? "portrait" : "landscape";
return {
alpha: t,
beta: n,
gamma: i,
orientation: r
};
}
async function Nt() {
if (!D) {
const e = "DeviceOrientationEvent" in window;
return e && (D = (t) => {
B({
event: "orientation",
orientation: St(t)
}), Ne();
}, window.addEventListener(Se, D)), {
supported: e
};
}
}
function Ne() {
D && (window.removeEventListener(Se, D), D = void 0);
}
const At = "not available", Dt = [
"userAgent",
"webdriver",
"language",
"colorDepth",
"deviceMemory",
"pixelRatio",
"hardwareConcurrency",
"timezoneOffset",
"timezone",
"sessionStorage",
"localStorage",
"indexedDb",
"openDatabase",
"platform",
"doNotTrack",
"plugins",
"canvas",
"webgl",
"webglVendorAndRenderer",
"adBlock",
"hasLiedOs",
"hasLiedBrowser",
"touchSupport",
"fonts",
"audio"
], z = 200, Ut = (e, t) => {
switch (e) {
case "touchSupport":
return Ft(t);
case "plugins":
return xt(t);
case "webgl":
case "canvas":
return kt(t);
default:
return Lt(t);
}
}, Lt = (e) => typeof e == "string" ? Ae(e) : Array.isArray(e) ? Pt(e) : e, Ae = (e) => e.length > z ? De(e) : e, Pt = (e) => ((e == null ? void 0 : e.length) > z && e.splice(0, z), e.map((t) => typeof t == "string" ? Ae(t) : t)), xt = (e) => {
if (Array.isArray(e) && e.length > 0)
return e.map((t) => Array.isArray(t) ? t[0] : "");
}, Ft = (e) => {
if ((e == null ? void 0 : e.length) === 3)
try {
return {
maxTouchPoints: Number(e[0]),
touchEvent: !!e[1],
touchStart: !!e[2]
};
} catch {
return;
}
}, De = (e) => C.x64hash128(e, 31), kt = (e) => {
if (e)
return De(e.toString());
}, Bt = 500;
async function de(e) {
const t = await qt(), n = [];
t.forEach(({ key: i, value: r }) => {
if (n.push(r), Dt.includes(i) && r !== At) {
const o = Ut(i, r);
o !== void 0 && (e[i] = o);
}
}), e.deviceFingerprint = C.x64hash128(n.join(""), 31);
}
async function Mt(e) {
return new Promise((t, n) => {
typeof window.requestIdleCallback == "function" ? requestIdleCallback(async () => {
try {
t(await de(e));
} catch (i) {
n(i);
}
}) : setTimeout(async () => {
try {
t(await de(e));
} catch (i) {
n(i);
}
}, Bt);
});
}
function qt() {
return new Promise((e) => C.get(e));
}
function $() {
return navigator instanceof window.Navigator;
}
async function $t(e) {
var t;
return !!($() && typeof ((t = navigator.permissions) == null ? void 0 : t.query) == "function" && (await navigator.permissions.query({ name: e })).state === "granted");
}
async function Kt() {
return new Promise((e) => {
navigator.geolocation.getCurrentPosition(
(t) => {
const n = t.coords.latitude, i = t.coords.longitude;
e(`${n}:${i}`);
},
() => {
e("unknown");
}
);
});
}
async function Vt() {
const e = await $t("geolocation"), t = {
permissionGranted: e
};
return $() && e && navigator.geolocation && (t.location = await Kt()), t;
}
async function jt() {
if ($() && "getBattery" in navigator && typeof navigator.getBattery == "function") {
const e = await navigator.getBattery();
if (e)
return {
level: e.level,
charging: e.charging
};
}
}
async function Gt() {
var e;
if ($() && typeof ((e = navigator.mediaDevices) == null ? void 0 : e.enumerateDevices) == "function")
return (await navigator.mediaDevices.enumerateDevices()).map(({ kind: n, label: i, deviceId: r, groupId: o }) => ({
kind: n,
// "|| undefined" to eliminate empty strings
label: i || void 0,
deviceId: r || void 0,
groupId: o || void 0
}));
}
function Ht() {
let e;
try {
throw "a";
} catch (t) {
try {
t.toSource(), e = !0;
} catch {
e = !1;
}
}
return e;
}
const Ct = "notDetected";
async function Wt() {
try {
return await $e();
} catch {
return {
browserName: Ct
};
}
}
async function Xt() {
var d;
const e = {}, { width: t, height: n, availWidth: i, availHeight: r } = window.screen;
e.width = t, e.height = n, e.availableWidth = i, e.availableHeight = r;
try {
await Mt(e);
} catch (c) {
v({ type: "FpInitError", message: c.message });
}
const o = await Wt();
if (e.browser = o.browserName, e.incognito = o.isPrivate, $() && "userAgentData" in navigator) {
const c = navigator.userAgentData;
e.mobile = c == null ? void 0 : c.mobile;
}
(d = navigator.languages) != null && d.length && (e.languages = [...navigator.languages]), e.geolocation = await Vt();
const a = await jt();
a && (e.battery = a);
const s = await Gt();
s && (e.mediaDevices = s);
const l = await Nt();
l && (e.orientation = l), e.oscpu = navigator.oscpu, e.productSub = navigator.productSub, e.evalLength = eval.toString().length, e.errFirefox = Ht(), await B(e);
}
const Ue = "navigate";
let x, Q;
function Yt() {
var t, n;
typeof ((t = window.navigation) == null ? void 0 : t.addEventListener) == "function" && (x = () => {
const i = zt();
i !== Q && (Q = i, B({ event: "urlchanged" }));
}, (n = window.navigation) == null || n.addEventListener(Ue, x));
}
function Jt() {
var e;
x && ((e = window.navigation) == null || e.removeEventListener(Ue, x), x = void 0, Q = void 0);
}
function zt() {
return window.location.href;
}
var H = function() {
return H = Object.assign || function(t) {
for (var n, i = 1, r = arguments.length; i < r; i++) {
n = arguments[i];
for (var o in n) Object.prototype.hasOwnProperty.call(n, o) && (t[o] = n[o]);
}
return t;
}, H.apply(this, arguments);
};
function Qt(e, t) {
var n = {};
for (var i in e) Object.prototype.hasOwnProperty.call(e, i) && t.indexOf(i) < 0 && (n[i] = e[i]);
if (e != null && typeof Object.getOwnPropertySymbols == "function")
for (var r = 0, i = Object.getOwnPropertySymbols(e); r < i.length; r++)
t.indexOf(i[r]) < 0 && Object.prototype.propertyIsEnumerable.call(e, i[r]) && (n[i[r]] = e[i[r]]);
return n;
}
function Zt(e, t, n) {
if (n || arguments.length === 2) for (var i = 0, r = t.length, o; i < r; i++)
(o || !(i in t)) && (o || (o = Array.prototype.slice.call(t, 0, i)), o[i] = t[i]);
return e.concat(o || Array.prototype.slice.call(t));
}
function en(e, t) {
return function(n, i) {
return Object.prototype.hasOwnProperty.call(n, i);
}(e, t) ? e[t] : void 0;
}
function tn(e, t, n, i) {
var r, o = document, a = "securitypolicyviolation", s = function(d) {
var c = new URL(e, location.href), u = d.blockedURI;
u !== c.href && u !== c.protocol.slice(0, -1) && u !== c.origin || (r = d, l());
};
o.addEventListener(a, s);
var l = function() {
return o.removeEventListener(a, s);
};
return Promise.resolve().then(t).then(function(d) {
return l(), d;
}, function(d) {
return new Promise(function(c) {
var u = new MessageChannel();
u.port1.onmessage = function() {
return c();
}, u.port2.postMessage(null);
}).then(function() {
if (l(), r) return n(r);
throw d;
});
});
}
var nn = { default: "endpoint" }, rn = { default: "tlsEndpoint" }, on = "Client timeout", an = "Network connection error", cn = "Network request aborted", sn = "Response cannot be parsed", ae = "Blocked by CSP", ce = "The endpoint parameter is not a valid URL";
function I(e) {
for (var t = "", n = 0; n < e.length; ++n) if (n > 0) {
var i = e[n].toLowerCase();
i !== e[n] ? t += " ".concat(i) : t += e[n];
} else t += e[n].toUpperCase();
return t;
}
var un = /* @__PURE__ */ I("WrongRegion"), ln = /* @__PURE__ */ I("SubscriptionNotActive"), dn = /* @__PURE__ */ I("UnsupportedVersion"), fn = /* @__PURE__ */ I("InstallationMethodRestricted"), pn = /* @__PURE__ */ I("HostnameRestricted"), gn = /* @__PURE__ */ I("IntegrationFailed"), vn = /* @__PURE__ */ I("NetworkRestricted"), En = /* @__PURE__ */ I("InvalidProxyIntegrationSecret"), Rn = /* @__PURE__ */ I("InvalidProxyIntegrationHeaders"), se = "API key required", Le = "API key not found", Pe = "API key expired", yn = "Request cannot be parsed", wn = "Request failed", hn = "Request failed to process", mn = "Too many requests, rate limit exceeded", In = "Not available for this origin", On = "Not available with restricted header", Tn = se, bn = Le, _n = Pe, Sn = "3.11.11", X = "Failed to load the JS script of the agent", ue = "9319";
function Nn(e, t) {
var n, i, r, o, a, s, l, d = [], c = (n = function(g) {
var p = Zt([], g, !0);
return { current: function() {
return p[0];
}, postpone: function() {
var f = p.shift();
f !== void 0 && p.push(f);
}, exclude: function() {
p.shift();
} };
}(e), o = 100, a = 3e3, s = 0, i = function() {
return Math.random() * Math.min(a, o * Math.pow(2, s++));
}, r = /* @__PURE__ */ new Set(), [n.current(), function(g, p) {
var f, E = p instanceof Error ? p.message : "";
if (E === ae || E === ce) n.exclude(), f = 0;
else if (E === ue) n.exclude();
else if (E === X) {
var N = Date.now() - g.getTime() < 50, _ = n.current();
_ && N && !r.has(_) && (r.add(_), f = 0), n.postpone();
} else n.postpone();
var U = n.current();
return U === void 0 ? void 0 : [U, f ?? g.getTime() + i() - Date.now()];
}]), u = c[0], T = c[1];
if (u === void 0) return Promise.reject(new TypeError("The list of script URL patterns is empty"));
var b = function(g) {
var p = /* @__PURE__ */ new Date(), f = function(N) {
return d.push({ url: g, startedAt: p, finishedAt: /* @__PURE__ */ new Date(), error: N });
}, E = t(g);
return E.then(function() {
return f();
}, f), E.catch(function(N) {
if (l != null || (l = N), d.length >= 5) throw l;
var _ = T(p, N);
if (!_) throw l;
var U, Be = _[0], Me = _[1];
return (U = Me, new Promise(function(qe) {
return setTimeout(qe, U);
})).then(function() {
return b(Be);
});
});
};
return b(u).then(function(g) {
return [g, d];
});
}
var xe = "https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js", An = xe;
function Dn(e) {
var t;
e.scriptUrlPattern;
var n = e.token, i = e.apiKey, r = i === void 0 ? n : i, o = Qt(e, ["scriptUrlPattern", "token", "apiKey"]), a = (t = en(e, "scriptUrlPattern")) !== null && t !== void 0 ? t : xe, s = function() {
var c = [], u = function() {
c.push({ time: /* @__PURE__ */ new Date(), state: document.visibilityState });
}, T = function(b, g, p, f) {
return b.addEventListener(g, p, f), function() {
return b.removeEventListener(g, p, f);
};
}(document, "visibilitychange", u);
return u(), [c, T];
}(), l = s[0], d = s[1];
return Promise.resolve().then(function() {
if (!r || typeof r != "string") throw new Error(se);
var c = function(u, T) {
return (Array.isArray(u) ? u : [u]).map(function(b) {
return function(g, p) {
var f = encodeURIComponent;
return g.replace(/<[^<>]+>/g, function(E) {
return E === "<version>" ? "3" : E === "<apiKey>" ? f(p) : E === "<loaderVersion>" ? f(Sn) : E;
});
}(String(b), T);
});
}(a, r);
return Nn(c, Un);
}).catch(function(c) {
throw d(), function(u) {
return u instanceof Error && u.message === ue ? new Error(X) : u;
}(c);
}).then(function(c) {
var u = c[0], T = c[1];
return d(), u.load(H(H({}, o), { ldi: { attempts: T, visibilityStates: l } }));
});
}
function Un(e) {
return tn(e, function() {
return function(t) {
return new Promise(function(n, i) {
if (function(s) {
if (URL.prototype) try {
return new URL(s, location.href), !1;
} catch (l) {
if (l instanceof Error && l.name === "TypeError") return !0;
throw l;
}
}(t)) throw new Error(ce);
var r = document.createElement("script"), o = function() {
var s;
return (s = r.parentNode) === null || s === void 0 ? void 0 : s.removeChild(r);
}, a = document.head || document.getElementsByTagName("head")[0];
r.onload = function() {
o(), n();
}, r.onerror = function() {
o(), i(new Error(X));
}, r.async = !0, r.src = t, a.appendChild(r);
});
}(e);
}, function() {
throw new Error(ae);
}).then(Ln);
}
function Ln() {
var e = window, t = "__fpjs_p_l_b", n = e[t];
if (function(i, r) {
var o, a = (o = Object.getOwnPropertyDescriptor) === null || o === void 0 ? void 0 : o.call(Object, i, r);
a != null && a.configurable ? delete i[r] : a && !a.writable || (i[r] = void 0);
}(e, t), typeof (n == null ? void 0 : n.load) != "function") throw new Error(ue);
return n;
}
var Z = { load: Dn, defaultScriptUrlPattern: An, ERROR_SCRIPT_LOAD_FAIL: X, ERROR_API_KEY_EXPIRED: Pe, ERROR_API_KEY_INVALID: Le, ERROR_API_KEY_MISSING: se, ERROR_BAD_REQUEST_FORMAT: yn, ERROR_BAD_RESPONSE_FORMAT: sn, ERROR_CLIENT_TIMEOUT: on, ERROR_CSP_BLOCK: ae, ERROR_FORBIDDEN_ENDPOINT: pn, ERROR_FORBIDDEN_HEADER: On, ERROR_FORBIDDEN_ORIGIN: In, ERROR_GENERAL_SERVER_FAILURE: wn, ERROR_INSTALLATION_METHOD_RESTRICTED: fn, ERROR_INTEGRATION_FAILURE: gn, ERROR_INVALID_ENDPOINT: ce, ERROR_INVALID_PROXY_INTEGRATION_HEADERS: Rn, ERROR_INVALID_PROXY_INTEGRATION_SECRET: En, ERROR_NETWORK_ABORT: cn, ERROR_NETWORK_CONNECTION: an, ERROR_NETWORK_RESTRICTED: vn, ERROR_RATE_LIMIT: mn, ERROR_SERVER_TIMEOUT: hn, ERROR_SUBSCRIPTION_NOT_ACTIVE: ln, ERROR_TOKEN_EXPIRED: _n, ERROR_TOKEN_INVALID: bn, ERROR_TOKEN_MISSING: Tn, ERROR_UNSUPPORTED_VERSION: dn, ERROR_WRONG_REGION: un, defaultEndpoint: nn, defaultTlsEndpoint: rn };
async function Pn(e, t) {
const n = `${t}/resources/di/info`;
return fetch(n, {
headers: {
"Content-Type": "application/json",
"X-Access-Token": e,
"X-Client-Id": "fisherman"
}
}).then((i) => {
if (i.status !== 204)
return i.json();
});
}
function Fe() {
try {
const e = typeof window < "u" && typeof window.sessionStorage < "u";
return e || v({ type: "OtherFpError", message: "SessionStorage unavailable" }), e;
} catch {
return v({ type: "OtherFpError", message: "SessionStorage unavailable" }), !1;
}
}
function xn(e) {
if (!Fe())
return null;
try {
const t = window.sessionStorage.getItem(e);
return t ? JSON.parse(t) : null;
} catch {
return v({ type: "OtherFpError", message: "Unable to parse SessionStorage response" }), null;
}
}
function Fn(e, t) {
if (Fe())
try {
window.sessionStorage.setItem(e, JSON.stringify(t));
} catch {
v({ type: "OtherFpError", message: "SessionStorage unavailable" });
}
}
const fe = "fisherman_fp_cache";
function ke(e) {
return e ? `${fe}_${e}` : fe;
}
function kn(e) {
return xn(ke(e));
}
function Bn(e, t) {
Fn(ke(t), e);
}
function Mn(e, t) {
const n = Date.now(), i = t * 1e3;
return n - e < i;
}
const qn = "https://fpmetrics.sumsub.com", $n = "eu", Kn = (e, t) => {
const n = (t == null ? void 0 : t.fpRegion) || $n, i = (t == null ? void 0 : t.fpUrl) || qn;
if (t != null && t.fpWorkerUrl && (t != null && t.fpWorkerScript)) {
const r = new URL(t == null ? void 0 : t.fpWorkerUrl);
return r.searchParams.set("region", n), {
apiKey: e,
scriptUrlPattern: t == null ? void 0 : t.fpWorkerScript,
endpoint: r.toString(),
region: n
};
}
return {
apiKey: e,
scriptUrlPattern: `${i}/web/v<version>/<apiKey>/loader_v<loaderVersion>.js`,
endpoint: i,
region: n
};
};
let F, h, k;
async function Vn(e, t) {
let n, i, r;
try {
r = await Pn(e, M());
} catch (s) {
v({ type: "LoadFpConfigError", message: s.message });
}
const o = !!(r != null && r.bhvEnabled);
if (n = r == null ? void 0 : r.evRelUrl, i = r == null ? void 0 : r.fpReqRelUrl, k = r == null ? void 0 : r.cacheTtlSeconds, rt(r == null ? void 0 : r.logLevel), r != null && r.fpKey)
try {
const s = Kn(r.fpKey, r);
F = await Z.load(s);
} catch (s) {
v({ type: "FpInitError", message: s.message });
}
t ? h = {
enabled: !0,
conf: t
} : r != null && r.simulation && (h = r.simulation);
const a = !!(r != null && r.fpKey || h);
return S("InitResult", `isDeviceIntelligenceEnabled=${a}`), { isDeviceIntelligenceEnabled: a, behavioralDataEnabled: o, eventsRelUrl: n, fpReqRelUrl: i };
}
async function jn(e) {
if (S("CollectFingerprintStarted"), h)
return await Gn(e);
let t, n, i = k && k > 0;
if (i) {
const r = kn(e == null ? void 0 : e.deviceBindingId);
if (r) {
if (Mn(r.timestamp, k))
return F ? (S("CacheHit", `requestId=${r.requestId}`), await G({
fpRequestId: r.requestId,
deviceBindingId: e == null ? void 0 : e.deviceBindingId
})) : v(le), { visitorId: r.visitorId };
S("CacheExpired");
} else
S("CacheMiss");
}
if (F) {
let r;
try {
r = await F.get({
timeout: 3e4,
linkedId: e == null ? void 0 : e.linkedId
});
} catch (o) {
let a;
switch (o.message) {
case Z.ERROR_CLIENT_TIMEOUT:
a = Xe;
break;
case Z.ERROR_RATE_LIMIT:
a = Ye;
break;
default:
a = { type: "OtherFpError", message: o.message };
}
v(a);
}
t = r == null ? void 0 : r.visitorId, n = r == null ? void 0 : r.requestId, S("FpResult", `visitorId=${t ?? "undefined"} requestId=${n ?? "undefined"}`), await G({
fpRequestId: n,
deviceBindingId: e == null ? void 0 : e.deviceBindingId
}), i && r && Bn({
visitorId: t,
requestId: n,
timestamp: Date.now()
}, e == null ? void 0 : e.deviceBindingId);
} else
v(le);
return { visitorId: t };
}
async function Gn(e) {
var i, r;
const t = { visitorId: (i = h == null ? void 0 : h.conf) == null ? void 0 : i.visitorId };
if (!h)
return t;
const n = { ...h };
if (!((r = n.conf) != null && r.requestId)) {
const o = `simulated-${Math.random().toString(36).substring(2, 10)}`;
n.conf = {
...n.conf,
requestId: o
};
}
try {
await G({
fpSimulation: n,
deviceBindingId: e == null ? void 0 : e.deviceBindingId
});
} catch (o) {
v({ type: "SimulationError", message: o.message });
}
return t;
}
const Hn = () => {
F = void 0, h = void 0, k = void 0;
};
let ee, te = !1;
async function Xn(e) {
let t = !1;
if (!ee) {
ee = !0, et(e);
const n = await Vn(e.token, e.simulationConfig);
t = n.isDeviceIntelligenceEnabled, te = n.behavioralDataEnabled, tt(n.eventsRelUrl), nt(n.fpReqRelUrl), te && (await Xt(), ut(), Yt(), bt());
}
return {
isDeviceIntelligenceEnabled: t,
async fingerprint(n) {
return jn(n);
}
};
}
function Yn() {
Ne(), lt(), Jt(), _t(), it(), Hn(), ee = !1, te = !1;
}
function Jn(e) {
q(e);
}
export {
Yn as destroy,
Xn as init,
Jn as updateAccessToken
};