@netacea/cloudflare 5.2.14 → 5.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +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={},y={},g={},m={};r=m,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.netaceaSettingsMap=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=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.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},e.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},e.netaceaSettingsMap={checkAllPostRequests:"checkAllPostRequests"}}(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 y(e,t){"string"==typeof e&&(e=o.parse(e));var a=e.headers=e.headers||{},i=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||a.Host||a.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||i[0]||"",this.region=e.region||i[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),a.Host||a.host||(a.Host=e.hostname||e.host||this.createHost(),e.port&&(a.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var a=0;a<2;a++)if(/^s3-/.test(t[a])){t[1]=t[a].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,a=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||a["Content-Type"]||a["content-type"]||(a["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||a["Content-Length"]||a["content-length"]||(a["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||a["X-Amz-Security-Token"]||a["x-amz-security-token"]||(a["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||(a["X-Amz-Content-Sha256"]=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)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,a,i=this.getDate(),s=[this.credentials.secretAccessKey,i,this.region,this.service].join(),o=c.get(s);return o||(e=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")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,a=this.parsedPath.query,i=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||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")},y.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")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),a=null;t>=0&&(a=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:a}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+p(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var V={};Object.defineProperty(V,"__esModule",{value:!0}),V.API_VERSION=V.REGION=V.PAYLOAD_TYPE=V.STATE=void 0,V.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},V.PAYLOAD_TYPE="string",V.REGION="eu-west-1",V.API_VERSION="2013-12-02",Object.defineProperty(E,"__esModule",{value:!0});const _=P,j=V;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 _.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:j.REGION},{accessKeyId:i,secretAccessKey:s})}},Object.defineProperty(M,"__esModule",{value:!0});const H=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=H.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(g,"__esModule",{value:!0}),g.configureMitataExpiry=g.safeParseInt=g.correctTimeout=void 0;const D=m,$=C,U=f,L=A;function F(e){return e<=0?X:e}function G(e,t=0){return isNaN(e)?t:parseInt(e)}g.correctTimeout=F,g.safeParseInt=G;const X=3e3;function z(e,t){return void 0===t?e===D.NetaceaMitigationType.INGEST?3600:60:t}g.configureMitataExpiry=z;g.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:y}){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=F(a),this.netaceaCookieName=null!=l?l:"_mitata",this.netaceaCaptchaCookieName=null!=y?y:"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=z(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 y=new Date;let g;"/"!==s[0]&&(s=`/${s}`);const m=s.split("?");m.length>1&&(g=`?${m[1]}`);const C=m[0],f=null===(l=U.matchMitataCookie(h))||void 0===l?void 0:l.userId;return{status:a,method:i,bytes_sent:G(r),referrer:""===n?void 0:n,request:`${i} ${C}${null!=g?g:""} ${o}`,request_time:G(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:y.getUTCHours(),minute:y.getUTCMinutes(),"@timestamp":y.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:g,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.objectIsNetaceaCookieV3=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:"",checkAllPostRequests:void 0};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);let o=Object.keys(Y.netaceaCookieV3KeyMap).find((e=>Y.netaceaCookieV3KeyMap[e]===t));void 0===o&&(o=Object.keys(Y.netaceaCookieV3OptionalKeyMap).find((e=>Y.netaceaCookieV3OptionalKeyMap[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&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).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in Y.netaceaCookieV3OptionalKeyMap?`${Y.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${Y.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},B.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(Y.netaceaCookieV3OptionalKeyMap).includes(e))).every((e=>Object.values(Y.netaceaCookieV3KeyMap).includes(e)))},B.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(Y.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},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=g;a(g,e),a(m,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}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return n.objectIsNetaceaCookieV3}}),e.dictionary=C;var r=Q;Object.defineProperty(e,"lib",{enumerable:!0,get:function(){return r.lib}}),e.default=i.default}(y);var se={name:"@netacea/cloudflare",version:"5.2.14",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.5.14","@netacea/netaceaintegrationbase":"^1.17.14",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:"fd9a755ef39e4dfc576eb16513685702867927d2"},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=y,ue=A,pe=se,de=oe,le=ne,ye=ce,{configureCookiesDomain:ge,extractAndRemoveCookieAttr:me,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:y,netaceaCaptchaCookieName:g,enableDynamicCaptchaContentType:m=!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!=y?y:"_mitata",this.netaceaCaptchaCookieName=null!=g?g:"_mitatacaptcha";const{cookieAttributes:k,captchaCookieAttributes:v}=ge(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 m?m:"true"===m),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,ye.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,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for")})}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,ye.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ye.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,xForwardedFor:l}){var y;const g=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const C=s.split("?");C.length>1&&(m=`?${C[1]}`);const f=C[0],k=null===(y=(0,he.matchMitataCookie)(h))||void 0===y?void 0:y.userId;return{status:a,method:i,bytes_sent:(0,he.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${f}${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:f,protocol:o,query:m,user_id:k,x_forwarded_for:l}}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,xForwardedFor:l}){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:"",XForwardedFor:l}}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,y;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const g=(0,he.checkMitataCookie)(e,t,this.secretKey);if(!g.isPrimaryHashValid||g.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=g.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=g.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],y=e.eventId}else c=-1,h=g.match,u=g.mitigate,p=g.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,y)}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}=me(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}=me(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,ye.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,ye.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ye.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=y;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"),i=require("url"),a=require("querystring"),s=require("jose");function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})})),i}var r,c,h,u,p={},d={};!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(r||(r={})),function(e){e.V1="V1",e.V2="V2"}(c||(c={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(h||(h={})),function(e){e.NO_SESSION="no_session",e.EXPIRED_SESSION="expired_session",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change"}(u||(u={}));const l="_/@#/",m={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},y={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"},g={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},C={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},f={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},k={0:m.none,1:m.block,2:m.none,3:m.block,4:m.block},v={1:m.captcha,2:m.captchaPass,3:m.captcha,4:m.allow,5:m.captcha},S={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},I={checkAllPostRequests:"fCAPR"};var T=Object.freeze({__proto__:null,COOKIEDELIMITER:l,bestMitigationCaptchaMap:v,bestMitigationMap:k,captchaMap:f,captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:g,mitigateMap:C,mitigationTypes:m,netaceaCookieV3KeyMap:S,netaceaCookieV3OptionalKeyMap:I,netaceaHeaders:y,netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const w="ignored",A="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),N=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function b(e){if(void 0===e)return;const t=e.match(N);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,match:parseInt(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function E(t=16,i=A){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function P(e,t,i,a,s="000"){void 0===t&&(t=E());const o=[i,t,x(e+"|"+String(i),a),s].join(l);return`${x(o,a)}${l}${o}`}function x(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function M(e,t,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return a;const s=b(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(l),a=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<a,n=[1,3,5].includes(s.captcha),r=x(t+"|"+s.expiry,i),c=s.ipHash===r;return{mitata:s,requiresReissue:o||!c,isExpired:o,shouldExpire:n,isSameIP:c,isPrimaryHashValid:s.signature===x(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return a}var K={},R={},_={},H={},O=function(e){return new q(e)};function q(e){this.capacity=0|e,this.map=Object.create(null),this.list=new j}function j(){this.firstNode=null,this.lastNode=null}function V(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}q.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},q.prototype.set=function(e,t){var i=this.map[e];if(null!=i)i.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new V(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},q.prototype.used=function(e){this.list.moveToFront(e)},q.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},j.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))},j.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},j.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=H,o=i,n=a,r=e,c=O(1e3);function h(e,t,i){return r.createHmac("sha256",e).update(t,"utf8").digest(i)}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 m(e,t){"string"==typeof e&&(e=o.parse(e));var i=e.headers=e.headers||{},a=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||i.Host||i.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||a[0]||"",this.region=e.region||a[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),i.Host||i.host||(i.Host=e.hostname||e.host||this.createHost(),e.port&&(i.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=i.Host||i.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}m.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 i=0;i<2;i++)if(/^s3-/.test(t[i])){t[1]=t[i].slice(3),t[0]="s3";break}return t},m.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},m.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},m.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,i=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||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},m.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},m.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},m.prototype.getDate=function(){return this.getDateTime().substr(0,8)},m.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},m.prototype.signature=function(){var e,t,i,a=this.getDate(),s=[this.credentials.secretAccessKey,a,this.region,this.service].join(),o=c.get(s);return o||(e=h("AWS4"+this.credentials.secretAccessKey,a),t=h(e,this.region),i=h(t,this.service),o=h(i,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},m.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},m.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,i=this.parsedPath.query,a=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?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||u(this.request.body||"","hex"),i){var h=Object.keys(i).reduce((function(e,t){return t?(e[d(t)]=Array.isArray(i[t])&&c?i[t][0]:i[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")},m.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")},m.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},m.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},m.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}},m.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),i=null;t>=0&&(i=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:i}},m.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=m,s.sign=function(e,t){return new m(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(_,"__esModule",{value:!0});const D=H,U=$;_.default=class{static batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const s=e.slice(a,a+t);i.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return i}static signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:s}=e,o={Records:this.batchArrayForKinesis(t,i),PartitionKey:Date.now().toString(),StreamName:e.streamName};return D.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:U.REGION},{accessKeyId:a,secretAccessKey:s})}},Object.defineProperty(R,"__esModule",{value:!0});const L=_;R.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:i,maxLogAgeSeconds:a,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=i,void 0!==a&&a<this.maxLogAgeSeconds&&a>0&&(this.maxLogAgeSeconds=a),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const i=L.default.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:i.headers,host:`https://${i.hostname}`,method:i.method,path:i.path,body:i.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(K,"__esModule",{value:!0});const F=R;var z=K.default=F.default;function G(e){return e<=0?W:e}function X(e,t=0){return isNaN(e)?t:parseInt(e)}const W=3e3;function Y(e,t){return void 0===t?e===h.INGEST?3600:60:t}function B(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),s=decodeURIComponent(a);let o=Object.keys(S).find((e=>S[e]===t));void 0===o&&(o=Object.keys(I).find((e=>I[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),i[o]=n}return i}function J(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0}}function Z(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function Q(e,t=!1){if(""===e)return"";return e.replace(/ /g,"").split(";").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).filter(((e,i,a)=>{const s=e=>e.split("=")[0],o=s(e),n=a.map(s);return t?i===n.lastIndexOf(o):i===n.indexOf(o)})).join("; ")}const ee={cookieAttributes:Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=Q(e??"",!0),a=t=Q(t??"",!0);if(void 0!==e&&void 0!==t){const s=Z(e,"Domain"),o=Z(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=Z(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=Z(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=Z(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:Z,removeDuplicateAttrs:Q})};var te=n(Object.freeze({__proto__:null,get NetaceaCookieV3IssueReason(){return u},get NetaceaIngestType(){return r},get NetaceaLogVersion(){return c},get NetaceaMitigationType(){return h},checkMitataCookie:M,checkNetaceaCookieV3:function(e,t){if(void 0===e||""===e)return J();const i=B(e);if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,s=t===i.clientIP;return{mitata:i,requiresReissue:a||!s,isExpired:a,shouldExpire:[1,3,5].includes(i.captcha),isSameIP:s,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha}}return J()},configureMitataExpiry:Y,cookieIsNetaceaV3Format:function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(I).includes(e))).every((e=>Object.values(S).includes(e)))},correctTimeout:G,createMitataCookie:P,createNetaceaCookieV3:function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in I?`${I[e]}=${encodeURIComponent(t)}`:`${S[e]}=${encodeURIComponent(t)}`)).join("&")},default:class{constructor({apiKey:e,secretKey:t,timeout:i=W,mitigationServiceUrl:a="https://mitigations.netacea.net",ingestServiceUrl:s="https://ingest.netacea.net",mitigationType:o=h.INGEST,captchaSiteKey:n,captchaSecretKey:u,ingestType:p=r.HTTP,kinesis:d,logVersion:l,mitataCookieExpirySeconds:m,netaceaCookieExpirySeconds:y,netaceaCookieName:g,netaceaCaptchaCookieName:C}){if(this.encryptedCookies=[],null==e)throw new Error("apiKey is a required parameter");this.apiKey=e,this.secretKey=t,this.mitigationServiceUrl=a,this.ingestServiceUrl=s,this.mitigationType=o,this.ingestType=p??r.HTTP,this.logVersion=l??c.V1,this.ingestType===r.KINESIS&&(void 0===d?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new z({...d,apiKey:this.apiKey})),void 0===n&&void 0===u||(this.captchaSiteKey=n,this.captchaSecretKey=u),this.timeout=G(i),this.netaceaCookieName=g??"_mitata",this.netaceaCaptchaCookieName=C??"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=Y(o,y??m)}async runMitigation(e){try{switch(this.mitigationType){case h.MITIGATE:return await this.mitigate(e);case h.INJECT:return await this.inject(e);case h.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 i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===r.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"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw this.APIError(i)}}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:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){const l=new Date;let m;"/"!==s[0]&&(s=`/${s}`);const y=s.split("?");y.length>1&&(m=`?${y[1]}`);const g=y[0],C=b(h)?.userId;return{status:i,method:a,bytes_sent:X(r),referrer:""===n?void 0:n,request:`${a} ${g}${m??""} ${o}`,request_time:X(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:l.getUTCHours(),minute:l.getUTCMinutes(),"@timestamp":l.toISOString().replace("Z","+00:00"),path:g,protocol:o,query:m,user_id:C}}constructV1WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d}){return{Request:`${a} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,RequestTime:c?.toString(),BytesSent:r?.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:h??"",NetaceaMitigationApplied:u??"",IntegrationType:p??"",IntegrationVersion:d??""}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===c.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,i,a){let s,o,n,r,c,h,u;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const p=M(e,t,this.secretKey);if(!p.isPrimaryHashValid||p.requiresReissue){const e=await this.makeMitigateAPICall(p.mitata?.userId,t,i,a);s=e.status,o=e.match,n=e.mitigate,r=e.captcha,c=e.body,h=[await this.createMitata(t,p.mitata?.userId,o,n,r,e.mitataMaxAge)],u=e.eventId}else s=-1,o=p.match,n=p.mitigate,r=p.captcha,c=void 0,h=[];return this.composeResult(c,h,s,o,n,r,!1,u)}async createMitata(e,t,i,a,s,o=86400,n=void 0){const r=[1,3,5].includes(s)?-this.mitataCookieExpirySeconds:this.mitataCookieExpirySeconds,c=n??Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,s].join(""),u=P(e,t,c,this.secretKey,h);return await this.buildCookieFromValues(this.netaceaCookieName,u,o,"/")}async processCaptcha(e,t,i,a){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,i,a);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,y.mitataCaptcha)){const t=e[y.mitataCaptcha],i=parseInt(e[y.mitataCaptchaExpiry]),a=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,i);if(void 0!==a)return a}}async makeCaptchaAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=b(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:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,o?.userId,t)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw this.APIError(e);const a=parseInt(e.headers[y.match]),s=parseInt(e.headers[y.mitigate]),o=parseInt(e.headers[y.captcha]);let n=parseInt(e.headers[y.mitataExpiry]);isNaN(n)&&(n=86400);const r=[await this.createMitata(i,t,a,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),c=e.headers[y.eventId];return{status:e.status,match:a,mitigate:s,captcha:o,setCookie:r,body:e.body,eventId:c,mitataMaxAge:n}}async buildCookieFromValues(e,t,i,a="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${i}; Path=${a}`}return`${e}=${t}; Max-Age=${i}; Path=${a}`}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}async makeMitigateAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};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,i,a,s,o,n,r){const c=this.findBestMitigation(a,s,o,n),u={body:e,apiCallStatus:i,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[m.block,m.captcha,m.captchaPass].includes(c.mitigation)};if(this.mitigationType===h.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),u.injectHeaders=e}return u}findBestMitigation(e,t,i,a){const s="unknown";a||(2===i?i=4:3===i&&(i=5));let o=g[e]??s+"_";o+=C[t]??s;let n=k[t];if(0!==i){o+=","+(f[i]??s);const e=v[i];void 0!==e&&(n=e)}return this.mitigationType===h.INJECT&&(n=m.none),{sessionStatus:o,mitigation:n,parts:{match:e,mitigate:t,captcha:i}}}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(w,e,0,0,0,86400)]}}async processIngest(e){if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const t=this.getCookieHeader(e),i=M(await this.readCookie(this.netaceaCookieName,t),w,this.secretKey);return i.isPrimaryHashValid?i.requiresReissue?await this.setIngestOnlyMitataCookie(i.mitata?.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async encryptCookieValue(e){return e}async decryptCookieValue(e){return e}},defaultInvalidResponse:J,dictionary:T,generateId:E,hexSha256:x,ingestIgnoredIpValue:w,lib:ee,matchMitataCookie:b,matchNetaceaCookieV3:B,objectIsNetaceaCookieV3:function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(S)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},safeParseInt:X,warmupCookie:{cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}})),ie={name:"@netacea/cloudflare",version:"5.2.16",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.5.16","@netacea/netaceaintegrationbase":"^1.17.16",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:"865ef1fdbea1cae3a29290629a3a697d329a35cf"},ae={};Object.defineProperty(ae,"__esModule",{value:!0}),ae.fetch=void 0,ae.fetch=globalThis.fetch.bind(globalThis);var se={};Object.defineProperty(se,"__esModule",{value:!0}),se.decrypt=se.encrypt=void 0;const oe=s;se.encrypt=async function(e,t){const i=oe.base64url.decode(t),a=(new TextEncoder).encode(e);return await new oe.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)},se.decrypt=async function(e,t){const i=oe.base64url.decode(t),{plaintext:a}=await oe.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)};var ne={};Object.defineProperty(ne,"__esModule",{value:!0}),ne.isUrlCaptchaGet=ne.getTrackingId=ne.modifyCaptchaJsonResponse=ne.getCaptchaPageContentType=void 0,ne.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"},ne.modifyCaptchaJsonResponse=async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${a}`})},ne.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},ne.isUrlCaptchaGet=async function(e,t,i){if(void 0===i||!Boolean(i))return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:s}=new URL(e);return a.includes(i)&&s.includes("trackingId")&&"get"===t.toLowerCase()},Object.defineProperty(d,"__esModule",{value:!0});const re=te,ce=K,he=ie,ue=ae,pe=se,de=ne,{configureCookiesDomain:le,extractAndRemoveCookieAttr:me,removeDuplicateAttrs:ye}=re.lib.cookieAttributes;d.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=re.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=re.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:m,netaceaCaptchaCookieName:y,enableDynamicCaptchaContentType:g=!1,captchaHeader:C,netaceaCaptchaPath:f}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=h?h:re.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:re.NetaceaLogVersion.V1,this.ingestType===re.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new ce.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,re.correctTimeout)(a),this.netaceaCookieName=null!=m?m:"_mitata",this.netaceaCaptchaCookieName=null!=y?y:"_mitatacaptcha";const{cookieAttributes:k,captchaCookieAttributes:v}=le(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===re.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 g?g:"true"===g),this.captchaHeader=C}async run(e,t){const i=await this.timeoutCheck(this.runMitigation(e.request),this.timeout);return await this.handleResponse(e.request,i,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 i=new Headers;if(!await(0,de.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)i.append("set-cookie",e);let a="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&i.append(this.captchaHeader.name,this.captchaHeader.value),i.append("content-type","text/html; charset=UTF-8"),a=t.body),{response:new Response(a,{status:403,statusText:"Forbidden",headers:i}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const i of t.setCookie)e.append("set-cookie",i);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 i,a,s;const o=null!==(i=await this.getNetaceaCookieFromResponse(t))&&void 0!==i?i:await this.getNetaceaCookieFromRequest(e),{match:n,mitigate:r,captcha:c}=null!==(a=(0,re.matchMitataCookie)(null!=o?o:""))&&void 0!==a?a:{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:he.name.replace("@netacea/",""),integrationVersion:he.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for")})}async handleGetCaptchaRequest(e,t,i,a,s,o,n){var r;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const c=(0,re.checkMitataCookie)(e,t,this.secretKey),h=await this.makeMitigateAPICall(null===(r=c.mitata)||void 0===r?void 0:r.userId,t,i,n,a,!0,s,o);return{body:h.body,apiCallStatus:h.status,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const o=`${e}${i}`,n=new Request(o,{method:t,body:s,headers:a}),r=await(0,ue.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 i;if(void 0===t)return e;const a=null!==(i=e.headers.get("set-cookie"))&&void 0!==i?i:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)a.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 i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}async handleResponse(e,t,i){if(void 0!==t)if(this.mitigationType===re.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===re.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));const a=await i(e);return this.addHeadersToResponse(a,t)}getHeaderValueOrDefault(e,t,i=""){var a;return null!==(a=e.get(t))&&void 0!==a?a:i}async getMitigationResponse(e){var t,i,a,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!==(i=e.headers.get("cf-connecting-ip"))&&void 0!==i?i:"",h=null!==(a=e.headers.get("user-agent"))&&void 0!==a?a:"",u=this.enableDynamicCaptchaContentType?(0,de.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,de.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,i)=>{setTimeout((()=>e(void 0)),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,pe.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,pe.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case re.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case re.NetaceaMitigationType.INJECT:return await this.inject(e);case re.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 i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){const t=e.headers.getSetCookie(),i=`${this.netaceaCookieName}=`;for(const e of t)if(e.startsWith(i))return await this.readCookie(this.netaceaCookieName,e)}async getNetaceaCookieFromRequest(e){var t;const i=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,i))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===re.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"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw this.APIError(i)}}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:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l}){var m;const y=new Date;let g;"/"!==s[0]&&(s=`/${s}`);const C=s.split("?");C.length>1&&(g=`?${C[1]}`);const f=C[0],k=null===(m=(0,re.matchMitataCookie)(h))||void 0===m?void 0:m.userId;return{status:i,method:a,bytes_sent:(0,re.safeParseInt)(r),referrer:""===n?void 0:n,request:`${a} ${f}${null!=g?g:""} ${o}`,request_time:(0,re.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:y.getUTCHours(),minute:y.getUTCMinutes(),"@timestamp":y.toISOString().replace("Z","+00:00"),path:f,protocol:o,query:g,user_id:k,x_forwarded_for:l}}constructV1WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l}){return{Request:`${a} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,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:"",XForwardedFor:l}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===re.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,i,a,s,o){var n,r;let c,h,u,p,d,l,m;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const y=(0,re.checkMitataCookie)(e,t,this.secretKey);if(!y.isPrimaryHashValid||y.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=y.mitata)||void 0===n?void 0:n.userId,t,i,o,a,!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=y.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],m=e.eventId}else c=-1,h=y.match,u=y.mitigate,p=y.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,m)}async createMitata(e,t,i,a,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}=me(h,"Max-Age");void 0!==e&&(u=parseInt(e,10)),h=t}const p=[i,a,s].join(""),d=(0,re.createMitataCookie)(e,t,c,this.secretKey,p),l=await this.buildCookieFromValues(this.netaceaCookieName,d,u,"/");return ye(l+(""!==h?`; ${h}`:""),!0)}async processCaptcha(e,t,i,a){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,i,a);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){if(Object.prototype.hasOwnProperty.call(e,re.dictionary.netaceaHeaders.mitataCaptcha)){const t=e[re.dictionary.netaceaHeaders.mitataCaptcha],i=parseInt(e[re.dictionary.netaceaHeaders.mitataCaptchaExpiry]);let a,s=this.netaceaCaptchaCookieAttributes;if(""!==s){const{extractedAttribute:e,cookieAttributes:t}=me(s,"Max-Age");void 0!==e&&(a=parseInt(e)),s=t}const o=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,t,null!=a?a:i);if(void 0!==o){return ye(o+(""!==s?`; ${s}`:""),!0)}}}async makeCaptchaAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=(0,re.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:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t,"")}async getApiCallResponseFromResponse(e,t,i,a){var s;if(200!==e.status)throw this.APIError(e);const o=parseInt(e.headers[re.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[re.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[re.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[re.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(i,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[re.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,de.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,a)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:u,mitataMaxAge:c}}async buildCookieFromValues(e,t,i,a="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${i}; Path=${a}`}return`${e}=${t}; Max-Age=${i}; Path=${a}`}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}async makeMitigateAPICall(e,t,i,a,s,o,n,r){const c={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};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,i,a,s,o,n,r){const c=this.findBestMitigation(a,s,o,n),h={body:e,apiCallStatus:i,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[re.dictionary.mitigationTypes.block,re.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===re.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,i,a){var s,o,n;const r="unknown";a||(2===i?i=4:3===i&&(i=5));let c=null!==(s=re.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=re.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=re.dictionary.bestMitigationMap[t];if(0!==i){c+=","+(null!==(n=re.dictionary.captchaMap[i])&&void 0!==n?n:r);const e=re.dictionary.bestMitigationCaptchaMap[i];void 0!==e&&(h=e)}return this.mitigationType===re.NetaceaMitigationType.INJECT&&(h=re.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:i}}}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,de.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,de.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(re.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 i=this.getCookieHeader(e),a=await this.readCookie(this.netaceaCookieName,i),s=(0,re.checkMitataCookie)(a,re.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=d;var i=te;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return i.NetaceaMitigationType}}),e.default=t.default}(p);var ge=o(p);module.exports=ge;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudflare",
|
|
3
|
-
"version": "5.2.
|
|
3
|
+
"version": "5.2.16",
|
|
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.5.
|
|
27
|
-
"@netacea/netaceaintegrationbase": "^1.17.
|
|
26
|
+
"@netacea/kinesisingest": "^1.5.16",
|
|
27
|
+
"@netacea/netaceaintegrationbase": "^1.17.16",
|
|
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": "
|
|
59
|
+
"gitHead": "865ef1fdbea1cae3a29290629a3a697d329a35cf"
|
|
60
60
|
}
|