@netacea/cloudflare 5.1.89 → 5.1.91

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="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r,c,h,u,p,d={},l={},g={},m={},y={};r=y,Object.defineProperty(r,"__esModule",{value:!0}),r.NetaceaCookieV3IssueReason=r.NetaceaMitigationType=r.NetaceaLogVersion=r.NetaceaIngestType=void 0,(c=r.NetaceaIngestType||(r.NetaceaIngestType={})).ORIGIN="ORIGIN",c.HTTP="HTTP",c.KINESIS="KINESIS",c.NATIVE="NATIVE",(h=r.NetaceaLogVersion||(r.NetaceaLogVersion={})).V1="V1",h.V2="V2",(u=r.NetaceaMitigationType||(r.NetaceaMitigationType={})).MITIGATE="MITIGATE",u.INJECT="INJECT",u.INGEST="INGEST",(p=r.NetaceaCookieV3IssueReason||(r.NetaceaCookieV3IssueReason={})).NO_SESSION="no_session",p.EXPIRED_SESSION="expired_session",p.INVALID_SESSION="invalid_session",p.IP_CHANGE="ip_change";var C={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.netaceaCookieV3KeyDict=e.bestMitigationCaptchaMap=e.bestMitigationMap=e.captchaStatusCodes=e.captchaMap=e.mitigateMap=e.matchMap=e.netaceaHeaders=e.mitigationTypes=e.COOKIEDELIMITER=void 0,e.COOKIEDELIMITER="_/@#/",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_"},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.netaceaCookieV3KeyDict={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"}}(C);var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.checkMitataCookie=f.warmupCookie=f.hexSha256=f.createMitataCookie=f.generateId=f.matchMitataCookie=f.ingestIgnoredIpValue=void 0;const k=e,v=C,I=t;f.ingestIgnoredIpValue="ignored";const S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),T=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function b(e){if(void 0===e)return;const t=e.match(T);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),mitigate:parseInt(r),captcha:parseInt(c)}}}function N(e=16,t=S){const a=k.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function w(e,t){const a=k.createHmac("sha256",t);return a.update(e),I.Buffer.from(a.digest("hex")).toString("base64")}f.matchMitataCookie=b,f.generateId=N,f.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=N());const o=[a,t,w(e+"|"+String(a),i),s].join(v.COOKIEDELIMITER);return`${w(o,i)}${v.COOKIEDELIMITER}${o}`},f.hexSha256=w,f.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"},f.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=b(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(v.COOKIEDELIMITER),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=w(t+"|"+s.expiry,a),c=s.ipHash===r;return{mitata:s,requiresReissue:o||!c,isExpired:o,shouldExpire:n,isSameIP:c,isPrimaryHashValid:s.signature===w(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i};var A={},M={},E={},P={},x=function(e){return new K(e)};function K(e){this.capacity=0|e,this.map=Object.create(null),this.list=new R}function R(){this.firstNode=null,this.lastNode=null}function O(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}K.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},K.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 O(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},K.prototype.used=function(e){this.list.moveToFront(e)},K.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},R.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))},R.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},R.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=P,o=a,n=i,r=e,c=x(1e3);function h(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function u(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function p(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function d(e){return p(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function g(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}g.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},g.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},g.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},g.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"]=u(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)},g.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},g.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},g.prototype.getDate=function(){return this.getDateTime().substr(0,8)},g.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},g.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=h("AWS4"+this.credentials.secretAccessKey,i),t=h(e,this.region),a=h(t,this.service),o=h(a,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},g.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},g.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"]||u(this.request.body||"","hex"),a){var h=Object.keys(a).reduce((function(e,t){return t?(e[d(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),p=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(d).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+d(h[e]))})),s=p.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")},g.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[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")},g.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},g.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},g.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}},g.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}},g.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+p(n.stringify(t))):e},s.RequestSigner=g,s.sign=function(e,t){return new g(e,t).sign()}}();var _={};Object.defineProperty(_,"__esModule",{value:!0}),_.API_VERSION=_.REGION=_.PAYLOAD_TYPE=_.STATE=void 0,_.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},_.PAYLOAD_TYPE="string",_.REGION="eu-west-1",_.API_VERSION="2013-12-02",Object.defineProperty(E,"__esModule",{value:!0});const V=P,H=_;E.default=class{static batchArrayForKinesis(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}static signRequest(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:this.batchArrayForKinesis(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return V.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:H.REGION},{accessKeyId:i,secretAccessKey:s})}},Object.defineProperty(M,"__esModule",{value:!0});const j=E;M.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=j.default.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})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){if(this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize)return await this.putToKinesis(t)}},Object.defineProperty(A,"__esModule",{value:!0});const q=M;A.default=q.default,Object.defineProperty(m,"__esModule",{value:!0}),m.configureMitataExpiry=m.safeParseInt=m.correctTimeout=void 0;const D=y,$=C,U=f,L=A;function G(e){return e<=0?X:e}function z(e,t=0){return isNaN(e)?t:parseInt(e)}m.correctTimeout=G,m.safeParseInt=z;const X=3e3;function F(e,t){return void 0===t?e===D.NetaceaMitigationType.INGEST?3600:60:t}m.configureMitataExpiry=F;m.default=class{constructor({apiKey:e,secretKey:t,timeout:a=X,mitigationServiceUrl:i="https://mitigations.netacea.net",ingestServiceUrl:s="https://ingest.netacea.net",mitigationType:o=D.NetaceaMitigationType.INGEST,captchaSiteKey:n,captchaSecretKey:r,ingestType:c=D.NetaceaIngestType.HTTP,kinesis:h,logVersion:u,mitataCookieExpirySeconds:p,netaceaCookieExpirySeconds:d,netaceaCookieName:l,netaceaCaptchaCookieName:g}){if(this.encryptedCookies=[],null==e)throw new Error("apiKey is a required parameter");this.apiKey=e,this.secretKey=t,this.mitigationServiceUrl=i,this.ingestServiceUrl=s,this.mitigationType=o,this.ingestType=null!=c?c:D.NetaceaIngestType.HTTP,this.logVersion=null!=u?u:D.NetaceaLogVersion.V1,this.ingestType===D.NetaceaIngestType.KINESIS&&(void 0===h?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new L.default({...h,apiKey:this.apiKey})),void 0===n&&void 0===r||(this.captchaSiteKey=n,this.captchaSecretKey=r),this.timeout=G(a),this.netaceaCookieName=null!=l?l:"_mitata",this.netaceaCaptchaCookieName=null!=g?g:"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=F(o,null!=d?d:p)}async runMitigation(e){try{switch(this.mitigationType){case D.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case D.NetaceaMitigationType.INJECT:return await this.inject(e);case D.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return console.error("Netacea FAILOPEN Error:",e),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}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(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===D.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 this.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})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){var l;const g=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const y=s.split("?");y.length>1&&(m=`?${y[1]}`);const C=y[0],f=null===(l=U.matchMitataCookie(h))||void 0===l?void 0:l.userId;return{status:a,method:i,bytes_sent:z(r),referrer:""===n?void 0:n,request:`${i} ${C}${null!=m?m:""} ${o}`,request_time:z(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:m,user_id:f}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){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!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:""}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===D.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i){var s,o;let n,r,c,h,u,p,d;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const l=U.checkMitataCookie(e,t,this.secretKey);if(!l.isPrimaryHashValid||l.requiresReissue){const e=await this.makeMitigateAPICall(null===(s=l.mitata)||void 0===s?void 0:s.userId,t,a,i);n=e.status,r=e.match,c=e.mitigate,h=e.captcha,u=e.body,p=[await this.createMitata(t,null===(o=l.mitata)||void 0===o?void 0:o.userId,r,c,h,e.mitataMaxAge)],d=e.eventId}else n=-1,r=l.match,c=l.mitigate,h=l.captcha,u=void 0,p=[];return this.composeResult(u,p,n,r,c,h,!1,d)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)?-this.mitataCookieExpirySeconds: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 h=[a,i,s].join(""),u=U.createMitataCookie(e,t,c,this.secretKey,h);return await this.buildCookieFromValues(this.netaceaCookieName,u,o,"/")}async processCaptcha(e,t,a,i){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,a,i);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,$.netaceaHeaders.mitataCaptcha)){const t=e[$.netaceaHeaders.mitataCaptcha],a=parseInt(e[$.netaceaHeaders.mitataCaptchaExpiry]),i=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,a);if(void 0!==i)return i}}async makeCaptchaAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=U.matchMitataCookie(e);void 0!==o&&(s["X-Netacea-UserId"]=o.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);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t)}async getApiCallResponseFromResponse(e,t,a){if(200!==e.status)throw this.APIError(e);const i=parseInt(e.headers[$.netaceaHeaders.match]),s=parseInt(e.headers[$.netaceaHeaders.mitigate]),o=parseInt(e.headers[$.netaceaHeaders.captcha]);let n=parseInt(e.headers[$.netaceaHeaders.mitataExpiry]);isNaN(n)&&(n=86400);const r=[await this.createMitata(a,t,i,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),c=e.headers[$.netaceaHeaders.eventId];return{status:e.status,match:i,mitigate:s,captcha:o,setCookie:r,body:e.body,eventId:c,mitataMaxAge:n}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(s["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const o=await this.makeRequest({host:this.mitigationServiceUrl,path:"/",headers:s,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(o,e,t)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[$.mitigationTypes.block,$.mitigationTypes.captcha,$.mitigationTypes.captchaPass].includes(c.mitigation)};if(this.mitigationType===D.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=$.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=$.mitigateMap[t])&&void 0!==o?o:r;let h=$.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=$.captchaMap[a])&&void 0!==n?n:r);const e=$.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===D.NetaceaMitigationType.INJECT&&(h=$.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){const t=this.isUrlCaptchaPost(e.url,e.method);return await(t?this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):this.check(e.mitata,e.clientIp,e.userAgent,e.mitataCaptcha))}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(U.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=U.checkMitataCookie(i,U.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async encryptCookieValue(e){return e}async decryptCookieValue(e){return e}};var W={};Object.defineProperty(W,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.defaultInvalidResponse=B.matchNetaceaCookieV3=B.checkNetaceaCookieV3=B.cookieIsNetaceaV3Format=B.createNetaceaCookieV3=void 0;const Y=C;function J(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:""};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i),o=Object.keys(Y.netaceaCookieV3KeyDict).find((e=>Y.netaceaCookieV3KeyDict[e]===t));let n=+s;isNaN(n)&&(n=s),a[o]=n}return a}function Z(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0}}B.createNetaceaCookieV3=function(e){return Object.entries(e).map((([e,t])=>`${Y.netaceaCookieV3KeyDict[e]}=${encodeURIComponent(t)}`)).join("&")},B.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).every((e=>Object.values(Y.netaceaCookieV3KeyDict).includes(e)))},B.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return Z();const a=J(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:[1,3,5].includes(a.captcha),isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha}}return Z()},B.matchNetaceaCookieV3=J,B.defaultInvalidResponse=Z;var Q={},ee={};function te(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?null==a?void 0:a.replace(`${t}=`,""):void 0}function ae(e,t=!1){if(""===e)return"";return e.replace(/ /g,"").split(";").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).filter(((e,a,i)=>{const s=e=>e.split("=")[0],o=s(e),n=i.map(s);return t?a===n.lastIndexOf(o):a===n.indexOf(o)})).join("; ")}Object.defineProperty(ee,"__esModule",{value:!0}),ee.removeDuplicateAttrs=ee.extractCookieAttr=ee.extractAndRemoveCookieAttr=ee.configureCookiesDomain=void 0,ee.configureCookiesDomain=function(e,t){let a=e=ae(null!=e?e:"",!0),i=t=ae(null!=t?t:"",!0);if(void 0!==e&&void 0!==t){const s=te(e,"Domain"),o=te(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=te(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=te(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},ee.extractAndRemoveCookieAttr=function(e,t){const a=te(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}},ee.extractCookieAttr=te,ee.removeDuplicateAttrs=ae,Object.defineProperty(Q,"__esModule",{value:!0}),Q.lib=void 0;const ie=ee;Q.lib={cookieAttributes:ie},function(e){var t=o&&o.__createBinding||(Object.create?function(e,t,a,i){void 0===i&&(i=a),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,i){void 0===i&&(i=a),e[i]=t[a]}),a=o&&o.__exportStar||function(e,a){for(var i in e)"default"===i||a.hasOwnProperty(i)||t(a,e,i)};Object.defineProperty(e,"__esModule",{value:!0});const i=m;a(m,e),a(y,e),a(W,e);var s=f;Object.defineProperty(e,"matchMitataCookie",{enumerable:!0,get:function(){return s.matchMitataCookie}}),Object.defineProperty(e,"checkMitataCookie",{enumerable:!0,get:function(){return s.checkMitataCookie}}),Object.defineProperty(e,"createMitataCookie",{enumerable:!0,get:function(){return s.createMitataCookie}}),Object.defineProperty(e,"generateId",{enumerable:!0,get:function(){return s.generateId}}),Object.defineProperty(e,"hexSha256",{enumerable:!0,get:function(){return s.hexSha256}}),Object.defineProperty(e,"ingestIgnoredIpValue",{enumerable:!0,get:function(){return s.ingestIgnoredIpValue}}),Object.defineProperty(e,"warmupCookie",{enumerable:!0,get:function(){return s.warmupCookie}});var n=B;Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return n.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return n.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return n.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return n.checkNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return n.defaultInvalidResponse}}),e.dictionary=C;var r=Q;Object.defineProperty(e,"lib",{enumerable:!0,get:function(){return r.lib}}),e.default=i.default}(g);var se={name:"@netacea/cloudflare",version:"5.1.89",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":"npx nyc tape -r ts-node/register -r tsconfig-paths/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './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:"npx tsc --project tsconfig.build.json && npm run rollup"},author:"Jack Scotson <jack.scotson@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.4.88","@netacea/netaceaintegrationbase":"^1.16.87",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.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",chai:"^4.3.7",eslint:"^6.8.0",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","ts-node":"^10.9.1","tsconfig-paths":"^4.2.0",typescript:"^5.2.2"},gitHead:"f494ba6fe9f9f49e477604c2fceef82db0cdbb49"},oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.fetch=void 0,oe.fetch=globalThis.fetch.bind(globalThis);var ne={};Object.defineProperty(ne,"__esModule",{value:!0}),ne.decrypt=ne.encrypt=void 0;const re=s;ne.encrypt=async function(e,t){const a=re.base64url.decode(t),i=(new TextEncoder).encode(e);return await new re.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},ne.decrypt=async function(e,t){const a=re.base64url.decode(t),{plaintext:i}=await re.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.isUrlCaptchaGet=ce.getTrackingId=ce.modifyCaptchaJsonResponse=ce.getCaptchaPageContentType=void 0,ce.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"},ce.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}`})},ce.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},ce.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||!Boolean(a))return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=new URL(e);return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()},Object.defineProperty(l,"__esModule",{value:!0});const he=g,ue=A,pe=se,de=oe,le=ne,ge=ce,{configureCookiesDomain:me,extractAndRemoveCookieAttr:ye,removeDuplicateAttrs:Ce}=he.lib.cookieAttributes;l.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=he.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=he.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:C,netaceaCaptchaPath:f}=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!=h?h:he.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:he.NetaceaLogVersion.V1,this.ingestType===he.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new ue.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,he.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:k,captchaCookieAttributes:v}=me(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=k?k:"",this.netaceaCaptchaCookieAttributes=null!=v?v:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===he.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(f)&&"string"==typeof f&&(this.netaceaCaptchaPath=f.startsWith("/")?f:`/${f}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=C}async run(e,t){const a=await this.timeoutCheck(this.runMitigation(e.request),this.timeout);return await this.handleResponse(e.request,a,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const a=new Headers;if(!await(0,ge.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)a.append("set-cookie",e);let i="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&a.append(this.captchaHeader.name,this.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),i=t.body),{response:new Response(i,{status:403,statusText:"Forbidden",headers:a}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const a of t.setCookie)e.append("set-cookie",a);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async ingest(e,t){var a,i,s;const o=null!==(a=await this.getNetaceaCookieFromResponse(t))&&void 0!==a?a:await this.getNetaceaCookieFromRequest(e),{match:n,mitigate:r,captcha:c}=null!==(i=(0,he.matchMitataCookie)(null!=o?o:""))&&void 0!==i?i:{match:0,mitigate:0,captcha:0},{sessionStatus:h}=this.findBestMitigation(n,r,c,this.isUrlCaptchaPost(e.url,e.method)),u=String(null===(s=e.cf)||void 0===s?void 0:s.httpProtocol);return await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip",""),method:e.method,path:new URL(e.url).pathname,protocol:u,referer:this.getHeaderValueOrDefault(e.headers,"referer",""),requestTime:"0",sessionStatus:h,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:o,integrationType:pe.name.replace("@netacea/",""),integrationVersion:pe.version})}async handleGetCaptchaRequest(e,t,a,i,s,o,n){var r;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const c=(0,he.checkMitataCookie)(e,t,this.secretKey),h=await this.makeMitigateAPICall(null===(r=c.mitata)||void 0===r?void 0:r.userId,t,a,n,i,!0,s,o);return{body:h.body,apiCallStatus:h.status,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,de.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(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})}addHeadersToRequest(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})}async handleResponse(e,t,a){if(void 0!==t)if(this.mitigationType===he.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===he.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));const i=await a(e);return this.addHeadersToResponse(i,t)}getHeaderValueOrDefault(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a}async getMitigationResponse(e){var t,a,i,s;const o=e.headers.get("cookie"),n=null!==(t=await this.readCookie(this.netaceaCookieName,o))&&void 0!==t?t:"",r=await this.readCookie(this.netaceaCaptchaCookieName,o),c=null!==(a=e.headers.get("cf-connecting-ip"))&&void 0!==a?a:"",h=null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",u=this.enableDynamicCaptchaContentType?(0,ge.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ge.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:c,getBodyFn:async()=>await Promise.resolve(e.body),method:e.method,mitata:n,mitataCaptcha:r,url:e.url,userAgent:h,captchaPageContentType:u})}async timeoutCheck(e,t){return await Promise.race([e,new Promise(((e,a)=>{setTimeout((()=>e(void 0)),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,le.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,le.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case he.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case he.NetaceaMitigationType.INJECT:return await this.inject(e);case he.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}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(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){const t=e.headers.getSetCookie(),a=`${this.netaceaCookieName}=`;for(const e of t)if(e.startsWith(a))return await this.readCookie(this.netaceaCookieName,e)}async getNetaceaCookieFromRequest(e){var t;const a=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===he.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)}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 this.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})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){var l;const g=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const y=s.split("?");y.length>1&&(m=`?${y[1]}`);const C=y[0],f=null===(l=(0,he.matchMitataCookie)(h))||void 0===l?void 0:l.userId;return{status:a,method:i,bytes_sent:(0,he.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${C}${null!=m?m:""} ${o}`,request_time:(0,he.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:m,user_id:f}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){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!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:""}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===he.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i,s,o){var n,r;let c,h,u,p,d,l,g;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const m=(0,he.checkMitataCookie)(e,t,this.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=m.mitata)||void 0===n?void 0:n.userId,t,a,o,i,!1,null,s);c=e.status,h=e.match,u=e.mitigate,p=e.captcha,d=e.body,l=[await this.createMitata(t,null===(r=m.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],g=e.eventId}else c=-1,h=m.match,u=m.mitigate,p=m.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,g)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)?-this.mitataCookieExpirySeconds: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.");let h=this.netaceaCookieAttributes,u=o;if(""!==h){const{extractedAttribute:e,cookieAttributes:t}=ye(h,"Max-Age");void 0!==e&&(u=parseInt(e,10)),h=t}const p=[a,i,s].join(""),d=(0,he.createMitataCookie)(e,t,c,this.secretKey,p),l=await this.buildCookieFromValues(this.netaceaCookieName,d,u,"/");return Ce(l+(""!==h?`; ${h}`:""),!0)}async processCaptcha(e,t,a,i){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,a,i);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,he.dictionary.netaceaHeaders.mitataCaptcha)){const t=e[he.dictionary.netaceaHeaders.mitataCaptcha],a=parseInt(e[he.dictionary.netaceaHeaders.mitataCaptchaExpiry]);let i,s=this.netaceaCaptchaCookieAttributes;if(""!==s){const{extractedAttribute:e,cookieAttributes:t}=ye(s,"Max-Age");void 0!==e&&(i=parseInt(e)),s=t}const o=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,null!=i?i:a);if(void 0!==o){return Ce(o+(""!==s?`; ${s}`:""),!0)}}}async makeCaptchaAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=(0,he.matchMitataCookie)(e);void 0!==o&&(s["X-Netacea-UserId"]=o.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);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t,"")}async getApiCallResponseFromResponse(e,t,a,i){var s;if(200!==e.status)throw this.APIError(e);const o=parseInt(e.headers[he.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[he.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[he.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[he.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(a,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[he.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,ge.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,i)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:u,mitataMaxAge:c}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i,s,o,n,r){const c={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(c["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),c["X-Netacea-Captcha-Content-Type"]=s;const h=await this.makeRequest({host:this.mitigationServiceUrl,path:o?"/captcha"+(null!==n?`?trackingId=${n}`:""):"/",headers:c,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(h,e,t,r)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[he.dictionary.mitigationTypes.block,he.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===he.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=he.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=he.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=he.dictionary.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=he.dictionary.captchaMap[a])&&void 0!==n?n:r);const e=he.dictionary.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===he.NetaceaMitigationType.INJECT&&(h=he.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){if(await(0,ge.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ge.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.url,e.mitataCaptcha)}return this.isUrlCaptchaPost(e.url,e.method)?await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(he.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=(0,he.checkMitataCookie)(i,he.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=l;var a=g;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(d);var fe=n(d);module.exports=fe;
1
+ "use strict";var e=require("crypto"),t=require("buffer"),a=require("url"),i=require("querystring"),s=require("jose"),o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r,c,h,u,p,d={},l={},g={},m={},y={};r=y,Object.defineProperty(r,"__esModule",{value:!0}),r.NetaceaCookieV3IssueReason=r.NetaceaMitigationType=r.NetaceaLogVersion=r.NetaceaIngestType=void 0,(c=r.NetaceaIngestType||(r.NetaceaIngestType={})).ORIGIN="ORIGIN",c.HTTP="HTTP",c.KINESIS="KINESIS",c.NATIVE="NATIVE",(h=r.NetaceaLogVersion||(r.NetaceaLogVersion={})).V1="V1",h.V2="V2",(u=r.NetaceaMitigationType||(r.NetaceaMitigationType={})).MITIGATE="MITIGATE",u.INJECT="INJECT",u.INGEST="INGEST",(p=r.NetaceaCookieV3IssueReason||(r.NetaceaCookieV3IssueReason={})).NO_SESSION="no_session",p.EXPIRED_SESSION="expired_session",p.INVALID_SESSION="invalid_session",p.IP_CHANGE="ip_change";var C={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.netaceaCookieV3KeyDict=e.bestMitigationCaptchaMap=e.bestMitigationMap=e.captchaStatusCodes=e.captchaMap=e.mitigateMap=e.matchMap=e.netaceaHeaders=e.mitigationTypes=e.COOKIEDELIMITER=void 0,e.COOKIEDELIMITER="_/@#/",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_"},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.netaceaCookieV3KeyDict={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"}}(C);var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.checkMitataCookie=f.warmupCookie=f.hexSha256=f.createMitataCookie=f.generateId=f.matchMitataCookie=f.ingestIgnoredIpValue=void 0;const k=e,v=C,I=t;f.ingestIgnoredIpValue="ignored";const S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),T=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function b(e){if(void 0===e)return;const t=e.match(T);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),mitigate:parseInt(r),captcha:parseInt(c)}}}function N(e=16,t=S){const a=k.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function w(e,t){const a=k.createHmac("sha256",t);return a.update(e),I.Buffer.from(a.digest("hex")).toString("base64")}f.matchMitataCookie=b,f.generateId=N,f.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=N());const o=[a,t,w(e+"|"+String(a),i),s].join(v.COOKIEDELIMITER);return`${w(o,i)}${v.COOKIEDELIMITER}${o}`},f.hexSha256=w,f.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"},f.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=b(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(v.COOKIEDELIMITER),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=w(t+"|"+s.expiry,a),c=s.ipHash===r;return{mitata:s,requiresReissue:o||!c,isExpired:o,shouldExpire:n,isSameIP:c,isPrimaryHashValid:s.signature===w(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i};var A={},M={},E={},P={},x=function(e){return new K(e)};function K(e){this.capacity=0|e,this.map=Object.create(null),this.list=new R}function R(){this.firstNode=null,this.lastNode=null}function O(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}K.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},K.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 O(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},K.prototype.used=function(e){this.list.moveToFront(e)},K.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},R.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))},R.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},R.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=P,o=a,n=i,r=e,c=x(1e3);function h(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function u(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function p(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function d(e){return p(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function g(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}g.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},g.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},g.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},g.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"]=u(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)},g.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},g.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},g.prototype.getDate=function(){return this.getDateTime().substr(0,8)},g.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},g.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=h("AWS4"+this.credentials.secretAccessKey,i),t=h(e,this.region),a=h(t,this.service),o=h(a,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},g.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},g.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"]||u(this.request.body||"","hex"),a){var h=Object.keys(a).reduce((function(e,t){return t?(e[d(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),p=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(d).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+d(h[e]))})),s=p.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")},g.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[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")},g.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},g.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},g.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}},g.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}},g.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+p(n.stringify(t))):e},s.RequestSigner=g,s.sign=function(e,t){return new g(e,t).sign()}}();var _={};Object.defineProperty(_,"__esModule",{value:!0}),_.API_VERSION=_.REGION=_.PAYLOAD_TYPE=_.STATE=void 0,_.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},_.PAYLOAD_TYPE="string",_.REGION="eu-west-1",_.API_VERSION="2013-12-02",Object.defineProperty(E,"__esModule",{value:!0});const V=P,H=_;E.default=class{static batchArrayForKinesis(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}static signRequest(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:this.batchArrayForKinesis(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return V.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:H.REGION},{accessKeyId:i,secretAccessKey:s})}},Object.defineProperty(M,"__esModule",{value:!0});const j=E;M.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=j.default.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})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){if(this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize)return await this.putToKinesis(t)}},Object.defineProperty(A,"__esModule",{value:!0});const q=M;A.default=q.default,Object.defineProperty(m,"__esModule",{value:!0}),m.configureMitataExpiry=m.safeParseInt=m.correctTimeout=void 0;const D=y,$=C,U=f,L=A;function G(e){return e<=0?X:e}function z(e,t=0){return isNaN(e)?t:parseInt(e)}m.correctTimeout=G,m.safeParseInt=z;const X=3e3;function F(e,t){return void 0===t?e===D.NetaceaMitigationType.INGEST?3600:60:t}m.configureMitataExpiry=F;m.default=class{constructor({apiKey:e,secretKey:t,timeout:a=X,mitigationServiceUrl:i="https://mitigations.netacea.net",ingestServiceUrl:s="https://ingest.netacea.net",mitigationType:o=D.NetaceaMitigationType.INGEST,captchaSiteKey:n,captchaSecretKey:r,ingestType:c=D.NetaceaIngestType.HTTP,kinesis:h,logVersion:u,mitataCookieExpirySeconds:p,netaceaCookieExpirySeconds:d,netaceaCookieName:l,netaceaCaptchaCookieName:g}){if(this.encryptedCookies=[],null==e)throw new Error("apiKey is a required parameter");this.apiKey=e,this.secretKey=t,this.mitigationServiceUrl=i,this.ingestServiceUrl=s,this.mitigationType=o,this.ingestType=null!=c?c:D.NetaceaIngestType.HTTP,this.logVersion=null!=u?u:D.NetaceaLogVersion.V1,this.ingestType===D.NetaceaIngestType.KINESIS&&(void 0===h?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new L.default({...h,apiKey:this.apiKey})),void 0===n&&void 0===r||(this.captchaSiteKey=n,this.captchaSecretKey=r),this.timeout=G(a),this.netaceaCookieName=null!=l?l:"_mitata",this.netaceaCaptchaCookieName=null!=g?g:"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=F(o,null!=d?d:p)}async runMitigation(e){try{switch(this.mitigationType){case D.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case D.NetaceaMitigationType.INJECT:return await this.inject(e);case D.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return console.error("Netacea FAILOPEN Error:",e),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}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(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===D.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 this.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})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){var l;const g=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const y=s.split("?");y.length>1&&(m=`?${y[1]}`);const C=y[0],f=null===(l=U.matchMitataCookie(h))||void 0===l?void 0:l.userId;return{status:a,method:i,bytes_sent:z(r),referrer:""===n?void 0:n,request:`${i} ${C}${null!=m?m:""} ${o}`,request_time:z(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:m,user_id:f}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){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!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:""}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===D.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i){var s,o;let n,r,c,h,u,p,d;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const l=U.checkMitataCookie(e,t,this.secretKey);if(!l.isPrimaryHashValid||l.requiresReissue){const e=await this.makeMitigateAPICall(null===(s=l.mitata)||void 0===s?void 0:s.userId,t,a,i);n=e.status,r=e.match,c=e.mitigate,h=e.captcha,u=e.body,p=[await this.createMitata(t,null===(o=l.mitata)||void 0===o?void 0:o.userId,r,c,h,e.mitataMaxAge)],d=e.eventId}else n=-1,r=l.match,c=l.mitigate,h=l.captcha,u=void 0,p=[];return this.composeResult(u,p,n,r,c,h,!1,d)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)?-this.mitataCookieExpirySeconds: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 h=[a,i,s].join(""),u=U.createMitataCookie(e,t,c,this.secretKey,h);return await this.buildCookieFromValues(this.netaceaCookieName,u,o,"/")}async processCaptcha(e,t,a,i){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,a,i);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,$.netaceaHeaders.mitataCaptcha)){const t=e[$.netaceaHeaders.mitataCaptcha],a=parseInt(e[$.netaceaHeaders.mitataCaptchaExpiry]),i=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,a);if(void 0!==i)return i}}async makeCaptchaAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=U.matchMitataCookie(e);void 0!==o&&(s["X-Netacea-UserId"]=o.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);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t)}async getApiCallResponseFromResponse(e,t,a){if(200!==e.status)throw this.APIError(e);const i=parseInt(e.headers[$.netaceaHeaders.match]),s=parseInt(e.headers[$.netaceaHeaders.mitigate]),o=parseInt(e.headers[$.netaceaHeaders.captcha]);let n=parseInt(e.headers[$.netaceaHeaders.mitataExpiry]);isNaN(n)&&(n=86400);const r=[await this.createMitata(a,t,i,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),c=e.headers[$.netaceaHeaders.eventId];return{status:e.status,match:i,mitigate:s,captcha:o,setCookie:r,body:e.body,eventId:c,mitataMaxAge:n}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(s["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const o=await this.makeRequest({host:this.mitigationServiceUrl,path:"/",headers:s,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(o,e,t)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[$.mitigationTypes.block,$.mitigationTypes.captcha,$.mitigationTypes.captchaPass].includes(c.mitigation)};if(this.mitigationType===D.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=$.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=$.mitigateMap[t])&&void 0!==o?o:r;let h=$.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=$.captchaMap[a])&&void 0!==n?n:r);const e=$.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===D.NetaceaMitigationType.INJECT&&(h=$.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){const t=this.isUrlCaptchaPost(e.url,e.method);return await(t?this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):this.check(e.mitata,e.clientIp,e.userAgent,e.mitataCaptcha))}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(U.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=U.checkMitataCookie(i,U.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async encryptCookieValue(e){return e}async decryptCookieValue(e){return e}};var W={};Object.defineProperty(W,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.defaultInvalidResponse=B.matchNetaceaCookieV3=B.checkNetaceaCookieV3=B.cookieIsNetaceaV3Format=B.createNetaceaCookieV3=void 0;const Y=C;function J(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:""};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i),o=Object.keys(Y.netaceaCookieV3KeyDict).find((e=>Y.netaceaCookieV3KeyDict[e]===t));let n=+s;isNaN(n)&&(n=s),a[o]=n}return a}function Z(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0}}B.createNetaceaCookieV3=function(e){return Object.entries(e).map((([e,t])=>`${Y.netaceaCookieV3KeyDict[e]}=${encodeURIComponent(t)}`)).join("&")},B.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).every((e=>Object.values(Y.netaceaCookieV3KeyDict).includes(e)))},B.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return Z();const a=J(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:[1,3,5].includes(a.captcha),isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha}}return Z()},B.matchNetaceaCookieV3=J,B.defaultInvalidResponse=Z;var Q={},ee={};function te(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?null==a?void 0:a.replace(`${t}=`,""):void 0}function ae(e,t=!1){if(""===e)return"";return e.replace(/ /g,"").split(";").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).filter(((e,a,i)=>{const s=e=>e.split("=")[0],o=s(e),n=i.map(s);return t?a===n.lastIndexOf(o):a===n.indexOf(o)})).join("; ")}Object.defineProperty(ee,"__esModule",{value:!0}),ee.removeDuplicateAttrs=ee.extractCookieAttr=ee.extractAndRemoveCookieAttr=ee.configureCookiesDomain=void 0,ee.configureCookiesDomain=function(e,t){let a=e=ae(null!=e?e:"",!0),i=t=ae(null!=t?t:"",!0);if(void 0!==e&&void 0!==t){const s=te(e,"Domain"),o=te(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=te(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=te(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},ee.extractAndRemoveCookieAttr=function(e,t){const a=te(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}},ee.extractCookieAttr=te,ee.removeDuplicateAttrs=ae,Object.defineProperty(Q,"__esModule",{value:!0}),Q.lib=void 0;const ie=ee;Q.lib={cookieAttributes:ie},function(e){var t=o&&o.__createBinding||(Object.create?function(e,t,a,i){void 0===i&&(i=a),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,i){void 0===i&&(i=a),e[i]=t[a]}),a=o&&o.__exportStar||function(e,a){for(var i in e)"default"===i||a.hasOwnProperty(i)||t(a,e,i)};Object.defineProperty(e,"__esModule",{value:!0});const i=m;a(m,e),a(y,e),a(W,e);var s=f;Object.defineProperty(e,"matchMitataCookie",{enumerable:!0,get:function(){return s.matchMitataCookie}}),Object.defineProperty(e,"checkMitataCookie",{enumerable:!0,get:function(){return s.checkMitataCookie}}),Object.defineProperty(e,"createMitataCookie",{enumerable:!0,get:function(){return s.createMitataCookie}}),Object.defineProperty(e,"generateId",{enumerable:!0,get:function(){return s.generateId}}),Object.defineProperty(e,"hexSha256",{enumerable:!0,get:function(){return s.hexSha256}}),Object.defineProperty(e,"ingestIgnoredIpValue",{enumerable:!0,get:function(){return s.ingestIgnoredIpValue}}),Object.defineProperty(e,"warmupCookie",{enumerable:!0,get:function(){return s.warmupCookie}});var n=B;Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return n.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return n.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return n.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return n.checkNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return n.defaultInvalidResponse}}),e.dictionary=C;var r=Q;Object.defineProperty(e,"lib",{enumerable:!0,get:function(){return r.lib}}),e.default=i.default}(g);var se={name:"@netacea/cloudflare",version:"5.1.91",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":"npx nyc tape -r ts-node/register -r tsconfig-paths/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './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:"npx tsc --project tsconfig.build.json && npm run rollup"},author:"Jack Scotson <jack.scotson@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.4.90","@netacea/netaceaintegrationbase":"^1.16.89",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.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",chai:"^4.3.7",eslint:"^6.8.0",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","ts-node":"^10.9.1","tsconfig-paths":"^4.2.0",typescript:"^5.2.2"},gitHead:"46a0ac398cf40694cc00b8407f06a1991966c9bd"},oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.fetch=void 0,oe.fetch=globalThis.fetch.bind(globalThis);var ne={};Object.defineProperty(ne,"__esModule",{value:!0}),ne.decrypt=ne.encrypt=void 0;const re=s;ne.encrypt=async function(e,t){const a=re.base64url.decode(t),i=(new TextEncoder).encode(e);return await new re.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},ne.decrypt=async function(e,t){const a=re.base64url.decode(t),{plaintext:i}=await re.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.isUrlCaptchaGet=ce.getTrackingId=ce.modifyCaptchaJsonResponse=ce.getCaptchaPageContentType=void 0,ce.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"},ce.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}`})},ce.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},ce.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||!Boolean(a))return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=new URL(e);return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()},Object.defineProperty(l,"__esModule",{value:!0});const he=g,ue=A,pe=se,de=oe,le=ne,ge=ce,{configureCookiesDomain:me,extractAndRemoveCookieAttr:ye,removeDuplicateAttrs:Ce}=he.lib.cookieAttributes;l.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=he.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=he.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:C,netaceaCaptchaPath:f}=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!=h?h:he.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:he.NetaceaLogVersion.V1,this.ingestType===he.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new ue.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,he.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:k,captchaCookieAttributes:v}=me(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=k?k:"",this.netaceaCaptchaCookieAttributes=null!=v?v:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===he.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(f)&&"string"==typeof f&&(this.netaceaCaptchaPath=f.startsWith("/")?f:`/${f}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=C}async run(e,t){const a=await this.timeoutCheck(this.runMitigation(e.request),this.timeout);return await this.handleResponse(e.request,a,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const a=new Headers;if(!await(0,ge.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)a.append("set-cookie",e);let i="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&a.append(this.captchaHeader.name,this.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),i=t.body),{response:new Response(i,{status:403,statusText:"Forbidden",headers:a}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const a of t.setCookie)e.append("set-cookie",a);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async ingest(e,t){var a,i,s;const o=null!==(a=await this.getNetaceaCookieFromResponse(t))&&void 0!==a?a:await this.getNetaceaCookieFromRequest(e),{match:n,mitigate:r,captcha:c}=null!==(i=(0,he.matchMitataCookie)(null!=o?o:""))&&void 0!==i?i:{match:0,mitigate:0,captcha:0},{sessionStatus:h}=this.findBestMitigation(n,r,c,this.isUrlCaptchaPost(e.url,e.method)),u=String(null===(s=e.cf)||void 0===s?void 0:s.httpProtocol);return await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip",""),method:e.method,path:new URL(e.url).pathname,protocol:u,referer:this.getHeaderValueOrDefault(e.headers,"referer",""),requestTime:"0",sessionStatus:h,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:o,integrationType:pe.name.replace("@netacea/",""),integrationVersion:pe.version})}async handleGetCaptchaRequest(e,t,a,i,s,o,n){var r;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const c=(0,he.checkMitataCookie)(e,t,this.secretKey),h=await this.makeMitigateAPICall(null===(r=c.mitata)||void 0===r?void 0:r.userId,t,a,n,i,!0,s,o);return{body:h.body,apiCallStatus:h.status,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,de.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(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})}addHeadersToRequest(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})}async handleResponse(e,t,a){if(void 0!==t)if(this.mitigationType===he.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===he.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));const i=await a(e);return this.addHeadersToResponse(i,t)}getHeaderValueOrDefault(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a}async getMitigationResponse(e){var t,a,i,s;const o=e.headers.get("cookie"),n=null!==(t=await this.readCookie(this.netaceaCookieName,o))&&void 0!==t?t:"",r=await this.readCookie(this.netaceaCaptchaCookieName,o),c=null!==(a=e.headers.get("cf-connecting-ip"))&&void 0!==a?a:"",h=null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",u=this.enableDynamicCaptchaContentType?(0,ge.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ge.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:c,getBodyFn:async()=>await Promise.resolve(e.body),method:e.method,mitata:n,mitataCaptcha:r,url:e.url,userAgent:h,captchaPageContentType:u})}async timeoutCheck(e,t){return await Promise.race([e,new Promise(((e,a)=>{setTimeout((()=>e(void 0)),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,le.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,le.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case he.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case he.NetaceaMitigationType.INJECT:return await this.inject(e);case he.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}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(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){const t=e.headers.getSetCookie(),a=`${this.netaceaCookieName}=`;for(const e of t)if(e.startsWith(a))return await this.readCookie(this.netaceaCookieName,e)}async getNetaceaCookieFromRequest(e){var t;const a=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===he.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)}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 this.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})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){var l;const g=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const y=s.split("?");y.length>1&&(m=`?${y[1]}`);const C=y[0],f=null===(l=(0,he.matchMitataCookie)(h))||void 0===l?void 0:l.userId;return{status:a,method:i,bytes_sent:(0,he.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${C}${null!=m?m:""} ${o}`,request_time:(0,he.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:m,user_id:f}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){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!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:""}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===he.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i,s,o){var n,r;let c,h,u,p,d,l,g;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const m=(0,he.checkMitataCookie)(e,t,this.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=m.mitata)||void 0===n?void 0:n.userId,t,a,o,i,!1,null,s);c=e.status,h=e.match,u=e.mitigate,p=e.captcha,d=e.body,l=[await this.createMitata(t,null===(r=m.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],g=e.eventId}else c=-1,h=m.match,u=m.mitigate,p=m.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,g)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)?-this.mitataCookieExpirySeconds: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.");let h=this.netaceaCookieAttributes,u=o;if(""!==h){const{extractedAttribute:e,cookieAttributes:t}=ye(h,"Max-Age");void 0!==e&&(u=parseInt(e,10)),h=t}const p=[a,i,s].join(""),d=(0,he.createMitataCookie)(e,t,c,this.secretKey,p),l=await this.buildCookieFromValues(this.netaceaCookieName,d,u,"/");return Ce(l+(""!==h?`; ${h}`:""),!0)}async processCaptcha(e,t,a,i){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,a,i);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,he.dictionary.netaceaHeaders.mitataCaptcha)){const t=e[he.dictionary.netaceaHeaders.mitataCaptcha],a=parseInt(e[he.dictionary.netaceaHeaders.mitataCaptchaExpiry]);let i,s=this.netaceaCaptchaCookieAttributes;if(""!==s){const{extractedAttribute:e,cookieAttributes:t}=ye(s,"Max-Age");void 0!==e&&(i=parseInt(e)),s=t}const o=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,null!=i?i:a);if(void 0!==o){return Ce(o+(""!==s?`; ${s}`:""),!0)}}}async makeCaptchaAPICall(e,t,a,i){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=(0,he.matchMitataCookie)(e);void 0!==o&&(s["X-Netacea-UserId"]=o.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);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t,"")}async getApiCallResponseFromResponse(e,t,a,i){var s;if(200!==e.status)throw this.APIError(e);const o=parseInt(e.headers[he.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[he.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[he.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[he.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(a,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[he.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,ge.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,i)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:u,mitataMaxAge:c}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i,s,o,n,r){const c={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(c["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),c["X-Netacea-Captcha-Content-Type"]=s;const h=await this.makeRequest({host:this.mitigationServiceUrl,path:o?"/captcha"+(null!==n?`?trackingId=${n}`:""):"/",headers:c,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(h,e,t,r)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[he.dictionary.mitigationTypes.block,he.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===he.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=he.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=he.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=he.dictionary.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=he.dictionary.captchaMap[a])&&void 0!==n?n:r);const e=he.dictionary.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===he.NetaceaMitigationType.INJECT&&(h=he.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){if(await(0,ge.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ge.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.url,e.mitataCaptcha)}return this.isUrlCaptchaPost(e.url,e.method)?await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(he.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=(0,he.checkMitataCookie)(i,he.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=l;var a=g;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(d);var fe=n(d);module.exports=fe;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "5.1.89",
3
+ "version": "5.1.91",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -23,8 +23,8 @@
23
23
  },
24
24
  "license": "ISC",
25
25
  "dependencies": {
26
- "@netacea/kinesisingest": "^1.4.88",
27
- "@netacea/netaceaintegrationbase": "^1.16.87",
26
+ "@netacea/kinesisingest": "^1.4.90",
27
+ "@netacea/netaceaintegrationbase": "^1.16.89",
28
28
  "jose": "^4.11.2"
29
29
  },
30
30
  "devDependencies": {
@@ -56,5 +56,5 @@
56
56
  "tsconfig-paths": "^4.2.0",
57
57
  "typescript": "^5.2.2"
58
58
  },
59
- "gitHead": "f494ba6fe9f9f49e477604c2fceef82db0cdbb49"
59
+ "gitHead": "46a0ac398cf40694cc00b8407f06a1991966c9bd"
60
60
  }