@netacea/cloudflare 6.0.83 → 6.0.85

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const n=d(e,"Domain"),s=d(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");if(n<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}},C=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-match",v="x-netacea-mitigate",I="x-netacea-captcha",b="x-netacea-mitata-expiry",N="x-netacea-mitatacaptcha-value",A="x-netacea-mitatacaptcha-expiry",T="x-netacea-event-id",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},_={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},x={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},R={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},O="_/@#/",L="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),K=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function D(e){if(void 0===e)return;const t=e.match(K);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function M(e=16,t=L){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function j(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function q(e,i){const a=await j(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var H;async function B(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function F(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function V(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}function $(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function U(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function G(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}function W(e){return void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)?function(e){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");const t=new Headers(e.responseHeaders);return t.append("Location",e.config.netaceaBlockedResponseRedirectLocation),new Response("Forbidden",{status:303,statusText:"",headers:t})}(e):function(e){return new Response("Forbidden",{status:403,statusText:"Forbidden",headers:e.responseHeaders})}(e)}function J(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(H||(H={}));class Q extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var X="@netacea/cloudflare",Y="6.0.83",Z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ee={},te={};Object.defineProperty(te,"__esModule",{value:!0}),te.validateRedirectLocation=void 0,te.validateRedirectLocation=function(e){if(""!==(e=e??""))try{return new URL(e).toString()}catch{if(/^https?:\/\//i.test(e))return;return e.startsWith("/")?e:`/${e}`}};var ie={},ae={};function ne(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=oe("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function se(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...re(s,t))}return i}function oe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function re(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ae,"__esModule",{value:!0}),ae.findAllInCookieString=ae.findFirstInCookieString=ae.findAllInHeaders=ae.findFirstInHeaders=ae.findOnlyValueInHeaders=ae.findAllValuesInHeaders=ae.findFirstValueInHeaders=void 0,ae.findFirstValueInHeaders=function(e,t){const i=ne(e,t);if(void 0!==i)return i.slice(t.length+1)},ae.findAllValuesInHeaders=function(e,t){return se(e,t).map((e=>e.slice(t.length+1)))},ae.findOnlyValueInHeaders=function(e,t){const i=se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ae.findFirstInHeaders=ne,ae.findAllInHeaders=se,ae.findFirstInCookieString=oe,ae.findAllInCookieString=re;var ce={};function ue(e){return"set-cookie"===e||"Set-Cookie"===e}function he(e,t){const i=t+"=";return e.startsWith(i)}function de(e,t){if(!he(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function pe(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function le(e,t){for(const i of Object.keys(e)){if(!ue(i))continue;const a=ge(pe(e,i),t);if(void 0!==a)return a}}function ge(e,t){return e.map((e=>e.trimStart())).find((e=>he(e,t)))}function fe(e,t){const i=[];for(const a of Object.keys(e)){if(!ue(a))continue;const n=pe(e,a);i.push(...ye(n,t))}return i}function ye(e,t){return e.map((e=>e.trimStart())).filter((e=>he(e,t)))}Object.defineProperty(ce,"__esModule",{value:!0}),ce.findAllInSetCookieStrings=ce.findAllInHeaders=ce.findValueInSetCookieStrings=ce.findFirstInSetCookieStrings=ce.findFirstInHeaders=ce.findOnlyValueInHeaders=ce.findFirstValueInHeaders=ce.parseValueFromString=void 0,ce.parseValueFromString=de,ce.findFirstValueInHeaders=function(e,t){const i=le(e,t);return void 0!==i?de(i,t):void 0},ce.findOnlyValueInHeaders=function(e,t){const i=fe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?de(i[0],t):void 0},ce.findFirstInHeaders=le,ce.findFirstInSetCookieStrings=ge,ce.findValueInSetCookieStrings=function(e,t){const i=ge(e,t);if(void 0!==i)return de(i,t)},ce.findAllInHeaders=fe,ce.findAllInSetCookieStrings=ye;var me=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Se=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ce=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&me(t,e,i);return Se(t,e),t};Object.defineProperty(ie,"__esModule",{value:!0}),ie.setCookie=ie.cookie=void 0,ie.cookie=Ce(ae),ie.setCookie=Ce(ce);var ke={},we={},ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.KINESIS_URL=ve.API_VERSION=ve.REGION=ve.PAYLOAD_TYPE=ve.STATE=void 0,ve.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ve.PAYLOAD_TYPE="string",ve.REGION="eu-west-1",ve.API_VERSION="2013-12-02",ve.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.headersToRecord=Ie.increaseBatchSize=Ie.handleFailedLogs=Ie.batchArrayForKinesis=Ie.sleep=void 0,Ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let n=0;n<e.length;n+=t){const s=e.slice(n,n+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Ie.handleFailedLogs=function(e,t,i){const a=2*i,n=[...e,...t],s=n.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),n.splice(0,s)),n},Ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(we,"__esModule",{value:!0}),we.WebStandardKinesis=void 0;const be=ve,Ne=Ie;we.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:(0,Ne.headersToRecord)(i.headers),host:be.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ne.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ne.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ne.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ne.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const n={Records:(0,Ne.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(be.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.Kinesis=void 0;const Te=ve,Ee=Ie;Ae.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Ee.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ee.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ee.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ee.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:n}=e,s={Records:(0,Ee.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:Te.REGION},{accessKeyId:a,secretAccessKey:n})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=we;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Ae;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ke);var _e={};function Pe(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(_e,"__esModule",{value:!0}),_e.parseHttpHeaderName=_e.stringOrDefault=_e.parseIntOrDefault=_e.parseNumberOrDefault=void 0,_e.parseNumberOrDefault=Pe,_e.parseIntOrDefault=function(e,t){const i=Pe(e,t);return"number"==typeof i?Math.floor(i):i},_e.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},_e.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.searchParamsFromRecord=void 0,xe.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Re={},Oe={},Le=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ke=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),De=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Le(t,e,i);return Ke(t,e),t};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.isJweEncrypted=Oe.decrypt=Oe.encrypt=void 0;const Me=De(i);Oe.encrypt=async function(e,t){const i=Me.base64url.decode(t),a=(new TextEncoder).encode(e);return await new Me.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},Oe.decrypt=async function(e,t){const i=Me.base64url.decode(t),{plaintext:a}=await Me.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},Oe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var je=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),qe=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),He=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&je(t,e,i);return qe(t,e),t};Object.defineProperty(Re,"__esModule",{value:!0}),Re.jwe=void 0,Re.jwe=He(Oe);var Be,Fe,Ve={};function $e(){if(Fe)return ee;Fe=1;var e=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),t=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=Z&&Z.__importStar||function(i){if(i&&i.__esModule)return i;var a={};if(null!=i)for(var n in i)"default"!==n&&Object.prototype.hasOwnProperty.call(i,n)&&e(a,i,n);return t(a,i),a};return Object.defineProperty(ee,"__esModule",{value:!0}),ee.graphql=ee.webcrypto=ee.url=ee.parsing=ee.ingest=ee.headers=ee.configValidation=void 0,ee.configValidation=i(te),ee.headers=i(ie),ee.ingest=i(ke),ee.parsing=i(_e),ee.url=i(xe),ee.webcrypto=i(Re),ee.graphql=i(function(){if(Be)return Ve;Be=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.truncateLongFields=Ve.parseGraphQl=Ve.parseGraphQlRequestBody=Ve.getGraphQLParserConfig=void 0;const e=$e();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(n=i,(a=s).length<=n?a:a.slice(0,n)+"…")}var a,n;return t}return Ve.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Ve.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const n=JSON.parse(a);if("object"!=typeof n)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,n?.query??"")},o=(n?.operationName??"").trim();return""!==o&&(s.OpName=o),i(e,s)},Ve.parseGraphQl=t,Ve.truncateLongFields=i,Ve}()),ee}var Ue=$e();const ze="unknown";function Ge(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let o=E[a]??ze+"_";o+=_[n]??ze;let r=x[n];if("0"!==s){o+=","+(P[s]??ze);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function We(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}async function Je(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const n=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new Qe("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");n.push(s)}const s=new Uint8Array(a);let o=0;for(const e of n)s.set(e,o),o+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:Ue.graphql.parseGraphQlRequestBody(e,a)}}class Qe extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class Xe{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.netaceaCookieName),n=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",r=Ue.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=D(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(O),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5","a","c","e"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await q(t+"|"+n.expiry,i),h=n.ipHash===u,d=n.signature===await q(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?H.RENEW_SESSION:H.EXISTING_SESSION,{sessionStatus:u}=Ge(e.mitigationType,s.protectorCheckCodes,U(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:s,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:M(),sessionCookieStatus:H.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await Ye(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:o,sessionDetails:{captchaToken:n,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await Je(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof Qe){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await F(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function Ye(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await We(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,n=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await async function(e){const t=e.join(",");return await We(t)}(n);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:Ze}=Ue.configValidation,{configureCookiesDomain:et}=S.cookie.attributes;class tt{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Ue.parsing.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:v}=et(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var I;this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(I=C)&&I.startsWith("/")&&I.length>=5?I:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=Ze(e.netaceaBlockedResponseRedirectLocation),this.graphQL=Ue.graphql.getGraphQLParserConfig(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new tt(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ue.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new Xe(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,a,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=U(t.url,e.method,this.config.netaceaCaptchaVerificationPath),n=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&$(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!s&&!n)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!n?"captcha"===i.mitigation?{...i,response:J({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:W({config:this.config,request:e,responseHeaders:o()})}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=D(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Ge(this.config.mitigationType,a,U(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),n=function(e,t,i,a){const n=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,o=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=Ue.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:X?.replace("@netacea/","")??"",IntegrationVersion:Y,NetaceaMitigationApplied:n??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${o} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...n,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(n)),t=await this.makeRequest(e);if(200!==t.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await C(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",X.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Y),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const n=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:z(n,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?V(e.headers.get("Accept")??void 0):V();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Q&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:U(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await F(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([H.NEW_SESSION,H.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,n=d.mitigate,s=d.captcha,o=d.body,u=d.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await q(e+"|"+String(i),a),n].join(O);return`${await q(s,a)}${O}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await B(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[N];const i=parseInt(e[A]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await B(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Q(e,i);const a=e.headers[w]??"0",n=e.headers[v]??"0",s=e.headers[I]??"0";let o=parseInt(e.headers[b]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[T];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:G({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t,n["X-Netacea-Request-Id"]=e.requestId;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=Ge(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[k.block,k.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if($(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaPath)){const t=await async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}}(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if(U(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===H.NEW_SESSION,a=t===H.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const n=d(e,"Domain"),s=d(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");if(n<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}},C=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-match",v="x-netacea-mitigate",I="x-netacea-captcha",b="x-netacea-mitata-expiry",N="x-netacea-mitatacaptcha-value",A="x-netacea-mitatacaptcha-expiry",T="x-netacea-event-id",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},_={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},x={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},R={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},O="_/@#/",L="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),K=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function D(e){if(void 0===e)return;const t=e.match(K);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function M(e=16,t=L){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function j(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function q(e,i){const a=await j(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var H;async function B(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function F(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function V(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}function $(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function U(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function G(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}function W(e){return void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)?function(e){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");const t=new Headers(e.responseHeaders);return t.append("Location",e.config.netaceaBlockedResponseRedirectLocation),new Response("Forbidden",{status:303,statusText:"",headers:t})}(e):function(e){return new Response("Forbidden",{status:403,statusText:"Forbidden",headers:e.responseHeaders})}(e)}function J(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(H||(H={}));class Q extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var X="@netacea/cloudflare",Y="6.0.85",Z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ee={},te={};Object.defineProperty(te,"__esModule",{value:!0}),te.validateRedirectLocation=void 0,te.validateRedirectLocation=function(e){if(""!==(e=e??""))try{return new URL(e).toString()}catch{if(/^https?:\/\//i.test(e))return;return e.startsWith("/")?e:`/${e}`}};var ie={},ae={};function ne(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=oe("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function se(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...re(s,t))}return i}function oe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function re(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ae,"__esModule",{value:!0}),ae.findAllInCookieString=ae.findFirstInCookieString=ae.findAllInHeaders=ae.findFirstInHeaders=ae.findOnlyValueInHeaders=ae.findAllValuesInHeaders=ae.findFirstValueInHeaders=void 0,ae.findFirstValueInHeaders=function(e,t){const i=ne(e,t);if(void 0!==i)return i.slice(t.length+1)},ae.findAllValuesInHeaders=function(e,t){return se(e,t).map((e=>e.slice(t.length+1)))},ae.findOnlyValueInHeaders=function(e,t){const i=se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ae.findFirstInHeaders=ne,ae.findAllInHeaders=se,ae.findFirstInCookieString=oe,ae.findAllInCookieString=re;var ce={};function ue(e){return"set-cookie"===e||"Set-Cookie"===e}function he(e,t){const i=t+"=";return e.startsWith(i)}function de(e,t){if(!he(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function pe(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function le(e,t){for(const i of Object.keys(e)){if(!ue(i))continue;const a=ge(pe(e,i),t);if(void 0!==a)return a}}function ge(e,t){return e.map((e=>e.trimStart())).find((e=>he(e,t)))}function fe(e,t){const i=[];for(const a of Object.keys(e)){if(!ue(a))continue;const n=pe(e,a);i.push(...ye(n,t))}return i}function ye(e,t){return e.map((e=>e.trimStart())).filter((e=>he(e,t)))}Object.defineProperty(ce,"__esModule",{value:!0}),ce.findAllInSetCookieStrings=ce.findAllInHeaders=ce.findValueInSetCookieStrings=ce.findFirstInSetCookieStrings=ce.findFirstInHeaders=ce.findOnlyValueInHeaders=ce.findFirstValueInHeaders=ce.parseValueFromString=void 0,ce.parseValueFromString=de,ce.findFirstValueInHeaders=function(e,t){const i=le(e,t);return void 0!==i?de(i,t):void 0},ce.findOnlyValueInHeaders=function(e,t){const i=fe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?de(i[0],t):void 0},ce.findFirstInHeaders=le,ce.findFirstInSetCookieStrings=ge,ce.findValueInSetCookieStrings=function(e,t){const i=ge(e,t);if(void 0!==i)return de(i,t)},ce.findAllInHeaders=fe,ce.findAllInSetCookieStrings=ye;var me=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Se=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ce=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&me(t,e,i);return Se(t,e),t};Object.defineProperty(ie,"__esModule",{value:!0}),ie.setCookie=ie.cookie=void 0,ie.cookie=Ce(ae),ie.setCookie=Ce(ce);var ke={},we={},ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.KINESIS_URL=ve.API_VERSION=ve.REGION=ve.PAYLOAD_TYPE=ve.STATE=void 0,ve.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ve.PAYLOAD_TYPE="string",ve.REGION="eu-west-1",ve.API_VERSION="2013-12-02",ve.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.headersToRecord=Ie.increaseBatchSize=Ie.handleFailedLogs=Ie.batchArrayForKinesis=Ie.sleep=void 0,Ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let n=0;n<e.length;n+=t){const s=e.slice(n,n+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Ie.handleFailedLogs=function(e,t,i){const a=2*i,n=[...e,...t],s=n.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),n.splice(0,s)),n},Ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(we,"__esModule",{value:!0}),we.WebStandardKinesis=void 0;const be=ve,Ne=Ie;we.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:(0,Ne.headersToRecord)(i.headers),host:be.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ne.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ne.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ne.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ne.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const n={Records:(0,Ne.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(be.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.Kinesis=void 0;const Te=ve,Ee=Ie;Ae.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Ee.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ee.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ee.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ee.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:n}=e,s={Records:(0,Ee.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:Te.REGION},{accessKeyId:a,secretAccessKey:n})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=we;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Ae;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ke);var _e={};function Pe(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(_e,"__esModule",{value:!0}),_e.parseHttpHeaderName=_e.stringOrDefault=_e.parseIntOrDefault=_e.parseNumberOrDefault=void 0,_e.parseNumberOrDefault=Pe,_e.parseIntOrDefault=function(e,t){const i=Pe(e,t);return"number"==typeof i?Math.floor(i):i},_e.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},_e.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.searchParamsFromRecord=void 0,xe.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Re={},Oe={},Le=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ke=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),De=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Le(t,e,i);return Ke(t,e),t};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.isJweEncrypted=Oe.decrypt=Oe.encrypt=void 0;const Me=De(i);Oe.encrypt=async function(e,t){const i=Me.base64url.decode(t),a=(new TextEncoder).encode(e);return await new Me.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},Oe.decrypt=async function(e,t){const i=Me.base64url.decode(t),{plaintext:a}=await Me.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},Oe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var je=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),qe=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),He=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&je(t,e,i);return qe(t,e),t};Object.defineProperty(Re,"__esModule",{value:!0}),Re.jwe=void 0,Re.jwe=He(Oe);var Be,Fe,Ve={};function $e(){if(Fe)return ee;Fe=1;var e=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),t=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=Z&&Z.__importStar||function(i){if(i&&i.__esModule)return i;var a={};if(null!=i)for(var n in i)"default"!==n&&Object.prototype.hasOwnProperty.call(i,n)&&e(a,i,n);return t(a,i),a};return Object.defineProperty(ee,"__esModule",{value:!0}),ee.graphql=ee.webcrypto=ee.url=ee.parsing=ee.ingest=ee.headers=ee.configValidation=void 0,ee.configValidation=i(te),ee.headers=i(ie),ee.ingest=i(ke),ee.parsing=i(_e),ee.url=i(xe),ee.webcrypto=i(Re),ee.graphql=i(function(){if(Be)return Ve;Be=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.truncateLongFields=Ve.parseGraphQl=Ve.parseGraphQlRequestBody=Ve.getGraphQLParserConfig=void 0;const e=$e();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(n=i,(a=s).length<=n?a:a.slice(0,n)+"…")}var a,n;return t}return Ve.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Ve.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const n=JSON.parse(a);if("object"!=typeof n)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,n?.query??"")},o=(n?.operationName??"").trim();return""!==o&&(s.OpName=o),i(e,s)},Ve.parseGraphQl=t,Ve.truncateLongFields=i,Ve}()),ee}var Ue=$e();const ze="unknown";function Ge(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let o=E[a]??ze+"_";o+=_[n]??ze;let r=x[n];if("0"!==s){o+=","+(P[s]??ze);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function We(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}async function Je(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const n=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new Qe("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");n.push(s)}const s=new Uint8Array(a);let o=0;for(const e of n)s.set(e,o),o+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:Ue.graphql.parseGraphQlRequestBody(e,a)}}class Qe extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class Xe{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.netaceaCookieName),n=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",r=Ue.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=D(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(O),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5","a","c","e"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await q(t+"|"+n.expiry,i),h=n.ipHash===u,d=n.signature===await q(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?H.RENEW_SESSION:H.EXISTING_SESSION,{sessionStatus:u}=Ge(e.mitigationType,s.protectorCheckCodes,U(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:s,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:M(),sessionCookieStatus:H.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await Ye(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:o,sessionDetails:{captchaToken:n,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await Je(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof Qe){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await F(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function Ye(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await We(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,n=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await async function(e){const t=e.join(",");return await We(t)}(n);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:Ze}=Ue.configValidation,{configureCookiesDomain:et}=S.cookie.attributes;class tt{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Ue.parsing.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:v}=et(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var I;this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(I=C)&&I.startsWith("/")&&I.length>=5?I:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=Ze(e.netaceaBlockedResponseRedirectLocation),this.graphQL=Ue.graphql.getGraphQLParserConfig(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new tt(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ue.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new Xe(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,a,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=U(t.url,e.method,this.config.netaceaCaptchaVerificationPath),n=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&$(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!s&&!n)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!n?"captcha"===i.mitigation?{...i,response:J({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:W({config:this.config,request:e,responseHeaders:o()})}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=D(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Ge(this.config.mitigationType,a,U(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),n=function(e,t,i,a){const n=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,o=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=Ue.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:X?.replace("@netacea/","")??"",IntegrationVersion:Y,NetaceaMitigationApplied:n??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${o} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...n,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(n)),t=await this.makeRequest(e);if(200!==t.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await C(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",X.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Y),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const n=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:z(n,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?V(e.headers.get("Accept")??void 0):V();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Q&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:U(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await F(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([H.NEW_SESSION,H.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,n=d.mitigate,s=d.captcha,o=d.body,u=d.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await q(e+"|"+String(i),a),n].join(O);return`${await q(s,a)}${O}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await B(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[N];const i=parseInt(e[A]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await B(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Q(e,i);const a=e.headers[w]??"0",n=e.headers[v]??"0",s=e.headers[I]??"0";let o=parseInt(e.headers[b]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[T];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:G({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t,n["X-Netacea-Request-Id"]=e.requestId;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=Ge(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[k.block,k.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if($(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaPath)){const t=await async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}}(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if(U(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===H.NEW_SESSION,a=t===H.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "6.0.83",
3
+ "version": "6.0.85",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,10 +18,10 @@
18
18
  },
19
19
  "license": "ISC",
20
20
  "dependencies": {
21
- "@netacea/netaceaintegrationbase": "^2.0.126",
21
+ "@netacea/netaceaintegrationbase": "^2.0.128",
22
22
  "aws4fetch": "^1.0.20",
23
23
  "jose": "^4.11.2",
24
24
  "uuid": "^10.0.0"
25
25
  },
26
- "gitHead": "e4d96549344c1ffebc1e47f65d0dd6fecfe154f7"
26
+ "gitHead": "1e3f889b8a9df68ddc27ba41ec5730a186587ed4"
27
27
  }