@netacea/cloudfront 7.0.3 → 7.0.5
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 +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("node:crypto"),t=require("node:buffer"),i=require("aws4"),a=require("jose"),s=require("uuid");function o(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 n,r,c,d=o(a),h=o(s);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(n||(n={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(r||(r={})),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"}(c||(c={}));function u(e,t=0){return isNaN(e)?t:parseInt(e)}const l=3e3;const p="_/@#/",g={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},f={0:g.none,1:g.block,2:g.none,3:g.block,4:g.none},m={1:g.captcha,2:g.captchaPass,3:g.captcha,4:g.allow,5:g.captcha,6:g.allow,7:g.captcha,a:g.captcha,b:g.captchaPass,c:g.captcha,d:g.allow,e:g.captcha};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:m,bestMitigationMap:f,captchaMap:{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"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5,checkpointSignal:6,checkpointPost:7,checkpointServe:"a",checkpointPass:"b",checkpointFail:"c",checkpointCookiePass:"d",checkpointCookieFail:"e"},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged"},mitigationTypes:g,netaceaCookieV3KeyMap:{clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},netaceaCookieV3OptionalKeyMap:{checkAllPostRequests:"fCAPR"},netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const S="ignored",k="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,match:n,mitigate:r,captcha:c}}}function I(t=16,i=k){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function w(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function b(e,t,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0"};if("string"!=typeof e||""===e)return a;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),a=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<a,n=["1","3","5","a","c","e"].includes(s.captcha),r="3"===s.mitigate,c=n||r,d=w(t+"|"+s.expiry,i),h=s.ipHash===d;return{mitata:s,requiresReissue:o||!h,isExpired:o,shouldExpire:c,isSameIP:h,isPrimaryHashValid:s.signature===w(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return a}function A(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 q(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":N(e.split(";"),t).join("; ")}function N(e,t=!1){if(t)return N(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 T=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=q(e??"",!0),a=t=q(t??"",!0);if(void 0!==e&&void 0!==t){const s=A(e,"Domain"),o=A(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=A(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=A(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=A(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:A,removeDuplicateAttrs:q});var E=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),s=a.indexOf(";");if(s<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const P={cookie:{parse:E,attributes:T}};class H{constructor(e){this.crypto=e}async hashString(e,t,i=!1){const a=i?[...t].sort():[...t],s=(new TextEncoder).encode(a.join(",")),o=await this.crypto.subtle.digest(e,s),n=Array.from(new Uint8Array(o)).map((e=>e.toString(16).padStart(2,"0"))).join("").substring(0,12);return"h"+(i?"s":"")+`_${t.length}_${n}`}static filterHeaderNames(e){return e.filter((e=>{const t=e.toLowerCase();return!["","cookie","referer"].includes(t)&&null===t.match(/^(x-netacea-|cloudfront-)/i)}))}async hashHeaders(e,t=!1){const i=H.filterHeaderNames(e);if(0===i.length)return"";try{return await this.hashString("SHA-256",i,t)}catch(e){return console.error(e),""}}}const O=globalThis.fetch.bind(globalThis);var _="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},x={},R={};Object.defineProperty(R,"__esModule",{value:!0}),R.validateRedirectLocation=void 0,R.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 K={},M={};function D(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=j("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function L(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const s=e[a]??"",o="string"==typeof s?s:s.join("; ");i.push(...F(o,t))}return i}function j(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function F(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(M,"__esModule",{value:!0}),M.findAllInCookieString=M.findFirstInCookieString=M.findAllInHeaders=M.findFirstInHeaders=M.findOnlyValueInHeaders=M.findAllValuesInHeaders=M.findFirstValueInHeaders=void 0,M.findFirstValueInHeaders=function(e,t){const i=D(e,t);if(void 0!==i)return i.slice(t.length+1)},M.findAllValuesInHeaders=function(e,t){return L(e,t).map((e=>e.slice(t.length+1)))},M.findOnlyValueInHeaders=function(e,t){const i=L(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},M.findFirstInHeaders=D,M.findAllInHeaders=L,M.findFirstInCookieString=j,M.findAllInCookieString=F;var B={};function V(e){return"set-cookie"===e||"Set-Cookie"===e}function U(e,t){const i=t+"=";return e.startsWith(i)}function $(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function z(e,t){for(const i of Object.keys(e)){if(!V(i))continue;const a=G($(e,i),t);if(void 0!==a)return a}}function G(e,t){return e.map((e=>e.trimStart())).find((e=>U(e,t)))}function W(e,t){const i=[];for(const a of Object.keys(e)){if(!V(a))continue;const s=$(e,a);i.push(...J(s,t))}return i}function J(e,t){return e.map((e=>e.trimStart())).filter((e=>U(e,t)))}Object.defineProperty(B,"__esModule",{value:!0}),B.findAllInSetCookieStrings=B.findAllInHeaders=B.findFirstInSetCookieStrings=B.findFirstInHeaders=B.findOnlyValueInHeaders=B.findFirstValueInHeaders=void 0,B.findFirstValueInHeaders=function(e,t){const i=z(e,t);return i?.slice(t.length+1)?.split(";")[0]},B.findOnlyValueInHeaders=function(e,t){const i=W(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]},B.findFirstInHeaders=z,B.findFirstInSetCookieStrings=G,B.findAllInHeaders=W,B.findAllInSetCookieStrings=J;var X=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Y=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Q=_&&_.__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)&&X(t,e,i);return Y(t,e),t};Object.defineProperty(K,"__esModule",{value:!0}),K.setCookie=K.cookie=void 0,K.cookie=Q(M),K.setCookie=Q(B);var Z={},ee={},te={};Object.defineProperty(te,"__esModule",{value:!0}),te.KINESIS_URL=te.API_VERSION=te.REGION=te.PAYLOAD_TYPE=te.STATE=void 0,te.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},te.PAYLOAD_TYPE="string",te.REGION="eu-west-1",te.API_VERSION="2013-12-02",te.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.headersToRecord=ie.increaseBatchSize=ie.handleFailedLogs=ie.batchArrayForKinesis=ie.sleep=void 0,ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let s=0;s<e.length;s+=t){const o=e.slice(s,s+t);a.push({Data:i.from(JSON.stringify(o)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ie.handleFailedLogs=function(e,t,i){const a=2*i,s=[...e,...t],o=s.length-a;return o>0&&(console.error(`Netacea Error :: failed to send ${o} log(s) to Kinesis ingest.`),s.splice(0,o)),s},ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ee,"__esModule",{value:!0}),ee.WebStandardKinesis=void 0;const ae=te,se=ie;ee.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,se.headersToRecord)(i.headers),host:ae.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,se.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,se.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,se.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,se.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 s={Records:(0,se.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ae.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.Kinesis=void 0;const ne=te,re=ie;oe.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,re.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,re.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,re.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,re.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:s}=e,o={Records:(0,re.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:ne.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ee;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=oe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Z);var ce={};function de(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(ce,"__esModule",{value:!0}),ce.parseHttpHeaderName=ce.stringOrDefault=ce.parseIntOrDefault=he=ce.parseNumberOrDefault=void 0;var he=ce.parseNumberOrDefault=de;ce.parseIntOrDefault=function(e,t){const i=de(e,t);return"number"==typeof i?Math.floor(i):i},ce.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},ce.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var ue={};Object.defineProperty(ue,"__esModule",{value:!0}),ue.searchParamsFromRecord=void 0,ue.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var le={},pe={},ge=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),me=_&&_.__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)&&ge(t,e,i);return fe(t,e),t};Object.defineProperty(pe,"__esModule",{value:!0}),pe.isJweEncrypted=pe.decrypt=pe.encrypt=void 0;const ye=me(a);pe.encrypt=async function(e,t){const i=ye.base64url.decode(t),a=(new TextEncoder).encode(e);return await new ye.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},pe.decrypt=async function(e,t){const i=ye.base64url.decode(t),{plaintext:a}=await ye.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},pe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var Se=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ke=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ce=_&&_.__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)&&Se(t,e,i);return ke(t,e),t};Object.defineProperty(le,"__esModule",{value:!0}),le.jwe=void 0,le.jwe=Ce(pe);var ve=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ie=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),we=_&&_.__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)&&ve(t,e,i);return Ie(t,e),t};Object.defineProperty(x,"__esModule",{value:!0}),x.webcrypto=qe=x.url=Ae=x.parsing=be=x.ingest=x.headers=x.configValidation=void 0,x.configValidation=we(R),x.headers=we(K);var be=x.ingest=we(Z),Ae=x.parsing=we(ce),qe=x.url=we(ue);async function Ne(e,t){const i=d.base64url.decode(t),a=(new TextEncoder).encode(e);return await new d.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function Te(e,t){const i=d.base64url.decode(t),{plaintext:a}=await d.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function Ee(e){const t={"set-cookie":[]};for(const i of e)t["set-cookie"]?.push({key:"set-cookie",value:i});return t}function Pe(e,t,i){return e===i&&"post"===t.toLowerCase()}function He(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a===i&&"get"===t.toLowerCase()}function Oe(e,t){const i=e[t];return"string"==typeof i?i:i?.[0]}function _e(e,t){const i=Oe(e,t);if(void 0!==i)return parseInt(i,36)}function xe(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,headerFingerprint:t,integrationMode:i,integrationType:a,integrationVersion:s,ip:o,method:n,mitataCookie:r,mitigationLatency:c,mitigationStatus:d,netaceaCookieStatus:h,path:u,protocol:l,query:p,referer:g,reqHandlerId:f,reqHandlerMs:m,requestHost:y,requestId:S,requestTime:k,resHandlerId:C,resHandlerMs:v,sessionStatus:I,status:w,timeUnixMsUTC:b,userAgent:A,workerInstanceId:q,xForwardedFor:N}){const{request:T}=function(e,t,i){"/"!==t[0]&&(t=`/${t}`);const a=t.split("?"),s=a[0],o=a.length>1?`?${a[1]}`:void 0;return{path:s,query:o,request:`${e} ${s}${o??""}${""!==(i??"")?` ${i}`:""}`}}(n,u,l);return{BytesSent:e?.toString(),HeaderHash:t,IntegrationType:a??"",IntegrationVersion:s??"",NetaceaMitigationApplied:I??"",NetaceaUserIdCookie:r??"",NetaceaUserIdCookieStatus:h,ProtectionMode:i,ProtectorLatencyMs:c,ProtectorStatus:d,Query:p,RealIp:o,Referer:""===g?"-":g,ReqHandlerId:f,ReqHandlerMs:m,Request:T,RequestHost:y,RequestId:S??"",RequestTime:k?.toString(),ResHandlerId:C,ResHandlerMs:v,Status:w,TimeLocal:new Date(b??Date.now()).toUTCString(),TimeUnixMsUTC:b??Date.now(),UserAgent:A,WorkerInstanceId:q,XForwardedFor:N}}(e)}x.webcrypto=we(le);const Re="unknown";function Ke(e,t,i,a,s,o=!1){a=function(e,t){let i=e;return t||("2"===e?i="4":"3"===e?i="5":"b"===e?i="d":"c"===e&&(i="e")),i}(a,s),o&&(a="6");let n=y.matchMap[t]??Re+"_";n+=y.mitigateMap[i]??Re;let c=y.bestMitigationMap[i];if("0"!==a){n+=","+(y.captchaMap[a]??Re);const e=y.bestMitigationCaptchaMap[a];void 0!==e&&(c=e)}return e===r.INJECT&&(c=y.mitigationTypes.none),{sessionStatus:n,mitigation:c,parts:{match:t,mitigate:i,captcha:a}}}function Me(e){if(void 0===e)return;const t={...e.headers??{}};if(""!==(e.body??"")){void 0===Object.entries(t).find((([e])=>"content-type"===e.toLowerCase()))&&(t["content-type"]=[{key:"content-type",value:"text/html; charset=UTF-8"}])}return{...e,headers:t}}function De(e,t){return{"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha}}class Le 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}}const{configureCookiesDomain:je}=P.cookie.attributes;class Fe{static NetaceaTrueUserAgentHeader="x-netacea-true-useragent-header";static HeadersInOriginalOrderHeader="cloudfront-viewer-header-order";cookieEncryptionKey;ingestEnabled=!0;netaceaCaptchaPath;netaceaCheckpointSignalPath;captchaHeader;dynamicCaptchaContentType;ipHeaderName;mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl="https://mitigations.netacea.net";ingestServiceUrl;timeout;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;kinesisConfigArgs;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;netaceaCaptchaVerificationPath;captchaFeedbackHeaderName;netaceaBlockedResponseRedirectLocation;netaceaBlockedResponseStatus=403;netaceaBlockedResponseBody="Forbidden";netaceaBlockedResponseContentType="text/plain; charset=utf-8";constructor(e){if(e.ingestType=n.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.kinesis&&(console.warn(['NETACEA :: Please move kinesis params to "kinesis" object in config.',"Backwards compatibility will soon be removed."].join(" ")),this.kinesisConfigArgs={kinesisStreamName:e.kinesisStreamName,kinesisAccessKey:e.kinesisAccessKey,kinesisSecretKey:e.kinesisSecretKey,maxLogAgeSeconds:1},void 0!==e.logBatchSize&&(this.kinesisConfigArgs.logBatchSize=e.logBatchSize)),null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,this.secretKey=e.secretKey,void 0!==e.mitigationServiceUrl){const t=e.mitigationServiceUrl;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t}var t;this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??r.INGEST,this.ingestType=e.ingestType??n.HTTP,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(t=e.timeout??3e3)<=0?l:t,this.netaceaCookieName=Be(e.netaceaCookieName)??"_mitata",this.netaceaCaptchaCookieName=Be(e.netaceaCaptchaCookieName)??"_mitatacaptcha",this.netaceaCaptchaPath=e.netaceaCaptchaPath,this.dynamicCaptchaContentType=e.dynamicCaptchaContentType??!1;const i=je(e.netaceaCookieAttributes??"",e.netaceaCaptchaCookieAttributes??"");var a,s;if(this.netaceaCookieAttributes=i.cookieAttributes??"",this.netaceaCaptchaCookieAttributes=i.captchaCookieAttributes??"",this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName?.toLowerCase()?.trim(),this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(a=this.mitigationType,void 0===(s=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?a===r.INGEST?3600:60:s),this.ingestEnabled=e.ingestEnabled??!0,this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaBlockedResponseRedirectLocation=Be(e.netaceaBlockedResponseRedirectLocation),void 0!==e.netaceaBlockedResponseStatus){const t=he(e.netaceaBlockedResponseStatus,{defaultValue:403});!isNaN(t)&&t>=100&&t<=599&&(this.netaceaBlockedResponseStatus=t)}void 0!==e.netaceaBlockedResponseBody&&(this.netaceaBlockedResponseBody=e.netaceaBlockedResponseBody);const o=e.netaceaBlockedResponseContentType;void 0!==o&&""!==o&&(this.netaceaBlockedResponseContentType=o),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,this.netaceaCaptchaVerificationPath=e.netaceaCaptchaVerificationPath??"/AtaVerifyCaptcha",""===this.netaceaCaptchaVerificationPath&&(this.netaceaCaptchaVerificationPath="/AtaVerifyCaptcha"),this.netaceaCaptchaVerificationPath?.startsWith("/")||(this.netaceaCaptchaVerificationPath="/"+this.netaceaCaptchaVerificationPath),this.captchaFeedbackHeaderName=Ae.parseHttpHeaderName(e.captchaFeedbackHeaderName)}}function Be(e){if("string"==typeof e&&""!==e){const t=e.trim();if(t.length>0)return t}}const Ve="x-netacea-integration-state";function Ue(e){return Ae.parseIntOrDefault(e,{defaultValue:void 0})}function $e(e){return"string"==typeof e?e:void 0}class ze{constructor(e){this.sessionCookieMaxAge=e.sessionCookieMaxAge,this.protectorApiLatency=e.protectorApiLatency,this.protectorApiStatus=e.protectorApiStatus,this.reqHandlerId=e.reqHandlerId,this.reqHandlerMs=e.reqHandlerMs,this.requestStartTimestamp=e.requestStartTimestamp??Date.now(),this.resHandlerId=e.resHandlerId,this.resHandlerStartTime=e.resHandlerStartTime,this.sessionStatus=e.sessionStatus,this.setCookies=e.setCookie??[],this.sessionCodes=e.sessionCodes??{match:"0",mitigate:"0",captcha:"0"},this.shouldSetSessionCookie=e.shouldSetSessionCookie??!1,this.eventId=e.eventId,this.headerFingerprint=e.headerFingerprint}async saveToRequest(e,t){const i=JSON.stringify({protectorApiLatency:this.protectorApiLatency,protectorApiStatus:this.protectorApiStatus,reqHandlerId:this.reqHandlerId,reqHandlerMs:this.reqHandlerMs,requestStartTimestamp:this.requestStartTimestamp,resHandlerId:this.resHandlerId,resHandlerStartTime:this.resHandlerStartTime,sessionStatus:this.sessionStatus,setCookies:this.setCookies,sessionCodes:this.sessionCodes,sessionCookieMaxAge:this.sessionCookieMaxAge,shouldSetSessionCookie:this.shouldSetSessionCookie,eventId:this.eventId,headerFingerprint:this.headerFingerprint});e.headers[Ve]=void 0!==t?[{key:Ve,value:await Ne(i,t)}]:[{key:Ve,value:Buffer.from(i).toString("base64")}]}recordProtectorApiError(e){this.sessionStatus="error_open",this.protectorApiLatency=e.latencyMs,this.protectorApiStatus=e.protectorApiResponse.status}static async fromRequest(e,t){let i=e.headers[Ve]?.[0]?.value;if(void 0===i)return new ze({});try{i=void 0!==t?await Te(i,t):Buffer.from(i,"base64").toString();const e=JSON.parse(i);if("object"==typeof e&&null!==e)return new ze({requestStartTimestamp:"requestStartTimestamp"in e?Ae.parseIntOrDefault(e.requestStartTimestamp,{defaultValue:Date.now()}):Date.now(),sessionStatus:"sessionStatus"in e?$e(e.sessionStatus):void 0,protectorApiLatency:"protectorApiLatency"in e?Ue(e.protectorApiLatency):void 0,protectorApiStatus:"protectorApiStatus"in e?Ue(e.protectorApiStatus):void 0,reqHandlerId:"reqHandlerId"in e?$e(e.reqHandlerId):void 0,reqHandlerMs:"reqHandlerMs"in e?Ue(e.reqHandlerMs):void 0,resHandlerId:"resHandlerId"in e?$e(e.resHandlerId):void 0,resHandlerStartTime:"resHandlerStartTime"in e?Ue(e.resHandlerStartTime):void 0,setCookie:"setCookies"in e&&Array.isArray(e.setCookies)?e.setCookies.filter((e=>"string"==typeof e)):[],sessionCodes:"sessionCodes"in e&&"object"==typeof e.sessionCodes&&null!==e.sessionCodes?{match:$e(e.sessionCodes.match)??"0",mitigate:$e(e.sessionCodes.mitigate)??"0",captcha:$e(e.sessionCodes.captcha)??"0"}:{match:"0",mitigate:"0",captcha:"0"},sessionCookieMaxAge:"sessionCookieMaxAge"in e?Ue(e.sessionCookieMaxAge):void 0,shouldSetSessionCookie:"shouldSetSessionCookie"in e&&Boolean(e.shouldSetSessionCookie),eventId:"eventId"in e?$e(e.eventId):void 0,headerFingerprint:"headerFingerprint"in e?$e(e.headerFingerprint):void 0})}catch{}return new ze({})}static getFreshState(e){return delete e.headers["x-netacea-integration-state"],new ze({})}}var Ge;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ge||(Ge={}));class We{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const{request:t}=e.cf,{uri:i,method:a}=t,s=await this.readCookie(t,this.config.sessionCookieName),o=await this.readCookie(t,this.config.captchaCookieName),n=function(e,t){const{clientIp:i}=e;if(void 0===t||""===t)return i;const a=e.headers[t]?.[0]?.value;return void 0===a||""===a?i:"x-forwarded-for"===t?a.split(/, ?/).pop()??i:a}(t,this.config.ipHeaderName),{sessionCookieDetails:c,sessionCookieStatus:d,sessionStatus:h,userId:u}=function(e,t,i,a,s){const o=b(a,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const a=o.userId,{isExpired:s,shouldExpire:n,isSameIP:c}=o,d=s||n||!c&&e.mitigationType!==r.INGEST?Ge.RENEW_SESSION:Ge.EXISTING_SESSION,{sessionStatus:h}=Ke(e.mitigationType,o.match,o.mitigate,o.captcha,Pe(t,i,e.netaceaCaptchaVerificationPath));return{userId:a,sessionCookieStatus:d,sessionStatus:h,sessionCookieDetails:o}}return{sessionStatus:"",userId:I(),sessionCookieStatus:Ge.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,i,a,s,n);return{clientIp:n,method:a,requestId:e.cf.config.requestId,url:i,headers:{host:t.headers.host?.[0]?.value,accept:t.headers.accept?.[0]?.value,userAgent:t.headers["user-agent"]?.[0]?.value??""},sessionDetails:{sessionCookie:s,sessionStatus:h,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:d,userId:u}}}async readCookie(e,t){const i=Je(e.headers,t,"set-cookie"),a=""!==i?i:Je(e.headers,t,"cookie");if(null==a)return;const s=a.split(/; ?/g),o=`${t}=`;for(const e of s)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Te(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}function Je(e,t,i,a=""){if(void 0!==e?.[i]){const a=e[i];if(void 0!==a){const e=a.find((e=>e.value.includes(t)));if(void 0!==e)return e.value}}return a}async function Xe(e,t,i){const a=t.Records[0],s=await Ye(e,t),o={config:e,request:a.cf.request,requestState:ze.getFreshState(a.cf.request),requestDetails:s};return function(e,t){const i=e.requestState;i.reqHandlerId=t.reqHandlerId,i.headerFingerprint=t.headerFingerprint;const{sessionCookieDetails:a}=e.requestDetails.sessionDetails;void 0!==a&&(i.sessionCodes={match:a.match,mitigate:a.mitigate,captcha:a.captcha})}(o,i),o}async function Ye(e,t){return await new We({cookieEncryptionKey:e.cookieEncryptionKey,encryptedCookies:e.encryptedCookies,mitigationType:e.mitigationType,secretKey:e.secretKey,sessionCookieName:e.netaceaCookieName,captchaCookieName:e.netaceaCaptchaCookieName,ipHeaderName:e.ipHeaderName,netaceaCaptchaVerificationPath:e.netaceaCaptchaVerificationPath}).getNetaceaRequestDetails(t.Records[0])}async function Qe(t){const i=new H(e),a=t.headers[Fe.HeadersInOriginalOrderHeader]?.[0].value??"";let s="";if(""!==a)s=await i.hashHeaders(a.split(":"));else{const e=Object.entries(t.headers).flatMap((([e,t])=>t.map((({key:t})=>t??e))));s=await i.hashHeaders(e,!0)}return s}const{extractCookieAttr:Ze,extractAndRemoveCookieAttr:et,removeDuplicateAttrs:tt}=P.cookie.attributes,it=P.cookie.parse.parseSetCookie,{mitigationTypes:at,netaceaHeaders:st}=y;exports.Cloudfront=class{workerInstanceId;config;kinesis;constructor(e){this.config=new Fe(e),this.config.ingestType===n.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new be.Kinesis({deps:{aws4:i,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey,rampUpBatchSize:!0,maxAwaitTimePerIngestCallMs:0}})),this.workerInstanceId=h.v4()}async handleRequest(e){let t;try{t=await Xe(this.config,e,{reqHandlerId:this.workerInstanceId,headerFingerprint:await Qe(e.Records[0].cf.request)});const i=await this.handleNetaceaRoutes(t),{respondWith:a}=i;if(void 0!==a){const{shouldSetSessionCookie:e}=t.requestState;if(e){const e=await this.createSetSessionCookie(t.requestDetails.clientIp,t.requestDetails.sessionDetails.userId,t.requestState.sessionCodes.match,t.requestState.sessionCodes.mitigate,t.requestState.sessionCodes.captcha,t.requestState.sessionCookieMaxAge);void 0===a.headers&&(a.headers={});const i=a.headers["set-cookie"]??[];i.push({key:"set-cookie",value:e}),a.headers["set-cookie"]=i}this.ingestUsingContext(t,a)}return i}catch(e){return console.error("Netacea FailOpen - ",e.message),void 0!==t?.request&&e instanceof Le&&t?.requestState.recordProtectorApiError(e),{}}finally{try{if(void 0!==t){const e=t.requestState.requestStartTimestamp;void 0!==e&&(t.requestState.reqHandlerMs=Date.now()-e),await t.requestState.saveToRequest(t.request,this.config.cookieEncryptionKey)}}catch(e){console.error("Netacea Error:",e)}}}async handleResponse(e){try{const t=await async function(e,t){const i=Date.now(),{request:a}=t.Records[0].cf,s=await ze.fromRequest(a,e.cookieEncryptionKey);return s.resHandlerStartTime=i,{config:e,request:a,requestState:s,requestDetails:await Ye(e,t)}}(this.config,e);try{const i=e.Records[0].cf.response;await this.handleCaptchaFeedback(t,i)}catch(e){console.error("Netacea Error: captcha feedback failed",e)}if(t.requestState.shouldSetSessionCookie){const e=await this.createSetSessionCookie(t.requestDetails.clientIp,t.requestDetails.sessionDetails.userId,t.requestState.sessionCodes.match,t.requestState.sessionCodes.mitigate,t.requestState.sessionCodes.captcha,t.requestState.sessionCookieMaxAge);t.requestState.setCookies.push(e)}const{response:i}=e.Records[0].cf;this.setNetaceaCookies(i,t.requestState),this.ingestUsingContext(t,i)}catch(e){console.error("Netacea Error:",e)}}async handleCaptchaFeedback(e,t){const{captchaFeedbackHeaderName:i}=this.config;if(void 0===i)return;const a=t.headers,s=a[i]?.[0].value;if(delete t.headers[i],void 0===s)return;const o=JSON.parse(s),n=o?.status;if(!["pass","fail"].includes(n))throw new Error("Netacea Error: Invalid captcha feedback status "+String(n));const r=await this.makeRequest({host:this.config.mitigationServiceUrl,method:"POST",path:"/UpdateCaptcha",headers:{"content-type":"application/json; charset=utf-8","x-netacea-api-key":e.config.apiKey,"x-netacea-client-ip":e.requestDetails.clientIp,"x-netacea-userid":e.requestDetails.sessionDetails.userId},body:JSON.stringify({result:"pass"===o.status})});if(200!==r.status)throw new Error(`Netacea Error: Got status ${r.status} for /UpdateCaptcha`);const c=await this.createMitataCaptcha(r.headers);void 0!==c&&e.requestState.setCookies.push(c);let d=r.headers["x-netacea-captcha"];d=Array.isArray(d)?d[0]:d;let h=_e(r.headers,st.mitataExpiry)??NaN;isNaN(h)&&(h=86400);const u=e.requestState;u.sessionCodes.captcha=d,u.sessionCookieMaxAge=h,u.shouldSetSessionCookie=!0;const l=y.captchaMap[d]??"unknown",[p]=e.requestState.sessionStatus?.split(",")??"";e.requestState.sessionStatus=p+","+l}async handleNetaceaRoutes(e){const{uri:t,method:i}=e.request;if(He(t,i,this.config.netaceaCheckpointSignalPath)){return{respondWith:Me({status:"200",headers:{}})}}if(function(e,t,i){return void 0!==i&&e.toLowerCase().includes(i.toLowerCase())&&"get"===t.toLowerCase()}(t,i,this.config.netaceaCaptchaPath)){return{respondWith:Me(await this.handleCaptchaGetRequest(e))}}const a=function(e,t){if(void 0===t)return!1;const i=e.uri;if(t.startsWith("/"))return t===i;try{const a=e.headers.host?.[0]?.value,s=new URL(t);return s.host===a&&s.pathname===i}catch{return!1}}(e.request,this.config.netaceaBlockedResponseRedirectLocation);let s={injectHeaders:De(e.requestState.sessionCodes),sessionStatus:""};return a||(s=await this.runMitigation(e)),void 0!==s&&"injectHeaders"in s&&(this.addNetaceaInjectHeadersToRequest(e.request,s?.injectHeaders),e.requestState.setCookies.push(...s.setCookie??[])),e.request.headers[Fe.NetaceaTrueUserAgentHeader]=[{key:Fe.NetaceaTrueUserAgentHeader,value:this.getValueFromHeaderOrDefault(e.request.headers,"user-agent","-")}],void 0!==s&&(void 0!==s.apiCallLatency&&(e.requestState.protectorApiLatency=s.apiCallLatency),void 0!==s.apiCallStatus&&(e.requestState.protectorApiStatus=s.apiCallStatus),void 0!==s.sessionStatus&&(e.requestState.sessionStatus=s.sessionStatus),void 0!==s.setCookie&&(e.requestState.setCookies=s.setCookie)),{respondWith:Me(s?.response)}}async makeRequest({host:e,method:t,path:i,headers:a,body:s,params:o}){const n=new URL(e);n.pathname=i,void 0!==o&&(o instanceof URLSearchParams?n.search=o.toString():"object"==typeof o&&null!==o&&(n.search=qe.searchParamsFromRecord(o).toString()));const r=n.toString(),c=new Request(r,{...{method:t,body:s,headers:a},duplex:"half"}),d=await O(r,c),h={};return d.headers.forEach(((e,t)=>{null!==e&&(h[t]=e)})),{status:d.status,body:await d.text(),headers:h}}async mitigate(e){const t=Pe(e.request.uri,e.request.method,this.config.netaceaCaptchaVerificationPath);try{const a=t?await this.handleCaptchaPostRequest(e):await this.check(e),s=Ke(this.config.mitigationType,a.match,a.mitigate,a.captcha,t);let o;if([at.block,at.captcha,at.captchaPass].includes(s.mitigation)){const r={"cache-control":[{key:"cache-control",value:["no-store","no-cache","must-revalidate","max-age=0"].join(", ")}],pragma:[{key:"pragma",value:"no-cache"}],"set-cookie":[]};for(const e of a.setCookie)r["set-cookie"]=r["set-cookie"]??[],r["set-cookie"].push({key:"set-cookie",value:e});const c="captcha"===s.mitigation;c&&void 0!==this.config.captchaHeader&&(r[this.config.captchaHeader.name]=[{key:this.config.captchaHeader.name,value:this.config.captchaHeader.value}]);let d={status:"200",statusDescription:"OK",body:""};if(t||(d={status:String(this.config.netaceaBlockedResponseStatus),statusDescription:"Forbidden",body:this.config.netaceaBlockedResponseBody},r["content-type"]=[{key:"content-type",value:this.config.netaceaBlockedResponseContentType}]),o={headers:r,...d},void 0!==this.config.netaceaBlockedResponseRedirectLocation&&!c&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=(e.headers["sec-fetch-mode"]??[]).map((e=>e.value));return!(t.length>0&&!t.includes("navigate"))&&(e.headers.accept??[]).map((e=>e.value.split(/, ?/))).flat().includes("text/html")}(e.request)&&(o.status="303",r.Location=[{key:"Location",value:this.config.netaceaBlockedResponseRedirectLocation}]),c&&void 0!==a.body&&a.body.length>0){const e=(i=a.body).includes("captchaRelativeURL")&&i.includes("captchaAbsoluteURL");o.status=e?"403":"200",o.statusDescription=e?"Forbidden":"OK",o.body=a.body,o.bodyEncoding="text",r["content-type"]=e?[{key:"content-type",value:"application/json"}]:[{key:"content-type",value:"text/html; charset=UTF-8"}]}this.config.ingestType===n.KINESIS&&(e.requestState.protectorApiLatency=a.apiCallLatency,e.requestState.protectorApiStatus=a.apiCallStatus,e.requestState.sessionStatus=s.sessionStatus)}return"4"===s.parts.mitigate&&this.addNetaceaInjectHeadersToRequest(e.request,De(s.parts)),{response:o,sessionStatus:s.sessionStatus,setCookie:a.setCookie,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}catch(i){if(i instanceof Le&&e.requestState.recordProtectorApiError(i),t){return{response:{status:"500",statusDescription:"Internal Server Error",body:"",headers:{}},sessionStatus:"error_open"}}return console.error("Netacea FailOpen Error: ",i),{sessionStatus:"error_open"}}var i}async inject(e){try{const t=Pe(e.request.uri,e.request.method,this.config.netaceaCaptchaVerificationPath),i=t?await this.handleCaptchaPostRequest(e):await this.check(e),a=Ke(this.config.mitigationType,i.match,i.mitigate,i.captcha,t);return{injectHeaders:this.config.mitigationType===r.INJECT||"4"===a.parts.mitigate?De(a.parts):void 0,sessionStatus:a.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}catch(e){return console.error("Netacea FailOpen Error: ",e),{sessionStatus:"",injectHeaders:void 0,setCookie:void 0}}}async ingestUsingContext(e,t=void 0){const i=e.request;if(!this.config.ingestEnabled)return;if(null==t)throw new Error("Cloudfront response is required to ingest");const a=await this.getSetSessionCookieValue(t.headers,"set-cookie")??"",s=""!==a?a:e.requestDetails.sessionDetails.sessionCookie;let o="0",n="0",r="0";const c=v(s);void 0!==c&&(o=c.match,n=c.mitigate,r=c.captcha);const d=e.requestState,h=d.sessionStatus,l=d.protectorApiLatency,p=d.protectorApiStatus,g=Date.now()-e.requestState.requestStartTimestamp,f=this.shouldSetCaptchaPass(i,t),m=He(i.uri,i.method,this.config.netaceaCheckpointSignalPath),y=e.requestDetails,S=void 0!==d.sessionStatus?void 0:Ke(this.config.mitigationType,o,n,r,f,m).sessionStatus,k=this.getValueFromHeaderOrDefault(i.headers,Fe.NetaceaTrueUserAgentHeader,y.headers.userAgent);await this.callIngest({bytesSent:this.getValueFromHeaderOrDefault(t.headers,"content-length","0"),headerFingerprint:e.requestState.headerFingerprint??"-",integrationMode:this.config.mitigationType,integrationType:"@netacea/cloudfront".replace("@netacea/",""),integrationVersion:"7.0.3",ip:y.clientIp,method:y.method,mitataCookie:s,mitigationLatency:void 0!==l?u(l):void 0,mitigationStatus:void 0!==p?u(p):void 0,netaceaCookieStatus:y.sessionDetails.sessionCookieStatus,path:y.url,protocol:null,query:i.querystring,referer:this.getValueFromHeaderOrDefault(i.headers,"referer"),requestHost:this.getValueFromHeaderOrDefault(i.headers,"host",void 0),requestId:y.requestId,requestTime:g,reqHandlerMs:d.reqHandlerMs??g,reqHandlerId:d.reqHandlerId,resHandlerMs:void 0!==d.resHandlerStartTime?Date.now()-d.resHandlerStartTime:0,resHandlerId:this.workerInstanceId,sessionStatus:h??S,status:t.status,userAgent:k,workerInstanceId:this.workerInstanceId,xForwardedFor:this.getValueFromHeaderOrDefault(i.headers,"x-forwarded-for")})}setNetaceaCookies(e,t){if(void 0===e)throw new Error("Response required to add cookies to response");if(null!=e.headers){let i=!1;if(i=void 0!==(e.headers["set-cookie"]??[]).find((e=>!!e.value.startsWith(`${this.config.netaceaCookieName}=`)||!!e.value.startsWith(`${this.config.netaceaCaptchaCookieName}=`))),!i&&t.setCookies.length>0){void 0===e.headers["set-cookie"]&&(e.headers["set-cookie"]=[]);for(const i of t.setCookies)e.headers["set-cookie"].push({key:"set-cookie",value:i})}}}getValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}async getSetSessionCookieValue(e,t){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i){const e=i.find((e=>e.value.startsWith(this.config.netaceaCookieName+"=")));if(void 0!==e){const t=e.value.slice(this.config.netaceaCookieName.length+1).split(";")[0],{cookieEncryptionKey:i,encryptedCookies:a}=this.config;if(void 0===i||!a.includes(this.config.netaceaCookieName))return t;try{return await Te(t,i)}catch{return t}}}}}async handleCaptchaPostRequest(e){const{status:t,match:i,mitigate:a,captcha:s,body:o,setCookie:n,latency:c,mitataMaxAge:d}=await this.makeCaptchaAPICall(e),h=e.requestState;h.sessionCodes={match:i,mitigate:a,captcha:s},h.sessionCookieMaxAge=d,h.shouldSetSessionCookie=String(s)!==String(y.captchaStatusCodes.checkpointPost);const u=Ke(this.config.mitigationType,i,a,s,!0),l={body:o,apiCallStatus:t,apiCallLatency:c,setCookie:n,sessionStatus:u.sessionStatus,mitigation:u.mitigation,injectHeaders:void 0,match:i,mitigate:a,captcha:s};return(this.config.mitigationType===r.INJECT||"4"===u.parts.mitigate)&&(l.injectHeaders=De(u.parts)),l}async handleCaptchaGetRequest(e){const{querystring:t}=e.request,i=t.split("&").find((e=>e.includes("trackingId=")))?.replace("trackingId=",""),a=await this.makeMitigateAPICall(e,{isCaptchaGet:!0,defaultMitataCodes:{match:"0",mitigate:"0",captcha:"1"},trackingId:i}),{match:s,mitigate:o,captcha:n}=a,c=Ke(e.config.mitigationType,s,o,n,!1),d={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:a.setCookie,sessionStatus:c.sessionStatus,injectHeaders:void 0,mitigated:[at.block,at.captcha,at.captchaPass].includes(c.mitigation)};(e.config.mitigationType===r.INJECT||"4"===c.parts.mitigate)&&(d.injectHeaders=De(c.parts));const h=e.requestState;h.sessionStatus=d.sessionStatus,h.protectorApiLatency=d.apiCallLatency,h.protectorApiStatus=d.apiCallStatus;return{headers:Ee(d.setCookie),status:"403",body:d.body,statusDescription:"Forbidden"}}addNetaceaInjectHeadersToRequest(e,t){if(void 0===t)return e;for(const[i,a]of Object.entries(t))e.headers[i]=[{key:i,value:a}];return e}async encryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await Ne(e,this.config.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await Te(e,this.config.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.config.mitigationType){case r.MITIGATE:return await this.mitigate(e);case r.INJECT:return await this.inject(e);case r.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.config.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:De(e.requestState.sessionCodes),sessionStatus:""}}}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(this.config.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}shouldSetCaptchaPass(e,t){if(Pe(e.uri,e.method,this.config.netaceaCaptchaVerificationPath))return!0;if(void 0===t)return!1;const i=null!=t.headers?t.headers["set-cookie"]:void 0,a=i?.find((e=>e.value.split("=")[0]===this.config.netaceaCaptchaCookieName)),s=void 0!==a;return this.config.mitigationType===r.INJECT&&s}async makeCaptchaAPICall(e){const t=e.requestDetails.sessionDetails.userId,i=this.getValueFromHeaderOrDefault(e.request.headers,"content-type","application/x-www-form-urlencoded; charset=UTF-8"),a={"X-Netacea-UserId":t,"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.requestDetails.clientIp,"X-Netacea-Request-Id":e.requestDetails.requestId,"user-agent":e.requestDetails.headers.userAgent,"Content-Type":i};void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(a["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,a["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const s=new URLSearchParams,o=e.requestState.headerFingerprint??"";""!==o&&s.append("headerFP",o),s.append("netaceaHeaders","request-id");const n=function(e,t){if(void 0!==e&&""!==e&&0!==e.trim().length){if(!t.includes("application/json"))return e;try{return JSON.parse(e),e}catch(t){return console.warn("Invalid JSON in captcha data, attempting to serialize:",t),JSON.stringify({data:e})}}}(function(e){if(void 0===e.body?.data||0===e.body.data.length)return"";if(e.body?.inputTruncated)throw new Error("Netacea Error :: Request body is too large.");let t;if("text"===e.body.encoding)t=e.body.data;else try{t=Buffer.from(e.body.data,"base64").toString("utf-8")}catch(i){console.warn("Failed to decode base64 request body:",i),t=e.body.data}if((e.headers["content-type"]?.[0]?.value?.toLowerCase()??"").includes("application/json"))try{JSON.parse(t)}catch(e){console.warn("Request body is not valid JSON despite content-type header:",e)}return t}(e.request),i),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:a,method:"POST",body:n,timeout:this.config.timeout,params:s}),d=Date.now()-r;return await this.getApiCallResponseFromResponse(c,d,void 0)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Le(e,t);const a=Oe(e.headers,st.match)??i?.match??"0",s=Oe(e.headers,st.mitigate)??i?.mitigate??"0",o=Oe(e.headers,st.captcha)??i?.captcha??"0";let n=_e(e.headers,st.mitataExpiry)??NaN;isNaN(n)&&(n=86400);const r=[];if(String(o)!==String(y.captchaStatusCodes.checkpointPost)){const t=await this.createMitataCaptcha(e.headers);void 0!==t&&r.push(t)}const c=Oe(e.headers,st.eventId);return{status:e.status,match:a,mitigate:s,captcha:o,setCookie:r,body:e.body,eventId:c,mitataMaxAge:n,latency:t}}APIError(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}`)}async createSetSessionCookie(e,t,i,a,s,o=86400,n=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=n??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const d=[i,a,s].join(""),h=function(e,t,i,a,s="000"){void 0===t&&(t=I());const o=[i,t,w(e+"|"+String(i),a),s].join(p);return`${w(o,a)}${p}${o}`}(e,t,c,this.config.secretKey,d);let u,l,g=o;if(""!==this.config.netaceaCookieAttributes){const{extractedAttribute:e,cookieAttributes:t}=et(this.config.netaceaCookieAttributes,"Max-Age");g=void 0!==e?Number(e):o;const{extractedAttribute:i,cookieAttributes:a}=et(t,"Path");u=i??"/",l=a??void 0}return await this.buildCookieFromValues(this.config.netaceaCookieName,h,g,l,u)}async createMitataCaptcha(e){let t=e["set-cookie"]??[];t="string"==typeof t?[t]:t;const i=t.find((e=>e.startsWith("_mitatacaptcha=")));let a,s="86400";if(void 0!==i&&""!==i)try{const e=it(i);a=e.value,s=Ze(e.attributes,"Max-Age")??"86400"}catch(e){return}if(""===a||void 0===a)return;const o=tt([this.config.netaceaCaptchaCookieAttributes,"Path=/",`Max-Age=${s}`]);return a=this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)?await this.encryptCookieValue(a):a,`${this.config.netaceaCaptchaCookieName}=${a}; ${o}`}async buildCookieFromValues(e,t,i,a,s="/"){const o=`${e}=${this.config.encryptedCookies.includes(e)?await this.encryptCookieValue(t):t}; Max-Age=${i}; Path=${s}`;return void 0!==a&&""!==a?`${o}; ${a}`:o}async callIngest(e){const t=xe(e);if(this.config.ingestType===n.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");if(void 0!==this.config.kinesisConfigArgs){const{kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:i}=this.config.kinesisConfigArgs;if(void 0===e||void 0===t||void 0===i)return void console.error("Netacea Error: Unable to log as Kinesis configuration misses credentials.")}try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status&&202!==i.status)throw this.APIError(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.request.headers.cookie?.[0].value??"",i=b(await this.readCookie(this.config.netaceaCookieName,t),S,this.config.secretKey);return i.isPrimaryHashValid?i.requiresReissue?await this.setIngestOnlyMitataCookie(i.mitata?.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createSetSessionCookie(S,e,"0","0","0",86400)]}}async check(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const t=e.requestDetails.sessionDetails.sessionCookieDetails;if(void 0===t||!t.isPrimaryHashValid||t.requiresReissue){const t=await this.makeMitigateAPICall(e,{}),i=e.requestState,{match:a,mitigate:s,captcha:o}=t;return i.sessionCodes={match:a,mitigate:s,captcha:o},i.sessionCookieMaxAge=t.mitataMaxAge,i.shouldSetSessionCookie=!0,{body:t.body,apiCallStatus:t.status,apiCallLatency:t.latency,setCookie:[],match:t.match,mitigate:t.mitigate,captcha:t.captcha}}return{body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],match:t.match,mitigate:t.mitigate,captcha:t.captcha}}async makeMitigateAPICall(e,{isCaptchaGet:t=!1,defaultMitataCodes:i,trackingId:a}){const s={"user-agent":e.requestDetails.headers.userAgent,"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.requestDetails.clientIp,"X-Netacea-Request-Id":e.requestDetails.requestId,"X-Netacea-UserId":e.requestDetails.sessionDetails.userId,cookie:this.buildCookieHeader({_mitatacaptcha:e.requestDetails.sessionDetails.captchaToken})};void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),this.config.dynamicCaptchaContentType&&void 0!==this.config.netaceaCaptchaPath&&(s["X-Netacea-Captcha-Content-Type"]=function(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}(e.requestDetails.headers.accept??"text/html"));const o="application/json"===s["X-Netacea-Captcha-Content-Type"],n=new URLSearchParams,r=e.requestState.headerFingerprint;"string"==typeof r&&n.set("headerFP",r),n.append("netaceaHeaders","request-id"),t&&void 0!==a&&n.append("trackingId",a);const c=Date.now(),d=await this.makeRequest({host:this.config.mitigationServiceUrl,path:t?"/captcha":"/",headers:s,method:"GET",timeout:this.config.timeout,params:n}),h=Date.now()-c;return o&&void 0!==this.config.netaceaCaptchaPath&&(d.body=function(e,t,i){let a;if(void 0===e||""===e)return"";if("string"==typeof e&&(a=JSON.parse(e)),!function(e){if(null==e)return!1;const t=e;return void 0!==t?.trackingId}(a))throw new Error("Body is not a Mitigation Service JSON response!");const s=`${i}?trackingId=${a.trackingId}`,o=void 0!==t?`https://${t}${s}`:void 0;return JSON.stringify({captchaRelativeURL:s,captchaAbsoluteURL:o})}(d.body,e.requestDetails.headers.host,this.config.netaceaCaptchaPath)),await this.getApiCallResponseFromResponse(d,h,i)}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}};
|
|
1
|
+
"use strict";var e=require("node:crypto"),t=require("node:buffer"),i=require("aws4"),a=require("jose"),s=require("uuid");function o(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 n,r,c,d=o(a),h=o(s);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(n||(n={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(r||(r={})),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"}(c||(c={}));function u(e,t=0){return isNaN(e)?t:parseInt(e)}const l=3e3;const p="_/@#/",g={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},f={0:g.none,1:g.block,2:g.none,3:g.block,4:g.none},m={1:g.captcha,2:g.captchaPass,3:g.captcha,4:g.allow,5:g.captcha,6:g.allow,7:g.captcha,a:g.captcha,b:g.captchaPass,c:g.captcha,d:g.allow,e:g.captcha};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:m,bestMitigationMap:f,captchaMap:{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"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5,checkpointSignal:6,checkpointPost:7,checkpointServe:"a",checkpointPass:"b",checkpointFail:"c",checkpointCookiePass:"d",checkpointCookieFail:"e"},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged"},mitigationTypes:g,netaceaCookieV3KeyMap:{clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},netaceaCookieV3OptionalKeyMap:{checkAllPostRequests:"fCAPR"},netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const S="ignored",k="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,match:n,mitigate:r,captcha:c}}}function I(t=16,i=k){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function w(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function b(e,t,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0"};if("string"!=typeof e||""===e)return a;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),a=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<a,n=["1","3","5","a","c","e"].includes(s.captcha),r="3"===s.mitigate,c=n||r,d=w(t+"|"+s.expiry,i),h=s.ipHash===d;return{mitata:s,requiresReissue:o||!h,isExpired:o,shouldExpire:c,isSameIP:h,isPrimaryHashValid:s.signature===w(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return a}function A(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 q(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":N(e.split(";"),t).join("; ")}function N(e,t=!1){if(t)return N(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 T=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=q(e??"",!0),a=t=q(t??"",!0);if(void 0!==e&&void 0!==t){const s=A(e,"Domain"),o=A(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=A(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=A(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=A(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:A,removeDuplicateAttrs:q});var E=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),s=a.indexOf(";");if(s<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const P={cookie:{parse:E,attributes:T}};class H{constructor(e){this.crypto=e}async hashString(e,t,i=!1){const a=i?[...t].sort():[...t],s=(new TextEncoder).encode(a.join(",")),o=await this.crypto.subtle.digest(e,s),n=Array.from(new Uint8Array(o)).map((e=>e.toString(16).padStart(2,"0"))).join("").substring(0,12);return"h"+(i?"s":"")+`_${t.length}_${n}`}static filterHeaderNames(e){return e.filter((e=>{const t=e.toLowerCase();return!["","cookie","referer"].includes(t)&&null===t.match(/^(x-netacea-|cloudfront-)/i)}))}async hashHeaders(e,t=!1){const i=H.filterHeaderNames(e);if(0===i.length)return"";try{return await this.hashString("SHA-256",i,t)}catch(e){return console.error(e),""}}}const O=globalThis.fetch.bind(globalThis);var _="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},x={},R={};Object.defineProperty(R,"__esModule",{value:!0}),R.validateRedirectLocation=void 0,R.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 K={},M={};function D(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=j("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function L(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const s=e[a]??"",o="string"==typeof s?s:s.join("; ");i.push(...F(o,t))}return i}function j(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function F(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(M,"__esModule",{value:!0}),M.findAllInCookieString=M.findFirstInCookieString=M.findAllInHeaders=M.findFirstInHeaders=M.findOnlyValueInHeaders=M.findAllValuesInHeaders=M.findFirstValueInHeaders=void 0,M.findFirstValueInHeaders=function(e,t){const i=D(e,t);if(void 0!==i)return i.slice(t.length+1)},M.findAllValuesInHeaders=function(e,t){return L(e,t).map((e=>e.slice(t.length+1)))},M.findOnlyValueInHeaders=function(e,t){const i=L(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},M.findFirstInHeaders=D,M.findAllInHeaders=L,M.findFirstInCookieString=j,M.findAllInCookieString=F;var B={};function V(e){return"set-cookie"===e||"Set-Cookie"===e}function U(e,t){const i=t+"=";return e.startsWith(i)}function $(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function z(e,t){for(const i of Object.keys(e)){if(!V(i))continue;const a=G($(e,i),t);if(void 0!==a)return a}}function G(e,t){return e.map((e=>e.trimStart())).find((e=>U(e,t)))}function W(e,t){const i=[];for(const a of Object.keys(e)){if(!V(a))continue;const s=$(e,a);i.push(...J(s,t))}return i}function J(e,t){return e.map((e=>e.trimStart())).filter((e=>U(e,t)))}Object.defineProperty(B,"__esModule",{value:!0}),B.findAllInSetCookieStrings=B.findAllInHeaders=B.findFirstInSetCookieStrings=B.findFirstInHeaders=B.findOnlyValueInHeaders=B.findFirstValueInHeaders=void 0,B.findFirstValueInHeaders=function(e,t){const i=z(e,t);return i?.slice(t.length+1)?.split(";")[0]},B.findOnlyValueInHeaders=function(e,t){const i=W(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]},B.findFirstInHeaders=z,B.findFirstInSetCookieStrings=G,B.findAllInHeaders=W,B.findAllInSetCookieStrings=J;var X=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Y=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Q=_&&_.__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)&&X(t,e,i);return Y(t,e),t};Object.defineProperty(K,"__esModule",{value:!0}),K.setCookie=K.cookie=void 0,K.cookie=Q(M),K.setCookie=Q(B);var Z={},ee={},te={};Object.defineProperty(te,"__esModule",{value:!0}),te.KINESIS_URL=te.API_VERSION=te.REGION=te.PAYLOAD_TYPE=te.STATE=void 0,te.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},te.PAYLOAD_TYPE="string",te.REGION="eu-west-1",te.API_VERSION="2013-12-02",te.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.headersToRecord=ie.increaseBatchSize=ie.handleFailedLogs=ie.batchArrayForKinesis=ie.sleep=void 0,ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let s=0;s<e.length;s+=t){const o=e.slice(s,s+t);a.push({Data:i.from(JSON.stringify(o)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ie.handleFailedLogs=function(e,t,i){const a=2*i,s=[...e,...t],o=s.length-a;return o>0&&(console.error(`Netacea Error :: failed to send ${o} log(s) to Kinesis ingest.`),s.splice(0,o)),s},ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ee,"__esModule",{value:!0}),ee.WebStandardKinesis=void 0;const ae=te,se=ie;ee.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,se.headersToRecord)(i.headers),host:ae.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,se.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,se.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,se.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,se.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 s={Records:(0,se.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ae.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.Kinesis=void 0;const ne=te,re=ie;oe.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,re.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,re.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,re.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,re.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:s}=e,o={Records:(0,re.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:ne.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ee;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=oe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Z);var ce={};function de(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(ce,"__esModule",{value:!0}),ce.parseHttpHeaderName=ce.stringOrDefault=ce.parseIntOrDefault=he=ce.parseNumberOrDefault=void 0;var he=ce.parseNumberOrDefault=de;ce.parseIntOrDefault=function(e,t){const i=de(e,t);return"number"==typeof i?Math.floor(i):i},ce.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},ce.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var ue={};Object.defineProperty(ue,"__esModule",{value:!0}),ue.searchParamsFromRecord=void 0,ue.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var le={},pe={},ge=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),me=_&&_.__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)&&ge(t,e,i);return fe(t,e),t};Object.defineProperty(pe,"__esModule",{value:!0}),pe.isJweEncrypted=pe.decrypt=pe.encrypt=void 0;const ye=me(a);pe.encrypt=async function(e,t){const i=ye.base64url.decode(t),a=(new TextEncoder).encode(e);return await new ye.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},pe.decrypt=async function(e,t){const i=ye.base64url.decode(t),{plaintext:a}=await ye.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},pe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var Se=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ke=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ce=_&&_.__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)&&Se(t,e,i);return ke(t,e),t};Object.defineProperty(le,"__esModule",{value:!0}),le.jwe=void 0,le.jwe=Ce(pe);var ve=_&&_.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ie=_&&_.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),we=_&&_.__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)&&ve(t,e,i);return Ie(t,e),t};Object.defineProperty(x,"__esModule",{value:!0}),x.webcrypto=qe=x.url=Ae=x.parsing=be=x.ingest=x.headers=x.configValidation=void 0,x.configValidation=we(R),x.headers=we(K);var be=x.ingest=we(Z),Ae=x.parsing=we(ce),qe=x.url=we(ue);async function Ne(e,t){const i=d.base64url.decode(t),a=(new TextEncoder).encode(e);return await new d.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function Te(e,t){const i=d.base64url.decode(t),{plaintext:a}=await d.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function Ee(e){const t={"set-cookie":[]};for(const i of e)t["set-cookie"]?.push({key:"set-cookie",value:i});return t}function Pe(e,t,i){return e===i&&"post"===t.toLowerCase()}function He(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a===i&&"get"===t.toLowerCase()}function Oe(e,t){const i=e[t];return"string"==typeof i?i:i?.[0]}function _e(e,t){const i=Oe(e,t);if(void 0!==i)return parseInt(i,36)}function xe(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,headerFingerprint:t,integrationMode:i,integrationType:a,integrationVersion:s,ip:o,method:n,mitataCookie:r,mitigationLatency:c,mitigationStatus:d,netaceaCookieStatus:h,path:u,protocol:l,query:p,referer:g,reqHandlerId:f,reqHandlerMs:m,requestHost:y,requestId:S,requestTime:k,resHandlerId:C,resHandlerMs:v,sessionStatus:I,status:w,timeUnixMsUTC:b,userAgent:A,workerInstanceId:q,xForwardedFor:N}){const{request:T}=function(e,t,i){"/"!==t[0]&&(t=`/${t}`);const a=t.split("?"),s=a[0],o=a.length>1?`?${a[1]}`:void 0;return{path:s,query:o,request:`${e} ${s}${o??""}${""!==(i??"")?` ${i}`:""}`}}(n,u,l);return{BytesSent:e?.toString(),HeaderHash:t,IntegrationType:a??"",IntegrationVersion:s??"",NetaceaMitigationApplied:I??"",NetaceaUserIdCookie:r??"",NetaceaUserIdCookieStatus:h,ProtectionMode:i,ProtectorLatencyMs:c,ProtectorStatus:d,Query:p,RealIp:o,Referer:""===g?"-":g,ReqHandlerId:f,ReqHandlerMs:m,Request:T,RequestHost:y,RequestId:S??"",RequestTime:k?.toString(),ResHandlerId:C,ResHandlerMs:v,Status:w,TimeLocal:new Date(b??Date.now()).toUTCString(),TimeUnixMsUTC:b??Date.now(),UserAgent:A,WorkerInstanceId:q,XForwardedFor:N}}(e)}x.webcrypto=we(le);const Re="unknown";function Ke(e,t,i,a,s,o=!1){a=function(e,t){let i=e;return t||("2"===e?i="4":"3"===e?i="5":"b"===e?i="d":"c"===e&&(i="e")),i}(a,s),o&&(a="6");let n=y.matchMap[t]??Re+"_";n+=y.mitigateMap[i]??Re;let c=y.bestMitigationMap[i];if("0"!==a){n+=","+(y.captchaMap[a]??Re);const e=y.bestMitigationCaptchaMap[a];void 0!==e&&(c=e)}return e===r.INJECT&&(c=y.mitigationTypes.none),{sessionStatus:n,mitigation:c,parts:{match:t,mitigate:i,captcha:a}}}function Me(e){if(void 0===e)return;const t={...e.headers??{}};if(""!==(e.body??"")){void 0===Object.entries(t).find((([e])=>"content-type"===e.toLowerCase()))&&(t["content-type"]=[{key:"content-type",value:"text/html; charset=UTF-8"}])}return{...e,headers:t}}function De(e,t){return{"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha}}class Le 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}}const{configureCookiesDomain:je}=P.cookie.attributes;class Fe{static NetaceaTrueUserAgentHeader="x-netacea-true-useragent-header";static HeadersInOriginalOrderHeader="cloudfront-viewer-header-order";cookieEncryptionKey;ingestEnabled=!0;netaceaCaptchaPath;netaceaCheckpointSignalPath;captchaHeader;dynamicCaptchaContentType;ipHeaderName;mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl="https://mitigations.netacea.net";ingestServiceUrl;timeout;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;kinesisConfigArgs;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;netaceaCaptchaVerificationPath;captchaFeedbackHeaderName;netaceaBlockedResponseRedirectLocation;netaceaBlockedResponseStatus=403;netaceaBlockedResponseBody="Forbidden";netaceaBlockedResponseContentType="text/plain; charset=utf-8";constructor(e){if(e.ingestType=n.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.kinesis&&(console.warn(['NETACEA :: Please move kinesis params to "kinesis" object in config.',"Backwards compatibility will soon be removed."].join(" ")),this.kinesisConfigArgs={kinesisStreamName:e.kinesisStreamName,kinesisAccessKey:e.kinesisAccessKey,kinesisSecretKey:e.kinesisSecretKey,maxLogAgeSeconds:1},void 0!==e.logBatchSize&&(this.kinesisConfigArgs.logBatchSize=e.logBatchSize)),null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,this.secretKey=e.secretKey,void 0!==e.mitigationServiceUrl){const t=e.mitigationServiceUrl;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t}var t;this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??r.INGEST,this.ingestType=e.ingestType??n.HTTP,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(t=e.timeout??3e3)<=0?l:t,this.netaceaCookieName=Be(e.netaceaCookieName)??"_mitata",this.netaceaCaptchaCookieName=Be(e.netaceaCaptchaCookieName)??"_mitatacaptcha",this.netaceaCaptchaPath=e.netaceaCaptchaPath,this.dynamicCaptchaContentType=e.dynamicCaptchaContentType??!1;const i=je(e.netaceaCookieAttributes??"",e.netaceaCaptchaCookieAttributes??"");var a,s;if(this.netaceaCookieAttributes=i.cookieAttributes??"",this.netaceaCaptchaCookieAttributes=i.captchaCookieAttributes??"",this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName?.toLowerCase()?.trim(),this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(a=this.mitigationType,void 0===(s=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?a===r.INGEST?3600:60:s),this.ingestEnabled=e.ingestEnabled??!0,this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaBlockedResponseRedirectLocation=Be(e.netaceaBlockedResponseRedirectLocation),void 0!==e.netaceaBlockedResponseStatus){const t=he(e.netaceaBlockedResponseStatus,{defaultValue:403});!isNaN(t)&&t>=100&&t<=599&&(this.netaceaBlockedResponseStatus=t)}void 0!==e.netaceaBlockedResponseBody&&(this.netaceaBlockedResponseBody=e.netaceaBlockedResponseBody);const o=e.netaceaBlockedResponseContentType;void 0!==o&&""!==o&&(this.netaceaBlockedResponseContentType=o),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,this.netaceaCaptchaVerificationPath=e.netaceaCaptchaVerificationPath??"/AtaVerifyCaptcha",""===this.netaceaCaptchaVerificationPath&&(this.netaceaCaptchaVerificationPath="/AtaVerifyCaptcha"),this.netaceaCaptchaVerificationPath?.startsWith("/")||(this.netaceaCaptchaVerificationPath="/"+this.netaceaCaptchaVerificationPath),this.captchaFeedbackHeaderName=Ae.parseHttpHeaderName(e.captchaFeedbackHeaderName)}}function Be(e){if("string"==typeof e&&""!==e){const t=e.trim();if(t.length>0)return t}}const Ve="x-netacea-integration-state";function Ue(e){return Ae.parseIntOrDefault(e,{defaultValue:void 0})}function $e(e){return"string"==typeof e?e:void 0}class ze{constructor(e){this.sessionCookieMaxAge=e.sessionCookieMaxAge,this.protectorApiLatency=e.protectorApiLatency,this.protectorApiStatus=e.protectorApiStatus,this.reqHandlerId=e.reqHandlerId,this.reqHandlerMs=e.reqHandlerMs,this.requestStartTimestamp=e.requestStartTimestamp??Date.now(),this.resHandlerId=e.resHandlerId,this.resHandlerStartTime=e.resHandlerStartTime,this.sessionStatus=e.sessionStatus,this.setCookies=e.setCookie??[],this.sessionCodes=e.sessionCodes??{match:"0",mitigate:"0",captcha:"0"},this.shouldSetSessionCookie=e.shouldSetSessionCookie??!1,this.eventId=e.eventId,this.headerFingerprint=e.headerFingerprint}async saveToRequest(e,t){const i=JSON.stringify({protectorApiLatency:this.protectorApiLatency,protectorApiStatus:this.protectorApiStatus,reqHandlerId:this.reqHandlerId,reqHandlerMs:this.reqHandlerMs,requestStartTimestamp:this.requestStartTimestamp,resHandlerId:this.resHandlerId,resHandlerStartTime:this.resHandlerStartTime,sessionStatus:this.sessionStatus,setCookies:this.setCookies,sessionCodes:this.sessionCodes,sessionCookieMaxAge:this.sessionCookieMaxAge,shouldSetSessionCookie:this.shouldSetSessionCookie,eventId:this.eventId,headerFingerprint:this.headerFingerprint});e.headers[Ve]=void 0!==t?[{key:Ve,value:await Ne(i,t)}]:[{key:Ve,value:Buffer.from(i).toString("base64")}]}recordProtectorApiError(e){this.sessionStatus="error_open",this.protectorApiLatency=e.latencyMs,this.protectorApiStatus=e.protectorApiResponse.status}static async fromRequest(e,t){let i=e.headers[Ve]?.[0]?.value;if(void 0===i)return new ze({});try{i=void 0!==t?await Te(i,t):Buffer.from(i,"base64").toString();const e=JSON.parse(i);if("object"==typeof e&&null!==e)return new ze({requestStartTimestamp:"requestStartTimestamp"in e?Ae.parseIntOrDefault(e.requestStartTimestamp,{defaultValue:Date.now()}):Date.now(),sessionStatus:"sessionStatus"in e?$e(e.sessionStatus):void 0,protectorApiLatency:"protectorApiLatency"in e?Ue(e.protectorApiLatency):void 0,protectorApiStatus:"protectorApiStatus"in e?Ue(e.protectorApiStatus):void 0,reqHandlerId:"reqHandlerId"in e?$e(e.reqHandlerId):void 0,reqHandlerMs:"reqHandlerMs"in e?Ue(e.reqHandlerMs):void 0,resHandlerId:"resHandlerId"in e?$e(e.resHandlerId):void 0,resHandlerStartTime:"resHandlerStartTime"in e?Ue(e.resHandlerStartTime):void 0,setCookie:"setCookies"in e&&Array.isArray(e.setCookies)?e.setCookies.filter((e=>"string"==typeof e)):[],sessionCodes:"sessionCodes"in e&&"object"==typeof e.sessionCodes&&null!==e.sessionCodes?{match:$e(e.sessionCodes.match)??"0",mitigate:$e(e.sessionCodes.mitigate)??"0",captcha:$e(e.sessionCodes.captcha)??"0"}:{match:"0",mitigate:"0",captcha:"0"},sessionCookieMaxAge:"sessionCookieMaxAge"in e?Ue(e.sessionCookieMaxAge):void 0,shouldSetSessionCookie:"shouldSetSessionCookie"in e&&Boolean(e.shouldSetSessionCookie),eventId:"eventId"in e?$e(e.eventId):void 0,headerFingerprint:"headerFingerprint"in e?$e(e.headerFingerprint):void 0})}catch{}return new ze({})}static getFreshState(e){return delete e.headers["x-netacea-integration-state"],new ze({})}}var Ge;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ge||(Ge={}));class We{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const{request:t}=e.cf,{uri:i,method:a}=t,s=await this.readCookie(t,this.config.sessionCookieName),o=await this.readCookie(t,this.config.captchaCookieName),n=function(e,t){const{clientIp:i}=e;if(void 0===t||""===t)return i;const a=e.headers[t]?.[0]?.value;return void 0===a||""===a?i:"x-forwarded-for"===t?a.split(/, ?/).pop()??i:a}(t,this.config.ipHeaderName),{sessionCookieDetails:c,sessionCookieStatus:d,sessionStatus:h,userId:u}=function(e,t,i,a,s){const o=b(a,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const a=o.userId,{isExpired:s,shouldExpire:n,isSameIP:c}=o,d=s||n||!c&&e.mitigationType!==r.INGEST?Ge.RENEW_SESSION:Ge.EXISTING_SESSION,{sessionStatus:h}=Ke(e.mitigationType,o.match,o.mitigate,o.captcha,Pe(t,i,e.netaceaCaptchaVerificationPath));return{userId:a,sessionCookieStatus:d,sessionStatus:h,sessionCookieDetails:o}}return{sessionStatus:"",userId:I(),sessionCookieStatus:Ge.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,i,a,s,n);return{clientIp:n,method:a,requestId:e.cf.config.requestId,url:i,headers:{host:t.headers.host?.[0]?.value,accept:t.headers.accept?.[0]?.value,userAgent:t.headers["user-agent"]?.[0]?.value??""},sessionDetails:{sessionCookie:s,sessionStatus:h,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:d,userId:u}}}async readCookie(e,t){const i=Je(e.headers,t,"set-cookie"),a=""!==i?i:Je(e.headers,t,"cookie");if(null==a)return;const s=a.split(/; ?/g),o=`${t}=`;for(const e of s)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Te(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}function Je(e,t,i,a=""){if(void 0!==e?.[i]){const a=e[i];if(void 0!==a){const e=a.find((e=>e.value.includes(t)));if(void 0!==e)return e.value}}return a}async function Xe(e,t,i){const a=t.Records[0],s=await Ye(e,t),o={config:e,request:a.cf.request,requestState:ze.getFreshState(a.cf.request),requestDetails:s};return function(e,t){const i=e.requestState;i.reqHandlerId=t.reqHandlerId,i.headerFingerprint=t.headerFingerprint;const{sessionCookieDetails:a}=e.requestDetails.sessionDetails;void 0!==a&&(i.sessionCodes={match:a.match,mitigate:a.mitigate,captcha:a.captcha})}(o,i),o}async function Ye(e,t){return await new We({cookieEncryptionKey:e.cookieEncryptionKey,encryptedCookies:e.encryptedCookies,mitigationType:e.mitigationType,secretKey:e.secretKey,sessionCookieName:e.netaceaCookieName,captchaCookieName:e.netaceaCaptchaCookieName,ipHeaderName:e.ipHeaderName,netaceaCaptchaVerificationPath:e.netaceaCaptchaVerificationPath}).getNetaceaRequestDetails(t.Records[0])}async function Qe(t){const i=new H(e),a=t.headers[Fe.HeadersInOriginalOrderHeader]?.[0].value??"";let s="";if(""!==a)s=await i.hashHeaders(a.split(":"));else{const e=Object.entries(t.headers).flatMap((([e,t])=>t.map((({key:t})=>t??e))));s=await i.hashHeaders(e,!0)}return s}const{extractCookieAttr:Ze,extractAndRemoveCookieAttr:et,removeDuplicateAttrs:tt}=P.cookie.attributes,it=P.cookie.parse.parseSetCookie,{mitigationTypes:at,netaceaHeaders:st}=y;exports.Cloudfront=class{workerInstanceId;config;kinesis;constructor(e){this.config=new Fe(e),this.config.ingestType===n.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new be.Kinesis({deps:{aws4:i,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey,rampUpBatchSize:!0,maxAwaitTimePerIngestCallMs:0}})),this.workerInstanceId=h.v4()}async handleRequest(e){let t;try{t=await Xe(this.config,e,{reqHandlerId:this.workerInstanceId,headerFingerprint:await Qe(e.Records[0].cf.request)});const i=await this.handleNetaceaRoutes(t),{respondWith:a}=i;if(void 0!==a){const{shouldSetSessionCookie:e}=t.requestState;if(e){const e=await this.createSetSessionCookie(t.requestDetails.clientIp,t.requestDetails.sessionDetails.userId,t.requestState.sessionCodes.match,t.requestState.sessionCodes.mitigate,t.requestState.sessionCodes.captcha,t.requestState.sessionCookieMaxAge);void 0===a.headers&&(a.headers={});const i=a.headers["set-cookie"]??[];i.push({key:"set-cookie",value:e}),a.headers["set-cookie"]=i}this.ingestUsingContext(t,a)}return i}catch(e){return console.error("Netacea FailOpen - ",e.message),void 0!==t?.request&&e instanceof Le&&t?.requestState.recordProtectorApiError(e),{}}finally{try{if(void 0!==t){const e=t.requestState.requestStartTimestamp;void 0!==e&&(t.requestState.reqHandlerMs=Date.now()-e),await t.requestState.saveToRequest(t.request,this.config.cookieEncryptionKey)}}catch(e){console.error("Netacea Error:",e)}}}async handleResponse(e){try{const t=await async function(e,t){const i=Date.now(),{request:a}=t.Records[0].cf,s=await ze.fromRequest(a,e.cookieEncryptionKey);return s.resHandlerStartTime=i,{config:e,request:a,requestState:s,requestDetails:await Ye(e,t)}}(this.config,e);try{const i=e.Records[0].cf.response;await this.handleCaptchaFeedback(t,i)}catch(e){console.error("Netacea Error: captcha feedback failed",e)}if(t.requestState.shouldSetSessionCookie){const e=await this.createSetSessionCookie(t.requestDetails.clientIp,t.requestDetails.sessionDetails.userId,t.requestState.sessionCodes.match,t.requestState.sessionCodes.mitigate,t.requestState.sessionCodes.captcha,t.requestState.sessionCookieMaxAge);t.requestState.setCookies.push(e)}const{response:i}=e.Records[0].cf;this.setNetaceaCookies(i,t.requestState),this.ingestUsingContext(t,i)}catch(e){console.error("Netacea Error:",e)}}async handleCaptchaFeedback(e,t){const{captchaFeedbackHeaderName:i}=this.config;if(void 0===i)return;const a=t.headers,s=a[i]?.[0].value;if(delete t.headers[i],void 0===s)return;const o=JSON.parse(s),n=o?.status;if(!["pass","fail"].includes(n))throw new Error("Netacea Error: Invalid captcha feedback status "+String(n));const r=await this.makeRequest({host:this.config.mitigationServiceUrl,method:"POST",path:"/UpdateCaptcha",headers:{"content-type":"application/json; charset=utf-8","x-netacea-api-key":e.config.apiKey,"x-netacea-client-ip":e.requestDetails.clientIp,"x-netacea-userid":e.requestDetails.sessionDetails.userId},body:JSON.stringify({result:"pass"===o.status})});if(200!==r.status)throw new Error(`Netacea Error: Got status ${r.status} for /UpdateCaptcha`);const c=await this.createMitataCaptcha(r.headers);void 0!==c&&e.requestState.setCookies.push(c);let d=r.headers["x-netacea-captcha"];d=Array.isArray(d)?d[0]:d;let h=_e(r.headers,st.mitataExpiry)??NaN;isNaN(h)&&(h=86400);const u=e.requestState;u.sessionCodes.captcha=d,u.sessionCookieMaxAge=h,u.shouldSetSessionCookie=!0;const l=y.captchaMap[d]??"unknown",[p]=e.requestState.sessionStatus?.split(",")??"";e.requestState.sessionStatus=p+","+l}async handleNetaceaRoutes(e){const{uri:t,method:i}=e.request;if(He(t,i,this.config.netaceaCheckpointSignalPath)){return{respondWith:Me({status:"200",headers:{}})}}if(function(e,t,i){return void 0!==i&&e.toLowerCase().includes(i.toLowerCase())&&"get"===t.toLowerCase()}(t,i,this.config.netaceaCaptchaPath)){return{respondWith:Me(await this.handleCaptchaGetRequest(e))}}const a=function(e,t){if(void 0===t)return!1;const i=e.uri;if(t.startsWith("/"))return t===i;try{const a=e.headers.host?.[0]?.value,s=new URL(t);return s.host===a&&s.pathname===i}catch{return!1}}(e.request,this.config.netaceaBlockedResponseRedirectLocation);let s={injectHeaders:De(e.requestState.sessionCodes),sessionStatus:""};return a||(s=await this.runMitigation(e)),void 0!==s&&"injectHeaders"in s&&(this.addNetaceaInjectHeadersToRequest(e.request,s?.injectHeaders),e.requestState.setCookies.push(...s.setCookie??[])),e.request.headers[Fe.NetaceaTrueUserAgentHeader]=[{key:Fe.NetaceaTrueUserAgentHeader,value:this.getValueFromHeaderOrDefault(e.request.headers,"user-agent","-")}],void 0!==s&&(void 0!==s.apiCallLatency&&(e.requestState.protectorApiLatency=s.apiCallLatency),void 0!==s.apiCallStatus&&(e.requestState.protectorApiStatus=s.apiCallStatus),void 0!==s.sessionStatus&&(e.requestState.sessionStatus=s.sessionStatus),void 0!==s.setCookie&&(e.requestState.setCookies=s.setCookie)),{respondWith:Me(s?.response)}}async makeRequest({host:e,method:t,path:i,headers:a,body:s,params:o}){const n=new URL(e);n.pathname=i,void 0!==o&&(o instanceof URLSearchParams?n.search=o.toString():"object"==typeof o&&null!==o&&(n.search=qe.searchParamsFromRecord(o).toString()));const r=n.toString(),c=new Request(r,{...{method:t,body:s,headers:a},duplex:"half"}),d=await O(r,c),h={};return d.headers.forEach(((e,t)=>{null!==e&&(h[t]=e)})),{status:d.status,body:await d.text(),headers:h}}async mitigate(e){const t=Pe(e.request.uri,e.request.method,this.config.netaceaCaptchaVerificationPath);try{const a=t?await this.handleCaptchaPostRequest(e):await this.check(e),s=Ke(this.config.mitigationType,a.match,a.mitigate,a.captcha,t);let o;if([at.block,at.captcha,at.captchaPass].includes(s.mitigation)){const r={"cache-control":[{key:"cache-control",value:["no-store","no-cache","must-revalidate","max-age=0"].join(", ")}],pragma:[{key:"pragma",value:"no-cache"}],"set-cookie":[]};for(const e of a.setCookie)r["set-cookie"]=r["set-cookie"]??[],r["set-cookie"].push({key:"set-cookie",value:e});const c="captcha"===s.mitigation;c&&void 0!==this.config.captchaHeader&&(r[this.config.captchaHeader.name]=[{key:this.config.captchaHeader.name,value:this.config.captchaHeader.value}]);let d={status:"200",statusDescription:"OK",body:""};if(t||(d={status:String(this.config.netaceaBlockedResponseStatus),statusDescription:"Forbidden",body:this.config.netaceaBlockedResponseBody},r["content-type"]=[{key:"content-type",value:this.config.netaceaBlockedResponseContentType}]),o={headers:r,...d},void 0!==this.config.netaceaBlockedResponseRedirectLocation&&!c&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=(e.headers["sec-fetch-mode"]??[]).map((e=>e.value));return!(t.length>0&&!t.includes("navigate"))&&(e.headers.accept??[]).map((e=>e.value.split(/, ?/))).flat().includes("text/html")}(e.request)&&(o.status="303",r.Location=[{key:"Location",value:this.config.netaceaBlockedResponseRedirectLocation}]),c&&void 0!==a.body&&a.body.length>0){const e=(i=a.body).includes("captchaRelativeURL")&&i.includes("captchaAbsoluteURL");o.status=e?"403":"200",o.statusDescription=e?"Forbidden":"OK",o.body=a.body,o.bodyEncoding="text",r["content-type"]=e?[{key:"content-type",value:"application/json"}]:[{key:"content-type",value:"text/html; charset=UTF-8"}]}this.config.ingestType===n.KINESIS&&(e.requestState.protectorApiLatency=a.apiCallLatency,e.requestState.protectorApiStatus=a.apiCallStatus,e.requestState.sessionStatus=s.sessionStatus)}return"4"===s.parts.mitigate&&this.addNetaceaInjectHeadersToRequest(e.request,De(s.parts)),{response:o,sessionStatus:s.sessionStatus,setCookie:a.setCookie,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}catch(i){if(i instanceof Le&&e.requestState.recordProtectorApiError(i),t){return{response:{status:"500",statusDescription:"Internal Server Error",body:"",headers:{}},sessionStatus:"error_open"}}return console.error("Netacea FailOpen Error: ",i),{sessionStatus:"error_open"}}var i}async inject(e){try{const t=Pe(e.request.uri,e.request.method,this.config.netaceaCaptchaVerificationPath),i=t?await this.handleCaptchaPostRequest(e):await this.check(e),a=Ke(this.config.mitigationType,i.match,i.mitigate,i.captcha,t);return{injectHeaders:this.config.mitigationType===r.INJECT||"4"===a.parts.mitigate?De(a.parts):void 0,sessionStatus:a.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}catch(e){return console.error("Netacea FailOpen Error: ",e),{sessionStatus:"",injectHeaders:void 0,setCookie:void 0}}}async ingestUsingContext(e,t=void 0){const i=e.request;if(!this.config.ingestEnabled)return;if(null==t)throw new Error("Cloudfront response is required to ingest");const a=await this.getSetSessionCookieValue(t.headers,"set-cookie")??"",s=""!==a?a:e.requestDetails.sessionDetails.sessionCookie;let o="0",n="0",r="0";const c=v(s);void 0!==c&&(o=c.match,n=c.mitigate,r=c.captcha);const d=e.requestState,h=d.sessionStatus,l=d.protectorApiLatency,p=d.protectorApiStatus,g=Date.now()-e.requestState.requestStartTimestamp,f=this.shouldSetCaptchaPass(i,t),m=He(i.uri,i.method,this.config.netaceaCheckpointSignalPath),y=e.requestDetails,S=void 0!==d.sessionStatus?void 0:Ke(this.config.mitigationType,o,n,r,f,m).sessionStatus,k=this.getValueFromHeaderOrDefault(i.headers,Fe.NetaceaTrueUserAgentHeader,y.headers.userAgent);await this.callIngest({bytesSent:this.getValueFromHeaderOrDefault(t.headers,"content-length","0"),headerFingerprint:e.requestState.headerFingerprint??"-",integrationMode:this.config.mitigationType,integrationType:"@netacea/cloudfront".replace("@netacea/",""),integrationVersion:"7.0.5",ip:y.clientIp,method:y.method,mitataCookie:s,mitigationLatency:void 0!==l?u(l):void 0,mitigationStatus:void 0!==p?u(p):void 0,netaceaCookieStatus:y.sessionDetails.sessionCookieStatus,path:y.url,protocol:null,query:i.querystring,referer:this.getValueFromHeaderOrDefault(i.headers,"referer"),requestHost:this.getValueFromHeaderOrDefault(i.headers,"host",void 0),requestId:y.requestId,requestTime:g,reqHandlerMs:d.reqHandlerMs??g,reqHandlerId:d.reqHandlerId,resHandlerMs:void 0!==d.resHandlerStartTime?Date.now()-d.resHandlerStartTime:0,resHandlerId:this.workerInstanceId,sessionStatus:h??S,status:t.status,userAgent:k,workerInstanceId:this.workerInstanceId,xForwardedFor:this.getValueFromHeaderOrDefault(i.headers,"x-forwarded-for")})}setNetaceaCookies(e,t){if(void 0===e)throw new Error("Response required to add cookies to response");if(null!=e.headers){let i=!1;if(i=void 0!==(e.headers["set-cookie"]??[]).find((e=>!!e.value.startsWith(`${this.config.netaceaCookieName}=`)||!!e.value.startsWith(`${this.config.netaceaCaptchaCookieName}=`))),!i&&t.setCookies.length>0){void 0===e.headers["set-cookie"]&&(e.headers["set-cookie"]=[]);for(const i of t.setCookies)e.headers["set-cookie"].push({key:"set-cookie",value:i})}}}getValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}async getSetSessionCookieValue(e,t){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i){const e=i.find((e=>e.value.startsWith(this.config.netaceaCookieName+"=")));if(void 0!==e){const t=e.value.slice(this.config.netaceaCookieName.length+1).split(";")[0],{cookieEncryptionKey:i,encryptedCookies:a}=this.config;if(void 0===i||!a.includes(this.config.netaceaCookieName))return t;try{return await Te(t,i)}catch{return t}}}}}async handleCaptchaPostRequest(e){const{status:t,match:i,mitigate:a,captcha:s,body:o,setCookie:n,latency:c,mitataMaxAge:d}=await this.makeCaptchaAPICall(e),h=e.requestState;h.sessionCodes={match:i,mitigate:a,captcha:s},h.sessionCookieMaxAge=d,h.shouldSetSessionCookie=String(s)!==String(y.captchaStatusCodes.checkpointPost);const u=Ke(this.config.mitigationType,i,a,s,!0),l={body:o,apiCallStatus:t,apiCallLatency:c,setCookie:n,sessionStatus:u.sessionStatus,mitigation:u.mitigation,injectHeaders:void 0,match:i,mitigate:a,captcha:s};return(this.config.mitigationType===r.INJECT||"4"===u.parts.mitigate)&&(l.injectHeaders=De(u.parts)),l}async handleCaptchaGetRequest(e){const{querystring:t}=e.request,i=t.split("&").find((e=>e.includes("trackingId=")))?.replace("trackingId=",""),a=await this.makeMitigateAPICall(e,{isCaptchaGet:!0,defaultMitataCodes:{match:"0",mitigate:"0",captcha:"1"},trackingId:i}),{match:s,mitigate:o,captcha:n}=a,c=Ke(e.config.mitigationType,s,o,n,!1),d={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:a.setCookie,sessionStatus:c.sessionStatus,injectHeaders:void 0,mitigated:[at.block,at.captcha,at.captchaPass].includes(c.mitigation)};(e.config.mitigationType===r.INJECT||"4"===c.parts.mitigate)&&(d.injectHeaders=De(c.parts));const h=e.requestState;h.sessionStatus=d.sessionStatus,h.protectorApiLatency=d.apiCallLatency,h.protectorApiStatus=d.apiCallStatus;return{headers:Ee(d.setCookie),status:"403",body:d.body,statusDescription:"Forbidden"}}addNetaceaInjectHeadersToRequest(e,t){if(void 0===t)return e;for(const[i,a]of Object.entries(t))e.headers[i]=[{key:i,value:a}];return e}async encryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await Ne(e,this.config.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await Te(e,this.config.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.config.mitigationType){case r.MITIGATE:return await this.mitigate(e);case r.INJECT:return await this.inject(e);case r.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.config.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:De(e.requestState.sessionCodes),sessionStatus:""}}}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(this.config.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}shouldSetCaptchaPass(e,t){if(Pe(e.uri,e.method,this.config.netaceaCaptchaVerificationPath))return!0;if(void 0===t)return!1;const i=null!=t.headers?t.headers["set-cookie"]:void 0,a=i?.find((e=>e.value.split("=")[0]===this.config.netaceaCaptchaCookieName)),s=void 0!==a;return this.config.mitigationType===r.INJECT&&s}async makeCaptchaAPICall(e){const t=e.requestDetails.sessionDetails.userId,i=this.getValueFromHeaderOrDefault(e.request.headers,"content-type","application/x-www-form-urlencoded; charset=UTF-8"),a={"X-Netacea-UserId":t,"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.requestDetails.clientIp,"X-Netacea-Request-Id":e.requestDetails.requestId,"user-agent":e.requestDetails.headers.userAgent,"Content-Type":i};void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(a["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,a["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const s=new URLSearchParams,o=e.requestState.headerFingerprint??"";""!==o&&s.append("headerFP",o),s.append("netaceaHeaders","request-id");const n=function(e,t){if(void 0!==e&&""!==e&&0!==e.trim().length){if(!t.includes("application/json"))return e;try{return JSON.parse(e),e}catch(t){return console.warn("Invalid JSON in captcha data, attempting to serialize:",t),JSON.stringify({data:e})}}}(function(e){if(void 0===e.body?.data||0===e.body.data.length)return"";if(e.body?.inputTruncated)throw new Error("Netacea Error :: Request body is too large.");let t;if("text"===e.body.encoding)t=e.body.data;else try{t=Buffer.from(e.body.data,"base64").toString("utf-8")}catch(i){console.warn("Failed to decode base64 request body:",i),t=e.body.data}if((e.headers["content-type"]?.[0]?.value?.toLowerCase()??"").includes("application/json"))try{JSON.parse(t)}catch(e){console.warn("Request body is not valid JSON despite content-type header:",e)}return t}(e.request),i),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:a,method:"POST",body:n,timeout:this.config.timeout,params:s}),d=Date.now()-r;return await this.getApiCallResponseFromResponse(c,d,void 0)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Le(e,t);const a=Oe(e.headers,st.match)??i?.match??"0",s=Oe(e.headers,st.mitigate)??i?.mitigate??"0",o=Oe(e.headers,st.captcha)??i?.captcha??"0";let n=_e(e.headers,st.mitataExpiry)??NaN;isNaN(n)&&(n=86400);const r=[];if(String(o)!==String(y.captchaStatusCodes.checkpointPost)){const t=await this.createMitataCaptcha(e.headers);void 0!==t&&r.push(t)}const c=Oe(e.headers,st.eventId);return{status:e.status,match:a,mitigate:s,captcha:o,setCookie:r,body:e.body,eventId:c,mitataMaxAge:n,latency:t}}APIError(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}`)}async createSetSessionCookie(e,t,i,a,s,o=86400,n=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=n??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const d=[i,a,s].join(""),h=function(e,t,i,a,s="000"){void 0===t&&(t=I());const o=[i,t,w(e+"|"+String(i),a),s].join(p);return`${w(o,a)}${p}${o}`}(e,t,c,this.config.secretKey,d);let u,l,g=o;if(""!==this.config.netaceaCookieAttributes){const{extractedAttribute:e,cookieAttributes:t}=et(this.config.netaceaCookieAttributes,"Max-Age");g=void 0!==e?Number(e):o;const{extractedAttribute:i,cookieAttributes:a}=et(t,"Path");u=i??"/",l=a??void 0}return await this.buildCookieFromValues(this.config.netaceaCookieName,h,g,l,u)}async createMitataCaptcha(e){let t=e["set-cookie"]??[];t="string"==typeof t?[t]:t;const i=t.find((e=>e.startsWith("_mitatacaptcha=")));let a,s="86400";if(void 0!==i&&""!==i)try{const e=it(i);a=e.value,s=Ze(e.attributes,"Max-Age")??"86400"}catch(e){return}if(""===a||void 0===a)return;const o=tt([this.config.netaceaCaptchaCookieAttributes,"Path=/",`Max-Age=${s}`]);return a=this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)?await this.encryptCookieValue(a):a,`${this.config.netaceaCaptchaCookieName}=${a}; ${o}`}async buildCookieFromValues(e,t,i,a,s="/"){const o=`${e}=${this.config.encryptedCookies.includes(e)?await this.encryptCookieValue(t):t}; Max-Age=${i}; Path=${s}`;return void 0!==a&&""!==a?`${o}; ${a}`:o}async callIngest(e){const t=xe(e);if(this.config.ingestType===n.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");if(void 0!==this.config.kinesisConfigArgs){const{kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:i}=this.config.kinesisConfigArgs;if(void 0===e||void 0===t||void 0===i)return void console.error("Netacea Error: Unable to log as Kinesis configuration misses credentials.")}try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status&&202!==i.status)throw this.APIError(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.request.headers.cookie?.[0].value??"",i=b(await this.readCookie(this.config.netaceaCookieName,t),S,this.config.secretKey);return i.isPrimaryHashValid?i.requiresReissue?await this.setIngestOnlyMitataCookie(i.mitata?.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createSetSessionCookie(S,e,"0","0","0",86400)]}}async check(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const t=e.requestDetails.sessionDetails.sessionCookieDetails;if(void 0===t||!t.isPrimaryHashValid||t.requiresReissue){const t=await this.makeMitigateAPICall(e,{}),i=e.requestState,{match:a,mitigate:s,captcha:o}=t;return i.sessionCodes={match:a,mitigate:s,captcha:o},i.sessionCookieMaxAge=t.mitataMaxAge,i.shouldSetSessionCookie=!0,{body:t.body,apiCallStatus:t.status,apiCallLatency:t.latency,setCookie:[],match:t.match,mitigate:t.mitigate,captcha:t.captcha}}return{body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],match:t.match,mitigate:t.mitigate,captcha:t.captcha}}async makeMitigateAPICall(e,{isCaptchaGet:t=!1,defaultMitataCodes:i,trackingId:a}){const s={"user-agent":e.requestDetails.headers.userAgent,"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.requestDetails.clientIp,"X-Netacea-Request-Id":e.requestDetails.requestId,"X-Netacea-UserId":e.requestDetails.sessionDetails.userId,cookie:this.buildCookieHeader({_mitatacaptcha:e.requestDetails.sessionDetails.captchaToken})};void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),this.config.dynamicCaptchaContentType&&void 0!==this.config.netaceaCaptchaPath&&(s["X-Netacea-Captcha-Content-Type"]=function(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}(e.requestDetails.headers.accept??"text/html"));const o="application/json"===s["X-Netacea-Captcha-Content-Type"],n=new URLSearchParams,r=e.requestState.headerFingerprint;"string"==typeof r&&n.set("headerFP",r),n.append("netaceaHeaders","request-id"),t&&void 0!==a&&n.append("trackingId",a);const c=Date.now(),d=await this.makeRequest({host:this.config.mitigationServiceUrl,path:t?"/captcha":"/",headers:s,method:"GET",timeout:this.config.timeout,params:n}),h=Date.now()-c;return o&&void 0!==this.config.netaceaCaptchaPath&&(d.body=function(e,t,i){let a;if(void 0===e||""===e)return"";if("string"==typeof e&&(a=JSON.parse(e)),!function(e){if(null==e)return!1;const t=e;return void 0!==t?.trackingId}(a))throw new Error("Body is not a Mitigation Service JSON response!");const s=`${i}?trackingId=${a.trackingId}`,o=void 0!==t?`https://${t}${s}`:void 0;return JSON.stringify({captchaRelativeURL:s,captchaAbsoluteURL:o})}(d.body,e.requestDetails.headers.host,this.config.netaceaCaptchaPath)),await this.getApiCallResponseFromResponse(d,h,i)}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudfront",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.5",
|
|
4
4
|
"description": "Netacea Cloudfront CDN integration",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist/index.js",
|
|
@@ -23,5 +23,5 @@
|
|
|
23
23
|
"jose": "^4.11.2",
|
|
24
24
|
"uuid": "^10.0.0"
|
|
25
25
|
},
|
|
26
|
-
"gitHead": "
|
|
26
|
+
"gitHead": "aa452a1813e3998d494e1507a67ca03831da633d"
|
|
27
27
|
}
|