@netacea/cloudflare 6.8.17 → 6.8.19

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 +2 -2
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/");function i(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 a,o,s,n=i(require("jose"));!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(a||(a={})),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"}(s||(s={}));const r=3e3;function c(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 u(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(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 h=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=u(e??"",!0),a=t=u(t??"",!0);if(void 0!==e&&void 0!==t){const o=c(e,"Domain"),s=c(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=c(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=c(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=c(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:c,removeDuplicateAttrs:u});function p(e){const t=u([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var l=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return p({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return p({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:p});var g=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),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const f={cookie:{parse:g,attributes:h,netaceaSession:l}},y=globalThis.fetch.bind(globalThis),m={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",flag:"flag",monetise:"monetise"},C="x-netacea-mitatacaptcha-value",S="x-netacea-mitatacaptcha-expiry",I={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"customer_session_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},v={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},k={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"},w={0:m.none,1:m.block,2:m.none,3:m.block,4:m.flag,5:m.monetise},N={1:m.captcha,2:m.captchaPass,3:m.captcha,4:m.allow,5:m.captcha,6:m.allow,7:m.captcha,a:m.captcha,b:m.captchaPass,c:m.captcha,d:m.allow,e:m.captcha},b="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),A=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function E(e=16,t=b){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function O(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))}var _,P,R,T="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},M={},x={};Object.defineProperty(x,"__esModule",{value:!0}),x.MitigateCode=x.MatchCode=x.CaptchaCode=void 0,function(e){e.NONE="0",e.SERVE="1",e.PASS="2",e.FAIL="3",e.COOKIE_PASS="4",e.COOKIE_FAIL="5",e.CHECKPOINT_SIGNAL="6",e.CHECKPOINT_POST="7",e.CHECKPOINT_SERVE="a",e.CHECKPOINT_PASS="b",e.CHECKPOINT_FAIL="c",e.CHECKPOINT_COOKIE_PASS="d",e.CHECKPOINT_COOKIE_FAIL="e"}(_||(x.CaptchaCode=_={})),function(e){e.NONE="0",e.USER_AGENT="1",e.IP="2",e.VISITOR="3",e.DATACENTER="4",e.CUSTOMER_SESSION="5",e.ORGANISATION="6",e.ASN="7",e.COUNTRY="8",e.COMBINATION="9",e.HEADER_FINGERPRINT="b",e.VENDOR_FAMILY="c",e.VENDOR_NAME="d",e.VENDOR="e",e.VENDOR_CRAWLER_CLASSIFICATION="f"}(P||(x.MatchCode=P={})),function(e){e.NONE="0",e.BLOCK="1",e.ALLOW="2",e.HARDBLOCK="3",e.FLAG="4",e.MONETISE="5"}(R||(x.MitigateCode=R={}));var K,V={};Object.defineProperty(V,"__esModule",{value:!0}),V.NetaceaCookieV3IssueReason=void 0,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",e.UNKNOWN="unknown"}(K||(V.NetaceaCookieV3IssueReason=K={}));var L={},H={},j={};Object.defineProperty(j,"__esModule",{value:!0}),j.netaceaCookieV3OptionalKeyMap=j.netaceaCookieV3KeyMap=j.COOKIEDELIMITER=void 0,j.COOKIEDELIMITER="_/@#/",j.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},j.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(H,"__esModule",{value:!0}),H.defaultInvalidResponse=H.matchNetaceaCookieV3=H.checkNetaceaCookieV3=H.objectIsNetaceaCookieV3=H.cookieIsNetaceaV3Format=H.createNetaceaCookieV3=void 0;const D=V,q=j;function F(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(q.netaceaCookieV3KeyMap).find((e=>q.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(q.netaceaCookieV3OptionalKeyMap).find((e=>q.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function U(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:D.NetaceaCookieV3IssueReason.NO_SESSION}}H.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in q.netaceaCookieV3OptionalKeyMap?`${q.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${q.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},H.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(q.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(q.netaceaCookieV3KeyMap).includes(e)))},H.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(q.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},H.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return U();let i;try{i=F(e)}catch{return U()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return U()},H.matchNetaceaCookieV3=F,H.defaultInvalidResponse=U;var $={};Object.defineProperty($,"__esModule",{value:!0}),$.AbstractCookieFactory=void 0;const B=V,G=H,z=j,W="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),J=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;$.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,G.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??this.generateUserId(),match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??B.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,G.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,G.cookieIsNetaceaV3Format)(i)?(0,G.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(z.COOKIEDELIMITER);return`${await this.hash(s,a)}${z.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(J);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,G.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(z.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:B.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>W[e%W.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=H;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=$;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=j;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=V;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(L);var Q={};Object.defineProperty(Q,"__esModule",{value:!0}),Q.validateRedirectLocation=void 0,Q.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 X={},Y={};function Z(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=te("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function ee(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...ie(s,t))}return i}function te(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Y,"__esModule",{value:!0}),Y.findAllInCookieString=Y.findFirstInCookieString=Y.findAllInHeaders=Y.findFirstInHeaders=Y.findOnlyValueInHeaders=Y.findAllValuesInHeaders=Y.findFirstValueInHeaders=void 0,Y.findFirstValueInHeaders=function(e,t){const i=Z(e,t);if(void 0!==i)return i.slice(t.length+1)},Y.findAllValuesInHeaders=function(e,t){return ee(e,t).map((e=>e.slice(t.length+1)))},Y.findOnlyValueInHeaders=function(e,t){const i=ee(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Y.findFirstInHeaders=Z,Y.findAllInHeaders=ee,Y.findFirstInCookieString=te,Y.findAllInCookieString=ie;var ae={};function oe(e){return"set-cookie"===e||"Set-Cookie"===e}function se(e,t){const i=t+"=";return e.startsWith(i)}function ne(e,t){if(!se(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function re(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ce(e,t){for(const i of Object.keys(e)){if(!oe(i))continue;const a=ue(re(e,i),t);if(void 0!==a)return a}}function ue(e,t){return e.map((e=>e.trimStart())).find((e=>se(e,t)))}function de(e,t){const i=[];for(const a of Object.keys(e)){if(!oe(a))continue;const o=re(e,a);i.push(...he(o,t))}return i}function he(e,t){return e.map((e=>e.trimStart())).filter((e=>se(e,t)))}Object.defineProperty(ae,"__esModule",{value:!0}),ae.findAllInSetCookieStrings=ae.findAllInHeaders=ae.findValueInSetCookieStrings=ae.findFirstInSetCookieStrings=ae.findFirstInHeaders=ae.findOnlyValueInHeaders=ae.findFirstValueInHeaders=ae.parseValueFromString=void 0,ae.parseValueFromString=ne,ae.findFirstValueInHeaders=function(e,t){const i=ce(e,t);return void 0!==i?ne(i,t):void 0},ae.findOnlyValueInHeaders=function(e,t){const i=de(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?ne(i[0],t):void 0},ae.findFirstInHeaders=ce,ae.findFirstInSetCookieStrings=ue,ae.findValueInSetCookieStrings=function(e,t){const i=ue(e,t);if(void 0!==i)return ne(i,t)},ae.findAllInHeaders=de,ae.findAllInSetCookieStrings=he;var pe=T&&T.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),le=T&&T.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ge=T&&T.__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)&&pe(t,e,i);return le(t,e),t};Object.defineProperty(X,"__esModule",{value:!0}),X.setCookie=X.cookie=void 0,X.cookie=ge(Y),X.setCookie=ge(ae);var fe={},ye={},me={};Object.defineProperty(me,"__esModule",{value:!0}),me.KINESIS_URL=me.API_VERSION=me.REGION=me.PAYLOAD_TYPE=me.STATE=void 0,me.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},me.PAYLOAD_TYPE="string",me.REGION="eu-west-1",me.API_VERSION="2013-12-02",me.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.headersToRecord=Ce.increaseBatchSize=Ce.handleFailedLogs=Ce.batchArrayForKinesis=Ce.sleep=void 0,Ce.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ce.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Ce.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},Ce.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ce.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ye,"__esModule",{value:!0}),ye.WebStandardKinesis=void 0;const Se=me,Ie=Ce;ye.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,Ie.headersToRecord)(i.headers),host:Se.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ie.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ie.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,Ie.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ie.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 o={Records:(0,Ie.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Se.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.Kinesis=void 0;const ke=me,we=Ce;ve.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,we.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,we.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,we.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,we.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:o}=e,s={Records:(0,we.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:ke.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ye;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=ve;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(fe);var Ne={};function be(e,t){let i=null;if("number"==typeof e&&Number.isFinite(e))i=e;else if("string"==typeof e&&""!==e.trim()){const t=Number(e);Number.isFinite(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(Ne,"__esModule",{value:!0}),Ne.parseUrl=Ne.parseHttpHeaderName=Ne.stringOrDefault=Ne.parseIntOrDefault=Ne.parseNumberOrDefault=void 0,Ne.parseNumberOrDefault=be,Ne.parseIntOrDefault=function(e,t){const i=be(e,t);return"number"==typeof i?Math.floor(i):i},Ne.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Ne.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0},Ne.parseUrl=function(e){const t=/^[a-z][a-z\d+.-]*:\/\/([^/?#]+)([^?#]*)?(?:[?#].*)?$/i.exec(e);if(null===t)return;const[,i,a]=t;return{host:i.slice(i.lastIndexOf("@")+1),path:void 0===a||""===a?"/":a}};var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.searchParamsFromRecord=void 0,Ae.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Ee={},Oe={};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.JweFactory=void 0;Oe.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var _e=T&&T.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Pe=T&&T.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Re=T&&T.__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)&&_e(t,e,i);return Pe(t,e),t};Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.jwe=void 0,Ee.jwe=Re(Oe);var Te={};Object.defineProperty(Te,"__esModule",{value:!0}),Te.truncateLongFields=Te.parseGraphQl=Te.parseGraphQlRequestBody=Te.getGraphQLParserConfig=void 0;const Me=Ne;function xe(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function Ke(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}Te.getGraphQLParserConfig=function(e){const t={includePaths:[],maxParsableBytes:(0,Me.parseIntOrDefault)(e?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:(0,Me.parseIntOrDefault)(e?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/,useStrictAcceptHeaderCheck:e?.useStrictAcceptHeaderCheck??!0};if(Array.isArray(e?.includePaths))for(const i of e.includePaths)"string"==typeof i&&t.includePaths.push(i);try{if(e?.parserRegex instanceof RegExp)t.parserRegex=e?.parserRegex;else if("object"==typeof e?.parserRegex){const{regex:i,flags:a}=e?.parserRegex;"string"==typeof i&&(t.parserRegex=new RegExp(i,a))}}catch{}return t},Te.parseGraphQlRequestBody=function(e,t){if(""===t)throw new Error("Netacea Error: Empty GraphQL body received");const i=JSON.parse(t);if("object"!=typeof i)throw new Error("Netacea Error: Invalid GraphQL JSON");const a={...xe(e,i?.query??"")},o=(i?.operationName??"").trim();return""!==o&&(a.OpName=o),Ke(e,a)},Te.parseGraphQl=xe,Te.truncateLongFields=Ke;var Ve={},Le={},He={};Object.defineProperty(He,"__esModule",{value:!0}),He.createComputedSignatureInputs=He.createComputedSignatureInput=void 0;const je=/^[a-z*][a-z0-9_.*-]{0,63}$/,De=/^"(?:[^"\\]|\\.)*"$/,qe=/^[^;"\s]+$/,Fe=/^"[^"\\]+"(?:;[a-z*][a-z0-9_.*-]*(?:=(?:"(?:[^"\\]|\\.)*"|[^; ]+))?)*$/;function Ue(e,t){const i=Ge(t);if(void 0===i)return;const a=[...i.componentIdentifiers.map((t=>{const i=function(e,t){const i=/^"([^"\\]+)"/.exec(t)?.[1];if(void 0===i)return;const a=$e(t,"name");let o;switch(i){case"@authority":o=e.url.host;break;case"@method":o=e.method;break;case"@path":o=e.url.path;break;case"@query":o=e.url.query;break;case"@query-param":o="string"==typeof a?function(e,t){const i=new URLSearchParams(e.slice(1)).getAll(t);return i.map(Be).join(", ")}(e.url.query,a):void 0;break;case"@request-target":o=`${e.method.toLowerCase()} ${e.url.path}${e.url.query}`;break;case"@scheme":o=e.url.scheme;break;case"@target-uri":o=e.url.toString();break;default:o=function(e,t,i){const a=e.readHeader(t),o=0===a.length?void 0:a.map((e=>e.trim())).join(", ");return void 0!==o&&i?function(e){let t="",i=!1,a=!1,o=!1,s=!1;for(const n of e.trim())a?(t+=n,a=!1):i&&"\\"===n?(t+=n,a=!0):'"'===n?(t+=n,i=!i):i?t+=n:/\s/.test(n)?s||(o=!0):"="===n||";"===n?(t=t.trimEnd()+n,o=!1,s=!0):","===n?(t=t.trimEnd()+", ",o=!1,s=!1):(o&&""!==t&&!t.endsWith(" ")&&(t+=" "),t+=n,o=!1,s=!1);return t.trimEnd()}(o):o}(e,i,!0===$e(t,"sf"))}return o}(e,t);return void 0===i?void 0:`${t}: ${i}`})),`"@signature-params": ${i.parameters}`];return a.some((e=>void 0===e))?void 0:a.join("\n")}function $e(e,t){const i=e.indexOf('"',1),a=e.slice(i+1);if(a.startsWith(";"))for(const e of We(a.slice(1),";")){const i=e.indexOf("=");if((-1===i?e:e.slice(0,i))!==t)continue;if(-1===i)return!0;const a=e.slice(i+1);return De.test(a)?a.slice(1,-1).replace(/\\(.)/g,"$1"):a}}function Be(e){return encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}function Ge(e){const t=e.indexOf("=");if(-1===t)return;const i=e.slice(0,t);if(!je.test(i))return;const a=e.slice(t+1),o=ze(a,")",1);if(!a.startsWith("(")||-1===o)return;if(!function(e){if(""===e)return!0;return e.startsWith(";")&&We(e.slice(1),";").every((e=>{const t=e.indexOf("=");if(-1===t)return!1;const i=e.slice(0,t),a=e.slice(t+1);return je.test(i)&&function(e){return De.test(e)||qe.test(e)}(a)}))}(a.slice(o+1)))return;const s=a.slice(1,o),n=""===s?[]:We(s," ");return n.every((e=>Fe.test(e)))?{label:i,componentIdentifiers:n,parameters:a}:void 0}function ze(e,t,i=0){let a=!1,o=!1;for(let s=i;s<e.length;s++){const i=e[s];if(o)o=!1;else if(a&&"\\"===i)o=!0;else if('"'===i)a=!a;else if(!a&&i===t)return s}return-1}function We(e,t){const i=[];let a=0,o=ze(e,t);for(;-1!==o;)i.push(e.slice(a,o)),a=o+1,o=ze(e,t,a);return i.push(e.slice(a)),i}He.createComputedSignatureInput=Ue,He.createComputedSignatureInputs=function(e,t){const i=We(t,","),a={};for(const t of i){const i=t.trim(),o=Ge(i),s=Ue(e,i);if(void 0===o||void 0===s)return;a[o.label]=s}return a},Object.defineProperty(Le,"__esModule",{value:!0}),Le.AbstractRequestView=void 0;const Je=Ne,Qe=He;Le.AbstractRequestView=class{constructor(e){this._httpMsgSignature=void 0,this._buffer=e}get contentLength(){return(0,Je.parseIntOrDefault)(this.readHeader("content-length")?.[0],{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get userAgent(){return this.readHeader("user-agent")?.[0]??""}get contentType(){return this.readHeader("content-type")?.[0]}get xForwardedFor(){return this.readHeader("x-forwarded-for")?.[0]}get referer(){return this.readHeader("referer")?.[0]}get accept(){return this.readHeader("accept")?.[0]}get host(){return this.readHeader("host")?.[0]}async getHttpMsgSignature(){const e=this.readJoinedHeader("Signature-Input"),t=this.readJoinedHeader("Signature"),i=void 0===e?void 0:this.createBase64SignatureInput(e);return void 0===this._httpMsgSignature&&(this._httpMsgSignature={signature:t,signatureSha256:void 0===t?void 0:(await this.sha256Hash(t)).toLowerCase().slice(0,12),signatureInput:e,signatureAgent:this.readJoinedHeader("Signature-Agent"),computedInput:i}),this._httpMsgSignature}readJoinedHeader(e){const t=this.readHeader(e).join(",");return""!==t?t:void 0}toBase64(e){if(void 0===e)return;return this._buffer.from(e).toString("base64")}createBase64SignatureInput(e){const t=(0,Qe.createComputedSignatureInputs)(this,e);if(void 0!==t)return Object.entries(t).map((([e,t])=>`${e}=:${this.toBase64(t)}:`)).join(", ")}};var Xe={};Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.RequestUrl=void 0;class Ye{constructor(e,t,i,a){this.scheme=e,this.host=t,this.path=i,this.query=a}static fromString(e){const t=/^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(?:#.*)?$/i.exec(e);if(null===t)throw new TypeError(`Invalid request URL: ${e}`);return new Ye(t[1]??"",t[2],t[3]??"/",t[4]??"")}toString(){return`${""===this.scheme?"":`${this.scheme}://`}${this.host}${this.path}${this.query}`}}Xe.RequestUrl=Ye,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.RequestView=void 0;const Ze=t,et=Le,tt=Xe;class it extends et.AbstractRequestView{constructor(e,t){super(Ze.Buffer),this.request=e,this.sha256Digest=t}get method(){return this.request.method}get url(){return tt.RequestUrl.fromString(this.request.url)}async getBody(){return void 0===this._body&&(this._body=await this.request.clone().text()??""),this._body}readHeader(e){const t=this.request.headers.get(e)??void 0;return void 0!==t?[t]:[]}async sha256Hash(e){const t=(new TextEncoder).encode(e),i=await this.sha256Digest.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}Ve.RequestView=it;var at={},ot={};Object.defineProperty(ot,"__esModule",{value:!0}),ot.findBestMitigation=ot.isCaptchaMitigation=void 0;const st=x;function nt(e){return`[${e}]`}const rt={[st.MatchCode.NONE]:"",[st.MatchCode.USER_AGENT]:"ua_",[st.MatchCode.IP]:"ip_",[st.MatchCode.VISITOR]:"visitor_",[st.MatchCode.DATACENTER]:"datacenter_",[st.MatchCode.CUSTOMER_SESSION]:"customer_session_",[st.MatchCode.ORGANISATION]:"organisation_",[st.MatchCode.ASN]:"asn_",[st.MatchCode.COUNTRY]:"country_",[st.MatchCode.COMBINATION]:"combination_",[st.MatchCode.HEADER_FINGERPRINT]:"headerFP_",[st.MatchCode.VENDOR_FAMILY]:"vendorFamily_",[st.MatchCode.VENDOR_NAME]:"vendorName_",[st.MatchCode.VENDOR]:"vendor_",[st.MatchCode.VENDOR_CRAWLER_CLASSIFICATION]:"vendorCrawlerClassification_"},ct={[st.MitigateCode.NONE]:"",[st.MitigateCode.BLOCK]:"blocked",[st.MitigateCode.ALLOW]:"allow",[st.MitigateCode.HARDBLOCK]:"hardblocked",[st.MitigateCode.FLAG]:"flagged",[st.MitigateCode.MONETISE]:"monetised"},ut={[st.CaptchaCode.NONE]:"",[st.CaptchaCode.SERVE]:"captcha_serve",[st.CaptchaCode.PASS]:"captcha_pass",[st.CaptchaCode.FAIL]:"captcha_fail",[st.CaptchaCode.COOKIE_PASS]:"captcha_cookiepass",[st.CaptchaCode.COOKIE_FAIL]:"captcha_cookiefail",[st.CaptchaCode.CHECKPOINT_SIGNAL]:"checkpoint_signal",[st.CaptchaCode.CHECKPOINT_POST]:"checkpoint_post",[st.CaptchaCode.CHECKPOINT_SERVE]:"checkpoint_serve",[st.CaptchaCode.CHECKPOINT_PASS]:"checkpoint_pass",[st.CaptchaCode.CHECKPOINT_FAIL]:"checkpoint_fail",[st.CaptchaCode.CHECKPOINT_COOKIE_PASS]:"checkpoint_cookiepass",[st.CaptchaCode.CHECKPOINT_COOKIE_FAIL]:"checkpoint_cookiefail"};ot.isCaptchaMitigation=function(e){return[st.CaptchaCode.SERVE,st.CaptchaCode.FAIL,st.CaptchaCode.COOKIE_FAIL,st.CaptchaCode.CHECKPOINT_POST,st.CaptchaCode.CHECKPOINT_SERVE,st.CaptchaCode.CHECKPOINT_FAIL,st.CaptchaCode.CHECKPOINT_COOKIE_FAIL].includes(e.captcha)},ot.findBestMitigation=function(e,t,i,a,o=!1){i=function(e,t){return t?e:{[st.CaptchaCode.PASS]:st.CaptchaCode.COOKIE_PASS,[st.CaptchaCode.FAIL]:st.CaptchaCode.COOKIE_FAIL,[st.CaptchaCode.CHECKPOINT_PASS]:st.CaptchaCode.CHECKPOINT_COOKIE_PASS,[st.CaptchaCode.CHECKPOINT_FAIL]:st.CaptchaCode.CHECKPOINT_COOKIE_FAIL}[e]??e}(i,a),o&&(i=st.CaptchaCode.CHECKPOINT_SIGNAL);let s=rt[e]??nt(e)+"_";return s+=ct[t]??nt(t),i!==st.CaptchaCode.NONE&&(s+=","+(ut[i]??nt(i))),{sessionStatus:s,codes:{match:e,mitigate:t,captcha:i}}},function(e){var t=T&&T.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=T&&T.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),i(ot,e)}(at);var dt={},ht={};Object.defineProperty(ht,"__esModule",{value:!0}),ht.ResponseView=ht.AbstractResponseView=void 0;class pt{constructor(e){this.cacheStatus=e}get contentType(){return this.readHeader("content-type")?.[0]}get contentLength(){return this.readHeader("content-length")?.[0]}get location(){return this.readHeader("location")?.[0]}get setCookie(){return this.readHeader("set-cookie")}}ht.AbstractResponseView=pt;ht.ResponseView=class extends pt{constructor(e,t){super(t),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}readHeaders(){const e={};return this.response.headers.forEach(((t,i)=>{e[i]=[t]})),e["set-cookie"]=this.response.headers.getSetCookie(),e}},Object.defineProperty(dt,"__esModule",{value:!0}),dt.HttpClient=dt.AbstractHttpClient=void 0;const lt=ht;class gt{constructor(e={}){this.cache=e.cache}async request(e,t){const i=this.cache?.get(e,t);if(void 0!==i)return this.createCachedResponseView(i);const a=await this.fetch(e,t);return await this.populateCache(e,t,a),a}async populateCache(e,t,i){void 0!==this.cache&&await this.cache.set(e,t,i).catch((()=>{}))}async get(e,t){return await this.request(e,{...t,method:"GET"})}async post(e,t,i){return await this.request(e,{...i,method:"POST",body:t})}}dt.AbstractHttpClient=gt;dt.HttpClient=class extends gt{constructor(e){super(e),this.fetchFn=e.fetch}async fetch(e,t){const i=new AbortController,a=await async function(e,t,i){if(void 0===t)return await e;let a;const o=new Promise(((e,o)=>{a=setTimeout((()=>{i(),o(new Error(`HTTP request timed out after ${t}ms`))}),t)}));try{return await Promise.race([e,o])}finally{void 0!==a&&clearTimeout(a),Promise.resolve(e).catch((()=>{}))}}(this.fetchFn(e,{...t,signal:i.signal}),t?.timeoutMs,(()=>{i.abort()}));return new lt.ResponseView(a,"MISS")}createCachedResponseView(e){const t=new Response(e.body,e);return new lt.ResponseView(t,"HIT")}};var ft={},yt={};Object.defineProperty(yt,"__esModule",{value:!0}),yt.LruCache=void 0;yt.LruCache=class{constructor(e){if(this.capacity=e,this.entries=new Map,!Number.isInteger(e)||e<=0)throw new RangeError("LruCache capacity must be a positive integer")}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){if(this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.capacity){const e=Array.from(this.entries.keys());e.length>0&&this.entries.delete(e[0])}}find(e){for(const[t,i]of this.entries)if(e(i,t))return this.get(t)}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}},Object.defineProperty(ft,"__esModule",{value:!0}),ft.HttpCache=void 0;const mt=yt,Ct=Ne,St=1048576;function It(e){const t={};if(void 0===e)return t;for(const[i,a]of Object.entries(e))t[i.toLowerCase()]=a;return t}function vt(e){if(void 0===e||""===e.trim())return{};const t={};for(const i of e.split(",")){const e=i.trim();if(""===e)continue;const a=e.indexOf("=");if(-1===a){t[e.toLowerCase()]=!0;continue}t[e.slice(0,a).trim().toLowerCase()]=e.slice(a+1).trim().replace(/^"(.+)"$/,"$1")}return t}function kt(e){const t=(0,Ct.parseNumberOrDefault)(e,{defaultValue:void 0});return"number"==typeof t&&t>=0?t:void 0}function wt(e){if(void 0===e)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Nt(e,t){return{method:(i=t?.method,(i??"GET").toUpperCase()),url:e,headers:It(t?.headers)};var i}function bt(e){if("GET"!==e.method)return`method=${e.method}`;if(void 0!==e.headers.authorization)return"authorization header present";if(void 0!==e.headers.range)return"range header present";if(void 0!==e.headers["if-match"])return"if-match header present";if(void 0!==e.headers["if-none-match"])return"if-none-match header present";if(void 0!==e.headers["if-modified-since"])return"if-modified-since header present";if(void 0!==e.headers["if-unmodified-since"])return"if-unmodified-since header present";if(void 0!==e.headers["if-range"])return"if-range header present";return void 0!==vt(e.headers["cache-control"])["no-store"]?"request cache-control=no-store":void 0}function At(e,t){return!t.vary.includes("*")&&t.vary.every((i=>(e.headers[i]??"")===(t.varyRequestHeaders[i]??"")))}function Et(e){const t=kt(e.cacheControl["s-maxage"]);if(void 0!==t)return t;const i=kt(e.cacheControl["max-age"]);if(void 0!==i)return i;const a=wt(e.headers.expires);return void 0===a?0:Math.max(0,Math.floor((a-(e.dateHeaderMs??e.storedAt))/1e3))}function Ot(e){return JSON.stringify([e.url,e.vary.map((t=>[t,e.varyRequestHeaders[t]??""]))])}ft.HttpCache=class{constructor(e={}){this.entries=new mt.LruCache(10),this.defaultCacheControl=e.defaultCacheControl,this.now=e.now??(()=>Date.now())}get(e,t){const i=Nt(e,t);if("GET"!==i.method)return{body:"Not Found",headers:{},status:404,storedAt:this.now(),url:i.url,vary:[],varyRequestHeaders:{},cacheControl:{},ageSeconds:0};if(void 0!==bt(i))return;const a=vt(i.headers["cache-control"]);if(void 0!==a["no-cache"])return;const o=this.entries.find((e=>e.url===i.url&&At(i,e)));if(void 0===o)return;if(void 0!==o.cacheControl["no-cache"])return;const s=kt(a["max-age"]),n=void 0===s?Et(o):Math.min(Et(o),s),r=function(e,t){return Math.max(0,Math.floor((t-e.storedAt)/1e3))+e.ageSeconds}(o,this.now());return r>=n?void 0:{...o,headers:{...o.headers,age:String(r)}}}async set(e,t,i){const a=Nt(e,t);if(void 0!==bt(a))return;const o=this.entries.find((e=>e.url===a.url&&At(a,e))),s=function(e){const t={};for(const[i,a]of Object.entries(e.readHeaders()))a.length>0&&(t[i.toLowerCase()]=a.join(", "));return t}(i),n=vt(s["cache-control"]??this.defaultCacheControl);if(200!==i.status||void 0!==n["no-store"]||void 0!==n.private||i.setCookie.length>0)return void this.removeEntry(o);const r=function(e){return void 0===e.vary?[]:e.vary.split(",").map((e=>e.trim().toLowerCase())).filter((e=>""!==e))}(s);if(r.includes("*"))return void this.removeEntry(o);const c=Number(s["content-length"]);if(Number.isFinite(c)&&c>St)return void this.removeEntry(o);const u=await i.getBody();if((new TextEncoder).encode(u).byteLength>St)return void this.removeEntry(o);const d=this.now(),h=Number(s.age??"0"),p=wt(s.date),l=void 0===p?0:Math.max(0,Math.floor((d-p)/1e3)),g={body:u,headers:s,status:i.status,storedAt:d,url:a.url,vary:r,varyRequestHeaders:Object.fromEntries(r.map((e=>[e,a.headers[e]??""]))),cacheControl:n,dateHeaderMs:p,ageSeconds:Math.max(Number.isFinite(h)&&h>=0?h:0,l)};void 0!==o&&this.entries.delete(Ot(o)),this.entries.set(Ot(g),g)}removeEntry(e){void 0!==e&&this.entries.delete(Ot(e))}};var _t={};Object.defineProperty(_t,"__esModule",{value:!0}),_t.ProtectorApiResponseView=void 0;const Pt=Ne;_t.ProtectorApiResponseView=class{constructor(e){this.responseView=e}get status(){return this.responseView.status}async getBody(){return await this.responseView.getBody()}readHeader(e){return this.responseView.readHeader(e)}get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Pt.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get signatureStatus(){return this.readHeader("x-netacea-signature-status")?.[0]}get netaceaSettings(){const e=this.readHeader("x-netacea-settings")?.[0];if(void 0===e)return{checkAllPostRequests:!1};try{const t=new URLSearchParams(e).get("checkAllPostRequests");return null===t?{checkAllPostRequests:!1}:{checkAllPostRequests:"1"===t}}catch{return{checkAllPostRequests:!1}}}get sessionCookieMaxAge(){return(0,Pt.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Pt.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}};var Rt={};Object.defineProperty(Rt,"__esModule",{value:!0}),Rt.acceptHeaderToNetaceaContentType=Rt.APIError=Rt.ProtectorApiClient=void 0;const Tt=_t;Rt.ProtectorApiClient=class{constructor(e,t){this.httpClient=e.httpClient,this.timeoutMs=e.timeoutMs;const i=/^https:\/\/([^/?#]+)/i.exec(t.protectorApiUrl);if(null===i)throw new Error("Protector API URL must use HTTPS");this.protectorApiHost=i[1],this.apiKey=t.apiKey}async getDecisionResponse(e){return await this.getResponse("/",e)}async getChallengePage(e){return await this.getResponse("/captcha",e)}async getResponse(e,t){const i=[],a=new Kt,o={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t.clientIp};void 0===t.userId||t.isNewUser||(o["X-Netacea-UserId"]=t.userId);const{captchaSiteKey:s,captchaSecretKey:n}=t;if(void 0!==s&&void 0!==n&&(o["X-Netacea-Captcha-Site-Key"]=s,o["X-Netacea-Captcha-Secret-Key"]=n),void 0!==t.customerSessionId&&(o["X-Netacea-Customer-Session-ID"]=t.customerSessionId),void 0!==t.accept){o.Accept=t.accept;const e=xt(t.accept);o["X-Netacea-Captcha-Content-Type"]=e}if(void 0!==t.headerFingerprint&&a.setQuery("headerFP",t.headerFingerprint),void 0===t.checkAllPostRequests&&a.setQuery("getSettings","checkAllPostRequests"),void 0!==t.challengeAssetsPath&&a.setQuery("challengeAssetsPath",t.challengeAssetsPath),void 0!==t.trackingId&&a.setQuery("trackingId",t.trackingId),void 0!==t.base64UserAgent?(o["X-Netacea-User-Agent"]=t.base64UserAgent,i.push("User-Agent")):void 0!==t.userAgent&&(o["User-Agent"]=t.userAgent),void 0!==t.requestId&&(o["X-Netacea-Request-Id"]=t.requestId,i.push("Request-Id")),void 0!==t.captchaCookie){let e=t.captchaCookie;e.startsWith("_mitatacaptcha=")||(e="_mitatacaptcha="+e),o.Cookie=e}void 0!==t.httpMsgSignature&&function(e,t,i){void 0!==i.signature&&(e.Signature=i.signature);void 0!==i.signatureInput&&(e["Signature-Input"]=i.signatureInput);void 0!==i.signatureAgent&&(e["Signature-Agent"]=i.signatureAgent);void 0!==i.computedInput&&(e["X-Netacea-Computed-Signature-Input"]=i.computedInput,t.push("Computed-Signature-Input"))}(o,i,t.httpMsgSignature),i.length>0&&a.setQuery("netaceaHeaders",i.join(","));const r=this.protectorApiHost,c=await this.httpClient.get(`https://${r}${e}`+a.buildQueryString(),{headers:o,timeoutMs:this.timeoutMs});if(200!==c.status)throw Mt.fromResponse(c);return new Tt.ProtectorApiResponseView(c)}};let Mt=class e extends Error{constructor(e,t){super(e),this.response=t}static fromResponse(t){let i="Unknown error";switch(t.status){case 403:i="Invalid credentials";break;case 500:i="Server error";break;case 502:i="Bad Gateway";break;case 503:i="Service Unavailable";break;case 400:i="Invalid request"}return new e(i,t)}};function xt(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}Rt.APIError=Mt,Rt.acceptHeaderToNetaceaContentType=xt;class Kt{constructor(){this.queries={}}setQuery(e,t){return this.queries[e]=encodeURIComponent(t),this}removeQuery(e){const{[e]:t,...i}=this.queries;return this.queries=i,this}buildQueryString(){const e=Object.entries(this.queries).map((([e,t])=>`${e}=${t}`)).join("&");return e.length>0?`?${e}`:""}}!function(e){var t=T&&T.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=T&&T.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=T&&T.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=T&&T.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.mitigation=e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=e.MitigateCode=e.MatchCode=e.CaptchaCode=void 0;var s=x;Object.defineProperty(e,"CaptchaCode",{enumerable:!0,get:function(){return s.CaptchaCode}}),Object.defineProperty(e,"MatchCode",{enumerable:!0,get:function(){return s.MatchCode}}),Object.defineProperty(e,"MitigateCode",{enumerable:!0,get:function(){return s.MitigateCode}});var n=V;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return n.NetaceaCookieV3IssueReason}}),e.cookie=a(L),e.configValidation=a(Q),e.headers=a(X),e.ingest=a(fe),e.parsing=a(Ne),e.url=a(Ae),e.webcrypto=a(Ee),e.graphql=a(Te),o(Ve,e),e.mitigation=a(at),o(dt,e),o(ft,e),o(yt,e),o(Le,e),o(Xe,e),o(ht,e),o(_t,e),o(Rt,e)}(M);const Vt=new M.webcrypto.jwe.JweFactory(n);class Lt extends M.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.encrypt called without a configured encryption key");return await Vt.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.decrypt called without a configured encryption key");return await Vt.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await O(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var Ht;function jt(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 Dt(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 qt(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function Ft(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 Ut(e){if(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)){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");return Bt(e,e.config.netaceaBlockedResponseRedirectLocation)}return $t(e)}function $t(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Bt(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}function Gt(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.has("content-type")||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"}(Ht||(Ht={}));class zt 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 Wt="@netacea/cloudflare",Jt="6.8.17";function Qt(e){return`[${e}]`}function Xt(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=I[a]??Qt(a)+"_";n+=v[o]??Qt(o);let r=w[o];if("0"!==s){n+=","+(k[s]??Qt(s));const e=N[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=m.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function Yt(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function Zt(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 ei(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 o=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new ti("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");o.push(s)}const s=new Uint8Array(a);let n=0;for(const e of o)s.set(e,n),n+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:M.graphql.parseGraphQlRequestBody(e,a)}}class ti extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class ii{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),o=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",n=e.headers.get("cf-ray")??"",r=M.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}=await async function(e,t,i,a,o){const s=await e.cookieFactory.retrieveCookieInfo(a,o),n={userId:void 0!==s.mitata?s.mitata.userId:void 0,requiresReissue:s.requiresReissue,isExpired:s.isExpired,shouldExpire:s.shouldExpire,isSameIP:s.isSameIP,isPrimaryHashValid:s.isPrimaryHashValid,protectorCheckCodes:{match:s.match,mitigate:s.mitigate,captcha:s.captcha},issueReason:s.issueReason};if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:o,shouldExpire:s,isSameIP:r}=n,c=o||s||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?Ht.RENEW_SESSION:Ht.EXISTING_SESSION,{sessionStatus:u}=Xt(e.mitigationType,n.protectorCheckCodes,qt(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:n,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:E(),sessionCookieStatus:Ht.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await oi(e),httpMessageSignatures:await ai(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:n,sessionDetails:{captchaToken:o,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}};try{if(function(e,t){const i=e.includePaths;return"POST"===t.method&&i.includes(t.url.pathname)&&(!e.useStrictAcceptHeaderCheck||void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql"))&&t.contentLength<=e.maxParsableBytes&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await ei(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof ti){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),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Vt.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ai(e){const t=new M.RequestView(e,crypto.subtle);return await t.getHttpMsgSignature()}async function oi(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 Zt(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,o=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 Zt(t)}(o);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:si}=M.configValidation,{configureCookiesDomain:ni}=f.cookie.attributes;class ri{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:o=3e3,mitigationServiceTimeoutMs:s=1e3,mitigationServiceUrl:n="https://mitigations.netacea.net",ingestServiceUrl:c="https://ingest.netacea.net",mitigationType:u=exports.NetaceaMitigationType.INGEST,captchaSiteKey:d,captchaSecretKey:h,ingestType:p=a.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:C,netaceaCaptchaVerificationPath:S,netaceaCheckpointSignalPath:I}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=n.endsWith("/")?n.slice(0,-1):n,this.ingestServiceUrl=c,this.mitigationType=u,this.ingestType=p??a.HTTP,this.kinesisConfigArgs=l,void 0===d&&void 0===h||(this.captchaSiteKey=d,this.captchaSecretKey=h),this.timeout=function(e){return e<=0?r:e}(o),this.mitigationServiceTimeoutMs=M.parsing.parseIntOrDefault(s,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=M.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=M.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:v,captchaCookieAttributes:k}=ni(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var w;this.netaceaCookieAttributes=v??"",this.netaceaCaptchaCookieAttributes=k??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(u,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(w=S)&&w.startsWith("/")&&w.length>=5?w:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=I,this.netaceaBlockedResponseRedirectLocation=si(e.netaceaBlockedResponseRedirectLocation),this.graphQL=M.graphql.getGraphQLParserConfig(e.graphQL)}}function ci(e){if(void 0===e.sessionDetails.sessionCookieDetails)return M.NetaceaCookieV3IssueReason.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?M.NetaceaCookieV3IssueReason.EXPIRED_SESSION:M.NetaceaCookieV3IssueReason.UNKNOWN:M.NetaceaCookieV3IssueReason.IP_CHANGE}exports.default=class{config;kinesis;requestAnalyser;cookieFactory;protectorApiClient;workerInstanceId;constructor(i){this.config=new ri(i),this.protectorApiClient=new M.ProtectorApiClient({httpClient:new M.HttpClient({fetch:y}),timeoutMs:this.config.mitigationServiceTimeoutMs},{apiKey:this.config.apiKey,protectorApiUrl:this.config.mitigationServiceUrl}),this.cookieFactory=new Lt({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===a.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new M.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 ii({...this.config,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=crypto.randomUUID());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 o=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 o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,a,o,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,signatureStatus:i.signatureStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=qt(t.url,e.method,this.config.netaceaCaptchaVerificationPath),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&Dt(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};if(i.mitigated&&!o){if("captcha"===i.mitigation){const e=n();return"application/json"===i.captchaPageContentType&&e.set("content-type","application/json"),{...i,response:Gt({config:this.config,responseHeaders:e,body:i.body})}}return{...i,response:Ut({config:this.config,request:e,responseHeaders:n()})}}return"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:$t({status:402,responseHeaders:n()})}:{...i,response:Bt({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=function(e){if(void 0===e)return;const t=e.match(A);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Xt(this.config.mitigationType,a,qt(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:o,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,signatureStatus:t.signatureStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=crypto.randomUUID());const i=await this.getResponseDetails(t),o="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),s=function(e,t,i,a){const o=i.sessionStatus??t.sessionDetails.sessionStatus,s=t.method,n=t.url.pathname,r=t.protocol??null,c=Date.now(),u=t.referer??"",d=M.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0}),{signatureAgent:h,signatureInput:p,signatureSha256:l}=t.httpMessageSignatures??{};return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:Wt?.replace("@netacea/","")??"",IntegrationVersion:Jt,NetaceaMitigationApplied:o??"",UserId:t.sessionDetails.userId,NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===u?"-":u,Request:`${s} ${n} ${r}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(c).toUTCString(),TimeUnixMsUTC:c,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint},HttpMsgSigAgent:h,HttpMsgSigInput:p,HttpMsgSigSha256:l,HttpMsgSigStatus:i.signatureStatus}}(this.config,o,i,this.workerInstanceId);try{if(this.config.ingestType===a.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({...s,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(s)),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),{match:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n},captchaPageContentType:t}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await y(s,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i,o){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??"",signatureStatus:i?.signatureStatus};if(void 0!==i&&"injectHeaders"in i){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)}if(this.config.ingestType===a.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",Wt.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Jt),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const s=await o(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:Ft(s,i),sessionStatus:i?.sessionStatus??"",signatureStatus:i?.signatureStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?jt(e.headers.get("Accept")??void 0):jt();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,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof zt&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:qt(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:Yt({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,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 Vt.decrypt(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){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Ht.NEW_SESSION,Ht.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),{responseView:o}=a,s=o.getProtectorCodes(),{match:n,mitigate:r,captcha:c}=s,u=[await this.createMitata(e.clientIp,i,n,r,c,a.mitataMaxAge,void 0,ci(e))],d={match:n,mitigate:r,captcha:c},h=Xt(this.config.mitigationType,d,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,signatureStatus:o.signatureStatus,setCookie:u,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[m.block,m.captcha].includes(h.mitigation),redirect:"5"===r?o.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:h.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&h.mitigation!==m.flag||(p.injectHeaders=Yt(h.parts,a.eventId)),p}{const i=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,a={match:i?.match??"0",mitigate:i?.mitigate??"0",captcha:i?.captcha??"0"},o=Xt(this.config.mitigationType,a,!1),s={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:o.sessionStatus,mitigation:o.mitigation,mitigated:[m.block,m.captcha].includes(o.mitigation),redirect:void 0,protectorCheckCodes:o.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&o.mitigation!==m.flag||(s.injectHeaders=Yt(o.parts)),s}}async createMitata(e,t,i,a,o,s=86400,n=void 0,r=M.NetaceaCookieV3IssueReason.NO_SESSION){const c=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,u=void 0!==n?n-Math.floor(Date.now()/1e3):c,d=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:u,cookieId:"",issueReason:r});return f.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:d,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=Xt(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[m.block,m.captcha].includes(d.mitigation),redirect:void 0,protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromResponseView(e){const t={[C]:e.readHeader(C)?.[0],[S]:String(e.captchaCookieMaxAge)};return await this.getMitataCaptchaFromHeaders(t)}async getMitataCaptchaFromHeaders(e){let t=e[C];const i=parseInt(e[S]??"");if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Vt.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),f.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!==Ht.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 o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",n=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:n,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new zt(c,u);const d=new M.ProtectorApiResponseView(new M.ResponseView(c.fetchResponse)),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=e.sessionDetails.userId,y=await this.getMitataCaptchaFromHeaders(c.headers),m=[await this.createMitata(e.clientIp,f,h,p,l,g,void 0,ci(e)),y].filter((e=>void 0!==e)),C=d.eventId,S="5"===p?d.getMonetisationRedirect(e.url.pathname,e.url.search):void 0;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:m,body:c.body,eventId:C,mitataMaxAge:g,latency:u,redirect:S}}async makeMitigateAPICall(e,t,i,a){const o=e.sessionDetails.sessionCookieStatus===Ht.NEW_SESSION,s={accept:t,base64UserAgent:void 0,captchaCookie:e.sessionDetails.captchaToken,captchaSecretKey:this.config.captchaSecretKey,captchaSiteKey:this.config.captchaSiteKey,checkAllPostRequests:!0,clientIp:e.clientIp,customerSessionId:void 0,headerFingerprint:e.fingerprints.headerFingerprint,isNewUser:o,requestId:e.requestId,trackingId:i&&null!==a?a:void 0,userAgent:e.userAgent,userId:e.sessionDetails.userId,httpMsgSignature:e.httpMessageSignatures},n=Date.now();let r;try{r=i?await this.protectorApiClient.getChallengePage(s):await this.protectorApiClient.getDecisionResponse(s)}catch(e){if(e instanceof M.APIError)throw new zt({headers:{},status:e.response.status},Date.now()-n);throw e}const c=Date.now()-n,{match:u,mitigate:d,captcha:h}=r.getProtectorCodes(),p=[await this.createMitata(e.clientIp,e.sessionDetails.userId,u,d,h,r.sessionCookieMaxAge,void 0,ci(e)),await this.getMitataCaptchaFromResponseView(r)].filter((e=>void 0!==e)),l=r.eventId;let g=await r.getBody();if("application/json"===r.readHeader("content-type")?.[0]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");g=await r.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:r,status:r.status,setCookie:p,body:g,eventId:l,mitataMaxAge:r.sessionCookieMaxAge,latency:c}}async processMitigateRequest(e){if(Dt(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(qt(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.sessionDetails.userId,"0","0","0",86400,void 0,ci(e))]}}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===Ht.NEW_SESSION,a=t===Ht.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/");function i(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 a,o,s,n=i(require("jose"));!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(a||(a={})),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"}(s||(s={}));const r=3e3;function c(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 u(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(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 h=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=u(e??"",!0),a=t=u(t??"",!0);if(void 0!==e&&void 0!==t){const o=c(e,"Domain"),s=c(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=c(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=c(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=c(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:c,removeDuplicateAttrs:u});function p(e){const t=u([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var l=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return p({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return p({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:p});var g=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),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const f={cookie:{parse:g,attributes:h,netaceaSession:l}},m=globalThis.fetch.bind(globalThis),y={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",flag:"flag",monetise:"monetise"},C="x-netacea-mitatacaptcha-value",S="x-netacea-mitatacaptcha-expiry",I={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"customer_session_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},v={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},k={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"},w={0:y.none,1:y.block,2:y.none,3:y.block,4:y.flag,5:y.monetise},N={1:y.captcha,2:y.captchaPass,3:y.captcha,4:y.allow,5:y.captcha,6:y.allow,7:y.captcha,a:y.captcha,b:y.captchaPass,c:y.captcha,d:y.allow,e:y.captcha},b="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),A=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function E(e){if(void 0===e)return;const t=e.match(A);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}function O(e=16,t=b){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function _(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))}var P,R,T,M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},x={},K={};Object.defineProperty(K,"__esModule",{value:!0}),K.MitigateCode=K.MatchCode=K.CaptchaCode=void 0,function(e){e.NONE="0",e.SERVE="1",e.PASS="2",e.FAIL="3",e.COOKIE_PASS="4",e.COOKIE_FAIL="5",e.CHECKPOINT_SIGNAL="6",e.CHECKPOINT_POST="7",e.CHECKPOINT_SERVE="a",e.CHECKPOINT_PASS="b",e.CHECKPOINT_FAIL="c",e.CHECKPOINT_COOKIE_PASS="d",e.CHECKPOINT_COOKIE_FAIL="e"}(P||(K.CaptchaCode=P={})),function(e){e.NONE="0",e.USER_AGENT="1",e.IP="2",e.VISITOR="3",e.DATACENTER="4",e.CUSTOMER_SESSION="5",e.ORGANISATION="6",e.ASN="7",e.COUNTRY="8",e.COMBINATION="9",e.HEADER_FINGERPRINT="b",e.VENDOR_FAMILY="c",e.VENDOR_NAME="d",e.VENDOR="e",e.VENDOR_CRAWLER_CLASSIFICATION="f"}(R||(K.MatchCode=R={})),function(e){e.NONE="0",e.BLOCK="1",e.ALLOW="2",e.HARDBLOCK="3",e.FLAG="4",e.MONETISE="5"}(T||(K.MitigateCode=T={}));var V,L={};Object.defineProperty(L,"__esModule",{value:!0}),L.NetaceaCookieV3IssueReason=void 0,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",e.UNKNOWN="unknown"}(V||(L.NetaceaCookieV3IssueReason=V={}));var H={},j={},D={};Object.defineProperty(D,"__esModule",{value:!0}),D.netaceaCookieV3OptionalKeyMap=D.netaceaCookieV3KeyMap=D.COOKIEDELIMITER=void 0,D.COOKIEDELIMITER="_/@#/",D.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},D.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(j,"__esModule",{value:!0}),j.defaultInvalidResponse=j.matchNetaceaCookieV3=j.checkNetaceaCookieV3=j.objectIsNetaceaCookieV3=j.cookieIsNetaceaV3Format=j.createNetaceaCookieV3=void 0;const q=L,F=D;function U(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(F.netaceaCookieV3KeyMap).find((e=>F.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(F.netaceaCookieV3OptionalKeyMap).find((e=>F.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function $(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:q.NetaceaCookieV3IssueReason.NO_SESSION}}j.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in F.netaceaCookieV3OptionalKeyMap?`${F.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${F.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},j.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(F.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(F.netaceaCookieV3KeyMap).includes(e)))},j.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(F.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},j.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return $();let i;try{i=U(e)}catch{return $()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return $()},j.matchNetaceaCookieV3=U,j.defaultInvalidResponse=$;var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.AbstractCookieFactory=void 0;const G=L,z=j,W=D,J="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),Q=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;B.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,z.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??this.generateUserId(),match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??G.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,z.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,z.cookieIsNetaceaV3Format)(i)?(0,z.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(W.COOKIEDELIMITER);return`${await this.hash(s,a)}${W.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(Q);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,z.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(W.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:G.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>J[e%J.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=j;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=B;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=D;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=L;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(H);var X={};Object.defineProperty(X,"__esModule",{value:!0}),X.validateRedirectLocation=void 0,X.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 Y={},Z={};function ee(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=ie("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function te(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...ae(s,t))}return i}function ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ae(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Z,"__esModule",{value:!0}),Z.findAllInCookieString=Z.findFirstInCookieString=Z.findAllInHeaders=Z.findFirstInHeaders=Z.findOnlyValueInHeaders=Z.findAllValuesInHeaders=Z.findFirstValueInHeaders=void 0,Z.findFirstValueInHeaders=function(e,t){const i=ee(e,t);if(void 0!==i)return i.slice(t.length+1)},Z.findAllValuesInHeaders=function(e,t){return te(e,t).map((e=>e.slice(t.length+1)))},Z.findOnlyValueInHeaders=function(e,t){const i=te(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Z.findFirstInHeaders=ee,Z.findAllInHeaders=te,Z.findFirstInCookieString=ie,Z.findAllInCookieString=ae;var oe={};function se(e){return"set-cookie"===e||"Set-Cookie"===e}function ne(e,t){const i=t+"=";return e.startsWith(i)}function re(e,t){if(!ne(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function ce(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ue(e,t){for(const i of Object.keys(e)){if(!se(i))continue;const a=de(ce(e,i),t);if(void 0!==a)return a}}function de(e,t){return e.map((e=>e.trimStart())).find((e=>ne(e,t)))}function he(e,t){const i=[];for(const a of Object.keys(e)){if(!se(a))continue;const o=ce(e,a);i.push(...pe(o,t))}return i}function pe(e,t){return e.map((e=>e.trimStart())).filter((e=>ne(e,t)))}Object.defineProperty(oe,"__esModule",{value:!0}),oe.findAllInSetCookieStrings=oe.findAllInHeaders=oe.findValueInSetCookieStrings=oe.findFirstInSetCookieStrings=oe.findFirstInHeaders=oe.findOnlyValueInHeaders=oe.findFirstValueInHeaders=oe.parseValueFromString=void 0,oe.parseValueFromString=re,oe.findFirstValueInHeaders=function(e,t){const i=ue(e,t);return void 0!==i?re(i,t):void 0},oe.findOnlyValueInHeaders=function(e,t){const i=he(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?re(i[0],t):void 0},oe.findFirstInHeaders=ue,oe.findFirstInSetCookieStrings=de,oe.findValueInSetCookieStrings=function(e,t){const i=de(e,t);if(void 0!==i)return re(i,t)},oe.findAllInHeaders=he,oe.findAllInSetCookieStrings=pe;var le=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ge=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=M&&M.__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 ge(t,e),t};Object.defineProperty(Y,"__esModule",{value:!0}),Y.setCookie=Y.cookie=void 0,Y.cookie=fe(Z),Y.setCookie=fe(oe);var me={},ye={},Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.KINESIS_URL=Ce.API_VERSION=Ce.REGION=Ce.PAYLOAD_TYPE=Ce.STATE=void 0,Ce.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ce.PAYLOAD_TYPE="string",Ce.REGION="eu-west-1",Ce.API_VERSION="2013-12-02",Ce.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Se={};Object.defineProperty(Se,"__esModule",{value:!0}),Se.headersToRecord=Se.increaseBatchSize=Se.handleFailedLogs=Se.batchArrayForKinesis=Se.sleep=void 0,Se.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Se.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Se.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},Se.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Se.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ye,"__esModule",{value:!0}),ye.WebStandardKinesis=void 0;const Ie=Ce,ve=Se;ye.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,ve.headersToRecord)(i.headers),host:Ie.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,ve.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,ve.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,ve.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,ve.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 o={Records:(0,ve.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Ie.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var ke={};Object.defineProperty(ke,"__esModule",{value:!0}),ke.Kinesis=void 0;const we=Ce,Ne=Se;ke.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,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}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,Ne.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:we.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ye;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=ke;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(me);var be={};function Ae(e,t){let i=null;if("number"==typeof e&&Number.isFinite(e))i=e;else if("string"==typeof e&&""!==e.trim()){const t=Number(e);Number.isFinite(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(be,"__esModule",{value:!0}),be.parseUrl=be.parseHttpHeaderName=be.stringOrDefault=be.parseIntOrDefault=be.parseNumberOrDefault=void 0,be.parseNumberOrDefault=Ae,be.parseIntOrDefault=function(e,t){const i=Ae(e,t);return"number"==typeof i?Math.floor(i):i},be.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},be.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0},be.parseUrl=function(e){const t=/^[a-z][a-z\d+.-]*:\/\/([^/?#]+)([^?#]*)?(?:[?#].*)?$/i.exec(e);if(null===t)return;const[,i,a]=t;return{host:i.slice(i.lastIndexOf("@")+1),path:void 0===a||""===a?"/":a}};var Ee={};Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.searchParamsFromRecord=void 0,Ee.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Oe={},_e={};Object.defineProperty(_e,"__esModule",{value:!0}),_e.JweFactory=void 0;_e.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Pe=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Re=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Te=M&&M.__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)&&Pe(t,e,i);return Re(t,e),t};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.jwe=void 0,Oe.jwe=Te(_e);var Me={};Object.defineProperty(Me,"__esModule",{value:!0}),Me.truncateLongFields=Me.parseGraphQl=Me.parseGraphQlRequestBody=Me.getGraphQLParserConfig=void 0;const xe=be;function Ke(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function Ve(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}Me.getGraphQLParserConfig=function(e){const t={includePaths:[],maxParsableBytes:(0,xe.parseIntOrDefault)(e?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:(0,xe.parseIntOrDefault)(e?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/,useStrictAcceptHeaderCheck:e?.useStrictAcceptHeaderCheck??!0};if(Array.isArray(e?.includePaths))for(const i of e.includePaths)"string"==typeof i&&t.includePaths.push(i);try{if(e?.parserRegex instanceof RegExp)t.parserRegex=e?.parserRegex;else if("object"==typeof e?.parserRegex){const{regex:i,flags:a}=e?.parserRegex;"string"==typeof i&&(t.parserRegex=new RegExp(i,a))}}catch{}return t},Me.parseGraphQlRequestBody=function(e,t){if(""===t)throw new Error("Netacea Error: Empty GraphQL body received");const i=JSON.parse(t);if("object"!=typeof i)throw new Error("Netacea Error: Invalid GraphQL JSON");const a={...Ke(e,i?.query??"")},o=(i?.operationName??"").trim();return""!==o&&(a.OpName=o),Ve(e,a)},Me.parseGraphQl=Ke,Me.truncateLongFields=Ve;var Le={},He={},je={};Object.defineProperty(je,"__esModule",{value:!0}),je.createComputedSignatureInputs=je.createComputedSignatureInput=void 0;const De=/^[a-z*][a-z0-9_.*-]{0,63}$/,qe=/^"(?:[^"\\]|\\.)*"$/,Fe=/^[^;"\s]+$/,Ue=/^"[^"\\]+"(?:;[a-z*][a-z0-9_.*-]*(?:=(?:"(?:[^"\\]|\\.)*"|[^; ]+))?)*$/;function $e(e,t){const i=ze(t);if(void 0===i)return;const a=[...i.componentIdentifiers.map((t=>{const i=function(e,t){const i=/^"([^"\\]+)"/.exec(t)?.[1];if(void 0===i)return;const a=Be(t,"name");let o;switch(i){case"@authority":o=e.url.host;break;case"@method":o=e.method;break;case"@path":o=e.url.path;break;case"@query":o=e.url.query;break;case"@query-param":o="string"==typeof a?function(e,t){const i=new URLSearchParams(e.slice(1)).getAll(t);return i.map(Ge).join(", ")}(e.url.query,a):void 0;break;case"@request-target":o=`${e.method.toLowerCase()} ${e.url.path}${e.url.query}`;break;case"@scheme":o=e.url.scheme;break;case"@target-uri":o=e.url.toString();break;default:o=function(e,t,i){const a=e.readHeader(t),o=0===a.length?void 0:a.map((e=>e.trim())).join(", ");return void 0!==o&&i?function(e){let t="",i=!1,a=!1,o=!1,s=!1;for(const n of e.trim())a?(t+=n,a=!1):i&&"\\"===n?(t+=n,a=!0):'"'===n?(t+=n,i=!i):i?t+=n:/\s/.test(n)?s||(o=!0):"="===n||";"===n?(t=t.trimEnd()+n,o=!1,s=!0):","===n?(t=t.trimEnd()+", ",o=!1,s=!1):(o&&""!==t&&!t.endsWith(" ")&&(t+=" "),t+=n,o=!1,s=!1);return t.trimEnd()}(o):o}(e,i,!0===Be(t,"sf"))}return o}(e,t);return void 0===i?void 0:`${t}: ${i}`})),`"@signature-params": ${i.parameters}`];return a.some((e=>void 0===e))?void 0:a.join("\n")}function Be(e,t){const i=e.indexOf('"',1),a=e.slice(i+1);if(a.startsWith(";"))for(const e of Je(a.slice(1),";")){const i=e.indexOf("=");if((-1===i?e:e.slice(0,i))!==t)continue;if(-1===i)return!0;const a=e.slice(i+1);return qe.test(a)?a.slice(1,-1).replace(/\\(.)/g,"$1"):a}}function Ge(e){return encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}function ze(e){const t=e.indexOf("=");if(-1===t)return;const i=e.slice(0,t);if(!De.test(i))return;const a=e.slice(t+1),o=We(a,")",1);if(!a.startsWith("(")||-1===o)return;if(!function(e){if(""===e)return!0;return e.startsWith(";")&&Je(e.slice(1),";").every((e=>{const t=e.indexOf("=");if(-1===t)return!1;const i=e.slice(0,t),a=e.slice(t+1);return De.test(i)&&function(e){return qe.test(e)||Fe.test(e)}(a)}))}(a.slice(o+1)))return;const s=a.slice(1,o),n=""===s?[]:Je(s," ");return n.every((e=>Ue.test(e)))?{label:i,componentIdentifiers:n,parameters:a}:void 0}function We(e,t,i=0){let a=!1,o=!1;for(let s=i;s<e.length;s++){const i=e[s];if(o)o=!1;else if(a&&"\\"===i)o=!0;else if('"'===i)a=!a;else if(!a&&i===t)return s}return-1}function Je(e,t){const i=[];let a=0,o=We(e,t);for(;-1!==o;)i.push(e.slice(a,o)),a=o+1,o=We(e,t,a);return i.push(e.slice(a)),i}je.createComputedSignatureInput=$e,je.createComputedSignatureInputs=function(e,t){const i=Je(t,","),a={};for(const t of i){const i=t.trim(),o=ze(i),s=$e(e,i);if(void 0===o||void 0===s)return;a[o.label]=s}return a},Object.defineProperty(He,"__esModule",{value:!0}),He.AbstractRequestView=void 0;const Qe=be,Xe=je;He.AbstractRequestView=class{constructor(e){this._httpMsgSignature=void 0,this._buffer=e}get contentLength(){return(0,Qe.parseIntOrDefault)(this.readHeader("content-length")?.[0],{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get userAgent(){return this.readHeader("user-agent")?.[0]??""}get contentType(){return this.readHeader("content-type")?.[0]}get xForwardedFor(){return this.readHeader("x-forwarded-for")?.[0]}get referer(){return this.readHeader("referer")?.[0]}get accept(){return this.readHeader("accept")?.[0]}get host(){return this.readHeader("host")?.[0]}async getHttpMsgSignature(){const e=this.readJoinedHeader("Signature-Input"),t=this.readJoinedHeader("Signature"),i=void 0===e?void 0:this.createBase64SignatureInput(e);return void 0===this._httpMsgSignature&&(this._httpMsgSignature={signature:t,signatureSha256:void 0===t?void 0:(await this.sha256Hash(t)).toLowerCase().slice(0,12),signatureInput:e,signatureAgent:this.readJoinedHeader("Signature-Agent"),computedInput:i}),this._httpMsgSignature}readJoinedHeader(e){const t=this.readHeader(e).join(",");return""!==t?t:void 0}toBase64(e){if(void 0===e)return;return this._buffer.from(e).toString("base64")}createBase64SignatureInput(e){const t=(0,Xe.createComputedSignatureInputs)(this,e);if(void 0!==t)return Object.entries(t).map((([e,t])=>`${e}=:${this.toBase64(t)}:`)).join(", ")}};var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.RequestUrl=void 0;class Ze{constructor(e,t,i,a){this.scheme=e,this.host=t,this.path=i,this.query=a}static fromString(e){const t=/^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(?:#.*)?$/i.exec(e);if(null===t)throw new TypeError(`Invalid request URL: ${e}`);return new Ze(t[1]??"",t[2],t[3]??"/",t[4]??"")}toString(){return`${""===this.scheme?"":`${this.scheme}://`}${this.host}${this.path}${this.query}`}}Ye.RequestUrl=Ze,Object.defineProperty(Le,"__esModule",{value:!0}),Le.RequestView=void 0;const et=t,tt=He,it=Ye;class at extends tt.AbstractRequestView{constructor(e,t){super(et.Buffer),this.request=e,this.sha256Digest=t}get method(){return this.request.method}get url(){return it.RequestUrl.fromString(this.request.url)}async getBody(){return void 0===this._body&&(this._body=await this.request.clone().text()??""),this._body}readHeader(e){const t=this.request.headers.get(e)??void 0;return void 0!==t?[t]:[]}async sha256Hash(e){const t=(new TextEncoder).encode(e),i=await this.sha256Digest.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}Le.RequestView=at;var ot={},st={};Object.defineProperty(st,"__esModule",{value:!0}),st.findBestMitigation=st.isCaptchaMitigation=void 0;const nt=K;function rt(e){return`[${e}]`}const ct={[nt.MatchCode.NONE]:"",[nt.MatchCode.USER_AGENT]:"ua_",[nt.MatchCode.IP]:"ip_",[nt.MatchCode.VISITOR]:"visitor_",[nt.MatchCode.DATACENTER]:"datacenter_",[nt.MatchCode.CUSTOMER_SESSION]:"customer_session_",[nt.MatchCode.ORGANISATION]:"organisation_",[nt.MatchCode.ASN]:"asn_",[nt.MatchCode.COUNTRY]:"country_",[nt.MatchCode.COMBINATION]:"combination_",[nt.MatchCode.HEADER_FINGERPRINT]:"headerFP_",[nt.MatchCode.VENDOR_FAMILY]:"vendorFamily_",[nt.MatchCode.VENDOR_NAME]:"vendorName_",[nt.MatchCode.VENDOR]:"vendor_",[nt.MatchCode.VENDOR_CRAWLER_CLASSIFICATION]:"vendorCrawlerClassification_"},ut={[nt.MitigateCode.NONE]:"",[nt.MitigateCode.BLOCK]:"blocked",[nt.MitigateCode.ALLOW]:"allow",[nt.MitigateCode.HARDBLOCK]:"hardblocked",[nt.MitigateCode.FLAG]:"flagged",[nt.MitigateCode.MONETISE]:"monetised"},dt={[nt.CaptchaCode.NONE]:"",[nt.CaptchaCode.SERVE]:"captcha_serve",[nt.CaptchaCode.PASS]:"captcha_pass",[nt.CaptchaCode.FAIL]:"captcha_fail",[nt.CaptchaCode.COOKIE_PASS]:"captcha_cookiepass",[nt.CaptchaCode.COOKIE_FAIL]:"captcha_cookiefail",[nt.CaptchaCode.CHECKPOINT_SIGNAL]:"checkpoint_signal",[nt.CaptchaCode.CHECKPOINT_POST]:"checkpoint_post",[nt.CaptchaCode.CHECKPOINT_SERVE]:"checkpoint_serve",[nt.CaptchaCode.CHECKPOINT_PASS]:"checkpoint_pass",[nt.CaptchaCode.CHECKPOINT_FAIL]:"checkpoint_fail",[nt.CaptchaCode.CHECKPOINT_COOKIE_PASS]:"checkpoint_cookiepass",[nt.CaptchaCode.CHECKPOINT_COOKIE_FAIL]:"checkpoint_cookiefail"};st.isCaptchaMitigation=function(e){return[nt.CaptchaCode.SERVE,nt.CaptchaCode.FAIL,nt.CaptchaCode.COOKIE_FAIL,nt.CaptchaCode.CHECKPOINT_POST,nt.CaptchaCode.CHECKPOINT_SERVE,nt.CaptchaCode.CHECKPOINT_FAIL,nt.CaptchaCode.CHECKPOINT_COOKIE_FAIL].includes(e.captcha)},st.findBestMitigation=function(e,t,i,a,o=!1){i=function(e,t){return t?e:{[nt.CaptchaCode.PASS]:nt.CaptchaCode.COOKIE_PASS,[nt.CaptchaCode.FAIL]:nt.CaptchaCode.COOKIE_FAIL,[nt.CaptchaCode.CHECKPOINT_PASS]:nt.CaptchaCode.CHECKPOINT_COOKIE_PASS,[nt.CaptchaCode.CHECKPOINT_FAIL]:nt.CaptchaCode.CHECKPOINT_COOKIE_FAIL}[e]??e}(i,a),o&&(i=nt.CaptchaCode.CHECKPOINT_SIGNAL);let s=ct[e]??rt(e)+"_";return s+=ut[t]??rt(t),i!==nt.CaptchaCode.NONE&&(s+=","+(dt[i]??rt(i))),{sessionStatus:s,codes:{match:e,mitigate:t,captcha:i}}},function(e){var t=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=M&&M.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),i(st,e)}(ot);var ht={},pt={};Object.defineProperty(pt,"__esModule",{value:!0}),pt.ResponseView=pt.AbstractResponseView=void 0;class lt{constructor(e){this.cacheStatus=e}get contentType(){return this.readHeader("content-type")?.[0]}get contentLength(){return this.readHeader("content-length")?.[0]}get location(){return this.readHeader("location")?.[0]}get setCookie(){return this.readHeader("set-cookie")}}pt.AbstractResponseView=lt;pt.ResponseView=class extends lt{constructor(e,t){super(t),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}readHeaders(){const e={};return this.response.headers.forEach(((t,i)=>{e[i]=[t]})),e["set-cookie"]=this.response.headers.getSetCookie(),e}},Object.defineProperty(ht,"__esModule",{value:!0}),ht.HttpClient=ht.AbstractHttpClient=void 0;const gt=pt;class ft{constructor(e={}){this.cache=e.cache}async request(e,t){const i=this.cache?.get(e,t);if(void 0!==i)return this.createCachedResponseView(i);const a=await this.fetch(e,t);return await this.populateCache(e,t,a),a}async populateCache(e,t,i){void 0!==this.cache&&await this.cache.set(e,t,i).catch((()=>{}))}async get(e,t){return await this.request(e,{...t,method:"GET"})}async post(e,t,i){return await this.request(e,{...i,method:"POST",body:t})}}ht.AbstractHttpClient=ft;ht.HttpClient=class extends ft{constructor(e){super(e),this.fetchFn=e.fetch}async fetch(e,t){const i=new AbortController,a=await async function(e,t,i){if(void 0===t)return await e;let a;const o=new Promise(((e,o)=>{a=setTimeout((()=>{i(),o(new Error(`HTTP request timed out after ${t}ms`))}),t)}));try{return await Promise.race([e,o])}finally{void 0!==a&&clearTimeout(a),Promise.resolve(e).catch((()=>{}))}}(this.fetchFn(e,{...t,signal:i.signal}),t?.timeoutMs,(()=>{i.abort()}));return new gt.ResponseView(a,"MISS")}createCachedResponseView(e){const t=new Response(e.body,e);return new gt.ResponseView(t,"HIT")}};var mt={},yt={};Object.defineProperty(yt,"__esModule",{value:!0}),yt.LruCache=void 0;yt.LruCache=class{constructor(e){if(this.capacity=e,this.entries=new Map,!Number.isInteger(e)||e<=0)throw new RangeError("LruCache capacity must be a positive integer")}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){if(this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.capacity){const e=Array.from(this.entries.keys());e.length>0&&this.entries.delete(e[0])}}find(e){for(const[t,i]of this.entries)if(e(i,t))return this.get(t)}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}},Object.defineProperty(mt,"__esModule",{value:!0}),mt.HttpCache=void 0;const Ct=yt,St=be,It=1048576;function vt(e){const t={};if(void 0===e)return t;for(const[i,a]of Object.entries(e))t[i.toLowerCase()]=a;return t}function kt(e){if(void 0===e||""===e.trim())return{};const t={};for(const i of e.split(",")){const e=i.trim();if(""===e)continue;const a=e.indexOf("=");if(-1===a){t[e.toLowerCase()]=!0;continue}t[e.slice(0,a).trim().toLowerCase()]=e.slice(a+1).trim().replace(/^"(.+)"$/,"$1")}return t}function wt(e){const t=(0,St.parseNumberOrDefault)(e,{defaultValue:void 0});return"number"==typeof t&&t>=0?t:void 0}function Nt(e){if(void 0===e)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function bt(e,t){return{method:(i=t?.method,(i??"GET").toUpperCase()),url:e,headers:vt(t?.headers)};var i}function At(e){if("GET"!==e.method)return`method=${e.method}`;if(void 0!==e.headers.authorization)return"authorization header present";if(void 0!==e.headers.range)return"range header present";if(void 0!==e.headers["if-match"])return"if-match header present";if(void 0!==e.headers["if-none-match"])return"if-none-match header present";if(void 0!==e.headers["if-modified-since"])return"if-modified-since header present";if(void 0!==e.headers["if-unmodified-since"])return"if-unmodified-since header present";if(void 0!==e.headers["if-range"])return"if-range header present";return void 0!==kt(e.headers["cache-control"])["no-store"]?"request cache-control=no-store":void 0}function Et(e,t){return!t.vary.includes("*")&&t.vary.every((i=>(e.headers[i]??"")===(t.varyRequestHeaders[i]??"")))}function Ot(e){const t=wt(e.cacheControl["s-maxage"]);if(void 0!==t)return t;const i=wt(e.cacheControl["max-age"]);if(void 0!==i)return i;const a=Nt(e.headers.expires);return void 0===a?0:Math.max(0,Math.floor((a-(e.dateHeaderMs??e.storedAt))/1e3))}function _t(e){return JSON.stringify([e.url,e.vary.map((t=>[t,e.varyRequestHeaders[t]??""]))])}mt.HttpCache=class{constructor(e={}){this.entries=new Ct.LruCache(10),this.defaultCacheControl=e.defaultCacheControl,this.now=e.now??(()=>Date.now())}get(e,t){const i=bt(e,t);if("GET"!==i.method)return{body:"Not Found",headers:{},status:404,storedAt:this.now(),url:i.url,vary:[],varyRequestHeaders:{},cacheControl:{},ageSeconds:0};if(void 0!==At(i))return;const a=kt(i.headers["cache-control"]);if(void 0!==a["no-cache"])return;const o=this.entries.find((e=>e.url===i.url&&Et(i,e)));if(void 0===o)return;if(void 0!==o.cacheControl["no-cache"])return;const s=wt(a["max-age"]),n=void 0===s?Ot(o):Math.min(Ot(o),s),r=function(e,t){return Math.max(0,Math.floor((t-e.storedAt)/1e3))+e.ageSeconds}(o,this.now());return r>=n?void 0:{...o,headers:{...o.headers,age:String(r)}}}async set(e,t,i){const a=bt(e,t);if(void 0!==At(a))return;const o=this.entries.find((e=>e.url===a.url&&Et(a,e))),s=function(e){const t={};for(const[i,a]of Object.entries(e.readHeaders()))a.length>0&&(t[i.toLowerCase()]=a.join(", "));return t}(i),n=kt(s["cache-control"]??this.defaultCacheControl);if(200!==i.status||void 0!==n["no-store"]||void 0!==n.private||i.setCookie.length>0)return void this.removeEntry(o);const r=function(e){return void 0===e.vary?[]:e.vary.split(",").map((e=>e.trim().toLowerCase())).filter((e=>""!==e))}(s);if(r.includes("*"))return void this.removeEntry(o);const c=Number(s["content-length"]);if(Number.isFinite(c)&&c>It)return void this.removeEntry(o);const u=await i.getBody();if((new TextEncoder).encode(u).byteLength>It)return void this.removeEntry(o);const d=this.now(),h=Number(s.age??"0"),p=Nt(s.date),l=void 0===p?0:Math.max(0,Math.floor((d-p)/1e3)),g={body:u,headers:s,status:i.status,storedAt:d,url:a.url,vary:r,varyRequestHeaders:Object.fromEntries(r.map((e=>[e,a.headers[e]??""]))),cacheControl:n,dateHeaderMs:p,ageSeconds:Math.max(Number.isFinite(h)&&h>=0?h:0,l)};void 0!==o&&this.entries.delete(_t(o)),this.entries.set(_t(g),g)}removeEntry(e){void 0!==e&&this.entries.delete(_t(e))}};var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.ProtectorApiResponseView=void 0;const Rt=be;Pt.ProtectorApiResponseView=class{constructor(e){this.responseView=e}get status(){return this.responseView.status}async getBody(){return await this.responseView.getBody()}readHeader(e){return this.responseView.readHeader(e)}get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Rt.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get signatureStatus(){return this.readHeader("x-netacea-signature-status")?.[0]}get netaceaSettings(){const e=this.readHeader("x-netacea-settings")?.[0];if(void 0===e)return{checkAllPostRequests:!1};try{const t=new URLSearchParams(e).get("checkAllPostRequests");return null===t?{checkAllPostRequests:!1}:{checkAllPostRequests:"1"===t}}catch{return{checkAllPostRequests:!1}}}get sessionCookieMaxAge(){return(0,Rt.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Rt.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}};var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.acceptHeaderToNetaceaContentType=Tt.APIError=Tt.ProtectorApiClient=void 0;const Mt=Pt;Tt.ProtectorApiClient=class{constructor(e,t){this.httpClient=e.httpClient,this.timeoutMs=e.timeoutMs;const i=/^https:\/\/([^/?#]+)/i.exec(t.protectorApiUrl);if(null===i)throw new Error("Protector API URL must use HTTPS");this.protectorApiHost=i[1],this.apiKey=t.apiKey}async getDecisionResponse(e){return await this.getResponse("/",e)}async getChallengePage(e){return await this.getResponse("/captcha",e)}async getResponse(e,t){const i=[],a=new Vt,o={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t.clientIp};void 0===t.userId||t.isNewUser||(o["X-Netacea-UserId"]=t.userId);const{captchaSiteKey:s,captchaSecretKey:n}=t;if(void 0!==s&&void 0!==n&&(o["X-Netacea-Captcha-Site-Key"]=s,o["X-Netacea-Captcha-Secret-Key"]=n),void 0!==t.customerSessionId&&(o["X-Netacea-Customer-Session-ID"]=t.customerSessionId),void 0!==t.accept){o.Accept=t.accept;const e=Kt(t.accept);o["X-Netacea-Captcha-Content-Type"]=e}if(void 0!==t.headerFingerprint&&a.setQuery("headerFP",t.headerFingerprint),void 0===t.checkAllPostRequests&&a.setQuery("getSettings","checkAllPostRequests"),void 0!==t.challengeAssetsPath&&a.setQuery("challengeAssetsPath",t.challengeAssetsPath),void 0!==t.trackingId&&a.setQuery("trackingId",t.trackingId),void 0!==t.base64UserAgent?(o["X-Netacea-User-Agent"]=t.base64UserAgent,i.push("User-Agent")):void 0!==t.userAgent&&(o["User-Agent"]=t.userAgent),void 0!==t.requestId&&(o["X-Netacea-Request-Id"]=t.requestId,i.push("Request-Id")),void 0!==t.captchaCookie){let e=t.captchaCookie;e.startsWith("_mitatacaptcha=")||(e="_mitatacaptcha="+e),o.Cookie=e}void 0!==t.httpMsgSignature&&function(e,t,i){void 0!==i.signature&&(e.Signature=i.signature);void 0!==i.signatureInput&&(e["Signature-Input"]=i.signatureInput);void 0!==i.signatureAgent&&(e["Signature-Agent"]=i.signatureAgent);void 0!==i.computedInput&&(e["X-Netacea-Computed-Signature-Input"]=i.computedInput,t.push("Computed-Signature-Input"))}(o,i,t.httpMsgSignature),i.length>0&&a.setQuery("netaceaHeaders",i.join(","));const r=this.protectorApiHost,c=await this.httpClient.get(`https://${r}${e}`+a.buildQueryString(),{headers:o,timeoutMs:this.timeoutMs});if(200!==c.status)throw xt.fromResponse(c);return new Mt.ProtectorApiResponseView(c)}};let xt=class e extends Error{constructor(e,t){super(e),this.response=t}static fromResponse(t){let i="Unknown error";switch(t.status){case 403:i="Invalid credentials";break;case 500:i="Server error";break;case 502:i="Bad Gateway";break;case 503:i="Service Unavailable";break;case 400:i="Invalid request"}return new e(i,t)}};function Kt(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}Tt.APIError=xt,Tt.acceptHeaderToNetaceaContentType=Kt;class Vt{constructor(){this.queries={}}setQuery(e,t){return this.queries[e]=encodeURIComponent(t),this}removeQuery(e){const{[e]:t,...i}=this.queries;return this.queries=i,this}buildQueryString(){const e=Object.entries(this.queries).map((([e,t])=>`${e}=${t}`)).join("&");return e.length>0?`?${e}`:""}}!function(e){var t=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=M&&M.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=M&&M.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.mitigation=e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=e.MitigateCode=e.MatchCode=e.CaptchaCode=void 0;var s=K;Object.defineProperty(e,"CaptchaCode",{enumerable:!0,get:function(){return s.CaptchaCode}}),Object.defineProperty(e,"MatchCode",{enumerable:!0,get:function(){return s.MatchCode}}),Object.defineProperty(e,"MitigateCode",{enumerable:!0,get:function(){return s.MitigateCode}});var n=L;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return n.NetaceaCookieV3IssueReason}}),e.cookie=a(H),e.configValidation=a(X),e.headers=a(Y),e.ingest=a(me),e.parsing=a(be),e.url=a(Ee),e.webcrypto=a(Oe),e.graphql=a(Me),o(Le,e),e.mitigation=a(ot),o(ht,e),o(mt,e),o(yt,e),o(He,e),o(Ye,e),o(pt,e),o(Pt,e),o(Tt,e)}(x);const Lt=new x.webcrypto.jwe.JweFactory(n);class Ht extends x.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.encrypt called without a configured encryption key");return await Lt.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.decrypt called without a configured encryption key");return await Lt.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await _(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var jt;function Dt(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 qt(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 Ft(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function Ut(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 $t(e){if(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)){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");return Gt(e,e.config.netaceaBlockedResponseRedirectLocation)}return Bt(e)}function Bt(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Gt(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}function zt(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.has("content-type")||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"}(jt||(jt={}));class Wt 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 Jt="@netacea/cloudflare",Qt="6.8.19";function Xt(e){return`[${e}]`}function Yt(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=I[a]??Xt(a)+"_";n+=v[o]??Xt(o);let r=w[o];if("0"!==s){n+=","+(k[s]??Xt(s));const e=N[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=y.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function Zt(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function ei(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 ti(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 o=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new ii("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");o.push(s)}const s=new Uint8Array(a);let n=0;for(const e of o)s.set(e,n),n+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:x.graphql.parseGraphQlRequestBody(e,a)}}class ii extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class ai{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e,t){const i=new URL(e.url),a=e.method,o=await this.readCookie(e,this.config.netaceaCookieName),s=await this.readCookie(e,this.config.netaceaCaptchaCookieName),n=e.headers.get("cf-connecting-ip")??"",r=e.headers.get("cf-ray")??"",c=x.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:u,sessionCookieStatus:d,sessionStatus:h,userId:p}=await async function(e,t,i,a,o,s){const n=await e.cookieFactory.retrieveCookieInfo(a,o),r={userId:void 0!==n.mitata?n.mitata.userId:void 0,requiresReissue:n.requiresReissue,isExpired:n.isExpired,shouldExpire:n.shouldExpire,isSameIP:n.isSameIP,isPrimaryHashValid:n.isPrimaryHashValid,protectorCheckCodes:{match:n.match,mitigate:n.mitigate,captcha:n.captcha},issueReason:n.issueReason};if(void 0!==r.userId&&r.isPrimaryHashValid){const a=r.userId,{isExpired:o,shouldExpire:s,isSameIP:n}=r,c=o||s||!n&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?jt.RENEW_SESSION:jt.EXISTING_SESSION,{sessionStatus:u}=Yt(e.mitigationType,r.protectorCheckCodes,Ft(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:r,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:s??O(),sessionCookieStatus:jt.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,i,a,o,n,t),l={contentLength:c,clientIp:n,fingerprints:await si(e),httpMessageSignatures:await oi(e),method:a,protocol:String(e.cf?.httpProtocol),url:i,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:r,sessionDetails:{captchaToken:s,sessionCookie:o,sessionCookieDetails:u,sessionCookieStatus:d,sessionStatus:h,userId:p}};try{if(function(e,t){const i=e.includePaths;return"POST"===t.method&&i.includes(t.url.pathname)&&(!e.useStrictAcceptHeaderCheck||void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql"))&&t.contentLength<=e.maxParsableBytes&&"application/json"===t.contentType}(this.config.graphQL,l)){const{contentLength:t,graphQL:i}=await ti(this.config.graphQL,e);l.contentLength=t,l.graphQL=i}}catch(e){if(e instanceof ii){const t=e.bodySize;t>l.contentLength&&(l.contentLength=t)}}return l}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Lt.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function oi(e){const t=new x.RequestView(e,crypto.subtle);return await t.getHttpMsgSignature()}async function si(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 ei(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,o=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 ei(t)}(o);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:ni}=x.configValidation,{configureCookiesDomain:ri}=f.cookie.attributes;class ci{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:o=3e3,mitigationServiceTimeoutMs:s=1e3,mitigationServiceUrl:n="https://mitigations.netacea.net",ingestServiceUrl:c="https://ingest.netacea.net",mitigationType:u=exports.NetaceaMitigationType.INGEST,captchaSiteKey:d,captchaSecretKey:h,ingestType:p=a.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:m=!1,captchaHeader:y,netaceaCaptchaPath:C,netaceaCaptchaVerificationPath:S,netaceaCheckpointSignalPath:I}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=n.endsWith("/")?n.slice(0,-1):n,this.ingestServiceUrl=c,this.mitigationType=u,this.ingestType=p??a.HTTP,this.kinesisConfigArgs=l,void 0===d&&void 0===h||(this.captchaSiteKey=d,this.captchaSecretKey=h),this.timeout=function(e){return e<=0?r:e}(o),this.mitigationServiceTimeoutMs=x.parsing.parseIntOrDefault(s,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=x.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=x.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:v,captchaCookieAttributes:k}=ri(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var w;this.netaceaCookieAttributes=v??"",this.netaceaCaptchaCookieAttributes=k??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(u,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof m?m:"true"===m),this.captchaHeader=y,this.netaceaCaptchaVerificationPath=void 0!==(w=S)&&w.startsWith("/")&&w.length>=5?w:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=I,this.netaceaBlockedResponseRedirectLocation=ni(e.netaceaBlockedResponseRedirectLocation),this.graphQL=x.graphql.getGraphQLParserConfig(e.graphQL)}}function ui(e){if(void 0===e.sessionDetails.sessionCookieDetails)return x.NetaceaCookieV3IssueReason.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?x.NetaceaCookieV3IssueReason.EXPIRED_SESSION:x.NetaceaCookieV3IssueReason.UNKNOWN:x.NetaceaCookieV3IssueReason.IP_CHANGE}exports.default=class{config;kinesis;requestAnalyser;cookieFactory;protectorApiClient;workerInstanceId;constructor(i){this.config=new ci(i),this.protectorApiClient=new x.ProtectorApiClient({httpClient:new x.HttpClient({fetch:m}),timeoutMs:this.config.mitigationServiceTimeoutMs},{apiKey:this.config.apiKey,protectorApiUrl:this.config.mitigationServiceUrl}),this.cookieFactory=new Ht({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===a.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new x.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 ai({...this.config,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=crypto.randomUUID());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 o=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 o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,a,o,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,signatureStatus:i.signatureStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=Ft(t.url,e.method,this.config.netaceaCaptchaVerificationPath),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&qt(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};if(i.mitigated&&!o){if("captcha"===i.mitigation){const e=n();return"application/json"===i.captchaPageContentType&&e.set("content-type","application/json"),{...i,response:zt({config:this.config,responseHeaders:e,body:i.body})}}return{...i,response:$t({config:this.config,request:e,responseHeaders:n()})}}return"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Bt({status:402,responseHeaders:n()})}:{...i,response:Gt({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=E(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Yt(this.config.mitigationType,a,Ft(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:o,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,signatureStatus:t.signatureStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=crypto.randomUUID());const i=await this.getResponseDetails(t);let o;if("requestDetails"in t)o=t.requestDetails;else{const i=await this.getNetaceaCookieFromResponse(t),a=E(i??"")?.userId;o=await this.requestAnalyser.getNetaceaRequestDetails(e,a)}const s=function(e,t,i,a){const o=i.sessionStatus??t.sessionDetails.sessionStatus,s=t.method,n=t.url.pathname,r=t.protocol??null,c=Date.now(),u=t.referer??"",d=x.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0}),{signatureAgent:h,signatureInput:p,signatureSha256:l}=t.httpMessageSignatures??{};return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:Jt?.replace("@netacea/","")??"",IntegrationVersion:Qt,NetaceaMitigationApplied:o??"",UserId:t.sessionDetails.userId,NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===u?"-":u,Request:`${s} ${n} ${r}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(c).toUTCString(),TimeUnixMsUTC:c,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint},HttpMsgSigAgent:h,HttpMsgSigInput:p,HttpMsgSigSha256:l,HttpMsgSigStatus:i.signatureStatus}}(this.config,o,i,this.workerInstanceId);try{if(this.config.ingestType===a.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({...s,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(s)),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),{match:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n},captchaPageContentType:t}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await m(s,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i,o){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??"",signatureStatus:i?.signatureStatus};if(void 0!==i&&"injectHeaders"in i){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)}if(this.config.ingestType===a.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",Jt.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Qt),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const s=await o(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:Ut(s,i),sessionStatus:i?.sessionStatus??"",signatureStatus:i?.signatureStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?Dt(e.headers.get("Accept")??void 0):Dt();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,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Wt&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:Ft(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:Zt({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,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 Lt.decrypt(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){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([jt.NEW_SESSION,jt.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),{responseView:o}=a,s=o.getProtectorCodes(),{match:n,mitigate:r,captcha:c}=s,u=[await this.createMitata(e.clientIp,i,n,r,c,a.mitataMaxAge,void 0,ui(e))],d={match:n,mitigate:r,captcha:c},h=Yt(this.config.mitigationType,d,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,signatureStatus:o.signatureStatus,setCookie:u,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[y.block,y.captcha].includes(h.mitigation),redirect:"5"===r?o.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:h.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&h.mitigation!==y.flag||(p.injectHeaders=Zt(h.parts,a.eventId)),p}{const i=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,a={match:i?.match??"0",mitigate:i?.mitigate??"0",captcha:i?.captcha??"0"},o=Yt(this.config.mitigationType,a,!1),s={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:o.sessionStatus,mitigation:o.mitigation,mitigated:[y.block,y.captcha].includes(o.mitigation),redirect:void 0,protectorCheckCodes:o.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&o.mitigation!==y.flag||(s.injectHeaders=Zt(o.parts)),s}}async createMitata(e,t,i,a,o,s=86400,n=void 0,r=x.NetaceaCookieV3IssueReason.NO_SESSION){const c=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,u=void 0!==n?n-Math.floor(Date.now()/1e3):c,d=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:u,cookieId:"",issueReason:r});return f.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:d,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=Yt(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[y.block,y.captcha].includes(d.mitigation),redirect:void 0,protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromResponseView(e){const t={[C]:e.readHeader(C)?.[0],[S]:String(e.captchaCookieMaxAge)};return await this.getMitataCaptchaFromHeaders(t)}async getMitataCaptchaFromHeaders(e){let t=e[C];const i=parseInt(e[S]??"");if(void 0!==t){const{cookieEncryptionKey:e,encryptedCookies:a}=this.config;return void 0!==e&&a.includes(this.config.netaceaCaptchaCookieName)&&(t=await Lt.encrypt(t,e,"A256GCM")),f.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!==jt.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 o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",n=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:n,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new Wt(c,u);const d=new x.ProtectorApiResponseView(new x.ResponseView(c.fetchResponse)),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=e.sessionDetails.userId,m=await this.getMitataCaptchaFromHeaders(c.headers),y=[await this.createMitata(e.clientIp,f,h,p,l,g,void 0,ui(e)),m].filter((e=>void 0!==e)),C=d.eventId,S="5"===p?d.getMonetisationRedirect(e.url.pathname,e.url.search):void 0;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:y,body:c.body,eventId:C,mitataMaxAge:g,latency:u,redirect:S}}async makeMitigateAPICall(e,t,i,a){const o=e.sessionDetails.sessionCookieStatus===jt.NEW_SESSION,s={accept:t,base64UserAgent:void 0,captchaCookie:e.sessionDetails.captchaToken,captchaSecretKey:this.config.captchaSecretKey,captchaSiteKey:this.config.captchaSiteKey,checkAllPostRequests:!0,clientIp:e.clientIp,customerSessionId:void 0,headerFingerprint:e.fingerprints.headerFingerprint,isNewUser:o,requestId:e.requestId,trackingId:i&&null!==a?a:void 0,userAgent:e.userAgent,userId:e.sessionDetails.userId,httpMsgSignature:e.httpMessageSignatures},n=Date.now();let r;try{r=i?await this.protectorApiClient.getChallengePage(s):await this.protectorApiClient.getDecisionResponse(s)}catch(e){if(e instanceof x.APIError)throw new Wt({headers:{},status:e.response.status},Date.now()-n);throw e}const c=Date.now()-n,{match:u,mitigate:d,captcha:h}=r.getProtectorCodes(),p=[await this.createMitata(e.clientIp,e.sessionDetails.userId,u,d,h,r.sessionCookieMaxAge,void 0,ui(e)),await this.getMitataCaptchaFromResponseView(r)].filter((e=>void 0!==e)),l=r.eventId;let g=await r.getBody();if("application/json"===r.readHeader("content-type")?.[0]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");g=await r.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:r,status:r.status,setCookie:p,body:g,eventId:l,mitataMaxAge:r.sessionCookieMaxAge,latency:c}}async processMitigateRequest(e){if(qt(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(Ft(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.sessionDetails.userId,"0","0","0",86400,void 0,ui(e))]}}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===jt.NEW_SESSION,a=t===jt.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{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.8.17",
3
+ "version": "6.8.19",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -22,5 +22,5 @@
22
22
  "buffer": "^6.0.3",
23
23
  "jose": "^4.15.9"
24
24
  },
25
- "gitHead": "d96fd5380c393172da95681e67876914a80ea456"
25
+ "gitHead": "e3b160ff78dd8ac6b486b14bd3893d76367f5a02"
26
26
  }