-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
171 lines (164 loc) · 26 KB
/
Copy pathworker.js
File metadata and controls
171 lines (164 loc) · 26 KB
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
// GENERATED — do not edit. Published byte-identical to the script the WebDecoy
// app deploys via its one-click installer. Source lives in the WebDecoy app repo.
// GENERATED by edge/clearance-worker/scripts/bundle.mjs — DO NOT EDIT.
// Source: edge/clearance-worker/src. Rebuild with `npm run build:bundle`.
var q="web-bot-auth";async function b(e,t){let n=e.headers.get("signature-input"),r=e.headers.get("signature");if(!n&&!r)return{status:"none"};if(!n||!r)return{status:"invalid"};if(!t||t.length===0)return{status:"unknown_key"};let i,s;try{i=ie(n),s=se(r)}catch{return{status:"invalid"}}let a=!1,o=!1;for(let u of i){if(u.params.get("tag")!==q)continue;a=!0;let l=s.get(u.label);if(!l)continue;let c=u.params.get("keyid");if(typeof c!="string")continue;let g=t.find(p=>p.keyid===c);if(!g)continue;o=!0;let m=Date.now()/1e3,P=u.params.get("created"),D=u.params.get("expires");if(typeof D=="number"&&m>=D+10||typeof P=="number"&&m+10<P||!u.components.some(p=>p.name==="@authority"||p.name==="@target-uri"))continue;let T;try{T=ee(e,u)}catch{continue}let v=!1;try{let p=await crypto.subtle.importKey("raw",B(g.public_key),{name:"Ed25519"},!1,["verify"]);v=await crypto.subtle.verify({name:"Ed25519"},p,l,new TextEncoder().encode(T))}catch{v=!1}if(v)return{status:"verified",name:g.name,category:g.category,keyid:c}}return o?{status:"invalid"}:a?{status:"unknown_key"}:{status:"none"}}function ee(e,t){let n=new URL(e.url),r=[];for(let i of t.components)r.push(`${te(i)}: ${ne(e,n,i)}`);return r.push(`"@signature-params": ${t.raw.trim()}`),r.join(`
`)}function te(e){let t=`"${e.name.toLowerCase()}"`;return e.keyParam!==void 0?`${t};key="${e.keyParam}"`:t}function ne(e,t,n){let r=n.name.toLowerCase();if(r==="@authority")return I(t);if(r==="@target-uri")return`${t.protocol}//${I(t)}${t.pathname}${t.search}`;if(r==="signature-agent"){let i=e.headers.get("signature-agent");if(i===null)throw new Error("signature-agent covered but absent");return n.keyParam!==void 0?re(i,n.keyParam):i.trim().replace(/\s+/g," ")}throw new Error(`unsupported covered component ${r}`)}function I(e){let t=e.hostname.toLowerCase(),n=e.port;return!n||e.protocol==="https:"&&n==="443"||e.protocol==="http:"&&n==="80"?t:`${t}:${n}`}function re(e,t){let r=S(e).find(i=>i.key===t);if(!r)throw new Error(`signature-agent has no member ${t}`);return r.raw}function ie(e){return S(e).map(n=>{if(!n.isList)throw new Error(`Signature-Input member ${n.key} is not an inner list`);let r=n.items.map(i=>{if(typeof i.value!="string")throw new Error("component identifier is not a string");let s=i.params.get("key");return{name:i.value,keyParam:typeof s=="string"?s:void 0}});return{label:n.key,components:r,params:n.params,raw:n.raw}})}function se(e){let t=S(e),n=new Map;for(let r of t){if(r.isList||r.items.length!==1)throw new Error(`Signature member ${r.key} is not a byte sequence`);let i=r.items[0].bytes;if(!i)throw new Error(`Signature member ${r.key} is not a byte sequence`);n.set(r.key,i)}return n}var k=class{constructor(t,n=0){this.s=t;this.i=n}s;i;eof(){return this.i>=this.s.length}peek(){return this.s[this.i]}skipSP(){for(;!this.eof()&&(this.peek()===" "||this.peek()===" ");)this.i++}};function S(e){let t=new k(e),n=[];for(t.skipSP();!t.eof();){let i={key:U(t),raw:"",isList:!1,items:[],params:new Map};if(!t.eof()&&t.peek()==="="){t.i++;let s=t.i;if(!t.eof()&&t.peek()==="(")i.isList=!0,ae(t,i);else{let{value:a,params:o,bytes:u}=O(t);i.items.push({value:a,params:o,...u?{bytes:u}:{}})}i.raw=e.slice(s,t.i)}else i.params=E(t),i.items.push({value:!0,params:new Map});if(n.push(i),t.skipSP(),t.eof())break;if(t.peek()!==",")throw new Error(`expected ',' at ${t.i}`);if(t.i++,t.skipSP(),t.eof())throw new Error("trailing comma")}return n}function ae(e,t){for(e.i++;;){if(e.skipSP(),e.eof())throw new Error("unterminated inner list");if(e.peek()===")"){e.i++;break}let{value:n,params:r}=O(e);if(t.items.push({value:n,params:r}),e.eof())throw new Error("unterminated inner list");let i=e.peek();if(i!==" "&&i!==")")throw new Error(`bad inner list at ${e.i}`)}t.params=E(e)}function O(e){let{value:t,bytes:n}=W(e),r=E(e);return{value:t,params:r,bytes:n}}function E(e){let t=new Map;for(;!e.eof()&&e.peek()===";";){e.i++,e.skipSP();let n=U(e),r=!0;if(!e.eof()&&e.peek()==="="){e.i++;let i=W(e);r=(typeof i.value=="boolean",i.value)}typeof r!="boolean"&&t.set(n,r)}return t}function U(e){let t=e.peek();if(!t||!/[a-z*]/.test(t))throw new Error(`invalid key at ${e.i}`);let n=e.i;for(;!e.eof()&&/[a-z0-9_\-.*]/.test(e.peek());)e.i++;return e.s.slice(n,e.i)}function W(e){let t=e.peek();if(t==='"')return{value:oe(e)};if(t===":")return{value:"",bytes:ce(e)};if(t==="?"){e.i++;let n=e.peek();if(e.i++,n==="1")return{value:!0};if(n==="0")return{value:!1};throw new Error("bad boolean")}if(t==="-"||/[0-9]/.test(t))return{value:ue(e)};if(/[a-zA-Z*]/.test(t))return{value:le(e)};throw new Error(`invalid bare item at ${e.i}`)}function oe(e){e.i++;let t="";for(;!e.eof();){let n=e.s[e.i++];if(n==='"')return t;if(n==="\\"){let r=e.s[e.i++];if(r!=='"'&&r!=="\\")throw new Error("bad escape");t+=r}else{let r=n.charCodeAt(0);if(r<32||r>126)throw new Error("bad char in string");t+=n}}throw new Error("unterminated string")}function ce(e){e.i++;let t=e.i;for(;!e.eof()&&e.peek()!==":";)e.i++;if(e.eof())throw new Error("unterminated byte sequence");let n=e.s.slice(t,e.i);return e.i++,B(n)}function ue(e){let t=e.i;for(e.peek()==="-"&&e.i++;!e.eof()&&/[0-9]/.test(e.peek());)e.i++;if(!e.eof()&&e.peek()===".")for(e.i++;!e.eof()&&/[0-9]/.test(e.peek());)e.i++;return Number(e.s.slice(t,e.i))}function le(e){let t=e.i;for(e.i++;!e.eof()&&/[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(e.peek());)e.i++;return e.s.slice(t,e.i)}function B(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function N(e,t){return e==="ai_crawlers"?t.ai_crawlers:e==="search_engines"?t.search_engines:e==="monitoring"?t.monitoring:!1}var de="wdfp1",L=`
async function wdDeviceFP() {
// Canvas: 32-bit rolling hash of the dataURL, matching
// EnvironmentalCollector._getCanvasHash in @webdecoy/client. The drawing
// parameters below are part of the fingerprint \u2014 changing any of them
// changes every fingerprint.
var canvas32 = 'na';
try {
var c = document.createElement('canvas');
c.width = 200; c.height = 50;
var x = c.getContext('2d');
x.textBaseline = 'top'; x.font = '14px Arial';
x.fillStyle = '#f60'; x.fillRect(125, 1, 62, 20);
x.fillStyle = '#069'; x.fillText('FCaptcha', 2, 15);
x.fillStyle = 'rgba(102, 204, 0, 0.7)'; x.fillText('FCaptcha', 4, 17);
var dataUrl = c.toDataURL();
var h = 0;
for (var i = 0; i < dataUrl.length; i++) { h = ((h << 5) - h) + dataUrl.charCodeAt(i); h = h & h; }
canvas32 = h.toString(16);
} catch (e) { canvas32 = 'na'; }
var webgl = 'na';
try {
var gc = document.createElement('canvas');
var gl = gc.getContext('webgl') || gc.getContext('experimental-webgl');
if (gl) {
var dbg = gl.getExtension('WEBGL_debug_renderer_info');
var vendor = dbg ? gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : 'unknown';
var renderer = dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : 'unknown';
webgl = String(renderer) + '~' + String(vendor);
}
} catch (e) { webgl = 'na'; }
var tz = 'na';
try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'na'; } catch (e) {}
var raw = ['${de}', canvas32, webgl,
screen.width + 'x' + screen.height + 'x' + screen.colorDepth,
tz, navigator.platform || 'na', navigator.language || 'na'
].join('|');
var buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
var fp = Array.from(new Uint8Array(buf)).map(function (b) {
return b.toString(16).padStart(2, '0');
}).join('');
return { fp: fp, canvas32: canvas32, webgl: webgl };
}
`;var ge=["/_astro/","/_next/","/_nuxt/","/_app/","/assets/","/static/","/build/","/dist/","/wp-content/","/wp-includes/","/cdn-cgi/"],fe=new Set(["js","mjs","cjs","css","map","png","jpg","jpeg","gif","svg","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","ogg","wav","avi","mov","zip","gz","br","wasm"]);function M(e){for(let r of ge)if(e.startsWith(r))return!0;let t=e.lastIndexOf("/"),n=e.lastIndexOf(".");return n<=t+1?!1:fe.has(e.slice(n+1).toLowerCase())}var $={window_seconds:60,max_per_path:3,max_per_ip:300,max_per_ip_unidentified:60},C=5e3,y=class{constructor(t={}){this.cfg=t}cfg;paths=new Map;ips=new Map;get windowMs(){let t=this.cfg.window_seconds;return(typeof t=="number"&&t>0?t:$.window_seconds)*1e3}limit(t){let n=this.cfg[t];return typeof n=="number"&&n>=0?n:$[t]}check(t,n,r,i=!0){if(!t)return{report:!0};let s=i?this.limit("max_per_ip"):Math.min(this.limit("max_per_ip"),this.limit("max_per_ip_unidentified")),a=this.bump(this.ips,t,r,s);if(!a.report)return a;let o=this.bump(this.paths,t+"\0"+n,r,this.limit("max_per_path")),u=a.suppressedCount??o.suppressedCount,l={report:o.report};return u!==void 0&&(l.suppressedCount=u),(a.suppressionStarted||o.suppressionStarted)&&(l.suppressionStarted=!0,l.report=!0),l}bump(t,n,r,i){let s=t.get(n);if(!s||r-s.windowStart>=this.windowMs){let a=s?.suppressed??0;return t.set(n,{windowStart:r,allowed:1,suppressed:0}),this.evictIfNeeded(t,r),a>0?{report:!0,suppressedCount:a}:{report:!0}}return s.allowed<i?(s.allowed++,{report:!0}):(s.suppressed++,s.suppressed===1?{report:!0,suppressionStarted:!0}:{report:!1})}evictIfNeeded(t,n){if(t.size<=C)return;let r=this.windowMs;for(let[i,s]of t)if(n-s.windowStart>=r&&t.delete(i),t.size<=C)return;for(let i of t.keys())if(t.delete(i),t.size<=C)return}};var A=null,j="";function pe(e){let t=JSON.stringify(e??{});return(!A||t!==j)&&(A=new y(e),j=t),A}var he=new Set(["wba_signature","known_crawler_ua","http_client_ua","crawler_path","cf_verified_bot","missing_client_hints"]),me={wba_signature:!0,known_crawler_ua:!0,http_client_ua:!0,crawler_path:!0,cf_verified_bot:!0,missing_client_hints:!0,no_user_agent:!0,no_language:!1,no_fetch_metadata:!1},V=new Set;function K(e,t){if(!e)return null;try{return new RegExp(e,"i")}catch{return V.has(t)||(V.add(t),console.warn(`[sensor] ignoring invalid ${t}; using built-in`)),null}}function we(e,t,n,r){let i=Array.isArray(t?.exclude_paths)?t.exclude_paths:[];for(let c of i)if(typeof c=="string"&&c&&n.startsWith(c))return{send:!1,flags:[],ai:""};let s=t?.flags&&typeof t.flags=="object"&&!Array.isArray(t.flags)?t.flags:{},a={...me,...s},o=e.flags.filter(c=>a[c]!==!1);if(o.length===0)return{send:!1,flags:[],ai:""};if(!o.some(c=>he.has(c))){let c=t?.sample_rate,g=typeof c=="number"&&c>=0&&c<=1?c:1;if(r>=g)return{send:!1,flags:[],ai:""}}let l=o.includes("known_crawler_ua")||o.includes("http_client_ua")?e.ai:"";return{send:!0,flags:o,ai:l}}function be(e){return e.includes("cf_verified_bot")?"verified":e.includes("known_crawler_ua")?"crawler":e.includes("http_client_ua")||e.includes("missing_client_hints")||e.includes("no_user_agent")?"script":"browser"}var ye=[["applebot-extended","Applebot-Extended"],["google-extended","Google-Extended"],["meta-externalagent","Meta-ExternalAgent"],["oai-searchbot","OAI-SearchBot"],["chatgpt-user","ChatGPT-User"],["perplexitybot","PerplexityBot"],["claudebot","ClaudeBot"],["anthropic-ai","Anthropic"],["gptbot","GPTBot"],["ccbot","CCBot"],["bytespider","ByteSpider"],["amazonbot","Amazonbot"],["facebookbot","FacebookBot"],["cohere-ai","Cohere"],["diffbot","Diffbot"],["youbot","YouBot"],["ai2bot","AI2Bot"],["deepseek","DeepSeek"],["mistralai","MistralAI"],["img2dataset","img2dataset"],["timpibot","Timpibot"],["omgili","Omgili"],["googlebot","Googlebot"],["bingbot","Bingbot"],["yandexbot","YandexBot"],["baiduspider","Baiduspider"],["duckduckbot","DuckDuckBot"],["applebot","Applebot"],["ia_archiver","Internet Archive"],["archive.org_bot","Archive.org"],["semrushbot","SEMrush"],["ahrefsbot","Ahrefs"],["mj12bot","Majestic"],["dotbot","Moz/DotBot"]],_e=[["python-requests","Python-Requests"],["python-urllib","Python-urllib"],["go-http-client","Go-HTTP-Client"],["node-fetch","node-fetch"],["libwww-perl","libwww-perl"],["beautifulsoup","BeautifulSoup"],["headlesschrome","HeadlessChrome"],["phantomjs","PhantomJS"],["playwright","Playwright"],["puppeteer","Puppeteer"],["aiohttp","aiohttp"],["scrapy","Scrapy"],["httrack","HTTrack"],["undici","Undici"],["okhttp","OkHttp"],["httpx","HTTPX"],["colly","Colly"],["curl/","cURL"],["wget/","Wget"],["axios/","Axios"],["java/","Java"],["got/","Got"]],ve=/(?:bot|crawler|spider)(?:[/\s);,]|$)/i,ke=/^\/(?:robots\.txt|sitemap[\w.-]*\.xml|sitemaps?\/)/i,Se=/(?:chrome|chromium|edg)\//i,Ee=/(?:crios|edgios|fxios)\//i;function z(e,t){for(let[n,r]of t)if(e.includes(n))return r;return""}function Ce(e,t,n){let r=[],i=e.headers,s=i.get("user-agent")??"",a=s.toLowerCase(),o=K(n?.crawler_ua_pattern,"crawler_ua_pattern"),u=K(n?.tool_ua_pattern,"tool_ua_pattern");(i.get("signature-agent")||i.get("signature-input"))&&r.push("wba_signature");let l=z(a,ye);(l||(o??ve).test(s))&&r.push("known_crawler_ua");let c=z(a,_e);return c?(r.push("http_client_ua"),l||(l=c)):u?.test(s)&&r.push("http_client_ua"),ke.test(t.pathname)&&r.push("crawler_path"),(e.cf?.verifiedBotCategory??"")&&r.push("cf_verified_bot"),t.protocol==="https:"&&Se.test(a)&&!Ee.test(a)&&!i.get("sec-ch-ua")&&r.push("missing_client_hints"),s||r.push("no_user_agent"),i.get("accept-language")||r.push("no_language"),i.get("sec-fetch-mode")||r.push("no_fetch_metadata"),{send:r.length>0,flags:r,ai:l}}var Ae="edge_worker",xe=["known_crawler_ua","cf_verified_bot","wba_signature"];function Re(e){return e.some(t=>xe.includes(t))}var Pe=2e3,De=/^(?:cf-|x-forwarded-|x-real-ip$|true-client-ip$|cdn-loop$)/;function Te(e){let t=e.headers,n=[];for(let[s]of t){let a=s.toLowerCase();De.test(a)||n.push(a)}n.sort();let r=e.cf??{},i=r.botManagement??{};return{hn:n,al:t.get("accept-language")??"",ae:t.get("accept-encoding")??"",ja3:f(i.ja3Hash),ja4:f(i.ja4),tls:Ie(r),tc:f(r.tlsClientCiphersSha1)}}function f(e){return typeof e=="string"?e:""}function Ie(e){let t=[f(e.tlsVersion),f(e.tlsCipher),f(e.tlsClientCiphersSha1),f(e.tlsClientExtensionsSha1)];return t.some(n=>n!=="")?t.join("|"):""}function Oe(e,t,n,r,i){let s=e.headers,a=e.cf;return{aid:n,sid:r,v:2,s:0,f:i.flags,ai:i.ai,source:Ae,ua:s.get("user-agent")??"",ip:s.get("cf-connecting-ip")??"",url:t.toString(),ref:s.get("referer")??"",ts:Date.now(),cs:Te(e),metadata:{edge:"cloudflare",method:e.method,asn:a?.asn??null,country:a?.country??null,verified_bot_category:a?.verifiedBotCategory??""}}}function G(e,t,n,r,i,s,a){try{if(M(t.pathname))return"";let o=Ce(e,t,i),u=be(o.flags);if(!i?.enabled||!i.scanner_id||!o.send)return u;let l=we(o,i,t.pathname,Math.random());if(!l.send)return u;let c=pe(i.burst).check(e.headers.get("cf-connecting-ip")??"",t.pathname,Date.now(),Re(l.flags));if(!c.report)return u;let g=Oe(e,t,n,i.scanner_id,l);if(c.suppressedCount||c.suppressionStarted){let m=g.metadata;c.suppressedCount&&(m.suppressed_count=c.suppressedCount),c.suppressionStarted&&(m.suppression_started=!0),l.flags.push("burst_suppressed")}return s.waitUntil(Ue(r,g,l,e,a).then(()=>{},()=>{})),u}catch{return""}}async function Ue(e,t,n,r,i){if(n.flags.includes("wba_signature"))try{let s=await b(r,i);t.agent={status:s.status,name:"name"in s?s.name:"",category:"category"in s?s.category:"",key_id:"keyid"in s?s.keyid:"",signature_input:r.headers.get("signature-input")??"",signature_agent:r.headers.get("signature-agent")??""}}catch{}return fetch(`${e}/api/v1/detect/public`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(Pe)})}var d=null;function F(e,t,n,r,i,s=Date.now()){try{if(!e||!n||!r)return;let a=Math.floor(s/1e3/60)*60;d&&(d.bucketStart!==a||d.mode!==t)&&(H(d,n,r,i),d=null),d||(d={bucketStart:a,mode:t,counts:new Map,total:0}),d.counts.set(e,(d.counts.get(e)??0)+1),d.total++,d.total>=500&&(H(d,n,r,i),d=null)}catch{}}function H(e,t,n,r){try{if(e.total<=0||e.counts.size===0)return;let i={};for(let[a,o]of e.counts)i[a]=o;let s=JSON.stringify({organization_id:t,bucket_start:e.bucketStart,mode:e.mode,counts:i});r.waitUntil(We(n,s).then(()=>{},()=>{}))}catch{}}async function We(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),3e3);try{await fetch(e.replace(/\/+$/,"")+"/api/v1/clearance/telemetry",{method:"POST",headers:{"content-type":"application/json"},body:t,signal:n.signal})}finally{clearTimeout(r)}}var Be=6e4,Ne="x-wd-service-token",Le="wd_clearance",w="x-wd-clearance",x="x-wd-class",Me="__wd_clearance_check",Z="/.well-known/wd-clearance/pat",h=null,J=0,pt={async fetch(e,t,n){try{return await $e(e,t,n)}catch{return fetch(e)}}};async function $e(e,t,n){let r=new URL(e.url),i=r.searchParams.get(Me);e=Ze(e);let s=await Je(t);if(i!==null)return Ye(i,s?s.mode:"unknown",t.WD_SITE_KEY);if(r.pathname===Z)return Xe(e,t);if(!s)return fetch(e);let a=G(e,r,t.WD_SITE_KEY,t.WD_API_BASE,s.sensor,n,s.signed_agents),o=await je(e,t,s);return F(o.label,s.mode,t.WD_SITE_KEY,t.WD_API_BASE,n),o.pass||s.mode!=="enforce"?Qe(e,o.label,a):qe(e,t)}async function je(e,t,n){let r=e.headers.get(Ne);if(r){let c=await Y(r,n.keys,t.WD_SITE_KEY);if(c&&c.typ==="machine"&&c.sub&&n.active_credentials.includes(c.sub))return{pass:!0,label:"machine"}}let i=e.cf?.verifiedBotCategory??"";if(i&&Ge(i,n.allow))return{pass:!0,label:"verified-bot"};let s=await b(e,n.signed_agents);if(s.status==="verified"&&N(s.category,n.allow))return{pass:!0,label:"signed-agent"};if(s.status==="invalid"){let c=new URL(e.url).pathname;if(R(c,n.routes))return{pass:!1,label:"agent-impersonation"}}let a=new URL(e.url).pathname;if(!R(a,n.routes))return{pass:!0,label:"unscoped"};let o=He(e.headers.get("cookie")??"",Le);if(!o)return{pass:!1,label:"missing"};let u=await Y(o,n.keys,t.WD_SITE_KEY);if(!u||(u.typ??"")!=="")return{pass:!1,label:"invalid"};if(n.denied_fps&&n.denied_fps.includes(u.fp))return{pass:!1,label:"revoked"};let l=ze(a,n.route_min_trust);return l&&!Ke(u.trust,l)?{pass:!1,label:"insufficient-trust"}:{pass:!0,label:"valid"}}var Ve={"attested-human":2,"human-likely":1,clean:0};function _(e){return Ve[e??""]??0}function Ke(e,t){return _(e)>=_(t)}function ze(e,t){let n="";if(!t)return n;for(let r of t)R(e,[r.pattern])&&_(r.min_trust)>_(n)&&(n=r.min_trust);return n}function Ge(e,t){let n=e.toLowerCase();return!!(t.search_engines&&n.includes("search engine crawler")||t.ai_crawlers&&n.startsWith("ai ")||t.monitoring&&n.includes("monitoring"))}function R(e,t){for(let n of t)if(n.endsWith("/*")){let r=n.slice(0,-2)||"/";if(e===r||e.startsWith(r+"/"))return!0}else if(e===n)return!0;return!1}function He(e,t){for(let n of e.split(";")){let r=n.indexOf("=");if(!(r<0)&&n.slice(0,r).trim()===t)return n.slice(r+1).trim()||null}return null}async function Y(e,t,n){try{let r=e.indexOf(".");if(r<0)return null;let i=X(e.slice(0,r)),s=X(e.slice(r+1)),a=JSON.parse(new TextDecoder().decode(i)),o=t.find(c=>c.kid===a.kid);if(!o)return null;let u=await crypto.subtle.importKey("raw",Fe(o.public_key),{name:"Ed25519"},!1,["verify"]);return!await crypto.subtle.verify({name:"Ed25519"},u,s,i)||a.tenant!==n||Date.now()/1e3>=a.exp?null:a}catch{return null}}function X(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);return Q(atob(t))}function Fe(e){return Q(atob(e))}function Q(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async function Je(e){let t=Date.now();if(h&&t-J<Be)return h;try{let n=await fetch(`${e.WD_API_BASE}/api/v1/clearance/config?aid=${encodeURIComponent(e.WD_SITE_KEY)}`,{signal:AbortSignal.timeout(3e3)});return n.ok&&(h=await n.json(),J=t),h}catch{return h}}function Ye(e,t,n){return new Response(JSON.stringify({wd_clearance:!0,nonce:e,mode:t,site_key:n}),{status:200,headers:{"content-type":"application/json","cache-control":"no-store","access-control-allow-origin":"*"}})}async function Xe(e,t){let n=new URL(e.url).searchParams.get("fp")??"",r=`${t.WD_API_BASE}/api/v1/clearance/pat?fp=${encodeURIComponent(n)}`,i=new Headers,s=e.headers.get("authorization");s&&i.set("authorization",s);let a;try{a=await fetch(r,{method:"GET",headers:i,redirect:"manual"})}catch{return new Response(JSON.stringify({attested:!1,reason:"unreachable"}),{status:200,headers:{"content-type":"application/json","cache-control":"no-store"}})}let o=new Headers({"content-type":"application/json","cache-control":"no-store"}),u=a.headers.get("www-authenticate");return u&&o.set("www-authenticate",u),new Response(a.body,{status:a.status,headers:o})}function Ze(e){if(!e.headers.has(x)&&!e.headers.has(w))return e;let t=new Headers(e.headers);return t.delete(x),t.delete(w),new Request(e,{headers:t})}function Qe(e,t,n=""){let r=new Headers(e.headers);return r.set(w,t),n&&r.set(x,n),fetch(new Request(e,{headers:r}))}function qe(e,t){let n=e.headers.get("accept")??"";if(e.method!=="GET"||!n.includes("text/html"))return new Response(JSON.stringify({error:"clearance required"}),{status:403,headers:{"content-type":"application/json",[w]:"challenged"}});let r=et(t.WD_API_BASE,t.WD_SITE_KEY);return new Response(r,{status:403,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store",[w]:"challenged"}})}function et(e,t){return`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Checking your browser\u2026</title>
<style>
body { font-family: system-ui, sans-serif; display: flex; align-items: center;
justify-content: center; min-height: 100vh; margin: 0; background: #0b0e14; color: #e6e6e6; }
.box { text-align: center; max-width: 24rem; padding: 2rem; }
.spin { width: 2rem; height: 2rem; margin: 0 auto 1rem; border: 3px solid #2a2f3a;
border-top-color: #22d3ee; border-radius: 50%; animation: r 0.8s linear infinite; }
@keyframes r { to { transform: rotate(360deg); } }
p { color: #9aa4b2; font-size: 0.9rem; line-height: 1.5; }
</style>
</head>
<body>
<div class="box">
<div class="spin" id="spin"></div>
<h1 style="font-size:1.1rem">Checking your browser</h1>
<p id="msg">This takes a moment and happens only once.</p>
</div>
<script>
${L}
(async function () {
var msg = document.getElementById('msg');
try {
// CANONICAL device fp, from the single shared source in device-fp.ts.
// Returns the fingerprint plus the raw canvas/WebGL signals the integrity
// check below also needs, so neither context is built twice.
var dfp = await wdDeviceFP();
var fp = dfp.fp;
var canvas32 = dfp.canvas32;
var webgl = dfp.webgl;
// Browser-integrity signals (#327). Collected in-browser and reported raw \u2014
// the server decides. A real browser is internally consistent; a standard
// headless/automation environment betrays incoherence it does not spoof by
// default (permission vs Notification state, absent navigator.languages,
// a Chrome UA with no window.chrome). Coherent signals earn the token a
// 'human-likely' grade; anything off falls back to 'clean' (never blocked).
var integrity = {
webdriver: navigator.webdriver === true,
headless_ua: /headless/i.test(navigator.userAgent),
no_plugins: !(navigator.plugins && navigator.plugins.length > 0),
no_languages: !(navigator.languages && navigator.languages.length > 0),
hardware: navigator.hardwareConcurrency || 0,
canvas_ok: canvas32 !== 'na',
webgl_ok: webgl !== 'na',
chrome_ua: /chrome|chromium|crios/i.test(navigator.userAgent),
chrome_obj: (typeof window.chrome === 'object' && window.chrome !== null),
perm_coherent: true
};
try {
if (navigator.permissions && navigator.permissions.query && typeof Notification !== 'undefined') {
var perm = await navigator.permissions.query({ name: 'notifications' });
// Classic headless-Chrome tell: Notification.permission is the default
// 'default', yet the Permissions API reports 'denied'. A real browser
// agrees with itself.
if (Notification.permission === 'default' && perm.state === 'denied') integrity.perm_coherent = false;
}
} catch (e) { /* permissions unsupported \u2014 leave coherent, fail open */ }
// Device attestation (#329). On a supporting client \u2014 Apple platforms
// today \u2014 this endpoint answers 401 with a PrivateToken challenge, the OS
// silently obtains a token and retries, and we get back a receipt worth an
// 'attested-human' grade. No puzzle, no interaction, nothing to see.
//
// Everywhere else it fails or 401s and we move on: the absence of
// attestation must never cost a visitor anything, because attester
// coverage is thin and not their fault.
var patReceipt = '';
try {
// SAME-ORIGIN by way of the validator's proxy. Fetching WebDecoy directly
// meant Safari ignored the 401 challenge entirely \u2014 cross-origin
// WWW-Authenticate does not trigger its challenge/response handling, so a
// token was never requested. credentials stay same-origin so the browser
// is permitted to do the auth exchange.
var patRes = await fetch(
${JSON.stringify(Z)} + '?fp=' + encodeURIComponent(fp),
{ credentials: 'same-origin' }
);
if (patRes.ok) {
var patOut = await patRes.json();
if (patOut && patOut.attested && patOut.receipt) patReceipt = patOut.receipt;
}
} catch (e) { /* unsupported or unreachable \u2014 proceed unattested */ }
var res = await fetch(${JSON.stringify(e)} + '/api/v1/clearance', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
aid: ${JSON.stringify(t)},
fp: fp,
scope: '',
ua: navigator.userAgent,
webdriver: integrity.webdriver,
headless: integrity.headless_ua,
integrity: integrity,
pat_receipt: patReceipt
})
});
var out = await res.json();
if (out && out.granted && out.token) {
document.cookie = 'wd_clearance=' + out.token +
'; path=/; secure; samesite=lax; max-age=' + (out.expires_in || 1800);
location.reload();
return;
}
document.getElementById('spin').style.display = 'none';
msg.textContent = 'Verification did not pass. If you believe this is an error, contact the site owner.';
} catch (e) {
document.getElementById('spin').style.display = 'none';
msg.textContent = 'Verification could not complete. Please retry shortly.';
}
})();
</script>
</body>
</html>`}export{pt as default,R as matchesScope,Ke as meetsTrust,ze as requiredTrust,_ as trustRank};