@netacea/cloudflare 5.2.20 → 5.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1 +1 @@
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.20",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.20","@netacea/netaceaintegrationbase":"^1.17.18",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:"e143af04541aee913c1eb4fbc64f89b2154ca6be"},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;
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.21",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.21","@netacea/netaceaintegrationbase":"^1.17.18",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:"032e657094f9b317dfe562984e882c52ec6ac1ea"},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.20",
3
+ "version": "5.2.21",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "license": "ISC",
25
25
  "dependencies": {
26
- "@netacea/kinesisingest": "^1.5.20",
26
+ "@netacea/kinesisingest": "^1.5.21",
27
27
  "@netacea/netaceaintegrationbase": "^1.17.18",
28
28
  "jose": "^4.11.2"
29
29
  },
@@ -56,5 +56,5 @@
56
56
  "tsconfig-paths": "^4.2.0",
57
57
  "typescript": "^5.2.2"
58
58
  },
59
- "gitHead": "e143af04541aee913c1eb4fbc64f89b2154ca6be"
59
+ "gitHead": "032e657094f9b317dfe562984e882c52ec6ac1ea"
60
60
  }