@netacea/cloudflare 6.0.13 → 6.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("crypto"),t=require("buffer"),a=require("url"),i=require("querystring"),s=require("jose"),o=require("uuid");function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={},c={},u={};!function(a){var i,s,o,n,r=e,c=t;a.NetaceaIngestType=void 0,(i=a.NetaceaIngestType||(a.NetaceaIngestType={})).ORIGIN="ORIGIN",i.HTTP="HTTP",i.KINESIS="KINESIS",i.NATIVE="NATIVE",a.NetaceaLogVersion=void 0,(s=a.NetaceaLogVersion||(a.NetaceaLogVersion={})).V1="V1",s.V2="V2",a.NetaceaMitigationType=void 0,(o=a.NetaceaMitigationType||(a.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",a.NetaceaCookieV3IssueReason=void 0,(n=a.NetaceaCookieV3IssueReason||(a.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const u=3e3;const p="_/@#/",h={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:h.none,1:h.block,2:h.none,3:h.block,4:h.block},l={1:h.captcha,2:h.captchaPass,3:h.captcha,4:h.allow,5:h.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",11:"headerFP_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:h,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,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 f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d))$/i;function S(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:parseInt(n,36),mitigate:parseInt(r),captcha:parseInt(c)}}}function v(e=16,t=f){const a=r.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function k(e,t){const a=r.createHmac("sha256",t);return a.update(e),c.Buffer.from(a.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),a={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),a[o]=n}return a}function N(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:a.NetaceaCookieV3IssueReason.NO_SESSION}}function T(e,t){const a=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==a&&a.length>0?a?.replace(`${t}=`,""):void 0}function w(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":E(e.split(";"),t).join("; ")}function E(e,t=!1){if(t)return E(e.reverse()).reverse();const a=new Set,i=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();a.has(e)||(a.add(e),i.push(t))}return i}var A=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let a=e=w(e??"",!0),i=t=w(t??"",!0);if(void 0!==e&&void 0!==t){const s=T(e,"Domain"),o=T(t,"Domain");void 0!==s&&void 0!==o?i=t.replace(o,s):void 0!==s&&void 0===o?i=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(a=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=T(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=T(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},extractAndRemoveCookieAttr:function(e,t){const a=T(e,t);if(void 0!==a){return{extractedAttribute:a,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${a}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:T,removeDuplicateAttrs:w});function b(e){const t=w([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var _=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return b({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return b({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:b});var x=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 a=e.slice(0,t),i=e.slice(t+1),s=i.indexOf(";");return{name:a,value:i.slice(0,s),attributes:i.slice(s).trimStart()}}});const P={cookie:{parse:x,attributes:A,netaceaSession:_}};class M{constructor(e){this.crypto=e}async hashString(e,t,a=!1){const i=a?[...t].sort():[...t],s=(new TextEncoder).encode(i.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"+(a?"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 a=M.filterHeaderNames(e);if(0===a.length)return"";try{return await this.hashString("SHA-256",a,t)}catch(e){return console.error(e),""}}}a.HashGenerator=M,a.checkMitataCookie=function(e,t,a){const i={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 i;const s=S(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,u=k(t+"|"+s.expiry,a),h=s.ipHash===u;return{mitata:s,requiresReissue:o||!h,isExpired:o,shouldExpire:c,isSameIP:h,isPrimaryHashValid:s.signature===k(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return i},a.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return N();const a=I(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP,o=[1,3,5].includes(a.captcha),n=3===a.mitigate;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:a.issueReason}}return N()},a.configureMitataExpiry=function(e,t){return void 0===t?e===a.NetaceaMitigationType.INGEST?3600:60:t},a.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},a.correctTimeout=function(e){return e<=0?u:e},a.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=v());const o=[a,t,k(e+"|"+String(a),i),s].join(p);return`${k(o,i)}${p}${o}`},a.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},a.defaultInvalidResponse=N,a.dictionary=y,a.generateId=v,a.hexSha256=k,a.ingestIgnoredIpValue="ignored",a.lib=P,a.matchMitataCookie=S,a.matchNetaceaCookieV3=I,a.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},a.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},a.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(u);var p={},h={},d={},l={},g=function(e){return new m(e)};function m(e){this.capacity=0|e,this.map=Object.create(null),this.list=new y}function y(){this.firstNode=null,this.lastNode=null}function f(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}m.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},m.prototype.set=function(e,t){var a=this.map[e];if(null!=a)a.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;a=new f(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},m.prototype.used=function(e){this.list.moveToFront(e)},m.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},y.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},y.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},y.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=l,o=a,n=i,r=e,c=g(1e3);function u(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function p(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function h(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function d(e){return h(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var a=e.headers=e.headers||{},i=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||a.Host||a.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||i[0]||"",this.region=e.region||i[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),a.Host||a.host||(a.Host=e.hostname||e.host||this.createHost(),e.port&&(a.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var a=0;a<2;a++)if(/^s3-/.test(t[a])){t[1]=t[a].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,a=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||a["Content-Type"]||a["content-type"]||(a["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||a["Content-Length"]||a["content-length"]||(a["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||a["X-Amz-Security-Token"]||a["x-amz-security-token"]||(a["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||(a["X-Amz-Content-Sha256"]=p(this.request.body||"","hex")),a["X-Amz-Date"]||a["x-amz-date"]?this.datetime=a["X-Amz-Date"]||a["x-amz-date"]:a["X-Amz-Date"]=this.getDateTime()),delete a.Authorization,delete a.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,a,i=this.getDate(),s=[this.credentials.secretAccessKey,i,this.region,this.service].join(),o=c.get(s);return o||(e=u("AWS4"+this.credentials.secretAccessKey,i),t=u(e,this.region),a=u(t,this.service),o=u(a,"aws4_request"),c.set(s,o)),u(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),p(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,a=this.parsedPath.query,i=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||p(this.request.body||"","hex"),a){var u=Object.keys(a).reduce((function(e,t){return t?(e[d(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),h=[];Object.keys(u).sort().forEach((function(e){Array.isArray(u[e])?u[e].map(d).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+d(u[e]))})),s=h.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(d(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),a=null;t>=0&&(a=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:a}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+h(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var C={};Object.defineProperty(C,"__esModule",{value:!0}),C.API_VERSION=C.REGION=C.PAYLOAD_TYPE=C.STATE=void 0,C.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},C.PAYLOAD_TYPE="string",C.REGION="eu-west-1",C.API_VERSION="2013-12-02",Object.defineProperty(d,"__esModule",{value:!0}),d.signRequest=void 0;const S=l,v=C;function k(e,t){const a=[];for(let i=0;i<e.length;i+=t){const s=e.slice(i,i+t);a.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a}d.signRequest=function(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:k(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return S.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:i,secretAccessKey:s})},Object.defineProperty(h,"__esModule",{value:!0});const I=d;async function N(e){await new Promise((t=>{setTimeout(t,e)}))}h.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s,rampUpBatchSize:o,maxAwaitTimePerIngestCallMs:n}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,this.maxAwaitTimePerIngestCallMs=n,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.maxLogBatchSize=s),this.logBatchSize=!0===o?1:this.maxLogBatchSize}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=(0,I.signRequest)({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:a.headers,host:`https://${a.hostname}`,method:a.method,path:a.path,body:a.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis(t)),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(N(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=N(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(t),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}},Object.defineProperty(p,"__esModule",{value:!0});const T=h;p.default=T.default;var w={name:"@netacea/cloudflare",version:"6.0.13",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"NODE_OPTIONS='--import tsx' npx nyc tape './tests/tape/*.test.ts'","test:integration":"NODE_OPTIONS='--import tsx' npx nyc mocha --timeout 60000 './tests/mocha/*.test.ts'","test:integration:no-clean":"NODE_OPTIONS='--import tsx' npx nyc --no-clean mocha --timeout 60000 './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup",postpack:"npx netacea-bundler postpack",prepack:"npx netacea-bundler prepack"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.74","@netacea/netaceaintegrationbase":"^2.0.56",jose:"^4.11.2",uuid:"^10.0.0"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/bundler":"^1.0.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@netacea/test-runner-scenarios":"^1.0.0","@netacea/test-runner-transforms":"^1.0.0","@netacea/test-runner-types":"^1.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0","@types/uuid":"^10.0.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1",typescript:"^5.2.2"},gitHead:"3631732cf87f8e0abc170bdf03cef29a934d3b01"},E={};Object.defineProperty(E,"__esModule",{value:!0}),E.fetch=void 0,E.fetch=globalThis.fetch.bind(globalThis);var A,b={};function _(){return A||(A=1,e=b,Object.defineProperty(e,"__esModule",{value:!0}),e.dictionary=e.bestMitigationCaptchaMap=e.bestMitigationMap=e.captchaStatusCodes=e.captchaMap=e.mitigateMap=e.matchMap=e.netaceaHeaders=e.mitigationTypes=void 0,e.mitigationTypes={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},e.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"},e.matchMap={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},e.mitigateMap={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},e.captchaMap={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},e.captchaStatusCodes={"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},e.bestMitigationMap={0:e.mitigationTypes.none,1:e.mitigationTypes.block,2:e.mitigationTypes.none,3:e.mitigationTypes.block,4:e.mitigationTypes.block},e.bestMitigationCaptchaMap={1:e.mitigationTypes.captcha,2:e.mitigationTypes.captchaPass,3:e.mitigationTypes.captcha,4:e.mitigationTypes.allow,5:e.mitigationTypes.captcha},e.dictionary=_()),b;var e}var x={};Object.defineProperty(x,"__esModule",{value:!0}),x.configureMitataExpiry=x.checkMitataCookie=x.hexSha256=x.createSessionCookie=x.generateId=x.parseNetaceaSessionCookie=x.ingestIgnoredIpValue=void 0;const P=e,M=t,R=u;x.ingestIgnoredIpValue="ignored";const O="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function q(e){if(void 0===e)return;const t=e.match(H);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}function j(e,t){const a=(0,P.createHmac)("sha256",t);return a.update(e),M.Buffer.from(a.digest("hex")).toString("base64")}x.parseNetaceaSessionCookie=q,x.generateId=function(e=16,t=D){const a=(0,P.randomBytes)(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`},x.createSessionCookie=function(e,t,a,i,s="000"){const o=[a,t,j(e+"|"+String(a),i),s].join(O);return`${j(o,i)}${O}${o}`},x.hexSha256=j,x.checkMitataCookie=function(e,t,a){const i={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return i;const s=q(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(O),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=["1","3","5"].includes(s.protectorCheckCodes.captcha),r="3"===s.protectorCheckCodes.mitigate,c=n||r,u=j(t+"|"+s.expiry,a),p=s.ipHash===u,h=s.signature===j(e,a);return{userId:s.userId,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:h,protectorCheckCodes:s.protectorCheckCodes}}return i},x.configureMitataExpiry=function(e,t){return void 0===t?e===R.NetaceaMitigationType.INGEST?3600:60:t};var K,L={};Object.defineProperty(L,"__esModule",{value:!0}),L.NetaceaSessionCookieStatus=void 0,function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(K||(L.NetaceaSessionCookieStatus=K={}));var V={};Object.defineProperty(V,"__esModule",{value:!0}),V.decrypt=V.encrypt=void 0;const $=s;V.encrypt=async function(e,t){const a=$.base64url.decode(t),i=(new TextEncoder).encode(e);return await new $.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},V.decrypt=async function(e,t){const a=$.base64url.decode(t),{plaintext:i}=await $.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var U={};Object.defineProperty(U,"__esModule",{value:!0}),U.isUrlCaptchaPost=U.isUrlCaptchaGet=U.getTrackingId=U.modifyCaptchaJsonResponse=U.getCaptchaPageContentType=void 0,U.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),a=t.includes("application/html")||t.includes("text/html"),i=t.includes("application/json");return!a&&i?"application/json":"text/html"},U.modifyCaptchaJsonResponse=async function(e,t,a){const i=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(a);return t.length<2||void 0===i?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${i}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${i}`})},U.getTrackingId=async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}},U.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||""===a)return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=e;return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()},U.isUrlCaptchaPost=function(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()};var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.buildCookieHeader=z.getCookieHeader=z.getHeaderValuesArray=z.getHeaderValueOrDefault=z.addHeadersToRequest=z.addHeadersToResponse=void 0,z.addHeadersToResponse=function(e,t){var a;if(void 0===t)return e;const i=null!==(a=e.headers.get("set-cookie"))&&void 0!==a?a:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},z.addHeadersToRequest=function(e,t){if(void 0===t.injectHeaders)return e;const a=new Headers(e.headers);for(const[e,i]of Object.entries(t.injectHeaders))a.set(e,i);return new Request(e,{headers:a})},z.getHeaderValueOrDefault=function(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a},z.getHeaderValuesArray=function(e,t){var a,i;return null!==(i=null===(a=e.get(t))||void 0===a?void 0:a.split(/; ?/))&&void 0!==i?i:[]},z.getCookieHeader=function(e){return e.headers.get("cookie")},z.buildCookieHeader=function(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t};var F={};Object.defineProperty(F,"__esModule",{value:!0}),F.APIError=F.createErrorResponse=F.timeoutCheck=F.parseIntOrReturnUnparsed=void 0,F.parseIntOrReturnUnparsed=function(e){const t=parseInt(e,10);return isNaN(t)?e:t},F.timeoutCheck=async function(e,t){const a=new Promise(((e,a)=>{setTimeout((()=>{e(void 0)}),t)}));return await Promise.race([e,a])},F.createErrorResponse=function(){return new Response("",{status:500,statusText:"Internal Server Error",headers:{}})},F.APIError=function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)};var G={};Object.defineProperty(G,"__esModule",{value:!0}),G.addIngestOriginHeaders=void 0;const X=w;G.addIngestOriginHeaders=function(e,t,a){e.headers.set("x-netacea-integration-type",X.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",X.version),e.headers.set("x-netacea-userid",a),e.headers.set("x-netacea-bc-type",t)};var W={};Object.defineProperty(W,"__esModule",{value:!0}),W.ProtectorApiError=void 0;class B extends Error{constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}W.ProtectorApiError=B;var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.constructWebLog=void 0;const J=u,Z=x;Y.constructWebLog=function(e,t){return t.bytesSent=""===t.bytesSent?"0":t.bytesSent,e===J.NetaceaLogVersion.V2?function({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:p,integrationType:h,integrationVersion:d,integrationMode:l,xForwardedFor:g,headerFingerprint:m,cookieFingerprint:y,requestHost:f,mitigationLatency:C,mitigationStatus:S,workerInstanceId:v}){var k;const I=new Date;let N;"/"!==s[0]&&(s=`/${s}`);const T=s.split("?");T.length>1&&(N=`?${T[1]}`);const w=T[0],E=null===(k=(0,Z.parseNetaceaSessionCookie)(u))||void 0===k?void 0:k.userId;return{status:a,method:i,bytes_sent:(0,J.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${w}${null!=N?N:""} ${o}`,request_time:(0,J.safeParseInt)(c),integration_type:h,integration_version:d,protection_mode:l,client:e,user_agent:t,bc_type:""===p?void 0:p,hour:I.getUTCHours(),minute:I.getUTCMinutes(),"@timestamp":I.toISOString().replace("Z","+00:00"),path:w,request_host:f,protector_latency_ms:C,protector_status:S,protocol:o,query:N,user_id:E,x_forwarded_for:g,worker_instance_id:v,optional:{headerFingerprint:m,cookieFingerprint:y}}}(t):function({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:p,integrationType:h,integrationVersion:d,integrationMode:l,xForwardedFor:g,headerFingerprint:m,cookieFingerprint:y,requestHost:f,mitigationLatency:C,mitigationStatus:S,netaceaCookieStatus:v,workerInstanceId:k}){return{Request:`${i} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:a,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=u?u:"",NetaceaMitigationApplied:null!=p?p:"",ProtectorLatencyMs:C,ProtectorStatus:S,IntegrationType:null!=h?h:"",IntegrationVersion:null!=d?d:"",ProtectionMode:null!=l?l:"",RequestHost:f,XForwardedFor:g,WorkerInstanceId:k,NetaceaUserIdCookieStatus:v,optional:{headerFingerprint:m,cookieFingerprint:y}}}(t)};var Q={};Object.defineProperty(Q,"__esModule",{value:!0}),Q.findBestMitigation=void 0;const ee=_(),te=u,ae="unknown";Q.findBestMitigation=function(e,t,a){var i,s,o;let{match:n,mitigate:r,captcha:c}=t;a||("2"===c?c="4":"3"===c&&(c="5"));let u=null!==(i=ee.dictionary.matchMap[n])&&void 0!==i?i:ae+"_";u+=null!==(s=ee.dictionary.mitigateMap[r])&&void 0!==s?s:ae;let p=ee.dictionary.bestMitigationMap[r];if("0"!==c){u+=","+(null!==(o=ee.dictionary.captchaMap[c])&&void 0!==o?o:ae);const e=ee.dictionary.bestMitigationCaptchaMap[c];void 0!==e&&(p=e)}return e===te.NetaceaMitigationType.INJECT&&(p=ee.dictionary.mitigationTypes.none),{sessionStatus:u,mitigation:p,parts:{match:n,mitigate:r,captcha:c}}};var ie={},se={};async function oe(e,t){const a=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,a);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function ne(e){const t=[];return e.forEach(((e,a)=>{const i=a.toLowerCase();"cookie"===i||"referer"===i||i.startsWith("x-netacea-")||t.push(a)})),t.join(",")}async function re(e){let t="";try{t=await oe("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty(se,"__esModule",{value:!0}),se.hashCookieNames=se.hashHeaders=se.extractHeaderNames=se.hashString=void 0,se.hashString=oe,se.extractHeaderNames=ne,se.hashHeaders=async function(e){const t=ne(e);return await re(t)},se.hashCookieNames=async function(e){const t=e.join(",");return await re(t)},Object.defineProperty(ie,"__esModule",{value:!0}),ie.RequestAnalyser=void 0;const ce=L,ue=se,pe=z,he=U,de=Q,le=x,ge=u,me=V;async function ye(e){const{headers:t}=e,a=await(0,ue.hashHeaders)(t),i=(0,pe.getHeaderValuesArray)(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await(0,ue.hashCookieNames)(i);return{headerFingerprint:""===a?a:`h_${a.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}ie.RequestAnalyser=class{constructor(e){this.config=e}async getNetaceaRequestDetails(e){var t,a,i;const s=new URL(e.url),o=e.method,n=await this.readCookie(e,this.config.sessionCookieName),r=await this.readCookie(e,this.config.captchaCookieName),c=null!==(t=e.headers.get("cf-connecting-ip"))&&void 0!==t?t:"",{sessionCookieDetails:u,sessionCookieStatus:p,sessionStatus:h,userId:d}=function(e,t,a,i,s){const o=(0,le.checkMitataCookie)(i,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const i=o.userId,{isExpired:s,shouldExpire:n,isSameIP:r}=o,c=s||n||!r&&e.mitigationType!==ge.NetaceaMitigationType.INGEST?ce.NetaceaSessionCookieStatus.RENEW_SESSION:ce.NetaceaSessionCookieStatus.EXISTING_SESSION,{sessionStatus:u}=(0,de.findBestMitigation)(e.mitigationType,o.protectorCheckCodes,(0,he.isUrlCaptchaPost)(t,a));return{userId:i,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:o}}return{sessionStatus:"",userId:(0,le.generateId)(),sessionCookieStatus:ce.NetaceaSessionCookieStatus.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,s,o,n,c);return{clientIp:c,fingerprints:await ye(e),method:o,protocol:String(null===(a=e.cf)||void 0===a?void 0:a.httpProtocol),url:s,userAgent:null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",sessionDetails:{sessionStatus:h,captchaToken:r,sessionCookieDetails:u,sessionCookieStatus:p,userId:d}}}async readCookie(e,t){var a;const i=e.headers.get("Cookie");if(null==i)return;const s=i.split(/; ?/g),o=`${t}=`;for(const e of s)if(e.startsWith(o)){const i=e.slice(o.length),s=null!==(a=this.config.encryptedCookies)&&void 0!==a?a:[];if(void 0!==this.config.cookieEncryptionKey&&s.includes(t))try{return await(0,me.decrypt)(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}},Object.defineProperty(c,"__esModule",{value:!0});const fe=u,Ce=p,Se=w,ve=E,ke=_(),Ie=x,Ne=L,Te=V,we=U,Ee=z,Ae=F,be=G,_e=W,xe=Y,Pe=Q,Me=ie,Re=o,{configureCookiesDomain:Oe}=fe.lib.cookie.attributes;c.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:a,timeout:i=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=fe.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:u=fe.NetaceaIngestType.HTTP,kinesis:p,logVersion:h,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=a,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=u?u:fe.NetaceaIngestType.HTTP,this.logVersion=null!=h?h:fe.NetaceaLogVersion.V1,this.ingestType===fe.NetaceaIngestType.KINESIS&&(void 0===p?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Ce.default({...p,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,fe.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:S,captchaCookieAttributes:v}=Oe(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=S?S:"",this.netaceaCaptchaCookieAttributes=null!=v?v:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(0,Ie.configureMitataExpiry)(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f,this.requestAnalyser=new Me.RequestAnalyser({cookieEncryptionKey:this.cookieEncryptionKey,encryptedCookies:this.encryptedCookies,mitigationType:this.mitigationType,secretKey:this.secretKey,sessionCookieName:this.netaceaCookieName,captchaCookieName:this.netaceaCaptchaCookieName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=Re.v4());const a=new Request(e.request),i=await this.requestAnalyser.getNetaceaRequestDetails(a);let s=await(0,Ae.timeoutCheck)(this.runMitigation(a,i),this.timeout);return void 0===s&&(s={sessionStatus:"error_open"}),await this.handleResponse(a,s,t)}async inject(e,t){const a=await this.getMitigationResponse(e,t);return{injectHeaders:a.injectHeaders,sessionStatus:a.sessionStatus,setCookie:a.setCookie,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}async mitigate(e,t){const a=await this.getMitigationResponse(e,t);if(a.mitigated){const i=new Headers;if(!await(0,we.isUrlCaptchaGet)(t.url,e.method,this.netaceaCaptchaPath))for(const e of a.setCookie)i.append("set-cookie",e);let s="Forbidden";return"captcha"===a.mitigation&&(void 0!==this.captchaHeader&&i.append(this.captchaHeader.name,this.captchaHeader.value),i.append("content-type","text/html; charset=UTF-8"),s=a.body),{response:new Response(s,{status:403,statusText:"Forbidden",headers:i}),setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}if((0,we.isUrlCaptchaPost)(t.url,e.method)){const e=new Headers;for(const t of a.setCookie)e.append("set-cookie",t);return{response:new Response(a.body,{status:200,statusText:"OK",headers:e}),setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}return{setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}async getNetaceaSession(e,t){var a;const i=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=i?i:await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:o,userId:n}=null!==(a=(0,Ie.parseNetaceaSessionCookie)(null!=s?s:""))&&void 0!==a?a:{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:r}=(0,Pe.findBestMitigation)(this.mitigationType,o,(0,we.isUrlCaptchaPost)(new URL(e.url),e.method));return{userId:n,sessionStatus:r,netaceaCookie:s}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){var a,i;""===this.workerInstanceId&&(this.workerInstanceId=Re.v4());const s=this.getResponseDetails(t),{netaceaCookie:o}=await this.getNetaceaSession(e,s.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:(0,Ee.getHeaderValueOrDefault)(s.rawResponse.headers,"content-length","0"),ip:(0,Ee.getHeaderValueOrDefault)(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:null!==(a=n.protocol)&&void 0!==a?a:null,referer:(0,Ee.getHeaderValueOrDefault)(e.headers,"referer"),requestTime:"0",sessionStatus:null!==(i=s.sessionStatus)&&void 0!==i?i:n.sessionDetails.sessionStatus,status:s.rawResponse.status.toString(),userAgent:(0,Ee.getHeaderValueOrDefault)(e.headers,"user-agent","-"),mitataCookie:o,integrationType:Se.name.replace("@netacea/",""),integrationVersion:Se.version,xForwardedFor:(0,Ee.getHeaderValueOrDefault)(e.headers,"x-forwarded-for"),headerFingerprint:n.fingerprints.headerFingerprint,cookieFingerprint:n.fingerprints.cookieFingerprint,integrationMode:this.mitigationType,requestHost:new URL(e.url).hostname,mitigationLatency:s.mitigationLatency,mitigationStatus:s.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,workerInstanceId:this.workerInstanceId})}async handleGetCaptchaRequest(e,t,a){if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const i=await this.makeMitigateAPICall(e,t,!0,a);return{body:i.body,apiCallStatus:i.status,apiCallLatency:i.latency,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:a,headers:i,body:s}){const o=`${e}${a}`,n=new Request(o,{method:t,body:s,headers:i}),r=await(0,ve.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,a){var i,s;if(this.mitigationType===fe.NetaceaMitigationType.MITIGATE&&void 0!==(null==t?void 0:t.response))return{sessionStatus:null!==(i=null==t?void 0:t.sessionStatus)&&void 0!==i?i:"",response:t.response,protectorLatencyMs:null==t?void 0:t.apiCallLatency,protectorStatus:null==t?void 0:t.apiCallStatus};if(this.mitigationType===fe.NetaceaMitigationType.INJECT&&(e=(0,Ee.addHeadersToRequest)(e,t)),this.ingestType===fe.NetaceaIngestType.ORIGIN){const{sessionStatus:a,userId:i}=await this.getNetaceaSession(e,t);(0,be.addIngestOriginHeaders)(e,a,i)}const o=await a(e);return{sessionStatus:null!==(s=null==t?void 0:t.sessionStatus)&&void 0!==s?s:"",response:(0,Ee.addHeadersToResponse)(o,t),protectorLatencyMs:null==t?void 0:t.apiCallLatency,protectorStatus:null==t?void 0:t.apiCallStatus}}async getMitigationResponse(e,t){var a;const i=this.enableDynamicCaptchaContentType?(0,we.getCaptchaPageContentType)(null!==(a=e.headers.get("Accept"))&&void 0!==a?a:void 0):(0,we.getCaptchaPageContentType)();return await this.processMitigateRequest({getBodyFn:async()=>{var t;return null!==(t=await Promise.resolve(e.body))&&void 0!==t?t:void 0},requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){var a;try{switch(this.mitigationType){case fe.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case fe.NetaceaMitigationType.INJECT:return await this.inject(e,t);case fe.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.mitigationType)} not recognised`)}}catch(i){let s,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof _e.ProtectorApiError&&(o=i.latencyMs,s=null===(a=i.protectorApiResponse)||void 0===a?void 0:a.status);return{response:(0,we.isUrlCaptchaPost)(t.url,e.method)?(0,Ae.createErrorResponse)():void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:o,apiCallStatus:s}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const a=`${e}=`;for(const i of t){const t=i.split(";")[0].trimStart();if(t.startsWith(a)){const i=t.slice(a.length);if(void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(e))try{return await(0,Te.decrypt)(i,this.cookieEncryptionKey)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const a of t)if(a.startsWith(e))return await this.readCookie(this.netaceaCookieName,a)}}async getNetaceaCookieFromRequest(e){var t;const a=(0,Ee.getHeaderValueOrDefault)(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=(0,xe.constructWebLog)(this.logVersion,e);if(this.ingestType===fe.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest.bind(this))}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},a=await this.makeIngestApiCall(e,t);if(200!==a.status)throw(0,Ae.APIError)(a)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}async check(e,t){var a,i,s,o;let n,r,c,u,p,h,d,l;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");if([Ne.NetaceaSessionCookieStatus.NEW_SESSION,Ne.NetaceaSessionCookieStatus.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const a=e.sessionDetails.userId,i=await this.makeMitigateAPICall(e,t,!1,null);n=i.status,r=i.match,c=i.mitigate,u=i.captcha,p=i.body,l=i.latency,h=[await this.createMitata(e.clientIp,a,r,c,u,i.mitataMaxAge)],d=i.eventId}else{const t=null===(a=e.sessionDetails.sessionCookieDetails)||void 0===a?void 0:a.protectorCheckCodes;r=null!==(i=null==t?void 0:t.match)&&void 0!==i?i:"0",c=null!==(s=null==t?void 0:t.mitigate)&&void 0!==s?s:"0",u=null!==(o=null==t?void 0:t.captcha)&&void 0!==o?o:"0",p=void 0,h=[]}const g={match:r,mitigate:c,captcha:u};return this.composeResult(p,h,n,g,!1,l,d)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=["1","3","5"].includes(s)||"3"===i?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[a,i,s].join("");let p=(0,Ie.createSessionCookie)(e,t,c,this.secretKey,u);return void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(this.netaceaCookieName)&&(p=await(0,Te.encrypt)(p,this.cookieEncryptionKey)),fe.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:p,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:a,match:i,mitigate:s,captcha:o,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:i,mitigate:s,captcha:o};return this.composeResult(n,r,a,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[ke.dictionary.netaceaHeaders.mitataCaptcha];const a=parseInt(e[ke.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await(0,Te.encrypt)(t,this.cookieEncryptionKey)),fe.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(a),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const a={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},i=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==Ne.NetaceaSessionCookieStatus.NEW_SESSION&&(a["X-Netacea-UserId"]=i),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(a["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,a["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const s=new URLSearchParams;s.append("headerFP",e.fingerprints.headerFingerprint);const o=Date.now(),n=await this.makeRequest({host:this.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${s.toString()}`,headers:a,method:"POST",body:t,timeout:this.timeout}),r=Date.now()-o;return await this.getApiCallResponseFromResponse(n,e,r)}async getApiCallResponseFromResponse(e,t,a){var i,s;if(200!==e.status)throw new _e.ProtectorApiError(e,a);const o=e.headers[ke.dictionary.netaceaHeaders.match],n=e.headers[ke.dictionary.netaceaHeaders.mitigate],r=e.headers[ke.dictionary.netaceaHeaders.captcha];let c=parseInt(e.headers[ke.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const u=t.sessionDetails.userId,p=[await this.createMitata(t.clientIp,u,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),h=e.headers[ke.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(i=e.headers["content-type"])||void 0===i?void 0:i.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,we.modifyCaptchaJsonResponse)(null!==(s=e.body)&&void 0!==s?s:"",this.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:p,body:e.body,eventId:h,mitataMaxAge:c,latency:a}}async makeMitigateAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:(0,Ee.buildCookieHeader)({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Ne.NetaceaSessionCookieStatus.NEW_SESSION&&(s["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),s["X-Netacea-Captcha-Content-Type"]=t;let o="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),a&&(o="/captcha",null!==i&&n.append("trackingId",i));const r=Date.now(),c=await this.makeRequest({host:this.mitigationServiceUrl,path:`${o}?${n.toString()}`,headers:s,method:"GET",timeout:this.timeout}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,a,i,s,o,n){const r=(0,Pe.findBestMitigation)(this.mitigationType,i,s),c={body:e,apiCallStatus:a,apiCallLatency:o,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[ke.dictionary.mitigationTypes.block,ke.dictionary.mitigationTypes.captcha].includes(r.mitigation)};if(this.mitigationType===fe.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==n&&(e["x-netacea-event-id"]=n),c.injectHeaders=e}return c}async processMitigateRequest(e){var t;if(await(0,we.isUrlCaptchaGet)(e.requestDetails.url,e.requestDetails.method,this.netaceaCaptchaPath)){const t=await(0,we.getTrackingId)(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if((0,we.isUrlCaptchaPost)(e.requestDetails.url,e.requestDetails.method)){const a=null!==(t=await e.getBodyFn())&&void 0!==t?t:"";return await this.processCaptcha(e.requestDetails,a)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(fe.ingestIgnoredIpValue,e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,a=t===Ne.NetaceaSessionCookieStatus.NEW_SESSION,i=t===Ne.NetaceaSessionCookieStatus.RENEW_SESSION;return a||i?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=c;var a=u;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(r);var De=n(r);module.exports=De;
1
+ "use strict";var e=require("crypto"),t=require("buffer"),a=require("url"),i=require("querystring"),s=require("jose"),o=require("uuid");function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={},c={},u={};!function(a){var i,s,o,n,r=e,c=t;a.NetaceaIngestType=void 0,(i=a.NetaceaIngestType||(a.NetaceaIngestType={})).ORIGIN="ORIGIN",i.HTTP="HTTP",i.KINESIS="KINESIS",i.NATIVE="NATIVE",a.NetaceaLogVersion=void 0,(s=a.NetaceaLogVersion||(a.NetaceaLogVersion={})).V1="V1",s.V2="V2",a.NetaceaMitigationType=void 0,(o=a.NetaceaMitigationType||(a.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",a.NetaceaCookieV3IssueReason=void 0,(n=a.NetaceaCookieV3IssueReason||(a.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const u=3e3;const p="_/@#/",h={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:h.none,1:h.block,2:h.none,3:h.block,4:h.block},l={1:h.captcha,2:h.captchaPass,3:h.captcha,4:h.allow,5:h.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",11:"headerFP_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:h,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,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 f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d))$/i;function S(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:parseInt(n,36),mitigate:parseInt(r),captcha:parseInt(c)}}}function v(e=16,t=f){const a=r.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function k(e,t){const a=r.createHmac("sha256",t);return a.update(e),c.Buffer.from(a.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),a={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),a[o]=n}return a}function N(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:a.NetaceaCookieV3IssueReason.NO_SESSION}}function T(e,t){const a=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==a&&a.length>0?a?.replace(`${t}=`,""):void 0}function w(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":E(e.split(";"),t).join("; ")}function E(e,t=!1){if(t)return E(e.reverse()).reverse();const a=new Set,i=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();a.has(e)||(a.add(e),i.push(t))}return i}var A=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let a=e=w(e??"",!0),i=t=w(t??"",!0);if(void 0!==e&&void 0!==t){const s=T(e,"Domain"),o=T(t,"Domain");void 0!==s&&void 0!==o?i=t.replace(o,s):void 0!==s&&void 0===o?i=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(a=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=T(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=T(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},extractAndRemoveCookieAttr:function(e,t){const a=T(e,t);if(void 0!==a){return{extractedAttribute:a,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${a}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:T,removeDuplicateAttrs:w});function b(e){const t=w([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var _=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return b({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return b({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:b});var x=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 a=e.slice(0,t),i=e.slice(t+1),s=i.indexOf(";");return{name:a,value:i.slice(0,s),attributes:i.slice(s).trimStart()}}});const P={cookie:{parse:x,attributes:A,netaceaSession:_}};class M{constructor(e){this.crypto=e}async hashString(e,t,a=!1){const i=a?[...t].sort():[...t],s=(new TextEncoder).encode(i.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"+(a?"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 a=M.filterHeaderNames(e);if(0===a.length)return"";try{return await this.hashString("SHA-256",a,t)}catch(e){return console.error(e),""}}}a.HashGenerator=M,a.checkMitataCookie=function(e,t,a){const i={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 i;const s=S(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,u=k(t+"|"+s.expiry,a),h=s.ipHash===u;return{mitata:s,requiresReissue:o||!h,isExpired:o,shouldExpire:c,isSameIP:h,isPrimaryHashValid:s.signature===k(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha,userId:s.userId}}return i},a.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return N();const a=I(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP,o=[1,3,5].includes(a.captcha),n=3===a.mitigate;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:a.issueReason}}return N()},a.configureMitataExpiry=function(e,t){return void 0===t?e===a.NetaceaMitigationType.INGEST?3600:60:t},a.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},a.correctTimeout=function(e){return e<=0?u:e},a.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=v());const o=[a,t,k(e+"|"+String(a),i),s].join(p);return`${k(o,i)}${p}${o}`},a.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},a.defaultInvalidResponse=N,a.dictionary=y,a.generateId=v,a.hexSha256=k,a.ingestIgnoredIpValue="ignored",a.lib=P,a.matchMitataCookie=S,a.matchNetaceaCookieV3=I,a.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},a.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},a.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(u);var p={},h={},d={},l={},g=function(e){return new m(e)};function m(e){this.capacity=0|e,this.map=Object.create(null),this.list=new y}function y(){this.firstNode=null,this.lastNode=null}function f(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}m.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},m.prototype.set=function(e,t){var a=this.map[e];if(null!=a)a.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;a=new f(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},m.prototype.used=function(e){this.list.moveToFront(e)},m.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},y.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},y.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},y.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=l,o=a,n=i,r=e,c=g(1e3);function u(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function p(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function h(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function d(e){return h(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var a=e.headers=e.headers||{},i=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||a.Host||a.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||i[0]||"",this.region=e.region||i[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),a.Host||a.host||(a.Host=e.hostname||e.host||this.createHost(),e.port&&(a.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var a=0;a<2;a++)if(/^s3-/.test(t[a])){t[1]=t[a].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,a=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||a["Content-Type"]||a["content-type"]||(a["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||a["Content-Length"]||a["content-length"]||(a["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||a["X-Amz-Security-Token"]||a["x-amz-security-token"]||(a["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||(a["X-Amz-Content-Sha256"]=p(this.request.body||"","hex")),a["X-Amz-Date"]||a["x-amz-date"]?this.datetime=a["X-Amz-Date"]||a["x-amz-date"]:a["X-Amz-Date"]=this.getDateTime()),delete a.Authorization,delete a.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,a,i=this.getDate(),s=[this.credentials.secretAccessKey,i,this.region,this.service].join(),o=c.get(s);return o||(e=u("AWS4"+this.credentials.secretAccessKey,i),t=u(e,this.region),a=u(t,this.service),o=u(a,"aws4_request"),c.set(s,o)),u(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),p(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,a=this.parsedPath.query,i=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||p(this.request.body||"","hex"),a){var u=Object.keys(a).reduce((function(e,t){return t?(e[d(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),h=[];Object.keys(u).sort().forEach((function(e){Array.isArray(u[e])?u[e].map(d).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+d(u[e]))})),s=h.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(d(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),a=null;t>=0&&(a=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:a}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+h(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var C={};Object.defineProperty(C,"__esModule",{value:!0}),C.API_VERSION=C.REGION=C.PAYLOAD_TYPE=C.STATE=void 0,C.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},C.PAYLOAD_TYPE="string",C.REGION="eu-west-1",C.API_VERSION="2013-12-02",Object.defineProperty(d,"__esModule",{value:!0}),d.signRequest=void 0;const S=l,v=C;function k(e,t){const a=[];for(let i=0;i<e.length;i+=t){const s=e.slice(i,i+t);a.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a}d.signRequest=function(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:k(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return S.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:i,secretAccessKey:s})},Object.defineProperty(h,"__esModule",{value:!0});const I=d;async function N(e){await new Promise((t=>{setTimeout(t,e)}))}h.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s,rampUpBatchSize:o,maxAwaitTimePerIngestCallMs:n}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,this.maxAwaitTimePerIngestCallMs=n,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.maxLogBatchSize=s),this.logBatchSize=!0===o?1:this.maxLogBatchSize}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=(0,I.signRequest)({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:a.headers,host:`https://${a.hostname}`,method:a.method,path:a.path,body:a.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis(t)),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(N(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=N(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(t),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}},Object.defineProperty(p,"__esModule",{value:!0});const T=h;p.default=T.default;var w={name:"@netacea/cloudflare",version:"6.0.15",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"NODE_OPTIONS='--import tsx' npx nyc tape './tests/tape/*.test.ts'","test:integration":"NODE_OPTIONS='--import tsx' npx nyc mocha --timeout 60000 './tests/mocha/*.test.ts'","test:integration:no-clean":"NODE_OPTIONS='--import tsx' npx nyc --no-clean mocha --timeout 60000 './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup",postpack:"npx netacea-bundler postpack",prepack:"npx netacea-bundler prepack"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.76","@netacea/netaceaintegrationbase":"^2.0.58",jose:"^4.11.2",uuid:"^10.0.0"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/bundler":"^1.0.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@netacea/test-runner-scenarios":"^1.0.0","@netacea/test-runner-transforms":"^1.0.0","@netacea/test-runner-types":"^1.0.0","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0","@types/uuid":"^10.0.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1",typescript:"^5.2.2"},gitHead:"d60331b35eb04a265668830f0e400072f40b2028"},E={};Object.defineProperty(E,"__esModule",{value:!0}),E.fetch=void 0,E.fetch=globalThis.fetch.bind(globalThis);var A,b={};function _(){return A||(A=1,e=b,Object.defineProperty(e,"__esModule",{value:!0}),e.dictionary=e.bestMitigationCaptchaMap=e.bestMitigationMap=e.captchaStatusCodes=e.captchaMap=e.mitigateMap=e.matchMap=e.netaceaHeaders=e.mitigationTypes=void 0,e.mitigationTypes={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},e.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"},e.matchMap={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},e.mitigateMap={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},e.captchaMap={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},e.captchaStatusCodes={"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},e.bestMitigationMap={0:e.mitigationTypes.none,1:e.mitigationTypes.block,2:e.mitigationTypes.none,3:e.mitigationTypes.block,4:e.mitigationTypes.block},e.bestMitigationCaptchaMap={1:e.mitigationTypes.captcha,2:e.mitigationTypes.captchaPass,3:e.mitigationTypes.captcha,4:e.mitigationTypes.allow,5:e.mitigationTypes.captcha},e.dictionary=_()),b;var e}var x={};Object.defineProperty(x,"__esModule",{value:!0}),x.configureMitataExpiry=x.checkMitataCookie=x.hexSha256=x.createSessionCookie=x.generateId=x.parseNetaceaSessionCookie=x.ingestIgnoredIpValue=void 0;const P=e,M=t,R=u;x.ingestIgnoredIpValue="ignored";const O="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function q(e){if(void 0===e)return;const t=e.match(H);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}function j(e,t){const a=(0,P.createHmac)("sha256",t);return a.update(e),M.Buffer.from(a.digest("hex")).toString("base64")}x.parseNetaceaSessionCookie=q,x.generateId=function(e=16,t=D){const a=(0,P.randomBytes)(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`},x.createSessionCookie=function(e,t,a,i,s="000"){const o=[a,t,j(e+"|"+String(a),i),s].join(O);return`${j(o,i)}${O}${o}`},x.hexSha256=j,x.checkMitataCookie=function(e,t,a){const i={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return i;const s=q(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(O),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=["1","3","5"].includes(s.protectorCheckCodes.captcha),r="3"===s.protectorCheckCodes.mitigate,c=n||r,u=j(t+"|"+s.expiry,a),p=s.ipHash===u,h=s.signature===j(e,a);return{userId:s.userId,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:h,protectorCheckCodes:s.protectorCheckCodes}}return i},x.configureMitataExpiry=function(e,t){return void 0===t?e===R.NetaceaMitigationType.INGEST?3600:60:t};var K,L={};Object.defineProperty(L,"__esModule",{value:!0}),L.NetaceaSessionCookieStatus=void 0,function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(K||(L.NetaceaSessionCookieStatus=K={}));var V={};Object.defineProperty(V,"__esModule",{value:!0}),V.decrypt=V.encrypt=void 0;const $=s;V.encrypt=async function(e,t){const a=$.base64url.decode(t),i=(new TextEncoder).encode(e);return await new $.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},V.decrypt=async function(e,t){const a=$.base64url.decode(t),{plaintext:i}=await $.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var U={};Object.defineProperty(U,"__esModule",{value:!0}),U.isUrlCaptchaPost=U.isUrlCaptchaGet=U.getTrackingId=U.modifyCaptchaJsonResponse=U.getCaptchaPageContentType=void 0,U.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),a=t.includes("application/html")||t.includes("text/html"),i=t.includes("application/json");return!a&&i?"application/json":"text/html"},U.modifyCaptchaJsonResponse=async function(e,t,a){const i=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(a);return t.length<2||void 0===i?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${i}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${i}`})},U.getTrackingId=async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}},U.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||""===a)return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=e;return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()},U.isUrlCaptchaPost=function(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()};var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.buildCookieHeader=z.getCookieHeader=z.getHeaderValuesArray=z.getHeaderValueOrDefault=z.addHeadersToRequest=z.addHeadersToResponse=void 0,z.addHeadersToResponse=function(e,t){var a;if(void 0===t)return e;const i=null!==(a=e.headers.get("set-cookie"))&&void 0!==a?a:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},z.addHeadersToRequest=function(e,t){if(void 0===t.injectHeaders)return e;const a=new Headers(e.headers);for(const[e,i]of Object.entries(t.injectHeaders))a.set(e,i);return new Request(e,{headers:a})},z.getHeaderValueOrDefault=function(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a},z.getHeaderValuesArray=function(e,t){var a,i;return null!==(i=null===(a=e.get(t))||void 0===a?void 0:a.split(/; ?/))&&void 0!==i?i:[]},z.getCookieHeader=function(e){return e.headers.get("cookie")},z.buildCookieHeader=function(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t};var F={};Object.defineProperty(F,"__esModule",{value:!0}),F.APIError=F.createErrorResponse=F.timeoutCheck=F.parseIntOrReturnUnparsed=void 0,F.parseIntOrReturnUnparsed=function(e){const t=parseInt(e,10);return isNaN(t)?e:t},F.timeoutCheck=async function(e,t){const a=new Promise(((e,a)=>{setTimeout((()=>{e(void 0)}),t)}));return await Promise.race([e,a])},F.createErrorResponse=function(){return new Response("",{status:500,statusText:"Internal Server Error",headers:{}})},F.APIError=function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)};var G={};Object.defineProperty(G,"__esModule",{value:!0}),G.addIngestOriginHeaders=void 0;const X=w;G.addIngestOriginHeaders=function(e,t,a){e.headers.set("x-netacea-integration-type",X.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",X.version),e.headers.set("x-netacea-userid",a),e.headers.set("x-netacea-bc-type",t)};var W={};Object.defineProperty(W,"__esModule",{value:!0}),W.ProtectorApiError=void 0;class B extends Error{constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}W.ProtectorApiError=B;var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.constructWebLog=void 0;const J=u,Z=x;Y.constructWebLog=function(e,t){return t.bytesSent=""===t.bytesSent?"0":t.bytesSent,e===J.NetaceaLogVersion.V2?function({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:p,integrationType:h,integrationVersion:d,integrationMode:l,xForwardedFor:g,headerFingerprint:m,cookieFingerprint:y,requestHost:f,mitigationLatency:C,mitigationStatus:S,workerInstanceId:v}){var k;const I=new Date;let N;"/"!==s[0]&&(s=`/${s}`);const T=s.split("?");T.length>1&&(N=`?${T[1]}`);const w=T[0],E=null===(k=(0,Z.parseNetaceaSessionCookie)(u))||void 0===k?void 0:k.userId;return{status:a,method:i,bytes_sent:(0,J.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${w}${null!=N?N:""} ${o}`,request_time:(0,J.safeParseInt)(c),integration_type:h,integration_version:d,protection_mode:l,client:e,user_agent:t,bc_type:""===p?void 0:p,hour:I.getUTCHours(),minute:I.getUTCMinutes(),"@timestamp":I.toISOString().replace("Z","+00:00"),path:w,request_host:f,protector_latency_ms:C,protector_status:S,protocol:o,query:N,user_id:E,x_forwarded_for:g,worker_instance_id:v,optional:{headerFingerprint:m,cookieFingerprint:y}}}(t):function({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:p,integrationType:h,integrationVersion:d,integrationMode:l,xForwardedFor:g,headerFingerprint:m,cookieFingerprint:y,requestHost:f,mitigationLatency:C,mitigationStatus:S,netaceaCookieStatus:v,workerInstanceId:k}){return{Request:`${i} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:a,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=u?u:"",NetaceaMitigationApplied:null!=p?p:"",ProtectorLatencyMs:C,ProtectorStatus:S,IntegrationType:null!=h?h:"",IntegrationVersion:null!=d?d:"",ProtectionMode:null!=l?l:"",RequestHost:f,XForwardedFor:g,WorkerInstanceId:k,NetaceaUserIdCookieStatus:v,optional:{headerFingerprint:m,cookieFingerprint:y}}}(t)};var Q={};Object.defineProperty(Q,"__esModule",{value:!0}),Q.findBestMitigation=void 0;const ee=_(),te=u,ae="unknown";Q.findBestMitigation=function(e,t,a){var i,s,o;let{match:n,mitigate:r,captcha:c}=t;a||("2"===c?c="4":"3"===c&&(c="5"));let u=null!==(i=ee.dictionary.matchMap[n])&&void 0!==i?i:ae+"_";u+=null!==(s=ee.dictionary.mitigateMap[r])&&void 0!==s?s:ae;let p=ee.dictionary.bestMitigationMap[r];if("0"!==c){u+=","+(null!==(o=ee.dictionary.captchaMap[c])&&void 0!==o?o:ae);const e=ee.dictionary.bestMitigationCaptchaMap[c];void 0!==e&&(p=e)}return e===te.NetaceaMitigationType.INJECT&&(p=ee.dictionary.mitigationTypes.none),{sessionStatus:u,mitigation:p,parts:{match:n,mitigate:r,captcha:c}}};var ie={},se={};async function oe(e,t){const a=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,a);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function ne(e){const t=[];return e.forEach(((e,a)=>{const i=a.toLowerCase();"cookie"===i||"referer"===i||i.startsWith("x-netacea-")||t.push(a)})),t.join(",")}async function re(e){let t="";try{t=await oe("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty(se,"__esModule",{value:!0}),se.hashCookieNames=se.hashHeaders=se.extractHeaderNames=se.hashString=void 0,se.hashString=oe,se.extractHeaderNames=ne,se.hashHeaders=async function(e){const t=ne(e);return await re(t)},se.hashCookieNames=async function(e){const t=e.join(",");return await re(t)},Object.defineProperty(ie,"__esModule",{value:!0}),ie.RequestAnalyser=void 0;const ce=L,ue=se,pe=z,he=U,de=Q,le=x,ge=u,me=V;async function ye(e){const{headers:t}=e,a=await(0,ue.hashHeaders)(t),i=(0,pe.getHeaderValuesArray)(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await(0,ue.hashCookieNames)(i);return{headerFingerprint:""===a?a:`h_${a.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}ie.RequestAnalyser=class{constructor(e){this.config=e}async getNetaceaRequestDetails(e){var t,a,i;const s=new URL(e.url),o=e.method,n=await this.readCookie(e,this.config.sessionCookieName),r=await this.readCookie(e,this.config.captchaCookieName),c=null!==(t=e.headers.get("cf-connecting-ip"))&&void 0!==t?t:"",{sessionCookieDetails:u,sessionCookieStatus:p,sessionStatus:h,userId:d}=function(e,t,a,i,s){const o=(0,le.checkMitataCookie)(i,s,e.secretKey);if(void 0!==o.userId&&o.isPrimaryHashValid){const i=o.userId,{isExpired:s,shouldExpire:n,isSameIP:r}=o,c=s||n||!r&&e.mitigationType!==ge.NetaceaMitigationType.INGEST?ce.NetaceaSessionCookieStatus.RENEW_SESSION:ce.NetaceaSessionCookieStatus.EXISTING_SESSION,{sessionStatus:u}=(0,de.findBestMitigation)(e.mitigationType,o.protectorCheckCodes,(0,he.isUrlCaptchaPost)(t,a));return{userId:i,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:o}}return{sessionStatus:"",userId:(0,le.generateId)(),sessionCookieStatus:ce.NetaceaSessionCookieStatus.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,s,o,n,c);return{clientIp:c,fingerprints:await ye(e),method:o,protocol:String(null===(a=e.cf)||void 0===a?void 0:a.httpProtocol),url:s,userAgent:null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",sessionDetails:{sessionStatus:h,captchaToken:r,sessionCookieDetails:u,sessionCookieStatus:p,userId:d}}}async readCookie(e,t){var a;const i=e.headers.get("Cookie");if(null==i)return;const s=i.split(/; ?/g),o=`${t}=`;for(const e of s)if(e.startsWith(o)){const i=e.slice(o.length),s=null!==(a=this.config.encryptedCookies)&&void 0!==a?a:[];if(void 0!==this.config.cookieEncryptionKey&&s.includes(t))try{return await(0,me.decrypt)(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}},Object.defineProperty(c,"__esModule",{value:!0});const fe=u,Ce=p,Se=w,ve=E,ke=_(),Ie=x,Ne=L,Te=V,we=U,Ee=z,Ae=F,be=G,_e=W,xe=Y,Pe=Q,Me=ie,Re=o,{configureCookiesDomain:Oe}=fe.lib.cookie.attributes;c.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:a,timeout:i=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=fe.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:u=fe.NetaceaIngestType.HTTP,kinesis:p,logVersion:h,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=a,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=u?u:fe.NetaceaIngestType.HTTP,this.logVersion=null!=h?h:fe.NetaceaLogVersion.V1,this.ingestType===fe.NetaceaIngestType.KINESIS&&(void 0===p?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Ce.default({...p,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,fe.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:S,captchaCookieAttributes:v}=Oe(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=S?S:"",this.netaceaCaptchaCookieAttributes=null!=v?v:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(0,Ie.configureMitataExpiry)(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f,this.requestAnalyser=new Me.RequestAnalyser({cookieEncryptionKey:this.cookieEncryptionKey,encryptedCookies:this.encryptedCookies,mitigationType:this.mitigationType,secretKey:this.secretKey,sessionCookieName:this.netaceaCookieName,captchaCookieName:this.netaceaCaptchaCookieName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=Re.v4());const a=new Request(e.request),i=await this.requestAnalyser.getNetaceaRequestDetails(a);let s=await(0,Ae.timeoutCheck)(this.runMitigation(a,i),this.timeout);return void 0===s&&(s={sessionStatus:"error_open"}),await this.handleResponse(a,s,t)}async inject(e,t){const a=await this.getMitigationResponse(e,t);return{injectHeaders:a.injectHeaders,sessionStatus:a.sessionStatus,setCookie:a.setCookie,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}async mitigate(e,t){const a=await this.getMitigationResponse(e,t);if(a.mitigated){const i=new Headers;if(!await(0,we.isUrlCaptchaGet)(t.url,e.method,this.netaceaCaptchaPath))for(const e of a.setCookie)i.append("set-cookie",e);let s="Forbidden";return"captcha"===a.mitigation&&(void 0!==this.captchaHeader&&i.append(this.captchaHeader.name,this.captchaHeader.value),i.append("content-type","text/html; charset=UTF-8"),s=a.body),{response:new Response(s,{status:403,statusText:"Forbidden",headers:i}),setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}if((0,we.isUrlCaptchaPost)(t.url,e.method)){const e=new Headers;for(const t of a.setCookie)e.append("set-cookie",t);return{response:new Response(a.body,{status:200,statusText:"OK",headers:e}),setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}return{setCookie:a.setCookie,sessionStatus:a.sessionStatus,apiCallLatency:a.apiCallLatency,apiCallStatus:a.apiCallStatus}}async getNetaceaSession(e,t){var a;const i=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=i?i:await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:o,userId:n}=null!==(a=(0,Ie.parseNetaceaSessionCookie)(null!=s?s:""))&&void 0!==a?a:{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:r}=(0,Pe.findBestMitigation)(this.mitigationType,o,(0,we.isUrlCaptchaPost)(new URL(e.url),e.method));return{userId:n,sessionStatus:r,netaceaCookie:s}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){var a,i;""===this.workerInstanceId&&(this.workerInstanceId=Re.v4());const s=this.getResponseDetails(t),{netaceaCookie:o}=await this.getNetaceaSession(e,s.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:(0,Ee.getHeaderValueOrDefault)(s.rawResponse.headers,"content-length","0"),ip:(0,Ee.getHeaderValueOrDefault)(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:null!==(a=n.protocol)&&void 0!==a?a:null,referer:(0,Ee.getHeaderValueOrDefault)(e.headers,"referer"),requestTime:"0",sessionStatus:null!==(i=s.sessionStatus)&&void 0!==i?i:n.sessionDetails.sessionStatus,status:s.rawResponse.status.toString(),userAgent:(0,Ee.getHeaderValueOrDefault)(e.headers,"user-agent","-"),mitataCookie:o,integrationType:Se.name.replace("@netacea/",""),integrationVersion:Se.version,xForwardedFor:(0,Ee.getHeaderValueOrDefault)(e.headers,"x-forwarded-for"),headerFingerprint:n.fingerprints.headerFingerprint,cookieFingerprint:n.fingerprints.cookieFingerprint,integrationMode:this.mitigationType,requestHost:new URL(e.url).hostname,mitigationLatency:s.mitigationLatency,mitigationStatus:s.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,workerInstanceId:this.workerInstanceId})}async handleGetCaptchaRequest(e,t,a){if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const i=await this.makeMitigateAPICall(e,t,!0,a);return{body:i.body,apiCallStatus:i.status,apiCallLatency:i.latency,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:a,headers:i,body:s}){const o=`${e}${a}`,n=new Request(o,{method:t,body:s,headers:i}),r=await(0,ve.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,a){var i,s;if(this.mitigationType===fe.NetaceaMitigationType.MITIGATE&&void 0!==(null==t?void 0:t.response))return{sessionStatus:null!==(i=null==t?void 0:t.sessionStatus)&&void 0!==i?i:"",response:t.response,protectorLatencyMs:null==t?void 0:t.apiCallLatency,protectorStatus:null==t?void 0:t.apiCallStatus};if(this.mitigationType===fe.NetaceaMitigationType.INJECT&&(e=(0,Ee.addHeadersToRequest)(e,t)),this.ingestType===fe.NetaceaIngestType.ORIGIN){const{sessionStatus:a,userId:i}=await this.getNetaceaSession(e,t);(0,be.addIngestOriginHeaders)(e,a,i)}const o=await a(e);return{sessionStatus:null!==(s=null==t?void 0:t.sessionStatus)&&void 0!==s?s:"",response:(0,Ee.addHeadersToResponse)(o,t),protectorLatencyMs:null==t?void 0:t.apiCallLatency,protectorStatus:null==t?void 0:t.apiCallStatus}}async getMitigationResponse(e,t){var a;const i=this.enableDynamicCaptchaContentType?(0,we.getCaptchaPageContentType)(null!==(a=e.headers.get("Accept"))&&void 0!==a?a:void 0):(0,we.getCaptchaPageContentType)();return await this.processMitigateRequest({getBodyFn:async()=>{var t;return null!==(t=await Promise.resolve(e.body))&&void 0!==t?t:void 0},requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){var a;try{switch(this.mitigationType){case fe.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case fe.NetaceaMitigationType.INJECT:return await this.inject(e,t);case fe.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.mitigationType)} not recognised`)}}catch(i){let s,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof _e.ProtectorApiError&&(o=i.latencyMs,s=null===(a=i.protectorApiResponse)||void 0===a?void 0:a.status);return{response:(0,we.isUrlCaptchaPost)(t.url,e.method)?(0,Ae.createErrorResponse)():void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:o,apiCallStatus:s}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const a=`${e}=`;for(const i of t){const t=i.split(";")[0].trimStart();if(t.startsWith(a)){const i=t.slice(a.length);if(void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(e))try{return await(0,Te.decrypt)(i,this.cookieEncryptionKey)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const a of t)if(a.startsWith(e))return await this.readCookie(this.netaceaCookieName,a)}}async getNetaceaCookieFromRequest(e){var t;const a=(0,Ee.getHeaderValueOrDefault)(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=(0,xe.constructWebLog)(this.logVersion,e);if(this.ingestType===fe.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest.bind(this))}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},a=await this.makeIngestApiCall(e,t);if(200!==a.status)throw(0,Ae.APIError)(a)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}async check(e,t){var a,i,s,o;let n,r,c,u,p,h,d,l;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");if([Ne.NetaceaSessionCookieStatus.NEW_SESSION,Ne.NetaceaSessionCookieStatus.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const a=e.sessionDetails.userId,i=await this.makeMitigateAPICall(e,t,!1,null);n=i.status,r=i.match,c=i.mitigate,u=i.captcha,p=i.body,l=i.latency,h=[await this.createMitata(e.clientIp,a,r,c,u,i.mitataMaxAge)],d=i.eventId}else{const t=null===(a=e.sessionDetails.sessionCookieDetails)||void 0===a?void 0:a.protectorCheckCodes;r=null!==(i=null==t?void 0:t.match)&&void 0!==i?i:"0",c=null!==(s=null==t?void 0:t.mitigate)&&void 0!==s?s:"0",u=null!==(o=null==t?void 0:t.captcha)&&void 0!==o?o:"0",p=void 0,h=[]}const g={match:r,mitigate:c,captcha:u};return this.composeResult(p,h,n,g,!1,l,d)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=["1","3","5"].includes(s)||"3"===i?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[a,i,s].join("");let p=(0,Ie.createSessionCookie)(e,t,c,this.secretKey,u);return void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(this.netaceaCookieName)&&(p=await(0,Te.encrypt)(p,this.cookieEncryptionKey)),fe.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:p,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:a,match:i,mitigate:s,captcha:o,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:i,mitigate:s,captcha:o};return this.composeResult(n,r,a,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[ke.dictionary.netaceaHeaders.mitataCaptcha];const a=parseInt(e[ke.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return void 0!==this.cookieEncryptionKey&&this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await(0,Te.encrypt)(t,this.cookieEncryptionKey)),fe.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(a),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const a={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},i=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==Ne.NetaceaSessionCookieStatus.NEW_SESSION&&(a["X-Netacea-UserId"]=i),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(a["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,a["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const s=new URLSearchParams;s.append("headerFP",e.fingerprints.headerFingerprint);const o=Date.now(),n=await this.makeRequest({host:this.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${s.toString()}`,headers:a,method:"POST",body:t,timeout:this.timeout}),r=Date.now()-o;return await this.getApiCallResponseFromResponse(n,e,r)}async getApiCallResponseFromResponse(e,t,a){var i,s;if(200!==e.status)throw new _e.ProtectorApiError(e,a);const o=e.headers[ke.dictionary.netaceaHeaders.match],n=e.headers[ke.dictionary.netaceaHeaders.mitigate],r=e.headers[ke.dictionary.netaceaHeaders.captcha];let c=parseInt(e.headers[ke.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const u=t.sessionDetails.userId,p=[await this.createMitata(t.clientIp,u,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),h=e.headers[ke.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(i=e.headers["content-type"])||void 0===i?void 0:i.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,we.modifyCaptchaJsonResponse)(null!==(s=e.body)&&void 0!==s?s:"",this.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:p,body:e.body,eventId:h,mitataMaxAge:c,latency:a}}async makeMitigateAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:(0,Ee.buildCookieHeader)({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Ne.NetaceaSessionCookieStatus.NEW_SESSION&&(s["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),s["X-Netacea-Captcha-Content-Type"]=t;let o="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),a&&(o="/captcha",null!==i&&n.append("trackingId",i));const r=Date.now(),c=await this.makeRequest({host:this.mitigationServiceUrl,path:`${o}?${n.toString()}`,headers:s,method:"GET",timeout:this.timeout}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,a,i,s,o,n){const r=(0,Pe.findBestMitigation)(this.mitigationType,i,s),c={body:e,apiCallStatus:a,apiCallLatency:o,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[ke.dictionary.mitigationTypes.block,ke.dictionary.mitigationTypes.captcha].includes(r.mitigation)};if(this.mitigationType===fe.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==n&&(e["x-netacea-event-id"]=n),c.injectHeaders=e}return c}async processMitigateRequest(e){var t;if(await(0,we.isUrlCaptchaGet)(e.requestDetails.url,e.requestDetails.method,this.netaceaCaptchaPath)){const t=await(0,we.getTrackingId)(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if((0,we.isUrlCaptchaPost)(e.requestDetails.url,e.requestDetails.method)){const a=null!==(t=await e.getBodyFn())&&void 0!==t?t:"";return await this.processCaptcha(e.requestDetails,a)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(fe.ingestIgnoredIpValue,e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,a=t===Ne.NetaceaSessionCookieStatus.NEW_SESSION,i=t===Ne.NetaceaSessionCookieStatus.RENEW_SESSION;return a||i?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=c;var a=u;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(r);var De=n(r);module.exports=De;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "6.0.13",
3
+ "version": "6.0.15",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -17,10 +17,10 @@
17
17
  },
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "@netacea/kinesisingest": "^1.5.74",
21
- "@netacea/netaceaintegrationbase": "^2.0.56",
20
+ "@netacea/kinesisingest": "^1.5.76",
21
+ "@netacea/netaceaintegrationbase": "^2.0.58",
22
22
  "jose": "^4.11.2",
23
23
  "uuid": "^10.0.0"
24
24
  },
25
- "gitHead": "3631732cf87f8e0abc170bdf03cef29a934d3b01"
25
+ "gitHead": "d60331b35eb04a265668830f0e400072f40b2028"
26
26
  }