@touchque/device-risk 0.0.0-stage → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +269 -2
- package/dist/device-sri.json +5 -0
- package/dist/index.d.mts +384 -0
- package/dist/index.d.ts +384 -0
- package/dist/index.js +1580 -0
- package/dist/index.mjs +1559 -0
- package/dist/touchque-device.global.js +9 -0
- package/package.json +34 -4
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
(function(){'use strict';var he="tq_device_id";function Ue(){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function ve(){try{let e=window.localStorage.getItem(he);if(e&&/^tq2_[0-9a-f]{32}$/.test(e))return e;let t=`tq2_${Ue()}`;return window.localStorage.setItem(he,t),t}catch{return null}}function be(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return null;let n=t.getExtension("WEBGL_debug_renderer_info");return n?`${t.getParameter(n.UNMASKED_VENDOR_WEBGL)}|${t.getParameter(n.UNMASKED_RENDERER_WEBGL)}`:t.getParameter(t.RENDERER)}catch{return null}}function ee(){try{let e=document.createElement("canvas");e.width=240,e.height=60;let t=e.getContext("2d");return t?(t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.font="14px 'Arial'",t.fillText("TouchQue device \u{1F512} \xE7\u011F\u0131\xF6\u015F\xFC",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.font="18px serif",t.fillText("TouchQue device \u{1F512} \xE7\u011F\u0131\xF6\u015F\xFC",4,40),t.globalCompositeOperation="multiply",t.fillStyle="rgb(255,0,255)",t.beginPath(),t.arc(50,30,20,0,Math.PI*2,!0),t.fill(),e.toDataURL()):null}catch{return null}}async function we(){try{let e=window,t=e.OfflineAudioContext||e.webkitOfflineAudioContext;if(!t)return null;let n=new t(1,5e3,44100),r=n.createOscillator();r.type="triangle",r.frequency.value=1e4;let i=n.createDynamicsCompressor();r.connect(i),i.connect(n.destination),r.start(0);let o=await Promise.race([n.startRendering(),new Promise(l=>setTimeout(()=>l(null),1500))]);if(!o)return null;let a=o.getChannelData(0),s=0;for(let l=4500;l<5e3;l++)s+=Math.abs(a[l]);return s.toFixed(6)}catch{return null}}var He=["Arial","Helvetica","Times New Roman","Courier New","Verdana","Georgia","Palatino","Garamond","Comic Sans MS","Trebuchet MS","Impact","Tahoma","Segoe UI","Calibri","Cambria","Consolas","Menlo","Monaco","Roboto","Ubuntu","Noto Sans","Lucida Grande","Helvetica Neue","SF Pro Text","Apple Color Emoji"];function Se(){try{let e=document.createElement("span");e.style.cssText="position:absolute;left:-9999px;top:-9999px;font-size:72px;visibility:hidden",e.textContent="mmmmmmmmmmlliWWW",document.body.appendChild(e);let t=i=>(e.style.fontFamily=i,`${e.offsetWidth}x${e.offsetHeight}`),n=["monospace","sans-serif","serif"].map(t),r=[];for(let i of He)["monospace","sans-serif","serif"].some((a,s)=>t(`'${i}',${a}`)!==n[s])&&r.push(i);return document.body.removeChild(e),r}catch{return null}}function Ve(e,t){let n=3735928559^t,r=1103547991^t;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677);}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&r)+(n>>>0)).toString(16).padStart(14,"0")}async function te(e){try{if(typeof crypto<"u"&&crypto.subtle){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return {hex:Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join(""),weak:!1}}}catch{}return {hex:[1,2,3,4,5].map(t=>Ve(e,t)).join("").slice(0,64),weak:true}}var We="touchque",X="keys",z="browser-key-v1";function Ge(e,t,n){return `touchque-browser:v1
|
|
2
|
+
${e}
|
|
3
|
+
${t}
|
|
4
|
+
${n}`}function je(e,t,n,r){return `touchque-device:v1
|
|
5
|
+
${e}
|
|
6
|
+
${t}
|
|
7
|
+
${n}
|
|
8
|
+
${r}`}function Xe(e){return JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y})}async function ze(e,t=globalThis.crypto.subtle){let n=await t.digest("SHA-256",V(Xe(e)));return K(new Uint8Array(n))}function V(e){return new TextEncoder().encode(e)}function K(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function W(e){let t=e;return !!t&&typeof t=="object"&&!!t.privateKey&&t.privateKey.type==="private"&&!!t.publicKey&&t.publicKey.type==="public"}function Je(e){let t=()=>new Promise((r,i)=>{let o=e.open(We,1);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(X)||o.result.createObjectStore(X);};let a=false;o.onsuccess=()=>{a?o.result.close():r(o.result);},o.onerror=()=>{a=true,i(o.error);},o.onblocked=()=>{a=true,i(new Error("IndexedDB open blocked"));};});async function n(r,i){let o=await t();try{return await new Promise((a,s)=>{let l=o.transaction(X,r),h;i(l.objectStore(X),d=>{h=d;}),l.oncomplete=()=>a(h),l.onerror=()=>s(l.error),l.onabort=()=>s(l.error??new Error("IndexedDB transaction aborted"));})}finally{o.close();}}return {load:()=>n("readonly",(r,i)=>{let o=r.get(z);o.onsuccess=()=>i(W(o.result)?o.result:void 0);}),save:r=>n("readwrite",(i,o)=>{let a=i.get(z);a.onsuccess=()=>{if(W(a.result))return o(a.result);i.put({privateKey:r.privateKey,publicKey:r.publicKey},z),o(r);};}),remove:()=>n("readwrite",(r,i)=>{r.delete(z),i(void 0);})}}function U(e,t){return new Promise(n=>{let r=setTimeout(()=>n(null),t);e().then(i=>{clearTimeout(r),n(i);},()=>{clearTimeout(r),n(null);});})}var Ye=300,Ze=8,Qe=64,et=2048,H=e=>typeof e=="string"?e.trim().slice(0,Qe):"";function tt(e,t){if(!e||typeof e!="object")return null;let n=e,r=Array.isArray(n.fullVersionList)?n.fullVersionList:[],i=[];for(let o of r){if(i.length>=Ze)break;let a=o&&typeof o=="object"?o:{},s=H(a.brand);s&&i.push({brand:s,version:H(a.version)});}return {platform:H(n.platform),platformVersion:H(n.platformVersion),fullVersionList:i,mobile:(typeof n.mobile=="boolean"?n.mobile:t)===true,model:H(n.model)}}function nt(){try{let e=typeof navigator<"u"?navigator.userAgentData:void 0;return e&&typeof e.getHighEntropyValues=="function"?e:null}catch{return null}}function rt(){try{return typeof indexedDB<"u"&&indexedDB?Je(indexedDB):null}catch{return null}}function ot(e={}){let t,n=()=>(t===void 0&&(t=e.store!==void 0?e.store:rt()),t),r=()=>{try{let d=e.crypto??globalThis.crypto;return d&&d.subtle&&typeof d.getRandomValues=="function"?d:null}catch{return null}},i=()=>{let d=e.origin;if(d===void 0)try{d=typeof location<"u"?location.origin:void 0;}catch{d=void 0;}return typeof d=="string"&&d!==""&&d!=="null"?d:null},o,a=(d,g)=>{if(!o){let v=(async()=>{let b=await g.load();if(!W(b)){let D=await d.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign"]);if(b=await g.save(D),!W(b))throw new Error("browser key not stored")}let _=await d.subtle.exportKey("jwk",b.publicKey);if(_.kty!=="EC"||_.crv!=="P-256"||typeof _.x!="string"||typeof _.y!="string")throw new Error("browser key is not P-256");return {pair:b,jwk:{kty:"EC",crv:"P-256",x:_.x,y:_.y}}})();o=v,v.catch(()=>{o===v&&(o=void 0);});}return o},s,l=()=>(s||(s=(async()=>{try{let d=e.userAgentData!==void 0?e.userAgentData:nt();if(!d||typeof d.getHighEntropyValues!="function")return null;let g=await d.getHighEntropyValues(["platformVersion","fullVersionList","model"]);return tt(g,d.mobile)}catch{return null}})()),s),h=e.timeoutMs??2e3;return {proof:()=>U(async()=>{let d=r(),g=n(),v=i();if(!d||!g||!v)return null;let{pair:b,jwk:_}=await a(d,g),D=Math.floor((e.now??Date.now)()/1e3),w=K(d.getRandomValues(new Uint8Array(16))),S=new Uint8Array(await d.subtle.sign({name:"ECDSA",hash:"SHA-256"},b.privateKey,V(Ge(v,D,w))));if(S.length!==64)return null;let k={v:1,jwk:_,aud:v,iat:D,nonce:w,sig:K(S)},E=await U(l,Ye);if(E){let x=K(V(JSON.stringify({...k,hints:E})));if(x.length<=et)return x}return K(V(JSON.stringify(k)))},h),sealDevice:d=>U(async()=>{let g=r(),v=n(),b=i();if(!g||!v||!b||!/^[A-Za-z0-9_-]{43}$/.test(d))return null;let{pair:_,jwk:D}=await a(g,v),w=Math.floor((e.now??Date.now)()/1e3),S=K(g.getRandomValues(new Uint8Array(16))),k=new Uint8Array(await g.subtle.sign({name:"ECDSA",hash:"SHA-256"},_.privateKey,V(je(b,w,S,d))));return k.length!==64?null:{jwk:D,aud:b,iat:w,nonce:S,sig:K(k)}},h),thumbprint:()=>U(async()=>{let d=r(),g=n();if(!d||!g)return null;if(!o){let b=await g.load();if(!W(b))return null}let{jwk:v}=await a(d,g);return ze(v,d.subtle)},h),async forget(){o=void 0,await U(async()=>(await n()?.remove(),null),h);}}}var _e=ot();var Ee=null;function xe(e){Ee=e;}function B(e){try{Ee?.warn(e);}catch{}}function J(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown error"}var De={kid:"9d8a2f55",jwk:{kty:"EC",crv:"P-256",x:"QXrbInfJL8yPadD1kbcSDFajSop7_-DoK7oTbEO5sGU",y:"LqIO9D9uliBoFiR1kLk_1hT3eKvoFQqqkhydzFAkM5Y"}};var Pe="tqe1",it=new TextEncoder().encode("touchque-device-report:v1");function ne(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ke(e,t=De,n=globalThis.crypto?.subtle){if(!n||!t)return null;try{let r=await n.importKey("jwk",{...t.jwk,ext:!0},{name:"ECDH",namedCurve:"P-256"},!1,[]),i=await n.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),o=new Uint8Array(await n.exportKey("raw",i.publicKey)),a=await n.deriveBits({name:"ECDH",public:r},i.privateKey,256),s=await n.importKey("raw",a,"HKDF",!1,["deriveKey"]),l=await n.deriveKey({name:"HKDF",hash:"SHA-256",salt:o,info:it},s,{name:"AES-GCM",length:256},!1,["encrypt"]),h=new Uint8Array(12);globalThis.crypto.getRandomValues(h);let d=new Uint8Array(await n.encrypt({name:"AES-GCM",iv:h,additionalData:new TextEncoder().encode(`${Pe}.${t.kid}`)},l,new TextEncoder().encode(e)));return [Pe,t.kid,ne(o),ne(h),ne(d)].join(".")}catch{return null}}var ie=["sign_in","sign_up","password_reset","approval"];var st=6144;function se(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function re(e){return se(new TextEncoder().encode(JSON.stringify(e)))}function at(){let e=new Uint8Array(16);try{crypto.getRandomValues(e);}catch{for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);}return se(e)}var oe=(e,t)=>typeof e=="string"?e.slice(0,t):"",G=async e=>e===null?null:(await te(e)).hex.slice(0,16);function Re(e,t,n){return new Promise(r=>{let i=setTimeout(()=>r(n),t);e.then(o=>{clearTimeout(i),r(o);},()=>{clearTimeout(i),r(n);});})}function Me(e,t){return /CrOS/.test(e)?"ChromeOS":/Android/i.test(e)?"Android":/iPhone|iPad|iPod/.test(e)||/Macintosh/.test(e)&&/Mobile\//.test(e)?"iOS":/Windows/.test(e)||/^Win/.test(t)?"Windows":/Mac OS X|Macintosh/.test(e)||/^Mac/.test(t)?"macOS":/Linux|X11/.test(e)||/Linux/.test(t)?"Linux":"Other"}function ae(e){let t=n=>{let r=n.exec(e);return r&&Number(r[1])||0};return /Edg(e|A|iOS)?\//.test(e)?{br:"Edge",bv:t(/Edg(?:e|A|iOS)?\/(\d+)/)}:/OPR\/|Opera/.test(e)?{br:"Opera",bv:t(/OPR\/(\d+)/)}:/SamsungBrowser\//.test(e)?{br:"Samsung",bv:t(/SamsungBrowser\/(\d+)/)}:/Firefox\/|FxiOS\//.test(e)?{br:"Firefox",bv:t(/(?:Firefox|FxiOS)\/(\d+)/)}:/Chrome\/|CriOS\//.test(e)?{br:"Chrome",bv:t(/(?:Chrome|CriOS)\/(\d+)/)}:/Safari\//.test(e)&&/Version\//.test(e)?{br:"Safari",bv:t(/Version\/(\d+)/)}:{br:"Other",bv:0}}function ct(){let e=Math;return [e.acos(.12312423423423424),e.acosh(1e308),e.asinh(1),e.atanh(.5),e.expm1(1),e.sinh(1),e.cosh(1),e.tan(-1e300),e.log1p(10),e.cbrt(Math.PI),e.exp(1)**10].map(String).join(",")}function ut(){try{let e=document.createElement("canvas").getContext("webgl");if(!e)return null;let n=[e.MAX_TEXTURE_SIZE,e.MAX_RENDERBUFFER_SIZE,e.MAX_VERTEX_ATTRIBS,e.MAX_VERTEX_UNIFORM_VECTORS,e.MAX_FRAGMENT_UNIFORM_VECTORS,e.MAX_VARYING_VECTORS,e.MAX_COMBINED_TEXTURE_IMAGE_UNITS,e.MAX_VIEWPORT_DIMS,e.ALIASED_LINE_WIDTH_RANGE,e.ALIASED_POINT_SIZE_RANGE].map(i=>{let o=e.getParameter(i);return o&&typeof o=="object"?Array.from(o).join("x"):String(o)}),r=(e.getSupportedExtensions()||[]).slice().sort().join(",");return `${n.join("|")}#${r}`}catch{return null}}async function lt(e){let t=e.navigator,n=t.userAgent||"",r=oe(t.platform,32),{br:i,bv:o}=ae(n),a="";try{a=Intl.DateTimeFormat().resolvedOptions().timeZone||"";}catch{}let s=e.screen?.width||0,l=e.screen?.height||0,h=ee(),d=be(),g=Se();return {traits:{os:Me(n,r),br:i,bv:o,pf:r,tz:oe(a,64),tzo:new Date().getTimezoneOffset(),lang:(Array.isArray(t.languages)&&t.languages.length?t.languages:[t.language||""]).slice(0,3).map(b=>oe(b,16)),scr:`${Math.max(s,l)}x${Math.min(s,l)}`,cd:e.screen?.colorDepth||0,dpr:Math.round((e.devicePixelRatio||1)*100)/100,hc:t.hardwareConcurrency||0,dm:typeof t.deviceMemory=="number"?t.deviceMemory:null,tp:t.maxTouchPoints||0,gpu:d?d.slice(0,128):null,cv:await G(h),au:null,fn:g?await G(g.join(",")):null,mt:await G(ct()),wg:await G(ut())},canvasRaw:h,gpuRaw:d,fonts:g}}var dt=/\{\s*\[native code\]\s*\}\s*$/,ft=[["nav_user_agent",()=>Navigator.prototype,"userAgent","get"],["nav_platform",()=>Navigator.prototype,"platform","get"],["nav_languages",()=>Navigator.prototype,"languages","get"],["nav_cores",()=>Navigator.prototype,"hardwareConcurrency","get"],["nav_webdriver",()=>Navigator.prototype,"webdriver","get"],["nav_touch",()=>Navigator.prototype,"maxTouchPoints","get"],["screen_width",()=>Screen.prototype,"width","get"],["screen_height",()=>Screen.prototype,"height","get"],["canvas_data_url",()=>HTMLCanvasElement.prototype,"toDataURL","value"],["canvas_context",()=>HTMLCanvasElement.prototype,"getContext","value"],["canvas_image_data",()=>typeof CanvasRenderingContext2D<"u"?CanvasRenderingContext2D.prototype:void 0,"getImageData","value"],["webgl_parameter",()=>typeof WebGLRenderingContext<"u"?WebGLRenderingContext.prototype:void 0,"getParameter","value"],["tz_resolved",()=>Intl.DateTimeFormat.prototype,"resolvedOptions","value"],["tz_offset",()=>Date.prototype,"getTimezoneOffset","value"],["audio_channel",()=>typeof AudioBuffer<"u"?AudioBuffer.prototype:void 0,"getChannelData","value"]],mt=[["nav_own_property",()=>navigator,"userAgent"],["nav_own_property",()=>navigator,"platform"],["nav_own_property",()=>navigator,"webdriver"],["nav_own_property",()=>navigator,"hardwareConcurrency"],["nav_own_property",()=>navigator,"languages"],["screen_own_property",()=>screen,"width"]];function pt(e){try{return typeof e!="function"?!0:dt.test(Function.prototype.toString.call(e))?!Object.prototype.hasOwnProperty.call(e,"prototype"):!1}catch{return false}}function gt(e,t=pt){let n=new Set;t(Function.prototype.toString)||n.add("fn_to_string");for(let[s,l,h,d]of ft)try{let g=l();if(!g)continue;let v=Object.getOwnPropertyDescriptor(g,h);if(!v)continue;t(d==="get"?v.get:v.value)||n.add(s);}catch{}for(let[s,l,h]of mt)try{let d=l();d&&Object.prototype.hasOwnProperty.call(d,h)&&n.add(s);}catch{}let r=e.navigator,i=r.userAgent||"",o=Me(i,""),a=r.platform||"";try{let s=/^Win/.test(a)?"Windows":/^Mac/.test(a)?"macOS":/^(iPhone|iPad|iPod)/.test(a)?"iOS":/Linux|Android/.test(a)?"Linux":"",l=o==="Android"||o==="ChromeOS"?"Linux":o;s&&l!=="Other"&&s!==l&&!(l==="iOS"&&s==="macOS")&&!(l==="macOS"&&s==="iOS")&&n.add("ua_platform_mismatch");}catch{}try{let s=r.userAgentData?.platform;if(s){let l={Windows:"Windows",macOS:"macOS",Linux:"Linux",Android:"Android","Chrome OS":"ChromeOS",ChromeOS:"ChromeOS",iOS:"iOS"};l[s]&&o!=="Other"&&l[s]!==o&&n.add("uach_platform_mismatch");}}catch{}try{let s=typeof e.mozInnerScreenX=="number",{br:l}=ae(i);l==="Firefox"&&!/FxiOS/.test(i)&&!s&&n.add("ua_engine_mismatch"),(l==="Chrome"||l==="Edge"||l==="Opera")&&!/CriOS|EdgiOS|OPT\//.test(i)&&s&&n.add("ua_engine_mismatch");}catch{}try{let s=r.languages;Array.isArray(s)&&s.length&&r.language&&s[0]!==r.language&&n.add("language_mismatch");}catch{}try{let s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s){let l=new Date,h=new Date(l.toLocaleString("en-US",{timeZone:s})),d=new Date(l.toLocaleString("en-US",{timeZone:"UTC"})),g=Math.round((d.getTime()-h.getTime())/6e4);Math.abs(g-l.getTimezoneOffset())>1&&n.add("timezone_mismatch");}}catch{}try{let s=r.hardwareConcurrency;typeof s=="number"&&(s<1||s>256||!Number.isInteger(s))&&n.add("impossible_cores");}catch{}return [...n].sort()}function yt(){try{return null.x===void 0,null}catch(e){let t=String(e?.message||"");return /Cannot read propert/.test(t)?"v8":/is not an object/.test(t)?"jsc":/has no properties|can't access property/.test(t)?"gecko":null}}var ht=/NVIDIA|GeForce|Quadro|Radeon|Intel\(R\)|Intel Iris|Intel UHD|Intel HD|Direct3D|D3D11|Apple M\d|Metal Renderer/i,vt=/Mali-|PowerVR|Xclipse|Immortalis|Adreno/i;function bt(e,t,n,r=yt()){let i=new Set;if(r){let a=t.os==="iOS"||t.br==="Safari"?"jsc":t.br==="Firefox"?"gecko":["Chrome","Edge","Opera","Samsung"].includes(t.br)?"v8":null;a&&r!==a&&i.add("ua_engine_mismatch");}let o=t.gpu||"";if(o&&(t.os==="iOS"&&!/Apple GPU/i.test(o)&&i.add("gpu_os_mismatch"),t.os==="Android"&&ht.test(o)&&i.add("gpu_os_mismatch"),t.os==="Windows"&&/Apple GPU|Apple M\d|Mali-|PowerVR|Xclipse|Immortalis/i.test(o)&&i.add("gpu_os_mismatch"),t.os==="macOS"&&(/Direct3D|D3D11/i.test(o)||vt.test(o)&&!/Apple/i.test(o))&&i.add("gpu_os_mismatch")),n){let a=s=>n.includes(s);(t.os==="macOS"||t.os==="iOS"||t.os==="Android")&&a("Segoe UI")&&i.add("fonts_os_mismatch"),(t.os==="Windows"||t.os==="Android")&&a("Apple Color Emoji")&&a("Menlo")&&i.add("fonts_os_mismatch");}if(t.os==="iOS"&&/^Mac/.test(t.pf||"")&&i.add("ua_platform_mismatch"),t.os==="iOS"||t.os==="Android"){let a=false;try{a=!!e.matchMedia&&e.matchMedia("(any-pointer: fine)").matches&&!e.matchMedia("(any-pointer: coarse)").matches;}catch{}(t.tp===0||a)&&i.add("mobile_desktop_mismatch");let s=Number(String(t.scr||"").split("x")[0])||0;t.os==="iOS"&&!/^iPad/.test(t.pf||"")&&(s>1e3||t.dpr&&t.dpr<2)&&i.add("mobile_desktop_mismatch");}return [...i].sort()}function wt(e,t){let n=new Set,r=e.navigator;t&&/SwiftShader|llvmpipe|softpipe|Software Rasterizer|Microsoft Basic Render|Mesa OffScreen/i.test(t)&&n.add("soft_gpu"),t&&/VMware|VirtualBox|Parallels|QXL|Red Hat|virgl|Hyper-V|Citrix|bochs|UTM|Apple Paravirtual/i.test(t)&&n.add("vm_gpu"),t&&/Android Emulator|Emulator OpenGL|Genymotion|BlueStacks|\bNox\b|LDPlayer|MuMu/i.test(t)&&n.add("emulator");try{/HeadlessChrome|PhantomJS|SlimerJS/.test(r.userAgent||"")&&n.add("headless");}catch{}try{(r.userAgentData?.brands||[]).some(i=>/Headless/i.test(i.brand))&&n.add("headless");}catch{}try{r.webdriver===!0&&n.add("webdriver");}catch{}try{e.outerWidth===0&&e.outerHeight===0&&n.add("zero_window");}catch{}try{r.hardwareConcurrency===1&&n.add("one_core");}catch{}try{let i=e.screen;!(r.maxTouchPoints>0)&&i&&i.width===800&&i.height===600&&e.outerHeight===e.innerHeight&&e.outerWidth===e.innerWidth&&n.add("headless_window");}catch{}return [...n].sort()}function St(e){let t=new Set,n=e,r=e.document,i=(o,a)=>{try{return a in o}catch{return false}};try{for(let o of Object.getOwnPropertyNames(e))(/^cdc_[A-Za-z0-9]{10,}/.test(o)||/^\$?wdc_/.test(o))&&t.add("selenium");for(let o of Object.keys(e.document))/^\$?cdc_|^\$wdc_/.test(o)&&t.add("selenium");}catch{}for(let o of ["__selenium_unwrapped","__selenium_evaluate","__webdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__driver_unwrapped","__fxdriver_evaluate","__fxdriver_unwrapped","__webdriver_script_fn","__webdriver_script_func","_Selenium_IDE_Recorder","callSelenium","_selenium","__webdriverFunc"])(i(n,o)||i(r,o))&&t.add("selenium");try{e.document.documentElement?.getAttribute("webdriver")!==null&&t.add("selenium");}catch{}for(let o of ["__playwright__binding__","__pwInitScripts","__playwright_evaluation_script__","__playwright"])i(n,o)&&t.add("playwright");for(let o of ["callPhantom","_phantom"])i(n,o)&&t.add("phantomjs");i(n,"__nightmare")&&t.add("nightmare");try{/HeadlessChrome/.test(e.navigator.userAgent||"")&&t.add("headless_chrome");}catch{}try{let o=!1,a=new Error("");Object.defineProperty(a,"stack",{configurable:!0,get(){return o=!0,""}}),e.console?.debug?.(a),o&&t.add("cdp");}catch{}return [...t].sort()}async function _t(e){let t=e.navigator,n=t.userAgent||"",{br:r}=ae(n);try{if(r==="Firefox"&&e.isSecureContext&&!("serviceWorker"in t))return "firefox_no_sw";if(r==="Safari"&&t.storage&&typeof t.storage.getDirectory=="function"){try{await t.storage.getDirectory();}catch(i){if(String(i?.message||"").includes("unknown transient reason"))return "safari_opfs"}return null}if((r==="Chrome"||r==="Edge"||r==="Opera"||r==="Samsung")&&t.storage?.estimate){let{quota:i}=await t.storage.estimate(),o=e.performance?.memory?.jsHeapSizeLimit||1073741824;if(typeof i=="number"&&i>0&&i<o*2)return "chromium_quota"}}catch{}return null}function Et(e){let t={ls:false,idb:false,cookie:false};try{let n="__tq_dr";e.localStorage.setItem(n,"1"),e.localStorage.removeItem(n),t.ls=!0;}catch{}try{t.idb=typeof e.indexedDB<"u"&&!!e.indexedDB;}catch{}try{t.cookie=e.navigator.cookieEnabled===!0;}catch{}return t}function xt(e){try{let t=e.location.origin;return t&&t!=="null"?t:""}catch{return ""}}async function Te(e,t=window){let n=Date.now(),r=e.timeoutMs??1500,i=ie.includes(e.purpose)?e.purpose:"sign_in",{traits:o,canvasRaw:a,gpuRaw:s,fonts:l}=await lt(t),[h,d]=await Promise.all([Re(we(),r,null),Re(_t(t),r,null)]);o.au=await G(h);let g=false;try{let S=ee();g=!!a&&!!S&&S!==a;}catch{}let v=t.navigator,b={v:1,p:i,aud:xt(t),iat:Math.floor(Date.now()/1e3),nonce:at(),sid:ve(),t:o,s:{tamper:[...new Set([...gt(t),...bt(t,o,l)])].sort(),vm:wt(t,s),auto:St(t),priv:d,brave:typeof v.brave=="object"&&v.brave!==null,cvNoise:g,storage:Et(t)},ms:Date.now()-n},_=JSON.stringify(b),D={v:1,body:_},w=e.browserKey===void 0?_e:e.browserKey;if(w&&typeof w.sealDevice=="function")try{let S=await te(_);if(!S.weak){let k=new Uint8Array(S.hex.match(/../g).map(x=>parseInt(x,16))),E=await w.sealDevice(se(k));E&&(D.seal=E);}}catch{}return D}var Dt=/^tqpk_[A-Za-z0-9_-]{32}$/,Pt="https://api.touchque.com";function ce(e){let t=()=>e??window,n={report:r=>Te(r,t()),async identify(r){if(!r||typeof r.siteKey!="string"||!Dt.test(r.siteKey))throw new Error("deviceRisk.identify: siteKey must be your workspace's Device risk site key (tqpk_\u2026)");let i=(r.apiBaseUrl||Pt).replace(/\/+$/,"");if(!/^https?:\/\/[^/]/i.test(i))throw new Error("deviceRisk.identify: apiBaseUrl must be an absolute URL, e.g. https://api.touchque.com");let o=r.fetch??(typeof fetch<"u"?fetch:void 0);if(!o)throw new Error("deviceRisk.identify: no `fetch` available, pass `fetch` in the options.");try{let a=await n.collect(r),s=await o.call(globalThis,`${i}/device-risk/identify`,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify({siteKey:r.siteKey,report:a,...r.pageView&&{view:!0}}),credentials:"same-origin"}),l=await s.json().catch(()=>null);return !s.ok||!l||typeof l.visitorId!="string"||typeof l.requestId!="string"?(B(`Touchque deviceRisk.identify: ${l?.code||s.status}`),null):{visitorId:l.visitorId,requestId:l.requestId,confidence:typeof l.confidence=="number"?l.confidence:0}}catch(a){return B(`Touchque deviceRisk.identify: Touchque could not be reached (${J(a)})`),null}},async collect(r){try{let i=await Te(r,t()),o=i,a=re(o);if(a.length>st){let s=JSON.parse(i.body);s.t.gpu=s.t.gpu?s.t.gpu.slice(0,48):null,o={v:1,body:JSON.stringify(s)},a=re(o);}return r.encrypt===!1?a:await ke(JSON.stringify(o))||a}catch{return re({v:1,body:JSON.stringify({v:1,p:r.purpose,error:true})})}}};return n}var kt=Math.tan(3*Math.PI/180),ue=64,Ae=2e3;function Oe(e){if(e.length<2)return {length:0,deviation:0,dx:0,dy:0};let t=e[0],n=e[e.length-1],r=n.x-t.x,i=n.y-t.y,o=Math.hypot(r,i),a=0,s=0;for(let l=1;l<e.length;l+=1){let h=e[l];a+=Math.hypot(h.x-e[l-1].x,h.y-e[l-1].y);let d=o>0?Math.abs(i*(h.x-t.x)-r*(h.y-t.y))/o:Math.hypot(h.x-t.x,h.y-t.y);d>s&&(s=d);}return {length:a,deviation:s,dx:r,dy:i}}var Rt=(e,t)=>Math.min(Math.abs(e),Math.abs(t))<=kt*Math.max(Math.abs(e),Math.abs(t)),Y=e=>e===null?null:Math.round(e*10)/10,le=(e,t)=>e===null?t:Math.min(e,t),Ie=(e,t)=>e===null?t:Math.max(e,t);function Tt(e){try{if(!e)return !0;let t=e.now(),n=t;for(let r=0;r<1e5&&n===t;r+=1)n=e.now();return n===t||n-t>=5}catch{return true}}function Ne(e=document,t={}){let n=e instanceof Document?e:e.ownerDocument,r=t.trusted??(f=>f.isTrusted),i=n.defaultView?.performance,o=Tt(i),a=0,s=0,l=0,h=0,d=0,g=null,v=0,b=null,_=0,D=null,w=[],S=[],k=-1/0,E=[],x=null,A=f=>{if(f.length<10)return null;let y=Oe(f);return y.length>=300&&!Rt(y.dx,y.dy)?y.deviation:null},I=()=>{let f=A(w);f!==null&&(d+=1,g=le(g,f)),w=[];},M=f=>r(f)&&(f.pointerType==="mouse"||f.pointerType==="pen"),C=f=>{if(!M(f))return;let y=typeof f.getCoalescedEvents=="function"?f.getCoalescedEvents():[];for(let P of y.length?y:[f]){let T={x:P.clientX,y:P.clientY,t:P.timeStamp},L=w[w.length-1];(L&&T.t-L.t>150||w.length>=Ae)&&I(),w.push(T),S.push(T),S.length>ue&&S.shift(),a+=1;}},N=f=>{if(!M(f)||f.button!==0)return;I(),l+=1;let y=f.timeStamp,P=Math.max(y-500,k),T=S.filter(F=>F.t>P),L=null;for(let F=S.length-1;F>=0;F-=1)if(S[F].t<=P){L=S[F];break}k=y,S.push({x:f.clientX,y:f.clientY,t:y}),S.length>ue&&S.shift(),T.length<=1&&(!L||Math.hypot(f.clientX-L.x,f.clientY-L.y)>=30)&&(h+=1,E.push({id:f.pointerId,down:y,up:null}),E.length>ue&&E.shift());},m=f=>{if(M(f)){for(let y=E.length-1;y>=0;y-=1)if(E[y].id===f.pointerId&&E[y].up===null){E[y].up=f.timeStamp;break}}},u=f=>{if(!r(f))return;let y=f.changedTouches[0];x=f.touches.length===1&&y?{id:y.identifier,start:f.timeStamp,samples:[{x:y.clientX,y:y.clientY,t:f.timeStamp}],far:0}:null;},c=f=>{if(!x)return null;let y=Array.from(f.changedTouches).find(T=>T.identifier===x.id);if(!y)return null;let P=x.samples[0];return x.samples.length<Ae&&x.samples.push({x:y.clientX,y:y.clientY,t:f.timeStamp}),x.far=Math.max(x.far,Math.hypot(y.clientX-P.x,y.clientY-P.y)),x},p=f=>{r(f)&&(s+=1,c(f));},R=f=>{if(!r(f))return;let y=c(f);if(y){if(x=null,y.far<10){v+=1,b=Ie(b,f.timeStamp-y.start);return}if(y.samples.length>=10){let P=Oe(y.samples);P.length>=300&&(_+=1,D=le(D,P.deviation));}}},j=()=>{x=null;},pe={capture:true,passive:true},ge=[["pointermove",C],["pointerdown",N],["pointerup",m],["touchstart",u],["touchmove",p],["touchend",R],["touchcancel",j]];for(let[f,y]of ge)e.addEventListener(f,y,pe);let ye=()=>{let f=i?i.now():0,y=null;for(let T of E)y=Ie(y,(T.up??f)-T.down);let P=A(w);return {v:1,p:l,pt:h,pth:o?null:Y(y),ls:d+(P===null?0:1),lsd:Y(P===null?g:le(g,P)),t:v,th:o?null:Y(b),sw:_,swd:Y(D),mv:a,tm:s}};return {summary:ye,encode:()=>Mt(ye()),stop(){for(let[f,y]of ge)e.removeEventListener(f,y,pe);}}}var de="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ce=4095,$=e=>de[Math.max(0,Math.min(63,Math.floor(e)))],q=e=>{let t=e===null?Ce:Math.max(0,Math.min(Ce-1,Math.round(e)));return de[t>>6]+de[t&63]};function Mt(e){let t=e.pt>=e.p?$(e.p):$(Math.min(e.pt,62));return `1${$(e.p)}${t}${q(e.pth)}${$(e.ls)}${q(e.lsd===null?null:e.lsd*10)}${$(e.t)}${q(e.th)}${$(e.sw)}${q(e.swd===null?null:e.swd*10)}${q(e.mv)}${q(e.tm)}`}function At(e){try{if(!e)return !0;let t=e.now(),n=t;for(let r=0;r<1e5&&n===t;r+=1)n=e.now();return n===t||n-t>=5}catch{return true}}var fe=e=>e.length?e.reduce((t,n)=>t+n,0)/e.length:null;function Ot(e){let t=fe(e);return t===null?null:Math.sqrt(e.reduce((n,r)=>n+(r-t)**2,0)/e.length)}function It(e){if(!e.length)return null;let t=[...e].sort((r,i)=>r-i),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2}function Ke(e=document,t={}){let n=e instanceof Document?e:e.ownerDocument,r=t.trusted??(m=>m.isTrusted),i=n.defaultView?.performance,o=At(i),a=0,s=0,l=0,h=0,d=0,g=-1/0,v=-1/0,b=[],_=[],D=new Map,w=[],S=m=>{w.push(m),w.length>200&&w.shift(),v=m;},k=m=>{if(!r(m)||m.repeat||typeof m.key!="string"||m.key.length!==1)return;let u=m.timeStamp;a+=1,u-g<1500?(b.push(u-g),b.length>200&&b.shift()):(u-v>=1500||v===-1/0)&&S(u),g=u,D.set(m.code||m.key,u);},E=m=>{if(!r(m))return;let u=m.code||m.key,c=D.get(u);c!==void 0&&(D.delete(u),_.push(m.timeStamp-c),_.length>200&&_.shift());},x=m=>{if(!r(m))return;let u=m,c=typeof u.inputType=="string"?u.inputType:"";if(c==="insertFromPaste"||c==="insertFromDrop"){l+=1;return}if(c!=="insertText"||u.isComposing)return;let p=m.timeStamp;p-g>150&&(s+=1,p-v>=1500&&S(p));},A=m=>{r(m)&&!(m.target instanceof Element&&m.target.closest("input,textarea,[contenteditable]"))&&(l+=1);},I=m=>{if(!r(m)||m.button!==0||(S(m.timeStamp),m.pointerType!=="mouse"&&m.pointerType!=="pen"))return;let u=m.target instanceof Element?m.target:null;if(u)try{let c=u.getBoundingClientRect();if(c.width<8||c.height<8)return;h+=1,Math.abs(m.clientX-(c.left+c.width/2))<=1&&Math.abs(m.clientY-(c.top+c.height/2))<=1&&(d+=1);}catch{}},M={capture:true,passive:true},C=[["keydown",k],["keyup",E],["input",x],["paste",A],["pointerdown",I]];for(let[m,u]of C)e.addEventListener(m,u,M);let N=()=>{let m=[];for(let p=1;p<w.length;p+=1)m.push(w[p]-w[p-1]);let u=m.filter(p=>p>=1500&&p<=2e4).length,c=p=>p===null?null:Math.round(p);return {v:1,kd:a,nk:s,pa:l,kn:b.length,km:o?null:c(fe(b)),ks:o?null:c(Ot(b)),hm:o?null:c(fe(_)),cp:h,cc:d,ac:w.length,lg:u,gm:o?null:c(It(m))}};return {summary:N,encode:()=>Ct(N()),stop(){for(let[m,u]of C)e.removeEventListener(m,u,M);}}}var me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Le=4095,O=e=>me[Math.max(0,Math.min(63,Math.floor(e)))],Z=e=>{let t=e===null?Le:Math.max(0,Math.min(Le-1,Math.round(e)));return me[t>>6]+me[t&63]};function Ct(e){let t=Math.min(e.cp,63),n=Math.min(e.ac,63);return `1${O(e.kd)}${O(e.nk)}${O(e.pa)}${O(e.kn)}${Z(e.km)}${Z(e.ks)}${Z(e.hm)}${O(t)}${O(Math.min(e.cc,t))}${O(n)}${O(Math.min(e.lg,n))}${Z(e.gm===null?null:e.gm/100)}`}var Fe="touchque_request_id",Nt="data-touchque-purpose",Lt="touchque:device",Be=600*1e3,Kt=1e3,$e="3.0.0",Q=e=>ie.includes(e);function Ft(e,t={}){let n=t.win??window,r=n.document,i=t.now??(()=>Date.now()),o=t.deviceRisk??ce(n),a=Q(e.purpose)?e.purpose:"sign_in",s=new Map,l=new Set([r]),h=false,d=null;try{d=t.pointer!==void 0?t.pointer:e.pointer===!1?null:Ne(r);}catch{}let g=null;try{g=d?t.input!==void 0?t.input:Ke(r):null;}catch{}let v=u=>{let c=s.get(u)?.current?.requestId;if(!c)return null;let p=c;try{d&&(p=`${c}.${d.encode()}`);}catch{return c}try{d&&g&&(p=`${p}.${g.encode()}`);}catch{}return p},b=u=>{let c=s.get(u);return c||(c={current:null,at:0,pending:null,timer:null,stale:false},s.set(u,c)),c},_=u=>{let c=u.getAttribute(Nt);return Q(c)?c:a},D=u=>{let c=[];return u.tagName==="FORM"&&c.push(u),typeof u.querySelectorAll=="function"&&c.push(...Array.from(u.querySelectorAll("form"))),c},w=u=>{let c=Array.from(u.querySelectorAll("input")).find(R=>R.name===Fe);if(c)return c;let p=r.createElement("input");return p.type="hidden",p.name=Fe,u.appendChild(p),p},S=u=>{let c=s.get(u)?.current?.requestId??"";for(let p of l)for(let R of D(p))_(R)===u&&(w(R).value=c);},k=u=>{let c=b(u);c.timer&&clearTimeout(c.timer),c.stale=false,c.timer=setTimeout(()=>{c.timer=null,r.visibilityState==="hidden"?c.stale=true:E(u);},Be);},E=u=>{let c=b(u);return c.pending?c.pending:h?Promise.resolve(c.current):(c.pending=o.identify({siteKey:e.siteKey,purpose:u,apiBaseUrl:e.apiBaseUrl,pageView:true}).catch(p=>(B(`Touchque device.js: ${J(p)}`),null)).then(p=>{if(c.pending=null,h)return p;c.current=p,c.at=i(),S(u),p&&k(u);try{r.dispatchEvent(new CustomEvent(Lt,{detail:{purpose:u,requestId:p?.requestId??null,visitorId:p?.visitorId??null,confidence:p?.confidence??null}}));}catch{}return p}),c.pending)},x=u=>{for(let c of D(u)){let p=_(c),R=w(c),j=s.get(p);j?.current?R.value=j.current.requestId:E(p);}},A=()=>{for(let[u,c]of s)(c.stale||c.at&&i()-c.at>=Be)&&E(u);},I=()=>{r.visibilityState!=="hidden"&&A();},M=u=>{let c=u.target;if(!c||c.tagName!=="FORM")return;let p=_(c),R=v(p);R&&(w(c).value=R),setTimeout(()=>{h||E(p);},Kt);},C=n.MutationObserver,N=typeof C=="function"?new C(u=>{for(let c of u)for(let p of Array.from(c.addedNodes))p.nodeType===1&&x(p);}):null,m=E(a);try{N?.observe(r.documentElement,{childList:!0,subtree:!0}),r.addEventListener("submit",M,!0),r.addEventListener("visibilitychange",I),r.addEventListener("focusin",A),x(r),r.readyState==="loading"&&r.addEventListener("DOMContentLoaded",()=>x(r),{once:!0});}catch{}return {ready:m,get requestId(){return s.get(a)?.current?.requestId??null},get visitorId(){return s.get(a)?.current?.visitorId??null},value:u=>v(Q(u)?u:a),refresh:u=>E(Q(u)?u:a),attach(u){l.add(u),x(u);},stop(){h=true,N?.disconnect(),r.removeEventListener("submit",M,true),r.removeEventListener("visibilitychange",I),r.removeEventListener("focusin",A);for(let u of s.values())u.timer&&clearTimeout(u.timer);d?.stop(),g?.stop();},version:$e}}function qe(e,t=window){let n=t;if(n.TouchqueDevice)return n.TouchqueDevice;let r=e??t.document.querySelector("script[data-site-key]"),i=r?.getAttribute("data-site-key")||"",o=r?.getAttribute("data-purpose")||void 0,a=r?.getAttribute("data-api")||void 0,s=r?.getAttribute("data-pointer")!=="off";r?.hasAttribute("data-debug")&&typeof console<"u"&&xe(console);let l=i?Ft({siteKey:i,purpose:o,apiBaseUrl:a,pointer:s},{win:t}):Bt();return n.TouchqueDevice=l,l}function Bt(){return B("Touchque device.js: data-site-key is missing on the script tag (dashboard \u2192 Device risk \u2192 Settings)."),{ready:Promise.resolve(null),requestId:null,visitorId:null,value:()=>null,refresh:()=>Promise.resolve(null),attach:()=>{},stop:()=>{},version:$e}}qe(typeof document<"u"?document.currentScript:null);
|
|
9
|
+
})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@touchque/device-risk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "3.0.0",
|
|
4
|
+
"description": "Touchque Device Risk for the browser: recognise browsers on sign-in, sign-up and payment pages, tell bots, emulators and spoofed browsers apart; the script tag served at cdn.touchque.com/device",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Touchque/touchque-device-risk-web.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://touchque.com",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"author": "Touchque",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"module": "./dist/index.mjs",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"import": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" },
|
|
18
|
+
"require": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": ["dist", "CHANGELOG.md"],
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"engines": { "node": ">=18" },
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"test": "vitest run",
|
|
27
|
+
"prepublishOnly": "npm run build && npm test"
|
|
28
|
+
},
|
|
29
|
+
"keywords": ["touchque", "device-risk", "device-fingerprint", "bot-detection", "fraud", "browser"],
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"jsdom": "^25.0.1",
|
|
32
|
+
"tsup": "^8.0.2",
|
|
33
|
+
"typescript": "^5.4.5",
|
|
34
|
+
"vitest": "^2.1.4"
|
|
35
|
+
}
|
|
36
|
+
}
|