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