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