@netacea/cloudfront 6.0.77 → 6.0.78
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.d.ts +12 -18
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -411,22 +411,13 @@ interface CloudfrontConstructorArgs extends NetaceaBaseArgs, KinesisIngestArgs$1
|
|
|
411
411
|
netaceaCookieAttributes?: string;
|
|
412
412
|
netaceaCaptchaCookieAttributes?: string;
|
|
413
413
|
logBatchSize?: number | undefined;
|
|
414
|
-
/**
|
|
415
|
-
* The name of the header from which to retrieve the client's IP address.
|
|
416
|
-
*/
|
|
417
414
|
ipHeaderName?: string;
|
|
418
|
-
/**
|
|
419
|
-
* Location to be used for a redirect response when performing a block.
|
|
420
|
-
*/
|
|
421
415
|
netaceaBlockedResponseRedirectLocation?: string;
|
|
422
|
-
/**
|
|
423
|
-
* The path to be accessed by the checkpoint script for measuring RTT.
|
|
424
|
-
*/
|
|
425
416
|
netaceaCheckpointSignalPath?: string;
|
|
426
|
-
/**
|
|
427
|
-
* The path for captcha verification. Defaults to /AtaVerifyCaptcha
|
|
428
|
-
*/
|
|
429
417
|
netaceaCaptchaVerificationPath?: string;
|
|
418
|
+
netaceaBlockedResponseStatus?: string | number;
|
|
419
|
+
netaceaBlockedResponseBody?: string;
|
|
420
|
+
netaceaBlockedResponseContentType?: string;
|
|
430
421
|
}
|
|
431
422
|
interface CustomHeader {
|
|
432
423
|
name: string;
|
|
@@ -442,14 +433,14 @@ declare class CloudfrontConfig {
|
|
|
442
433
|
static NetaceaCookieHeader: string;
|
|
443
434
|
static NetaceaTrueUserAgentHeader: string;
|
|
444
435
|
/**
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
436
|
+
* CloudFront special header names to grab header names in original order
|
|
437
|
+
* The get these headers in edge function, they need to be activated through origin request policy
|
|
438
|
+
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/adding-cloudfront-headers.html#cloudfront-headers-viewer-headers
|
|
439
|
+
*/
|
|
449
440
|
static HeadersInOriginalOrderHeader: string;
|
|
450
441
|
static NetaceaHeaderFingerPrintHeader: string;
|
|
451
442
|
readonly cookieEncryptionKey: string | undefined;
|
|
452
|
-
ingestEnabled: boolean;
|
|
443
|
+
readonly ingestEnabled: boolean;
|
|
453
444
|
readonly netaceaCaptchaPath?: string;
|
|
454
445
|
readonly netaceaCheckpointSignalPath?: string;
|
|
455
446
|
readonly captchaHeader?: CustomHeader;
|
|
@@ -471,8 +462,11 @@ declare class CloudfrontConfig {
|
|
|
471
462
|
readonly netaceaCaptchaCookieName: string;
|
|
472
463
|
readonly netaceaCookieAttributes: string;
|
|
473
464
|
readonly netaceaCaptchaCookieAttributes: string;
|
|
474
|
-
readonly netaceaBlockedResponseRedirectLocation: string | undefined;
|
|
475
465
|
readonly netaceaCaptchaVerificationPath: string;
|
|
466
|
+
readonly netaceaBlockedResponseRedirectLocation: string | undefined;
|
|
467
|
+
readonly netaceaBlockedResponseStatus: number;
|
|
468
|
+
readonly netaceaBlockedResponseBody: string;
|
|
469
|
+
readonly netaceaBlockedResponseContentType: string;
|
|
476
470
|
constructor(options: CloudfrontConstructorArgs);
|
|
477
471
|
}
|
|
478
472
|
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("node:crypto"),t=require("node:buffer"),i=require("axios"),a=require("aws4"),s=require("jose"),o=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var r,c,h,d=n(s),u=n(o);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(r||(r={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(c||(c={})),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"}(h||(h={}));function l(e,t=0){return isNaN(e)?t:parseInt(e)}const p=3e3;const g="_/@#/",f={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},m={0:f.none,1:f.block,2:f.none,3:f.block,4:f.block},y={1:f.captcha,2:f.captchaPass,3:f.captcha,4:f.allow,5:f.captcha,6:f.allow,7:f.captcha,a:f.captcha,b:f.captchaPass,c:f.captcha,d:f.allow,e:f.captcha};var k=Object.freeze({__proto__:null,COOKIEDELIMITER:g,bestMitigationCaptchaMap:y,bestMitigationMap:m,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:"block"},mitigationTypes:f,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 C="ignored",S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),v=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function I(e){if(void 0===e)return;const t=e.match(v);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 w(t=16,i=S){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function b(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function A(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=I(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(g),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,h=b(t+"|"+s.expiry,i),d=s.ipHash===h;return{mitata:s,requiresReissue:o||!d,isExpired:o,shouldExpire:c,isSameIP:d,isPrimaryHashValid:s.signature===b(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return a}function N(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 E(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":P(e.split(";"),t).join("; ")}function P(e,t=!1){if(t)return P(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var T=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=E(e??"",!0),a=t=E(t??"",!0);if(void 0!==e&&void 0!==t){const s=N(e,"Domain"),o=N(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=N(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=N(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=N(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:N,removeDuplicateAttrs:E});var O=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(";");return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const _={cookie:{parse:O,attributes:T}};class K{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=K.filterHeaderNames(e);if(0===i.length)return"";try{return await this.hashString("SHA-256",i,t)}catch(e){return console.error(e),""}}}var x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},R={},H={},M={},F=x&&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]}),q=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),L=x&&x.__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)&&F(t,e,i);return q(t,e),t};Object.defineProperty(M,"__esModule",{value:!0}),M.isJweEncrypted=M.decrypt=M.encrypt=void 0;const j=L(s);M.encrypt=async function(e,t){const i=j.base64url.decode(t),a=(new TextEncoder).encode(e);return await new j.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},M.decrypt=async function(e,t){const i=j.base64url.decode(t),{plaintext:a}=await j.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},M.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var D=x&&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]}),V=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$=x&&x.__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)&&D(t,e,i);return V(t,e),t};Object.defineProperty(H,"__esModule",{value:!0}),H.jwe=void 0,H.jwe=$(M);var B={},U={};function z(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=W("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function G(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(...X(o,t))}return i}function W(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function X(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(U,"__esModule",{value:!0}),U.findAllInCookieString=U.findFirstInCookieString=U.findAllInHeaders=U.findFirstInHeaders=U.findOnlyValueInHeaders=U.findAllValuesInHeaders=U.findFirstValueInHeaders=void 0,U.findFirstValueInHeaders=function(e,t){const i=z(e,t);if(void 0!==i)return i.slice(t.length+1)},U.findAllValuesInHeaders=function(e,t){return G(e,t).map((e=>e.slice(t.length+1)))},U.findOnlyValueInHeaders=function(e,t){const i=G(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},U.findFirstInHeaders=z,U.findAllInHeaders=G,U.findFirstInCookieString=W,U.findAllInCookieString=X;var J={};function Y(e){return"set-cookie"===e||"Set-Cookie"===e}function Q(e,t){const i=t+"=";return e.startsWith(i)}function Z(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ee(e,t){for(const i of Object.keys(e)){if(!Y(i))continue;const a=te(Z(e,i),t);if(void 0!==a)return a}}function te(e,t){return e.map((e=>e.trimStart())).find((e=>Q(e,t)))}function ie(e,t){const i=[];for(const a of Object.keys(e)){if(!Y(a))continue;const s=Z(e,a);i.push(...ae(s,t))}return i}function ae(e,t){return e.map((e=>e.trimStart())).filter((e=>Q(e,t)))}Object.defineProperty(J,"__esModule",{value:!0}),J.findAllInSetCookieStrings=J.findAllInHeaders=J.findFirstInSetCookieStrings=J.findFirstInHeaders=J.findOnlyValueInHeaders=J.findFirstValueInHeaders=void 0,J.findFirstValueInHeaders=function(e,t){const i=ee(e,t);return i?.slice(t.length+1)?.split(";")[0]},J.findOnlyValueInHeaders=function(e,t){const i=ie(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]},J.findFirstInHeaders=ee,J.findFirstInSetCookieStrings=te,J.findAllInHeaders=ie,J.findAllInSetCookieStrings=ae;var se=x&&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]}),oe=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ne=x&&x.__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 oe(t,e),t};Object.defineProperty(B,"__esModule",{value:!0}),B.setCookie=B.cookie=void 0,B.cookie=ne(U),B.setCookie=ne(J);var re={},ce={},he={};Object.defineProperty(he,"__esModule",{value:!0}),he.KINESIS_URL=he.API_VERSION=he.REGION=he.PAYLOAD_TYPE=he.STATE=void 0,he.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},he.PAYLOAD_TYPE="string",he.REGION="eu-west-1",he.API_VERSION="2013-12-02",he.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var de={};Object.defineProperty(de,"__esModule",{value:!0}),de.headersToRecord=de.increaseBatchSize=de.handleFailedLogs=de.batchArrayForKinesis=de.sleep=void 0,de.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},de.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},de.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},de.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},de.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ce,"__esModule",{value:!0}),ce.WebStandardKinesis=void 0;const ue=he,le=de;ce.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,le.headersToRecord)(i.headers),host:ue.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,le.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,le.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,le.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,le.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,le.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ue.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var pe={};Object.defineProperty(pe,"__esModule",{value:!0}),pe.Kinesis=void 0;const ge=he,fe=de;pe.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,fe.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,fe.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,fe.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,fe.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,fe.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:ge.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ce;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=pe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(re);var me={};function ye(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(me,"__esModule",{value:!0}),me.stringOrDefault=me.parseIntOrDefault=me.parseNumberOrDefault=void 0,me.parseNumberOrDefault=ye,me.parseIntOrDefault=function(e,t){const i=ye(e,t);return"number"==typeof i?Math.floor(i):i},me.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t};var ke={};Object.defineProperty(ke,"__esModule",{value:!0}),ke.validateRedirectLocation=void 0,ke.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 Ce=x&&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]}),Se=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ve=x&&x.__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)&&Ce(t,e,i);return Se(t,e),t};Object.defineProperty(R,"__esModule",{value:!0}),R.configValidation=R.parsing=Ie=R.ingest=R.headers=R.webcrypto=void 0,R.webcrypto=ve(H),R.headers=ve(B);var Ie=R.ingest=ve(re);async function we(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 be(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}R.parsing=ve(me),R.configValidation=ve(ke);const Ae={sessionStatus:"x-netacea-session-status",mitigationLatency:"x-netacea-api-call-latency",mitigationStatus:"x-netacea-api-call-status"};function Ne(e,t){Ee(e,t.protectorApiResponse.status,t.latencyMs),e.headers[Ae.sessionStatus]=[{key:Ae.sessionStatus,value:"error_open"}]}function Ee(e,t,i,a=void 0){i!==t&&(e.headers[Ae.mitigationStatus]=[{key:Ae.mitigationStatus,value:String(t)}]),void 0!==i&&(e.headers[Ae.mitigationLatency]=[{key:Ae.mitigationLatency,value:String(i)}]),void 0!==a&&(e.headers[Ae.sessionStatus]=[{key:Ae.sessionStatus,value:String(a)}])}function Pe(e,t){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}}async function Te(e,t,i){const a=t.cookie?.[0].value.split(";"),s=a?.find((t=>t.includes(`${e}=`)))?.trimStart()?.replace(`${e}=`,"");if(void 0!==s){if(void 0!==i)try{return await we(s,i)}catch(e){return}return s}}function Oe(e){const t={"set-cookie":[]};for(const i of e)t["set-cookie"]?.push({key:"set-cookie",value:i});return t}function _e(e,t,i){return e===i&&"post"===t.toLowerCase()}function Ke(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 xe(e,t){const i=e[t];return"string"==typeof i?i:i?.[0]}function Re(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:h,netaceaCookieStatus:d,path:u,protocol:l,referer:p,requestHost:g,requestId:f,requestTime:m,sessionStatus:y,status:k,timeUnixMsUTC:C,userAgent:S,workerInstanceId:v,xForwardedFor:I}){const{request:w}=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:y??"",NetaceaUserIdCookie:r??"",NetaceaUserIdCookieStatus:d,ProtectionMode:i,ProtectorLatencyMs:c,ProtectorStatus:h,RealIp:o,Referer:""===p?"-":p,Request:w,RequestHost:g,RequestId:f??"",RequestTime:m?.toString(),Status:k,TimeLocal:new Date(C??Date.now()).toUTCString(),TimeUnixMsUTC:C??Date.now(),UserAgent:S,WorkerInstanceId:v,XForwardedFor:I}}(e)}const He="unknown";function Me(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=k.matchMap[t]??He+"_";n+=k.mitigateMap[i]??He;let r=k.bestMitigationMap[i];if("0"!==a){n+=","+(k.captchaMap[a]??He);const e=k.bestMitigationCaptchaMap[a];void 0!==e&&(r=e)}return e===c.INJECT&&(r=k.mitigationTypes.none),{sessionStatus:n,mitigation:r,parts:{match:t,mitigate:i,captcha:a}}}function Fe(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}}class qe extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var Le;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Le||(Le={}));class je{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const{uri:t,method:i}=e,a=await this.readCookie(e,this.config.sessionCookieName),s=await this.readCookie(e,this.config.captchaCookieName),o=be(e,this.config.ipHeaderName),{sessionCookieDetails:n,sessionCookieStatus:r,sessionStatus:h,userId:d}=function(e,t,i,a,s){const o=A(a,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const a=o.userId,{isExpired:s,shouldExpire:n,isSameIP:r}=o,h=s||n||!r&&e.mitigationType!==c.INGEST?Le.RENEW_SESSION:Le.EXISTING_SESSION,{sessionStatus:d}=Me(e.mitigationType,o.match,o.mitigate,o.captcha,_e(t,i,e.netaceaCaptchaVerificationPath));return{userId:a,sessionCookieStatus:h,sessionStatus:d,sessionCookieDetails:o}}return{sessionStatus:"",userId:w(),sessionCookieStatus:Le.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,o);return{clientIp:o,method:i,url:t,userAgent:Ve(e.headers,"user-agent"),sessionDetails:{sessionStatus:h,captchaToken:s,sessionCookieDetails:n,sessionCookieStatus:r,userId:d},fingerprints:{headerFingerprint:Ve(e.headers,this.config.headerFingerprintHeaderName)}}}async readCookie(e,t){const i=De(e.headers,t,"set-cookie"),a=""!==i?i:De(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 we(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}function De(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}function Ve(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}const{configureCookiesDomain:$e}=_.cookie.attributes;class Be{static NetaceaCookieHeader="x-netacea-cloudfront-mitata-cookie";static NetaceaTrueUserAgentHeader="x-netacea-true-useragent-header";static HeadersInOriginalOrderHeader="cloudfront-viewer-header-order";static NetaceaHeaderFingerPrintHeader="x-netacea-header-fingerprint";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;netaceaBlockedResponseRedirectLocation;netaceaCaptchaVerificationPath;constructor(e){if(e.ingestType=r.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??c.INGEST,this.ingestType=e.ingestType??r.HTTP,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(t=e.timeout??3e3)<=0?p:t,this.netaceaCookieName=Ue(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue(e.netaceaCaptchaCookieName,"_mitatacaptcha"),this.netaceaCaptchaPath=e.netaceaCaptchaPath,this.dynamicCaptchaContentType=e.dynamicCaptchaContentType??!1;const i=$e(e.netaceaCookieAttributes??"",e.netaceaCaptchaCookieAttributes??"");var a,s;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===c.INGEST?3600:60:s),this.ingestEnabled=e.ingestEnabled??!0,this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaBlockedResponseRedirectLocation=e.netaceaBlockedResponseRedirectLocation,this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,this.netaceaCaptchaVerificationPath=e.netaceaCaptchaVerificationPath??"/AtaVerifyCaptcha",""===this.netaceaCaptchaVerificationPath&&(this.netaceaCaptchaVerificationPath="/AtaVerifyCaptcha"),this.netaceaCaptchaVerificationPath?.startsWith("/")||(this.netaceaCaptchaVerificationPath="/"+this.netaceaCaptchaVerificationPath)}}function Ue(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t}const{extractCookieAttr:ze,extractAndRemoveCookieAttr:Ge,removeDuplicateAttrs:We}=_.cookie.attributes,Xe=_.cookie.parse.parseSetCookie,{mitigationTypes:Je,netaceaHeaders:Ye}=k;exports.Cloudfront=class{config;kinesis;requestAnalyser;workerInstanceId;hashGenerator;constructor(i){this.config=new Be(i),this.config.ingestType===r.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ie.Kinesis({deps:{aws4:a,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey,rampUpBatchSize:!0,maxAwaitTimePerIngestCallMs:0}})),this.requestAnalyser=new je({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName,headerFingerprintHeaderName:Be.NetaceaHeaderFingerPrintHeader,netaceaCaptchaVerificationPath:this.config.netaceaCaptchaVerificationPath}),this.workerInstanceId=u.v4(),this.hashGenerator=new K(e)}async run(e){let t,i;try{t=this.getRecordFromEvent(e),i=t.cf.request,function(e){for(const t of Object.values(Ae))delete e.headers[t.toLowerCase()]}(i);const{uri:a,method:s}=i;if(Ke(a,s,this.config.netaceaCheckpointSignalPath)){const t={status:"200",headers:{}};return await this.ingest(e,t),{respondWith:Fe(t)}}if(function(e,t,i){return void 0!==i&&e.toLowerCase().includes(i.toLowerCase())&&"get"===t.toLowerCase()}(a,s,this.config.netaceaCaptchaPath)){const a=await async function({request:e,requestId:t,secretKey:i,mitigationCallFn:a,composeResultFn:s,cookieEncryptionKey:o,netaceaCookieName:n,netaceaCaptchaCookieName:r,ipHeaderName:c}){const{querystring:h}=e,d=be(e,c),u=e.headers["user-agent"]?.[0].value??"",l=e.headers.accept?.[0].value??"text/html",p=e.headers.host?.[0].value??"";if(void 0===i)throw new Error("Secret key needs to be defined to make mitigation calls.");const g=h.split("&").find((e=>e.includes("trackingId=")))?.replace("trackingId=",""),{headers:f}=e,m=await Te(n,f,o),y=await Te(r,f,o),{userId:k}=I(m)??{},C=await async function({userId:e,requestId:t,clientIp:i,userAgent:a,trackingId:s,accept:o,host:n,captchaCookie:r,mitigationCallFn:c,composeResultFn:h}){const d={match:"0",mitigate:"0",captcha:"1"},u=await c({userId:e,requestId:t,clientIP:i,userAgent:a,captchaCookie:r,accept:o,host:n,isCaptchaGet:!0,defaultMitataCodes:d,trackingId:s});return h(u.body,u.setCookie,u.status,u.match,u.mitigate,u.captcha,!0,u.latency??0)}({userId:k,requestId:t,clientIp:d,userAgent:u,captchaCookie:y,accept:l,host:p,trackingId:g,mitigationCallFn:a,composeResultFn:s});return Ee(e,C.apiCallStatus,C.apiCallLatency),{headers:Oe(C.setCookie),status:"403",body:C.body,statusDescription:"Forbidden"}}({request:i,requestId:t.cf.config.requestId,secretKey:this.config.secretKey,mitigationCallFn:this.makeMitigateAPICall.bind(this),composeResultFn:this.composeResult.bind(this),cookieEncryptionKey:this.config.cookieEncryptionKey,netaceaCookieName:this.config.netaceaCookieName,netaceaCaptchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName});return await this.ingest(e,a),{respondWith:Fe(a)}}const o=await this.runMitigation(t);return this.addNetaceaCookiesToRequest(i,o),i.headers[Be.NetaceaTrueUserAgentHeader]=[{key:Be.NetaceaTrueUserAgentHeader,value:this.getValueFromHeaderOrDefault(i.headers,"user-agent","-")}],void 0!==o&&this.config.ingestType===r.KINESIS&&Ee(i,o.apiCallStatus,o.apiCallLatency,o.sessionStatus),{respondWith:Fe(o?.response)}}catch(e){return console.error("Netacea FailOpen - ",e.message),void 0!==i&&e instanceof qe&&Ne(i,e),{}}}async makeRequest({host:e,path:t,method:a,body:s,headers:o,timeout:n,params:r}){const c=`${e}${t}`,h=await i.request({url:c,data:s,headers:o,method:a,timeout:n,params:r,transformResponse:e=>e,validateStatus:()=>!0});return{headers:h.headers,status:h.status,body:h.data}}async getFingerprints(e){const t=this.getValueFromHeaderOrDefault(e.headers,Be.HeadersInOriginalOrderHeader,"");let i="";if(""!==t)i=await this.hashGenerator.hashHeaders(t.split(":"));else{const t=Object.entries(e.headers).flatMap((([e,t])=>t.map((({key:t})=>t??e))));i=await this.hashGenerator.hashHeaders(t,!0)}return{headerFingerprint:i}}async mitigate(e){try{const{netaceaResult:i,request:a}=await this.getMitigationResponse(e);let s;if(i.mitigated){const o={"set-cookie":[]};for(const e of i.setCookie)o["set-cookie"]=o["set-cookie"]??[],o["set-cookie"].push({key:"set-cookie",value:e});const n="captcha"===i.mitigation;n&&void 0!==this.config.captchaHeader&&(o[this.config.captchaHeader.name]=[{key:this.config.captchaHeader.name,value:this.config.captchaHeader.value}]);s={headers:o,..._e(a.uri,a.method,this.config.netaceaCaptchaVerificationPath)?{status:"200",statusDescription:"OK",body:""}:{status:"403",statusDescription:"Forbidden",body:"Forbidden"}},void 0!==this.config.netaceaBlockedResponseRedirectLocation&&!n&&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.cf.request)&&(s.status="303",o.Location=[{key:"Location",value:this.config.netaceaBlockedResponseRedirectLocation}]);let c=0;if(n&&void 0!==i.body&&i.body.length>0){c=i.body.length;const e=(t=i.body).includes("captchaRelativeURL")&&t.includes("captchaAbsoluteURL");if(s.status=e?"403":"200",s.statusDescription=e?"Forbidden":"OK",s.body=i.body,s.bodyEncoding="text",e){const e=s.headers??{};e["content-type"]=[{key:"content-type",value:"application/json"}],s.headers=e}}const h={status:s.status,statusDescription:s.statusDescription??"",headers:{"content-length":[{key:"content-length",value:c.toString()}],"set-cookie":i.setCookie.map((e=>({key:"set-cookie",value:e})))}};this.config.ingestType===r.KINESIS&&Ee(a,i.apiCallStatus,i.apiCallLatency,i.sessionStatus),await this.ingest(e,h)}return this.addNetaceaCookiesToRequest(a,i),{response:s,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}catch(t){if(t instanceof qe&&Ne(e.cf.request,t),_e(e.cf.request.uri,e.cf.request.method,this.config.netaceaCaptchaVerificationPath)){const t={status:"500",statusDescription:"Internal Server Error",body:"",headers:{}},i={response:t,sessionStatus:"error_open"};return await this.ingest(e,t),i}return console.error("Netacea FailOpen Error: ",t),{sessionStatus:"error_open"}}var t}async inject(e){try{const{netaceaResult:t}=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie,apiCallLatency:t.apiCallLatency,apiCallStatus:t.apiCallStatus}}catch(e){return console.error("Netacea FailOpen Error: ",e),{sessionStatus:"",injectHeaders:void 0,setCookie:void 0}}}async ingest(e,t=void 0){let i,a;if(Object.prototype.hasOwnProperty.call(e,"Records")){const s=this.getRecordFromEvent(e);a=s,i=s.cf.request,void 0===t&&(t=s.cf.response)}else a=e,i=a.cf.request;if(!this.config.ingestEnabled)return;if(null==t)throw new Error("Cloudfront response is required to ingest");const s=this.getMitataValueFromHeaderOrDefault(t.headers,"set-cookie"),o=""!==s?s:this.getMitataValueFromHeaderOrDefault(i.headers,"cookie");let n=await this.readCookie(this.config.netaceaCookieName,o)??"";if(void 0===n||""===n){const e=this.getMitataValueFromHeaderOrDefault(i.headers,"cookie");n=await this.readCookie(this.config.netaceaCookieName,e)??""}let r="0",c="0",h="0";const d=I(n);void 0!==d&&(r=d.match,c=d.mitigate,h=d.captcha);const{sessionStatus:u,mitigationLatency:p,mitigationStatus:g}=function(e){return{sessionStatus:Pe(e.headers,Ae.sessionStatus),mitigationLatency:Pe(e.headers,Ae.mitigationLatency),mitigationStatus:Pe(e.headers,Ae.mitigationStatus)}}(i),f=this.shouldSetCaptchaPass(i,t),m=Ke(i.uri,i.method,this.config.netaceaCheckpointSignalPath),y=await this.requestAnalyser.getNetaceaRequestDetails(i),k=void 0!==u?void 0:Me(this.config.mitigationType,r,c,h,f,m).sessionStatus,C=this.getValueFromHeaderOrDefault(i.headers,Be.NetaceaTrueUserAgentHeader,y.userAgent),S=a.cf.config.requestId??"";await this.callIngest({bytesSent:this.getValueFromHeaderOrDefault(t.headers,"content-length","0"),headerFingerprint:y.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:"@netacea/cloudfront".replace("@netacea/",""),integrationVersion:"6.0.77",ip:y.clientIp,method:y.method,mitataCookie:n,mitigationLatency:void 0!==p?l(p):void 0,mitigationStatus:void 0!==g?l(g):void 0,netaceaCookieStatus:y.sessionDetails.sessionCookieStatus,path:y.url,protocol:null,referer:this.getValueFromHeaderOrDefault(i.headers,"referer"),requestHost:this.getValueFromHeaderOrDefault(i.headers,"host",void 0),requestId:S,requestTime:"0",sessionStatus:u??k,status:t.status,userAgent:C,workerInstanceId:this.workerInstanceId,xForwardedFor:this.getValueFromHeaderOrDefault(i.headers,"x-forwarded-for")})}addNetaceaCookiesToResponse(e){const{response:t,request:i}=this.getRecordFromEvent(e).cf;if(void 0===t)throw new Error("Response required to add cookies to response");const a=i.headers[Be.NetaceaCookieHeader];if(null!=a&&null!=t.headers){let e=!1;if(void 0===t.headers["set-cookie"]?t.headers["set-cookie"]=[]:e=void 0!==t.headers["set-cookie"].find((e=>!!e.value.startsWith(`${this.config.netaceaCookieName}=`)||!!e.value.startsWith(`${this.config.netaceaCaptchaCookieName}=`))),!e)for(const e of a)t.headers["set-cookie"].push({key:"set-cookie",value:e.value})}this.setInjectHeaders(e)}setInjectHeaders(e){const{response:t,request:i}=this.getRecordFromEvent(e).cf;void 0!==t&&(i.headers["x-netacea-captcha"]=this.shouldSetCaptchaPass(i,t)?[{key:"x-netacea-captcha",value:"2"}]:i.headers["x-netacea-captcha"])}getValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}getMitataValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i){const e=i.find((e=>e.value.includes(this.config.netaceaCookieName)));if(void 0!==e)return e.value}}return i}getRecordFromEvent(e){return e.Records[0]}async getMitigationResponse(e){const{request:t,config:i}=e.cf,a=i.requestId,s=this.getMitataValueFromHeaderOrDefault(t.headers,"cookie"),o=await this.readCookie(this.config.netaceaCookieName,s),n=await this.readCookie(this.config.netaceaCaptchaCookieName,s),r=be(t,this.config.ipHeaderName),c=this.getValueFromHeaderOrDefault(t.headers,"user-agent"),h=this.getValueFromHeaderOrDefault(t.headers,"accept","text/html"),d=this.getValueFromHeaderOrDefault(t.headers,"host"),u=this.getValueFromHeaderOrDefault(t.headers,"content-type","application/x-www-form-urlencoded; charset=UTF-8"),{headerFingerprint:l}=await this.getFingerprints(t);return t.headers[Be.NetaceaHeaderFingerPrintHeader]=[{key:Be.NetaceaHeaderFingerPrintHeader,value:""===l?"-":l}],{netaceaResult:await this.processMitigateRequest({getBodyFn:async()=>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}(t),clientIp:r,method:t.method,url:t.uri,userAgent:c,accept:h,host:d,mitata:o,mitataCaptcha:n,requestId:a,headerFingerprint:l,contentType:u}),request:t}}addNetaceaCookiesToRequest(e,t){if(void 0===t)return e;if(e.headers[Be.NetaceaCookieHeader]=[],void 0!==t.setCookie)for(const i of t.setCookie){const t=e.headers[Be.NetaceaCookieHeader]??[];t.push({key:Be.NetaceaCookieHeader,value:i}),e.headers[Be.NetaceaCookieHeader]=t}if(this.config.mitigationType===c.INJECT)for(const[i,a]of Object.entries(t.injectHeaders??{}))e.headers[i]=[{key:i,value:a}];return e}getCookieHeader(e){return this.getMitataValueFromHeaderOrDefault(e.headers,"cookie")}async encryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await async function(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)}(e,this.config.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await we(e,this.config.cookieEncryptionKey):e}async runMitigation(e){const t={"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"};try{if(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.cf.request,this.config.netaceaBlockedResponseRedirectLocation))return{injectHeaders:t,sessionStatus:""};switch(this.config.mitigationType){case c.MITIGATE:return await this.mitigate(e);case c.INJECT:return await this.inject(e);case c.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.config.mitigationType} not recognised`)}}catch(e){return console.error("Netacea FAILOPEN Error:",e),{injectHeaders:t,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}}}async processMitigateRequest(e){const t=_e(e.url,e.method,this.config.netaceaCaptchaVerificationPath);return await(t?this.processCaptcha({...e,netaceaCookie:e.mitata,captchaData:await e.getBodyFn()}):this.check(e.mitata,e.clientIp,e.userAgent,e.accept,e.host,e.requestId,e.mitataCaptcha,e.headerFingerprint))}shouldSetCaptchaPass(e,t){if(_e(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===c.INJECT&&s}async processCaptcha(e){const{status:t,match:i,mitigate:a,captcha:s,body:o,setCookie:n,latency:r}=await this.makeCaptchaAPICall(e);return this.composeResult(o,n,t,i,a,s,!0,r)}async makeCaptchaAPICall(e){const{netaceaCookie:t,clientIp:i,userAgent:a,headerFingerprint:s,captchaData:o,contentType:n,requestId:r}=e,c={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":i,"X-Netacea-Request-Id":r,"user-agent":a,"Content-Type":n},h=I(t);void 0!==h&&(c["X-Netacea-UserId"]=h.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const d=new URLSearchParams;""!==s&&d.append("headerFP",s),d.append("netaceaHeaders","request-id");const u=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})}}}(o,n),l=Date.now(),p=await this.makeRequest({host:this.config.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:c,method:"POST",body:u,timeout:this.config.timeout,params:d}),g=Date.now()-l;return await this.getApiCallResponseFromResponse(p,h?.userId,i,g)}async getApiCallResponseFromResponse(e,t,i,a,s){if(200!==e.status)throw new qe(e,a);const o=xe(e.headers,Ye.match)??s?.match??"0",n=xe(e.headers,Ye.mitigate)??s?.mitigate??"0",r=xe(e.headers,Ye.captcha)??s?.captcha??"0";let c=function(e,t){const i=xe(e,t);if(void 0!==i)return parseInt(i,36)}(e.headers,Ye.mitataExpiry)??NaN;isNaN(c)&&(c=86400);const h=[];if(String(r)!==String(k.captchaStatusCodes.checkpointPost)){const a=await this.createMitata(i,t,o,n,r);void 0!==a&&h.push(a);const s=await this.createMitataCaptcha(e.headers);void 0!==s&&h.push(s)}const d=xe(e.headers,Ye.eventId);return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:d,mitataMaxAge:c,latency:a}}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 createMitata(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 h=[i,a,s].join(""),d=function(e,t,i,a,s="000"){void 0===t&&(t=w());const o=[i,t,b(e+"|"+String(i),a),s].join(g);return`${b(o,a)}${g}${o}`}(e,t,c,this.config.secretKey,h);let u,l,p=o;if(""!==this.config.netaceaCookieAttributes){const{extractedAttribute:e,cookieAttributes:t}=Ge(this.config.netaceaCookieAttributes,"Max-Age");p=void 0!==e?Number(e):o;const{extractedAttribute:i,cookieAttributes:a}=Ge(t,"Path");u=i??"/",l=a??void 0}return await this.buildCookieFromValues(this.config.netaceaCookieName,d,p,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=Xe(i);a=e.value,s=ze(e.attributes,"Max-Age")??"86400"}catch(e){return}if(""===a||void 0===a)return;const o=We([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=Re(e);if(this.config.ingestType===r.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=this.getCookieHeader(e.cf.request),i=A(await this.readCookie(this.config.netaceaCookieName,t),C,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.createMitata(C,e,"0","0","0",86400)]}}async check(e,t,i,a,s,o,n,r){let c,h,d,u,l,p,g,f;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const m=A(e,t,this.config.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall({userId:m.mitata?.userId,clientIP:t,userAgent:i,captchaCookie:n,accept:a,host:s,requestId:o,headerFingerprint:r});c=e.status,h=e.match,d=e.mitigate,u=e.captcha,l=e.body,f=e.latency,p=[await this.createMitata(t,m.mitata?.userId,h,d,u,e.mitataMaxAge)],g=e.eventId}else h=m.match,d=m.mitigate,u=m.captcha,l=void 0,p=[];return this.composeResult(l,p,c,h,d,u,!1,f,g)}async makeMitigateAPICall({userId:e,clientIP:t,userAgent:i,captchaCookie:a,accept:s,host:o,isCaptchaGet:n=!1,defaultMitataCodes:r,trackingId:c,requestId:h,headerFingerprint:d}){const u={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":t,"X-Netacea-Request-Id":h,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==e&&(u["X-Netacea-UserId"]=e),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(u["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,u["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),this.config.dynamicCaptchaContentType&&void 0!==this.config.netaceaCaptchaPath&&(u["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"}(s));const l="application/json"===u["X-Netacea-Captcha-Content-Type"],p=void 0!==c?`?trackingId=${c}`:"",g=new URLSearchParams;"string"==typeof d&&g.set("headerFP",d),g.append("netaceaHeaders","request-id");const f=Date.now(),m=await this.makeRequest({host:this.config.mitigationServiceUrl,path:n?`/captcha${p}`:"/",headers:u,method:"GET",timeout:this.config.timeout,params:g}),y=Date.now()-f;return l&&void 0!==this.config.netaceaCaptchaPath&&(m.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=`https://${t}${s}`;return JSON.stringify({captchaRelativeURL:s,captchaAbsoluteURL:o})}(m.body,o,this.config.netaceaCaptchaPath)),await this.getApiCallResponseFromResponse(m,e,t,y,r)}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}composeResult(e,t,i,a,s,o,n,r,h){const d=Me(this.config.mitigationType,a,s,o,n),u={body:e,apiCallStatus:i,apiCallLatency:r,setCookie:t,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[Je.block,Je.captcha,Je.captchaPass].includes(d.mitigation)};if(this.config.mitigationType===c.INJECT){const e={"x-netacea-match":d.parts.match,"x-netacea-mitigate":d.parts.mitigate,"x-netacea-captcha":d.parts.captcha};void 0!==h&&(e["x-netacea-event-id"]=h),u.injectHeaders=e}return u}};
|
|
1
|
+
"use strict";var e=require("node:crypto"),t=require("node:buffer"),i=require("axios"),a=require("aws4"),s=require("jose"),o=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var r,c,h,d=n(s),u=n(o);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(r||(r={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(c||(c={})),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"}(h||(h={}));function l(e,t=0){return isNaN(e)?t:parseInt(e)}const p=3e3;const g="_/@#/",f={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},m={0:f.none,1:f.block,2:f.none,3:f.block,4:f.block},y={1:f.captcha,2:f.captchaPass,3:f.captcha,4:f.allow,5:f.captcha,6:f.allow,7:f.captcha,a:f.captcha,b:f.captchaPass,c:f.captcha,d:f.allow,e:f.captcha};var k=Object.freeze({__proto__:null,COOKIEDELIMITER:g,bestMitigationCaptchaMap:y,bestMitigationMap:m,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:"block"},mitigationTypes:f,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 C="ignored",S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),v=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function I(e){if(void 0===e)return;const t=e.match(v);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 w(t=16,i=S){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function b(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function A(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=I(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(g),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,h=b(t+"|"+s.expiry,i),d=s.ipHash===h;return{mitata:s,requiresReissue:o||!d,isExpired:o,shouldExpire:c,isSameIP:d,isPrimaryHashValid:s.signature===b(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return a}function N(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 E(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":P(e.split(";"),t).join("; ")}function P(e,t=!1){if(t)return P(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var T=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=E(e??"",!0),a=t=E(t??"",!0);if(void 0!==e&&void 0!==t){const s=N(e,"Domain"),o=N(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=N(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=N(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=N(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:N,removeDuplicateAttrs:E});var O=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(";");return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const _={cookie:{parse:O,attributes:T}};class K{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=K.filterHeaderNames(e);if(0===i.length)return"";try{return await this.hashString("SHA-256",i,t)}catch(e){return console.error(e),""}}}var R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},x={},H={},M={},F=R&&R.__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]}),q=R&&R.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),j=R&&R.__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)&&F(t,e,i);return q(t,e),t};Object.defineProperty(M,"__esModule",{value:!0}),M.isJweEncrypted=M.decrypt=M.encrypt=void 0;const L=j(s);M.encrypt=async function(e,t){const i=L.base64url.decode(t),a=(new TextEncoder).encode(e);return await new L.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},M.decrypt=async function(e,t){const i=L.base64url.decode(t),{plaintext:a}=await L.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},M.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var D=R&&R.__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]}),V=R&&R.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),B=R&&R.__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)&&D(t,e,i);return V(t,e),t};Object.defineProperty(H,"__esModule",{value:!0}),H.jwe=void 0,H.jwe=B(M);var $={},U={};function z(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=W("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function G(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(...X(o,t))}return i}function W(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function X(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(U,"__esModule",{value:!0}),U.findAllInCookieString=U.findFirstInCookieString=U.findAllInHeaders=U.findFirstInHeaders=U.findOnlyValueInHeaders=U.findAllValuesInHeaders=U.findFirstValueInHeaders=void 0,U.findFirstValueInHeaders=function(e,t){const i=z(e,t);if(void 0!==i)return i.slice(t.length+1)},U.findAllValuesInHeaders=function(e,t){return G(e,t).map((e=>e.slice(t.length+1)))},U.findOnlyValueInHeaders=function(e,t){const i=G(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},U.findFirstInHeaders=z,U.findAllInHeaders=G,U.findFirstInCookieString=W,U.findAllInCookieString=X;var J={};function Y(e){return"set-cookie"===e||"Set-Cookie"===e}function Q(e,t){const i=t+"=";return e.startsWith(i)}function Z(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ee(e,t){for(const i of Object.keys(e)){if(!Y(i))continue;const a=te(Z(e,i),t);if(void 0!==a)return a}}function te(e,t){return e.map((e=>e.trimStart())).find((e=>Q(e,t)))}function ie(e,t){const i=[];for(const a of Object.keys(e)){if(!Y(a))continue;const s=Z(e,a);i.push(...ae(s,t))}return i}function ae(e,t){return e.map((e=>e.trimStart())).filter((e=>Q(e,t)))}Object.defineProperty(J,"__esModule",{value:!0}),J.findAllInSetCookieStrings=J.findAllInHeaders=J.findFirstInSetCookieStrings=J.findFirstInHeaders=J.findOnlyValueInHeaders=J.findFirstValueInHeaders=void 0,J.findFirstValueInHeaders=function(e,t){const i=ee(e,t);return i?.slice(t.length+1)?.split(";")[0]},J.findOnlyValueInHeaders=function(e,t){const i=ie(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]},J.findFirstInHeaders=ee,J.findFirstInSetCookieStrings=te,J.findAllInHeaders=ie,J.findAllInSetCookieStrings=ae;var se=R&&R.__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]}),oe=R&&R.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ne=R&&R.__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 oe(t,e),t};Object.defineProperty($,"__esModule",{value:!0}),$.setCookie=$.cookie=void 0,$.cookie=ne(U),$.setCookie=ne(J);var re={},ce={},he={};Object.defineProperty(he,"__esModule",{value:!0}),he.KINESIS_URL=he.API_VERSION=he.REGION=he.PAYLOAD_TYPE=he.STATE=void 0,he.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},he.PAYLOAD_TYPE="string",he.REGION="eu-west-1",he.API_VERSION="2013-12-02",he.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var de={};Object.defineProperty(de,"__esModule",{value:!0}),de.headersToRecord=de.increaseBatchSize=de.handleFailedLogs=de.batchArrayForKinesis=de.sleep=void 0,de.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},de.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},de.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},de.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},de.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(ce,"__esModule",{value:!0}),ce.WebStandardKinesis=void 0;const ue=he,le=de;ce.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,le.headersToRecord)(i.headers),host:ue.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,le.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,le.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,le.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,le.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,le.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ue.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var pe={};Object.defineProperty(pe,"__esModule",{value:!0}),pe.Kinesis=void 0;const ge=he,fe=de;pe.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,fe.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,fe.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,fe.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,fe.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,fe.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:ge.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=ce;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=pe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(re);var me={};function ye(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(me,"__esModule",{value:!0}),me.stringOrDefault=me.parseIntOrDefault=ke=me.parseNumberOrDefault=void 0;var ke=me.parseNumberOrDefault=ye;me.parseIntOrDefault=function(e,t){const i=ye(e,t);return"number"==typeof i?Math.floor(i):i},me.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t};var Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.validateRedirectLocation=void 0,Ce.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 Se=R&&R.__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]}),ve=R&&R.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ie=R&&R.__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 ve(t,e),t};Object.defineProperty(x,"__esModule",{value:!0}),x.configValidation=x.parsing=we=x.ingest=x.headers=x.webcrypto=void 0,x.webcrypto=Ie(H),x.headers=Ie($);var we=x.ingest=Ie(re);async function be(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 Ae(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}x.parsing=Ie(me),x.configValidation=Ie(Ce);const Ne={sessionStatus:"x-netacea-session-status",mitigationLatency:"x-netacea-api-call-latency",mitigationStatus:"x-netacea-api-call-status"};function Ee(e,t){Pe(e,t.protectorApiResponse.status,t.latencyMs),e.headers[Ne.sessionStatus]=[{key:Ne.sessionStatus,value:"error_open"}]}function Pe(e,t,i,a=void 0){i!==t&&(e.headers[Ne.mitigationStatus]=[{key:Ne.mitigationStatus,value:String(t)}]),void 0!==i&&(e.headers[Ne.mitigationLatency]=[{key:Ne.mitigationLatency,value:String(i)}]),void 0!==a&&(e.headers[Ne.sessionStatus]=[{key:Ne.sessionStatus,value:String(a)}])}function Te(e,t){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}}async function Oe(e,t,i){const a=t.cookie?.[0].value.split(";"),s=a?.find((t=>t.includes(`${e}=`)))?.trimStart()?.replace(`${e}=`,"");if(void 0!==s){if(void 0!==i)try{return await be(s,i)}catch(e){return}return s}}function _e(e){const t={"set-cookie":[]};for(const i of e)t["set-cookie"]?.push({key:"set-cookie",value:i});return t}function Ke(e,t,i){return e===i&&"post"===t.toLowerCase()}function Re(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 xe(e,t){const i=e[t];return"string"==typeof i?i:i?.[0]}function He(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:h,netaceaCookieStatus:d,path:u,protocol:l,referer:p,requestHost:g,requestId:f,requestTime:m,sessionStatus:y,status:k,timeUnixMsUTC:C,userAgent:S,workerInstanceId:v,xForwardedFor:I}){const{request:w}=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:y??"",NetaceaUserIdCookie:r??"",NetaceaUserIdCookieStatus:d,ProtectionMode:i,ProtectorLatencyMs:c,ProtectorStatus:h,RealIp:o,Referer:""===p?"-":p,Request:w,RequestHost:g,RequestId:f??"",RequestTime:m?.toString(),Status:k,TimeLocal:new Date(C??Date.now()).toUTCString(),TimeUnixMsUTC:C??Date.now(),UserAgent:S,WorkerInstanceId:v,XForwardedFor:I}}(e)}const Me="unknown";function Fe(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=k.matchMap[t]??Me+"_";n+=k.mitigateMap[i]??Me;let r=k.bestMitigationMap[i];if("0"!==a){n+=","+(k.captchaMap[a]??Me);const e=k.bestMitigationCaptchaMap[a];void 0!==e&&(r=e)}return e===c.INJECT&&(r=k.mitigationTypes.none),{sessionStatus:n,mitigation:r,parts:{match:t,mitigate:i,captcha:a}}}function qe(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}}class je extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var Le;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Le||(Le={}));class De{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const{uri:t,method:i}=e,a=await this.readCookie(e,this.config.sessionCookieName),s=await this.readCookie(e,this.config.captchaCookieName),o=Ae(e,this.config.ipHeaderName),{sessionCookieDetails:n,sessionCookieStatus:r,sessionStatus:h,userId:d}=function(e,t,i,a,s){const o=A(a,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const a=o.userId,{isExpired:s,shouldExpire:n,isSameIP:r}=o,h=s||n||!r&&e.mitigationType!==c.INGEST?Le.RENEW_SESSION:Le.EXISTING_SESSION,{sessionStatus:d}=Fe(e.mitigationType,o.match,o.mitigate,o.captcha,Ke(t,i,e.netaceaCaptchaVerificationPath));return{userId:a,sessionCookieStatus:h,sessionStatus:d,sessionCookieDetails:o}}return{sessionStatus:"",userId:w(),sessionCookieStatus:Le.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,o);return{clientIp:o,method:i,url:t,userAgent:Be(e.headers,"user-agent"),sessionDetails:{sessionStatus:h,captchaToken:s,sessionCookieDetails:n,sessionCookieStatus:r,userId:d},fingerprints:{headerFingerprint:Be(e.headers,this.config.headerFingerprintHeaderName)}}}async readCookie(e,t){const i=Ve(e.headers,t,"set-cookie"),a=""!==i?i:Ve(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 be(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}function Ve(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}function Be(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}const{configureCookiesDomain:$e}=_.cookie.attributes;class Ue{static NetaceaCookieHeader="x-netacea-cloudfront-mitata-cookie";static NetaceaTrueUserAgentHeader="x-netacea-true-useragent-header";static HeadersInOriginalOrderHeader="cloudfront-viewer-header-order";static NetaceaHeaderFingerPrintHeader="x-netacea-header-fingerprint";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;netaceaBlockedResponseRedirectLocation;netaceaBlockedResponseStatus=403;netaceaBlockedResponseBody="Forbidden";netaceaBlockedResponseContentType="text/plain; charset=utf-8";constructor(e){if(e.ingestType=r.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??c.INGEST,this.ingestType=e.ingestType??r.HTTP,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(t=e.timeout??3e3)<=0?p:t,this.netaceaCookieName=ze(e.netaceaCookieName)??"_mitata",this.netaceaCaptchaCookieName=ze(e.netaceaCaptchaCookieName)??"_mitatacaptcha",this.netaceaCaptchaPath=e.netaceaCaptchaPath,this.dynamicCaptchaContentType=e.dynamicCaptchaContentType??!1;const i=$e(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===c.INGEST?3600:60:s),this.ingestEnabled=e.ingestEnabled??!0,this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaBlockedResponseRedirectLocation=ze(e.netaceaBlockedResponseRedirectLocation),void 0!==e.netaceaBlockedResponseStatus){const t=ke(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)}}function ze(e){if("string"==typeof e&&""!==e){const t=e.trim();if(t.length>0)return t}}const{extractCookieAttr:Ge,extractAndRemoveCookieAttr:We,removeDuplicateAttrs:Xe}=_.cookie.attributes,Je=_.cookie.parse.parseSetCookie,{mitigationTypes:Ye,netaceaHeaders:Qe}=k;exports.Cloudfront=class{config;kinesis;requestAnalyser;workerInstanceId;hashGenerator;constructor(i){this.config=new Ue(i),this.config.ingestType===r.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new we.Kinesis({deps:{aws4:a,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey,rampUpBatchSize:!0,maxAwaitTimePerIngestCallMs:0}})),this.requestAnalyser=new De({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName,headerFingerprintHeaderName:Ue.NetaceaHeaderFingerPrintHeader,netaceaCaptchaVerificationPath:this.config.netaceaCaptchaVerificationPath}),this.workerInstanceId=u.v4(),this.hashGenerator=new K(e)}async run(e){let t,i;try{t=this.getRecordFromEvent(e),i=t.cf.request,function(e){for(const t of Object.values(Ne))delete e.headers[t.toLowerCase()]}(i);const{uri:a,method:s}=i;if(Re(a,s,this.config.netaceaCheckpointSignalPath)){const t={status:"200",headers:{}};return await this.ingest(e,t),{respondWith:qe(t)}}if(function(e,t,i){return void 0!==i&&e.toLowerCase().includes(i.toLowerCase())&&"get"===t.toLowerCase()}(a,s,this.config.netaceaCaptchaPath)){const a=await async function({request:e,requestId:t,secretKey:i,mitigationCallFn:a,composeResultFn:s,cookieEncryptionKey:o,netaceaCookieName:n,netaceaCaptchaCookieName:r,ipHeaderName:c}){const{querystring:h}=e,d=Ae(e,c),u=e.headers["user-agent"]?.[0].value??"",l=e.headers.accept?.[0].value??"text/html",p=e.headers.host?.[0].value??"";if(void 0===i)throw new Error("Secret key needs to be defined to make mitigation calls.");const g=h.split("&").find((e=>e.includes("trackingId=")))?.replace("trackingId=",""),{headers:f}=e,m=await Oe(n,f,o),y=await Oe(r,f,o),{userId:k}=I(m)??{},C=await async function({userId:e,requestId:t,clientIp:i,userAgent:a,trackingId:s,accept:o,host:n,captchaCookie:r,mitigationCallFn:c,composeResultFn:h}){const d={match:"0",mitigate:"0",captcha:"1"},u=await c({userId:e,requestId:t,clientIP:i,userAgent:a,captchaCookie:r,accept:o,host:n,isCaptchaGet:!0,defaultMitataCodes:d,trackingId:s});return h(u.body,u.setCookie,u.status,u.match,u.mitigate,u.captcha,!0,u.latency??0)}({userId:k,requestId:t,clientIp:d,userAgent:u,captchaCookie:y,accept:l,host:p,trackingId:g,mitigationCallFn:a,composeResultFn:s});return Pe(e,C.apiCallStatus,C.apiCallLatency),{headers:_e(C.setCookie),status:"403",body:C.body,statusDescription:"Forbidden"}}({request:i,requestId:t.cf.config.requestId,secretKey:this.config.secretKey,mitigationCallFn:this.makeMitigateAPICall.bind(this),composeResultFn:this.composeResult.bind(this),cookieEncryptionKey:this.config.cookieEncryptionKey,netaceaCookieName:this.config.netaceaCookieName,netaceaCaptchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName});return await this.ingest(e,a),{respondWith:qe(a)}}const o=await this.runMitigation(t);return this.addNetaceaCookiesToRequest(i,o),i.headers[Ue.NetaceaTrueUserAgentHeader]=[{key:Ue.NetaceaTrueUserAgentHeader,value:this.getValueFromHeaderOrDefault(i.headers,"user-agent","-")}],void 0!==o&&this.config.ingestType===r.KINESIS&&Pe(i,o.apiCallStatus,o.apiCallLatency,o.sessionStatus),{respondWith:qe(o?.response)}}catch(e){return console.error("Netacea FailOpen - ",e.message),void 0!==i&&e instanceof je&&Ee(i,e),{}}}async makeRequest({host:e,path:t,method:a,body:s,headers:o,timeout:n,params:r}){const c=`${e}${t}`,h=await i.request({url:c,data:s,headers:o,method:a,timeout:n,params:r,transformResponse:e=>e,validateStatus:()=>!0});return{headers:h.headers,status:h.status,body:h.data}}async getFingerprints(e){const t=this.getValueFromHeaderOrDefault(e.headers,Ue.HeadersInOriginalOrderHeader,"");let i="";if(""!==t)i=await this.hashGenerator.hashHeaders(t.split(":"));else{const t=Object.entries(e.headers).flatMap((([e,t])=>t.map((({key:t})=>t??e))));i=await this.hashGenerator.hashHeaders(t,!0)}return{headerFingerprint:i}}async mitigate(e){try{const{netaceaResult:i,request:a}=await this.getMitigationResponse(e);let s;if(i.mitigated){const o={"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 i.setCookie)o["set-cookie"]=o["set-cookie"]??[],o["set-cookie"].push({key:"set-cookie",value:e});const n="captcha"===i.mitigation;n&&void 0!==this.config.captchaHeader&&(o[this.config.captchaHeader.name]=[{key:this.config.captchaHeader.name,value:this.config.captchaHeader.value}]);let c={status:"200",statusDescription:"OK",body:""};Ke(a.uri,a.method,this.config.netaceaCaptchaVerificationPath)||(c={status:String(this.config.netaceaBlockedResponseStatus),statusDescription:"Forbidden",body:this.config.netaceaBlockedResponseBody},o["content-type"]=[{key:"content-type",value:this.config.netaceaBlockedResponseContentType}]),s={headers:o,...c},void 0!==this.config.netaceaBlockedResponseRedirectLocation&&!n&&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.cf.request)&&(s.status="303",o.Location=[{key:"Location",value:this.config.netaceaBlockedResponseRedirectLocation}]);let h=0;if(n&&void 0!==i.body&&i.body.length>0){h=i.body.length;const e=(t=i.body).includes("captchaRelativeURL")&&t.includes("captchaAbsoluteURL");s.status=e?"403":"200",s.statusDescription=e?"Forbidden":"OK",s.body=i.body,s.bodyEncoding="text",o["content-type"]=e?[{key:"content-type",value:"application/json"}]:[{key:"content-type",value:"text/html; charset=UTF-8"}]}const d={status:s.status,statusDescription:s.statusDescription??"",headers:{"content-length":[{key:"content-length",value:h.toString()}],"set-cookie":i.setCookie.map((e=>({key:"set-cookie",value:e})))}};this.config.ingestType===r.KINESIS&&Pe(a,i.apiCallStatus,i.apiCallLatency,i.sessionStatus),await this.ingest(e,d)}return this.addNetaceaCookiesToRequest(a,i),{response:s,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}catch(t){if(t instanceof je&&Ee(e.cf.request,t),Ke(e.cf.request.uri,e.cf.request.method,this.config.netaceaCaptchaVerificationPath)){const t={status:"500",statusDescription:"Internal Server Error",body:"",headers:{}},i={response:t,sessionStatus:"error_open"};return await this.ingest(e,t),i}return console.error("Netacea FailOpen Error: ",t),{sessionStatus:"error_open"}}var t}async inject(e){try{const{netaceaResult:t}=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie,apiCallLatency:t.apiCallLatency,apiCallStatus:t.apiCallStatus}}catch(e){return console.error("Netacea FailOpen Error: ",e),{sessionStatus:"",injectHeaders:void 0,setCookie:void 0}}}async ingest(e,t=void 0){let i,a;if(Object.prototype.hasOwnProperty.call(e,"Records")){const s=this.getRecordFromEvent(e);a=s,i=s.cf.request,void 0===t&&(t=s.cf.response)}else a=e,i=a.cf.request;if(!this.config.ingestEnabled)return;if(null==t)throw new Error("Cloudfront response is required to ingest");const s=this.getMitataValueFromHeaderOrDefault(t.headers,"set-cookie"),o=""!==s?s:this.getMitataValueFromHeaderOrDefault(i.headers,"cookie");let n=await this.readCookie(this.config.netaceaCookieName,o)??"";if(void 0===n||""===n){const e=this.getMitataValueFromHeaderOrDefault(i.headers,"cookie");n=await this.readCookie(this.config.netaceaCookieName,e)??""}let r="0",c="0",h="0";const d=I(n);void 0!==d&&(r=d.match,c=d.mitigate,h=d.captcha);const{sessionStatus:u,mitigationLatency:p,mitigationStatus:g}=function(e){return{sessionStatus:Te(e.headers,Ne.sessionStatus),mitigationLatency:Te(e.headers,Ne.mitigationLatency),mitigationStatus:Te(e.headers,Ne.mitigationStatus)}}(i),f=this.shouldSetCaptchaPass(i,t),m=Re(i.uri,i.method,this.config.netaceaCheckpointSignalPath),y=await this.requestAnalyser.getNetaceaRequestDetails(i),k=void 0!==u?void 0:Fe(this.config.mitigationType,r,c,h,f,m).sessionStatus,C=this.getValueFromHeaderOrDefault(i.headers,Ue.NetaceaTrueUserAgentHeader,y.userAgent),S=a.cf.config.requestId??"";await this.callIngest({bytesSent:this.getValueFromHeaderOrDefault(t.headers,"content-length","0"),headerFingerprint:y.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:"@netacea/cloudfront".replace("@netacea/",""),integrationVersion:"6.0.78",ip:y.clientIp,method:y.method,mitataCookie:n,mitigationLatency:void 0!==p?l(p):void 0,mitigationStatus:void 0!==g?l(g):void 0,netaceaCookieStatus:y.sessionDetails.sessionCookieStatus,path:y.url,protocol:null,referer:this.getValueFromHeaderOrDefault(i.headers,"referer"),requestHost:this.getValueFromHeaderOrDefault(i.headers,"host",void 0),requestId:S,requestTime:"0",sessionStatus:u??k,status:t.status,userAgent:C,workerInstanceId:this.workerInstanceId,xForwardedFor:this.getValueFromHeaderOrDefault(i.headers,"x-forwarded-for")})}addNetaceaCookiesToResponse(e){const{response:t,request:i}=this.getRecordFromEvent(e).cf;if(void 0===t)throw new Error("Response required to add cookies to response");const a=i.headers[Ue.NetaceaCookieHeader];if(null!=a&&null!=t.headers){let e=!1;if(void 0===t.headers["set-cookie"]?t.headers["set-cookie"]=[]:e=void 0!==t.headers["set-cookie"].find((e=>!!e.value.startsWith(`${this.config.netaceaCookieName}=`)||!!e.value.startsWith(`${this.config.netaceaCaptchaCookieName}=`))),!e)for(const e of a)t.headers["set-cookie"].push({key:"set-cookie",value:e.value})}this.setInjectHeaders(e)}setInjectHeaders(e){const{response:t,request:i}=this.getRecordFromEvent(e).cf;void 0!==t&&(i.headers["x-netacea-captcha"]=this.shouldSetCaptchaPass(i,t)?[{key:"x-netacea-captcha",value:"2"}]:i.headers["x-netacea-captcha"])}getValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i)return i[0].value}return i}getMitataValueFromHeaderOrDefault(e,t,i=""){if(void 0!==e?.[t]){const i=e[t];if(void 0!==i){const e=i.find((e=>e.value.includes(this.config.netaceaCookieName)));if(void 0!==e)return e.value}}return i}getRecordFromEvent(e){return e.Records[0]}async getMitigationResponse(e){const{request:t,config:i}=e.cf,a=i.requestId,s=this.getMitataValueFromHeaderOrDefault(t.headers,"cookie"),o=await this.readCookie(this.config.netaceaCookieName,s),n=await this.readCookie(this.config.netaceaCaptchaCookieName,s),r=Ae(t,this.config.ipHeaderName),c=this.getValueFromHeaderOrDefault(t.headers,"user-agent"),h=this.getValueFromHeaderOrDefault(t.headers,"accept","text/html"),d=this.getValueFromHeaderOrDefault(t.headers,"host"),u=this.getValueFromHeaderOrDefault(t.headers,"content-type","application/x-www-form-urlencoded; charset=UTF-8"),{headerFingerprint:l}=await this.getFingerprints(t);return t.headers[Ue.NetaceaHeaderFingerPrintHeader]=[{key:Ue.NetaceaHeaderFingerPrintHeader,value:""===l?"-":l}],{netaceaResult:await this.processMitigateRequest({getBodyFn:async()=>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}(t),clientIp:r,method:t.method,url:t.uri,userAgent:c,accept:h,host:d,mitata:o,mitataCaptcha:n,requestId:a,headerFingerprint:l,contentType:u}),request:t}}addNetaceaCookiesToRequest(e,t){if(void 0===t)return e;if(e.headers[Ue.NetaceaCookieHeader]=[],void 0!==t.setCookie)for(const i of t.setCookie){const t=e.headers[Ue.NetaceaCookieHeader]??[];t.push({key:Ue.NetaceaCookieHeader,value:i}),e.headers[Ue.NetaceaCookieHeader]=t}if(this.config.mitigationType===c.INJECT)for(const[i,a]of Object.entries(t.injectHeaders??{}))e.headers[i]=[{key:i,value:a}];return e}getCookieHeader(e){return this.getMitataValueFromHeaderOrDefault(e.headers,"cookie")}async encryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await async function(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)}(e,this.config.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.config.cookieEncryptionKey?await be(e,this.config.cookieEncryptionKey):e}async runMitigation(e){const t={"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"};try{if(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.cf.request,this.config.netaceaBlockedResponseRedirectLocation))return{injectHeaders:t,sessionStatus:""};switch(this.config.mitigationType){case c.MITIGATE:return await this.mitigate(e);case c.INJECT:return await this.inject(e);case c.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.config.mitigationType} not recognised`)}}catch(e){return console.error("Netacea FAILOPEN Error:",e),{injectHeaders:t,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}}}async processMitigateRequest(e){const t=Ke(e.url,e.method,this.config.netaceaCaptchaVerificationPath);return await(t?this.processCaptcha({...e,netaceaCookie:e.mitata,captchaData:await e.getBodyFn()}):this.check(e.mitata,e.clientIp,e.userAgent,e.accept,e.host,e.requestId,e.mitataCaptcha,e.headerFingerprint))}shouldSetCaptchaPass(e,t){if(Ke(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===c.INJECT&&s}async processCaptcha(e){const{status:t,match:i,mitigate:a,captcha:s,body:o,setCookie:n,latency:r}=await this.makeCaptchaAPICall(e);return this.composeResult(o,n,t,i,a,s,!0,r)}async makeCaptchaAPICall(e){const{netaceaCookie:t,clientIp:i,userAgent:a,headerFingerprint:s,captchaData:o,contentType:n,requestId:r}=e,c={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":i,"X-Netacea-Request-Id":r,"user-agent":a,"Content-Type":n},h=I(t);void 0!==h&&(c["X-Netacea-UserId"]=h.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const d=new URLSearchParams;""!==s&&d.append("headerFP",s),d.append("netaceaHeaders","request-id");const u=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})}}}(o,n),l=Date.now(),p=await this.makeRequest({host:this.config.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:c,method:"POST",body:u,timeout:this.config.timeout,params:d}),g=Date.now()-l;return await this.getApiCallResponseFromResponse(p,h?.userId,i,g)}async getApiCallResponseFromResponse(e,t,i,a,s){if(200!==e.status)throw new je(e,a);const o=xe(e.headers,Qe.match)??s?.match??"0",n=xe(e.headers,Qe.mitigate)??s?.mitigate??"0",r=xe(e.headers,Qe.captcha)??s?.captcha??"0";let c=function(e,t){const i=xe(e,t);if(void 0!==i)return parseInt(i,36)}(e.headers,Qe.mitataExpiry)??NaN;isNaN(c)&&(c=86400);const h=[];if(String(r)!==String(k.captchaStatusCodes.checkpointPost)){const a=await this.createMitata(i,t,o,n,r);void 0!==a&&h.push(a);const s=await this.createMitataCaptcha(e.headers);void 0!==s&&h.push(s)}const d=xe(e.headers,Qe.eventId);return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:d,mitataMaxAge:c,latency:a}}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 createMitata(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 h=[i,a,s].join(""),d=function(e,t,i,a,s="000"){void 0===t&&(t=w());const o=[i,t,b(e+"|"+String(i),a),s].join(g);return`${b(o,a)}${g}${o}`}(e,t,c,this.config.secretKey,h);let u,l,p=o;if(""!==this.config.netaceaCookieAttributes){const{extractedAttribute:e,cookieAttributes:t}=We(this.config.netaceaCookieAttributes,"Max-Age");p=void 0!==e?Number(e):o;const{extractedAttribute:i,cookieAttributes:a}=We(t,"Path");u=i??"/",l=a??void 0}return await this.buildCookieFromValues(this.config.netaceaCookieName,d,p,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=Je(i);a=e.value,s=Ge(e.attributes,"Max-Age")??"86400"}catch(e){return}if(""===a||void 0===a)return;const o=Xe([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=He(e);if(this.config.ingestType===r.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=this.getCookieHeader(e.cf.request),i=A(await this.readCookie(this.config.netaceaCookieName,t),C,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.createMitata(C,e,"0","0","0",86400)]}}async check(e,t,i,a,s,o,n,r){let c,h,d,u,l,p,g,f;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const m=A(e,t,this.config.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall({userId:m.mitata?.userId,clientIP:t,userAgent:i,captchaCookie:n,accept:a,host:s,requestId:o,headerFingerprint:r});c=e.status,h=e.match,d=e.mitigate,u=e.captcha,l=e.body,f=e.latency,p=[await this.createMitata(t,m.mitata?.userId,h,d,u,e.mitataMaxAge)],g=e.eventId}else h=m.match,d=m.mitigate,u=m.captcha,l=void 0,p=[];return this.composeResult(l,p,c,h,d,u,!1,f,g)}async makeMitigateAPICall({userId:e,clientIP:t,userAgent:i,captchaCookie:a,accept:s,host:o,isCaptchaGet:n=!1,defaultMitataCodes:r,trackingId:c,requestId:h,headerFingerprint:d}){const u={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":t,"X-Netacea-Request-Id":h,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==e&&(u["X-Netacea-UserId"]=e),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(u["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,u["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),this.config.dynamicCaptchaContentType&&void 0!==this.config.netaceaCaptchaPath&&(u["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"}(s));const l="application/json"===u["X-Netacea-Captcha-Content-Type"],p=void 0!==c?`?trackingId=${c}`:"",g=new URLSearchParams;"string"==typeof d&&g.set("headerFP",d),g.append("netaceaHeaders","request-id");const f=Date.now(),m=await this.makeRequest({host:this.config.mitigationServiceUrl,path:n?`/captcha${p}`:"/",headers:u,method:"GET",timeout:this.config.timeout,params:g}),y=Date.now()-f;return l&&void 0!==this.config.netaceaCaptchaPath&&(m.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=`https://${t}${s}`;return JSON.stringify({captchaRelativeURL:s,captchaAbsoluteURL:o})}(m.body,o,this.config.netaceaCaptchaPath)),await this.getApiCallResponseFromResponse(m,e,t,y,r)}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}composeResult(e,t,i,a,s,o,n,r,h){const d=Fe(this.config.mitigationType,a,s,o,n),u={body:e,apiCallStatus:i,apiCallLatency:r,setCookie:t,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[Ye.block,Ye.captcha,Ye.captchaPass].includes(d.mitigation)};if(this.config.mitigationType===c.INJECT){const e={"x-netacea-match":d.parts.match,"x-netacea-mitigate":d.parts.mitigate,"x-netacea-captcha":d.parts.captcha};void 0!==h&&(e["x-netacea-event-id"]=h),u.injectHeaders=e}return u}};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudfront",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.78",
|
|
4
4
|
"description": "Netacea Cloudfront CDN integration",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist/index.js",
|
|
@@ -24,5 +24,5 @@
|
|
|
24
24
|
"jose": "^4.11.2",
|
|
25
25
|
"uuid": "^10.0.0"
|
|
26
26
|
},
|
|
27
|
-
"gitHead": "
|
|
27
|
+
"gitHead": "ed358a03a5bbcb78307205e72a95bfc513bf9e41"
|
|
28
28
|
}
|