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