@netacea/akamai 6.1.13 → 6.1.14

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 CHANGED
@@ -38,6 +38,7 @@ interface ProtoMitata {
38
38
  mitigate: number;
39
39
  captcha: number;
40
40
  mitataMaxAge: number;
41
+ netaceaSettings: NetaceaSettings;
41
42
  }
42
43
  declare type AkamaiMitigateResponse = MitigateResponse<ResponseProperties>;
43
44
  interface UpstreamMitHeaders {
@@ -72,6 +73,9 @@ interface AkamaiRuntimeDependencies {
72
73
  httpRequest: AkamaiHttpRequestFn;
73
74
  cachedEncryption?: CachedEncryption;
74
75
  }
76
+ interface NetaceaSettings {
77
+ checkAllPostRequests?: number;
78
+ }
75
79
 
76
80
  declare type DefaultConfig = Readonly<Partial<LegacyAkamaiConstructorArgs>>;
77
81
  declare class ConfigLoader {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{httpRequest as t}from"http-request";import{logger as e}from"log";import*as i from"crypto";import a from"crypto";import n from"buffer";import r from"querystring";import o from"url";import*as s from"encoding";var c,u,h,p,f="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},l={},d={},g={};c=g,Object.defineProperty(c,"__esModule",{value:!0}),c.NetaceaCookieV3IssueReason=c.NetaceaMitigationType=c.NetaceaLogVersion=c.NetaceaIngestType=void 0,(u=c.NetaceaIngestType||(c.NetaceaIngestType={})).ORIGIN="ORIGIN",u.HTTP="HTTP",u.KINESIS="KINESIS",u.NATIVE="NATIVE",(h=c.NetaceaLogVersion||(c.NetaceaLogVersion={})).V1="V1",h.V2="V2",function(t){t.MITIGATE="MITIGATE",t.INJECT="INJECT",t.INGEST="INGEST"}(c.NetaceaMitigationType||(c.NetaceaMitigationType={})),(p=c.NetaceaCookieV3IssueReason||(c.NetaceaCookieV3IssueReason={})).NO_SESSION="no_session",p.EXPIRED_SESSION="expired_session",p.INVALID_SESSION="invalid_session",p.IP_CHANGE="ip_change";var y={};!function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.netaceaCookieV3KeyDict=t.bestMitigationCaptchaMap=t.bestMitigationMap=t.captchaStatusCodes=t.captchaMap=t.mitigateMap=t.matchMap=t.netaceaHeaders=t.mitigationTypes=t.COOKIEDELIMITER=void 0,t.COOKIEDELIMITER="_/@#/",t.mitigationTypes={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},t.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"},t.matchMap={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},t.mitigateMap={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},t.captchaMap={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},t.captchaStatusCodes={"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},t.bestMitigationMap={0:t.mitigationTypes.none,1:t.mitigationTypes.block,2:t.mitigationTypes.none,3:t.mitigationTypes.block,4:t.mitigationTypes.block},t.bestMitigationCaptchaMap={1:t.mitigationTypes.captcha,2:t.mitigationTypes.captchaPass,3:t.mitigationTypes.captcha,4:t.mitigationTypes.allow,5:t.mitigationTypes.captcha},t.netaceaCookieV3KeyDict={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"}}(y);var m={};Object.defineProperty(m,"__esModule",{value:!0}),m.checkMitataCookie=m.warmupCookie=m.hexSha256=m.createMitataCookie=m.generateId=m.matchMitataCookie=m.ingestIgnoredIpValue=void 0;const w=a,I=y,C=n;m.ingestIgnoredIpValue="ignored";const v="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),S=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function b(t){if(void 0===t)return;const e=t.match(S);if(null!=e){const[,t,i,a,n,r,o,s,c]=e;return{signature:t,expiry:i,userId:a,ipHash:n,mitigationType:r,match:parseInt(o),mitigate:parseInt(s),captcha:parseInt(c)}}}function E(t=16,e=v){const i=w.randomBytes(t-1);return`c${Array.from(i).map((t=>e[t%e.length])).join("")}`}function k(t,e){const i=w.createHmac("sha256",e);return i.update(t),C.Buffer.from(i.digest("hex")).toString("base64")}m.matchMitataCookie=b,m.generateId=E,m.createMitataCookie=function(t,e,i,a,n="000"){void 0===e&&(e=E());const r=[i,e,k(t+"|"+String(i),a),n].join(I.COOKIEDELIMITER);return`${k(r,a)}${I.COOKIEDELIMITER}${r}`},m.hexSha256=k,m.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"},m.checkMitataCookie=function(t,e,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof t||""===t)return a;const n=b(t);if(void 0!==n){const t=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(I.COOKIEDELIMITER),a=Math.floor(Date.now()/1e3),r=parseInt(n.expiry)<a,o=[1,3,5].includes(n.captcha),s=k(e+"|"+n.expiry,i),c=n.ipHash===s;return{mitata:n,requiresReissue:r||!c,isExpired:r,shouldExpire:o,isSameIP:c,isPrimaryHashValid:n.signature===k(t,i),match:n.match,mitigate:n.mitigate,captcha:n.captcha}}return a};var A={},N={},T={},M={},x=function(t){return new _(t)};function _(t){this.capacity=0|t,this.map=Object.create(null),this.list=new P}function P(){this.firstNode=null,this.lastNode=null}function R(t,e){this.key=t,this.val=e,this.prev=null,this.next=null}_.prototype.get=function(t){var e=this.map[t];if(null!=e)return this.used(e),e.val},_.prototype.set=function(t,e){var i=this.map[t];if(null!=i)i.val=e;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new R(t,e),this.map[t]=i,this.capacity--}return this.used(i),!0},_.prototype.used=function(t){this.list.moveToFront(t)},_.prototype.prune=function(){var t=this.list.pop();null!=t&&(delete this.map[t.key],this.capacity++)},P.prototype.moveToFront=function(t){this.firstNode!=t&&(this.remove(t),null==this.firstNode?(this.firstNode=t,this.lastNode=t,t.prev=null,t.next=null):(t.prev=null,t.next=this.firstNode,t.next.prev=t,this.firstNode=t))},P.prototype.pop=function(){var t=this.lastNode;return null!=t&&this.remove(t),t},P.prototype.remove=function(t){this.firstNode==t?this.firstNode=t.next:null!=t.prev&&(t.prev.next=t.next),this.lastNode==t?this.lastNode=t.prev:null!=t.next&&(t.next.prev=t.prev)},function(t){var e=M,i=o,n=r,s=a,c=x(1e3);function u(t,e,i){return s.createHmac("sha256",t).update(e,"utf8").digest(i)}function h(t,e){return s.createHash("sha256").update(t,"utf8").digest(e)}function p(t){return t.replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}function f(t){return p(encodeURIComponent(t))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function d(t,e){"string"==typeof t&&(t=i.parse(t));var a=t.headers=t.headers||{},n=(!this.service||!this.region)&&this.matchHost(t.hostname||t.host||a.Host||a.host);this.request=t,this.credentials=e||this.defaultCredentials(),this.service=t.service||n[0]||"",this.region=t.region||n[1]||"us-east-1","email"===this.service&&(this.service="ses"),!t.method&&t.body&&(t.method="POST"),a.Host||a.host||(a.Host=t.hostname||t.host||this.createHost(),t.port&&(a.Host+=":"+t.port)),t.hostname||t.host||(t.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===t.method}d.prototype.matchHost=function(t){var e=((t||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===e[1]&&(e=e.reverse()),"s3"==e[1])e[0]="s3",e[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(e[i])){e[1]=e[i].slice(3),e[0]="s3";break}return e},d.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},d.prototype.createHost=function(){var t=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+t+".amazonaws.com"},d.prototype.prepareRequest=function(){this.parsePath();var t,e=this.request,i=e.headers;e.signQuery?(this.parsedPath.query=t=this.parsedPath.query||{},this.credentials.sessionToken&&(t["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||t["X-Amz-Expires"]||(t["X-Amz-Expires"]=86400),t["X-Amz-Date"]?this.datetime=t["X-Amz-Date"]:t["X-Amz-Date"]=this.getDateTime(),t["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",t["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),t["X-Amz-SignedHeaders"]=this.signedHeaders()):(e.doNotModifyHeaders||this.isCodeCommitGit||(!e.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!e.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(e.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=h(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},d.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},d.prototype.getDateTime=function(){if(!this.datetime){var t=this.request.headers,e=new Date(t.Date||t.date||new Date);this.datetime=e.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},d.prototype.getDate=function(){return this.getDateTime().substr(0,8)},d.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},d.prototype.signature=function(){var t,e,i,a=this.getDate(),n=[this.credentials.secretAccessKey,a,this.region,this.service].join(),r=c.get(n);return r||(t=u("AWS4"+this.credentials.secretAccessKey,a),e=u(t,this.region),i=u(e,this.service),r=u(i,"aws4_request"),c.set(n,r)),u(r,this.stringToSign(),"hex")},d.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),h(this.canonicalString(),"hex")].join("\n")},d.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var t,e=this.parsedPath.path,i=this.parsedPath.query,a=this.request.headers,n="",r="s3"!==this.service,o="s3"===this.service||this.request.doNotEncodePath,s="s3"===this.service,c="s3"===this.service;if(t="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||h(this.request.body||"","hex"),i){var u=Object.keys(i).reduce((function(t,e){return e?(t[f(e)]=Array.isArray(i[e])&&c?i[e][0]:i[e],t):t}),{}),p=[];Object.keys(u).sort().forEach((function(t){Array.isArray(u[t])?u[t].map(f).sort().forEach((function(e){p.push(t+"="+e)})):p.push(t+"="+f(u[t]))})),n=p.join("&")}return"/"!==e&&(r&&(e=e.replace(/\/{2,}/g,"/")),"/"!==(e=e.split("/").reduce((function(t,e){return r&&".."===e?t.pop():r&&"."===e||(o&&(e=decodeURIComponent(e.replace(/\+/g," "))),t.push(f(e))),t}),[]).join("/"))[0]&&(e="/"+e),s&&(e=e.replace(/%2F/g,"/"))),[this.request.method||"GET",e,n,this.canonicalHeaders()+"\n",this.signedHeaders(),t].join("\n")},d.prototype.canonicalHeaders=function(){var t=this.request.headers;return Object.keys(t).filter((function(t){return null==l[t.toLowerCase()]})).sort((function(t,e){return t.toLowerCase()<e.toLowerCase()?-1:1})).map((function(e){return e.toLowerCase()+":"+t[e].toString().trim().replace(/\s+/g," ")})).join("\n")},d.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(t){return t.toLowerCase()})).filter((function(t){return null==l[t]})).sort().join(";")},d.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},d.prototype.defaultCredentials=function(){var t=process.env;return{accessKeyId:t.AWS_ACCESS_KEY_ID||t.AWS_ACCESS_KEY,secretAccessKey:t.AWS_SECRET_ACCESS_KEY||t.AWS_SECRET_KEY,sessionToken:t.AWS_SESSION_TOKEN}},d.prototype.parsePath=function(){var t=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(t)&&(t=encodeURI(decodeURI(t)));var e=t.indexOf("?"),i=null;e>=0&&(i=n.parse(t.slice(e+1)),t=t.slice(0,e)),this.parsedPath={path:t,query:i}},d.prototype.formatPath=function(){var t=this.parsedPath.path,e=this.parsedPath.query;return e?(null!=e[""]&&delete e[""],t+"?"+p(n.stringify(e))):t},e.RequestSigner=d,e.sign=function(t,e){return new d(t,e).sign()}}();var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.API_VERSION=O.REGION=O.PAYLOAD_TYPE=O.STATE=void 0,O.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},O.PAYLOAD_TYPE="string",O.REGION="eu-west-1",O.API_VERSION="2013-12-02",Object.defineProperty(T,"__esModule",{value:!0});const B=M,U=O;T.default=class{static batchArrayForKinesis(t,e){const i=[];for(let a=0;a<t.length;a+=e){const n=t.slice(a,a+e);i.push({Data:Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}static signRequest(t,e,i){const{accessKeyId:a,secretAccessKey:n}=t,r={Records:this.batchArrayForKinesis(e,i),PartitionKey:Date.now().toString(),StreamName:t.streamName};return B.sign({service:"kinesis",body:JSON.stringify(r),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:U.REGION},{accessKeyId:a,secretAccessKey:n})}},Object.defineProperty(N,"__esModule",{value:!0});const K=T;N.default=class{constructor({kinesisStreamName:t,kinesisAccessKey:e,kinesisSecretKey:i,maxLogAgeSeconds:a,logBatchSize:n}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=t,this.kinesisAccessKey=e,this.kinesisSecretKey=i,void 0!==a&&a<this.maxLogAgeSeconds&&a>0&&(this.maxLogAgeSeconds=a),void 0!==n&&(this.logBatchSize=n)}async putToKinesis(t){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const i=K.default.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await t({headers:i.headers,host:`https://${i.hostname}`,method:i.method,path:i.path,body:i.body})}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(t,e){if(this.logCache.push(t),this.intervalSet||(this.intervalSet=!0,await async function(t){await new Promise((e=>{setTimeout(e,t)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(e),this.intervalSet=!1),this.logCache.length>=this.logBatchSize)return await this.putToKinesis(e)}},Object.defineProperty(A,"__esModule",{value:!0});const H=N;A.default=H.default,Object.defineProperty(d,"__esModule",{value:!0}),d.configureMitataExpiry=d.safeParseInt=d.correctTimeout=void 0;const V=g,j=y,$=m,L=A;function D(t){return t<=0?z:t}function q(t,e=0){return isNaN(t)?e:parseInt(t)}d.correctTimeout=D,d.safeParseInt=q;const z=3e3;function X(t,e){return void 0===e?t===V.NetaceaMitigationType.INGEST?3600:60:e}d.configureMitataExpiry=X;d.default=class{constructor({apiKey:t,secretKey:e,timeout:i=z,mitigationServiceUrl:a="https://mitigations.netacea.net",ingestServiceUrl:n="https://ingest.netacea.net",mitigationType:r=V.NetaceaMitigationType.INGEST,captchaSiteKey:o,captchaSecretKey:s,ingestType:c=V.NetaceaIngestType.HTTP,kinesis:u,logVersion:h,mitataCookieExpirySeconds:p,netaceaCookieExpirySeconds:f,netaceaCookieName:l,netaceaCaptchaCookieName:d}){if(this.encryptedCookies=[],null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=e,this.mitigationServiceUrl=a,this.ingestServiceUrl=n,this.mitigationType=r,this.ingestType=null!=c?c:V.NetaceaIngestType.HTTP,this.logVersion=null!=h?h:V.NetaceaLogVersion.V1,this.ingestType===V.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new L.default({...u,apiKey:this.apiKey})),void 0===o&&void 0===s||(this.captchaSiteKey=o,this.captchaSecretKey=s),this.timeout=D(i),this.netaceaCookieName=null!=l?l:"_mitata",this.netaceaCaptchaCookieName=null!=d?d:"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=X(r,null!=f?f:p)}async runMitigation(t){try{switch(this.mitigationType){case V.NetaceaMitigationType.MITIGATE:return await this.mitigate(t);case V.NetaceaMitigationType.INJECT:return await this.inject(t);case V.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(t,e){if(null==e)return;if("string"==typeof e)return await this.readCookie(t,e.split(";"));const i=`${t}=`;for(const a of e){const e=a.split(";")[0].trimStart();if(e.startsWith(i)){const a=e.slice(i.length);if(this.encryptedCookies.includes(t))try{return await this.decryptCookieValue(a)}catch(t){return}return a}}}async callIngest(t){const e=this.constructWebLog(t);if(this.ingestType===V.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({...e,apiKey:this.apiKey},this.makeRequest.bind(this))}catch(t){console.error("NETACEA Error: ",t.message)}}else{const t={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(t,e);if(200!==i.status)throw this.APIError(i)}}async makeIngestApiCall(t,e){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:t,body:JSON.stringify(e),timeout:this.timeout})}constructV2WebLog({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){var l;const d=new Date;let g;"/"!==n[0]&&(n=`/${n}`);const y=n.split("?");y.length>1&&(g=`?${y[1]}`);const m=y[0],w=null===(l=$.matchMitataCookie(u))||void 0===l?void 0:l.userId;return{status:i,method:a,bytes_sent:q(s),referrer:""===o?void 0:o,request:`${a} ${m}${null!=g?g:""} ${r}`,request_time:q(c),integration_type:p,integration_version:f,client:t,user_agent:e,bc_type:""===h?void 0:h,hour:d.getUTCHours(),minute:d.getUTCMinutes(),"@timestamp":d.toISOString().replace("Z","+00:00"),path:m,protocol:r,query:g,user_id:w}}constructV1WebLog({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){return{Request:`${a} ${n} ${r}`,TimeLocal:(new Date).toUTCString(),RealIp:t,UserAgent:e,Status:i,RequestTime:null==c?void 0:c.toString(),BytesSent:null==s?void 0:s.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:null!=u?u:"",NetaceaMitigationApplied:null!=h?h:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=f?f:""}}constructWebLog(t){return t.bytesSent=""===t.bytesSent?"0":t.bytesSent,this.logVersion===V.NetaceaLogVersion.V2?this.constructV2WebLog(t):this.constructV1WebLog(t)}async check(t,e,i,a){var n,r;let o,s,c,u,h,p,f;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const l=$.checkMitataCookie(t,e,this.secretKey);if(!l.isPrimaryHashValid||l.requiresReissue){const t=await this.makeMitigateAPICall(null===(n=l.mitata)||void 0===n?void 0:n.userId,e,i,a);o=t.status,s=t.match,c=t.mitigate,u=t.captcha,h=t.body,p=[await this.createMitata(e,null===(r=l.mitata)||void 0===r?void 0:r.userId,s,c,u,t.mitataMaxAge)],f=t.eventId}else o=-1,s=l.match,c=l.mitigate,u=l.captcha,h=void 0,p=[];return this.composeResult(h,p,o,s,c,u,!1,f)}async createMitata(t,e,i,a,n,r=86400,o=void 0){const s=[1,3,5].includes(n)?-this.mitataCookieExpirySeconds:this.mitataCookieExpirySeconds,c=null!=o?o:Math.floor(Date.now()/1e3)+s;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join(""),h=$.createMitataCookie(t,e,c,this.secretKey,u);return await this.buildCookieFromValues(this.netaceaCookieName,h,r,"/")}async processCaptcha(t,e,i,a){const{status:n,match:r,mitigate:o,captcha:s,body:c,setCookie:u}=await this.makeCaptchaAPICall(t,e,i,a);return this.composeResult(c,u,n,r,o,s,!0)}async getMitataCaptchaFromHeaders(t){if(Object.prototype.hasOwnProperty.call(t,j.netaceaHeaders.mitataCaptcha)){const e=t[j.netaceaHeaders.mitataCaptcha],i=parseInt(t[j.netaceaHeaders.mitataCaptchaExpiry]),a=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,e,i);if(void 0!==a)return a}}async makeCaptchaAPICall(t,e,i,a){const n={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},r=$.matchMitataCookie(t);void 0!==r&&(n["X-Netacea-UserId"]=r.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const o=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:n,method:"POST",body:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(o,null==r?void 0:r.userId,e)}async getApiCallResponseFromResponse(t,e,i){if(200!==t.status)throw this.APIError(t);const a=parseInt(t.headers[j.netaceaHeaders.match]),n=parseInt(t.headers[j.netaceaHeaders.mitigate]),r=parseInt(t.headers[j.netaceaHeaders.captcha]);let o=parseInt(t.headers[j.netaceaHeaders.mitataExpiry]);isNaN(o)&&(o=86400);const s=[await this.createMitata(i,e,a,n,r),await this.getMitataCaptchaFromHeaders(t.headers)].filter((t=>void 0!==t)),c=t.headers[j.netaceaHeaders.eventId];return{status:t.status,match:a,mitigate:n,captcha:r,setCookie:s,body:t.body,eventId:c,mitataMaxAge:o}}async buildCookieFromValues(t,e,i,a="/"){if(this.encryptedCookies.includes(t)){return`${t}=${await this.encryptCookieValue(e)}; Max-Age=${i}; Path=${a}`}return`${t}=${e}; Max-Age=${i}; Path=${a}`}buildCookieHeader(t){let e="",i="";for(const a in t){const n=t[a];void 0!==n&&(e=`${e}${i}${a}=${n}`,i="; ")}return e}async makeMitigateAPICall(t,e,i,a){const n={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==t&&(n["X-Netacea-UserId"]=t),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const r=await this.makeRequest({host:this.mitigationServiceUrl,path:"/",headers:n,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(r,t,e)}composeResult(t,e,i,a,n,r,o,s){const c=this.findBestMitigation(a,n,r,o),u={body:t,apiCallStatus:i,setCookie:e,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[j.mitigationTypes.block,j.mitigationTypes.captcha,j.mitigationTypes.captchaPass].includes(c.mitigation)};if(this.mitigationType===V.NetaceaMitigationType.INJECT){const t={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==s&&(t["x-netacea-event-id"]=s),u.injectHeaders=t}return u}findBestMitigation(t,e,i,a){var n,r,o;const s="unknown";a||(2===i?i=4:3===i&&(i=5));let c=null!==(n=j.matchMap[t])&&void 0!==n?n:s+"_";c+=null!==(r=j.mitigateMap[e])&&void 0!==r?r:s;let u=j.bestMitigationMap[e];if(0!==i){c+=","+(null!==(o=j.captchaMap[i])&&void 0!==o?o:s);const t=j.bestMitigationCaptchaMap[i];void 0!==t&&(u=t)}return this.mitigationType===V.NetaceaMitigationType.INJECT&&(u=j.mitigationTypes.none),{sessionStatus:c,mitigation:u,parts:{match:t,mitigate:e,captcha:i}}}APIError(t){let e="Unknown error";switch(t.status){case 403:e="Invalid credentials";break;case 500:e="Server error";break;case 502:e="Bad Gateway";break;case 503:e="Service Unavailable";break;case 400:e="Invalid request"}return new Error(`Error reaching Netacea API (${e}), status: ${t.status}`)}isUrlCaptchaPost(t,e){return t.includes("/AtaVerifyCaptcha")&&"post"===e.toLowerCase()}async processMitigateRequest(t){const e=this.isUrlCaptchaPost(t.url,t.method);return await(e?this.processCaptcha(t.mitata,t.clientIp,t.userAgent,await t.getBodyFn()):this.check(t.mitata,t.clientIp,t.userAgent,t.mitataCaptcha))}async setIngestOnlyMitataCookie(t){return{sessionStatus:"",setCookie:[await this.createMitata($.ingestIgnoredIpValue,t,0,0,0,86400)]}}async processIngest(t){var e;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const i=this.getCookieHeader(t),a=await this.readCookie(this.netaceaCookieName,i),n=$.checkMitataCookie(a,$.ingestIgnoredIpValue,this.secretKey);return n.isPrimaryHashValid?n.requiresReissue?await this.setIngestOnlyMitataCookie(null===(e=n.mitata)||void 0===e?void 0:e.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async encryptCookieValue(t){return t}async decryptCookieValue(t){return t}};var G={};Object.defineProperty(G,"__esModule",{value:!0});var F={};Object.defineProperty(F,"__esModule",{value:!0}),F.defaultInvalidResponse=F.matchNetaceaCookieV3=F.checkNetaceaCookieV3=F.objectIsNetaceaCookieV3=F.cookieIsNetaceaV3Format=F.createNetaceaCookieV3=void 0;const Y=y;function W(t){if(void 0===t||""===t)return;const e=t.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:""};for(const t of e){const[e,a]=t.split("="),n=decodeURIComponent(a),r=Object.keys(Y.netaceaCookieV3KeyDict).find((t=>Y.netaceaCookieV3KeyDict[t]===e));let o=+n;isNaN(o)&&(o=n),i[r]=o}return i}function J(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0}}F.createNetaceaCookieV3=function(t){return Object.entries(t).map((([t,e])=>`${Y.netaceaCookieV3KeyDict[t]}=${encodeURIComponent(e)}`)).join("&")},F.cookieIsNetaceaV3Format=function(t){return void 0!==t&&t.split("&").map((t=>t.split("=")[0])).every((t=>Object.values(Y.netaceaCookieV3KeyDict).includes(t)))},F.objectIsNetaceaCookieV3=function(t){if("object"!=typeof t||null===t)return!1;for(const e of Object.keys(Y.netaceaCookieV3KeyDict)){if(!(e in t))return!1;if(void 0===t[e])return!1}return!0},F.checkNetaceaCookieV3=function(t,e){if(void 0===t||""===t)return J();const i=W(t);if(void 0!==i){const t=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<t,n=e===i.clientIP;return{mitata:i,requiresReissue:a||!n,isExpired:a,shouldExpire:[1,3,5].includes(i.captcha),isSameIP:n,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha}}return J()},F.matchNetaceaCookieV3=W,F.defaultInvalidResponse=J;var Z={},Q={};function tt(t,e){const i=t.split(";").map((t=>t.trim())).filter((t=>t.toLowerCase().startsWith(e.toLowerCase())))[0];return void 0!==i&&i.length>0?null==i?void 0:i.replace(`${e}=`,""):void 0}function et(t,e=!1){if(""===t)return"";return t.replace(/ /g,"").split(";").map((t=>t.charAt(0).toUpperCase()+t.slice(1))).filter(((t,i,a)=>{const n=t=>t.split("=")[0],r=n(t),o=a.map(n);return e?i===o.lastIndexOf(r):i===o.indexOf(r)})).join("; ")}Object.defineProperty(Q,"__esModule",{value:!0}),Q.removeDuplicateAttrs=Q.extractCookieAttr=Q.extractAndRemoveCookieAttr=Q.configureCookiesDomain=void 0,Q.configureCookiesDomain=function(t,e){let i=t=et(null!=t?t:"",!0),a=e=et(null!=e?e:"",!0);if(void 0!==t&&void 0!==e){const n=tt(t,"Domain"),r=tt(e,"Domain");void 0!==n&&void 0!==r?a=e.replace(r,n):void 0!==n&&void 0===r?a=e+(""!==e?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==r&&(i=t+(""!==t?`; Domain=${r}`:`Domain=${r}`))}else if(void 0!==t&&void 0===e){const e=tt(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}else if(void 0===t&&void 0!==e){const t=tt(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},Q.extractAndRemoveCookieAttr=function(t,e){const i=tt(t,e);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:t.replace(/ /g,"").replace(`${e}=${i}`,"").split(";").filter((t=>t.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:t}},Q.extractCookieAttr=tt,Q.removeDuplicateAttrs=et,Object.defineProperty(Z,"__esModule",{value:!0}),Z.lib=void 0;const it=Q;Z.lib={cookieAttributes:it},function(t){var e=f&&f.__createBinding||(Object.create?function(t,e,i,a){void 0===a&&(a=i),Object.defineProperty(t,a,{enumerable:!0,get:function(){return e[i]}})}:function(t,e,i,a){void 0===a&&(a=i),t[a]=e[i]}),i=f&&f.__exportStar||function(t,i){for(var a in t)"default"===a||i.hasOwnProperty(a)||e(i,t,a)};Object.defineProperty(t,"__esModule",{value:!0});const a=d;i(d,t),i(g,t),i(G,t);var n=m;Object.defineProperty(t,"matchMitataCookie",{enumerable:!0,get:function(){return n.matchMitataCookie}}),Object.defineProperty(t,"checkMitataCookie",{enumerable:!0,get:function(){return n.checkMitataCookie}}),Object.defineProperty(t,"createMitataCookie",{enumerable:!0,get:function(){return n.createMitataCookie}}),Object.defineProperty(t,"generateId",{enumerable:!0,get:function(){return n.generateId}}),Object.defineProperty(t,"hexSha256",{enumerable:!0,get:function(){return n.hexSha256}}),Object.defineProperty(t,"ingestIgnoredIpValue",{enumerable:!0,get:function(){return n.ingestIgnoredIpValue}}),Object.defineProperty(t,"warmupCookie",{enumerable:!0,get:function(){return n.warmupCookie}});var r=F;Object.defineProperty(t,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return r.matchNetaceaCookieV3}}),Object.defineProperty(t,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return r.cookieIsNetaceaV3Format}}),Object.defineProperty(t,"createNetaceaCookieV3",{enumerable:!0,get:function(){return r.createNetaceaCookieV3}}),Object.defineProperty(t,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return r.checkNetaceaCookieV3}}),Object.defineProperty(t,"defaultInvalidResponse",{enumerable:!0,get:function(){return r.defaultInvalidResponse}}),Object.defineProperty(t,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return r.objectIsNetaceaCookieV3}}),t.dictionary=y;var o=Z;Object.defineProperty(t,"lib",{enumerable:!0,get:function(){return o.lib}}),t.default=a.default}(l);const{configureCookiesDomain:at}=l.lib.cookieAttributes,nt="PMUSER_NETACEA_";class rt{constructor(t){this.getBoolean=(t,e)=>{const i=this.getString(t);return void 0!==i?"true"===(i?.toLowerCase()??"false"):e},this.request=t}getString(t,e){t.startsWith(nt)&&(t=t.slice(15));const i=`${nt}${t}`,a=this.request.getVariable(i)??e;return Boolean(a)?a:e}}class ot{constructor(t){this.defaults=t}loadConfig(t){const e=new rt(t),i=e.getString("MITIGATION_TYPE",this.defaults.mitigationType),a=e.getString("INGEST_TYPE",this.defaults.ingestType),n=e.getString("COOKIE_ATTR"),r=e.getString("CAP_COOKIE_ATTR"),{cookieAttributes:o,captchaCookieAttributes:s}=at(n,r);let c=e.getString("CAPT_PATH");void 0!==c&&c.length>0&&"/"!==c?.[0]&&(c=`/${c}`);const u=e.getString("SECRET_KEY",this.defaults.secretKey);if(void 0===u)throw new Error("A secret key is required to configure this integration.");const h={...this.defaults,apiKey:e.getString("API_KEY",this.defaults.apiKey),cookieEncryptionKey:e.getString("ENCRYPTION_KEY",this.defaults.cookieEncryptionKey),ingestType:a,mitigationType:i,netaceaCaptchaCookieAttributes:s??"",netaceaCaptchaCookieName:e.getString("CAPT_COOKIE_NAME",this.defaults.netaceaCaptchaCookieName),netaceaCookieAttributes:o??"",netaceaCookieExpirySeconds:st(this.defaults,i),netaceaCookieName:e.getString("COOKIE_NAME",this.defaults.netaceaCookieName),netaceaCaptchaPath:c,netaceaCaptchaHeaderKey:e.getString("CAPT_HEADER_KEY"),netaceaCaptchaHeaderValue:e.getString("CAPT_HEADER_VALUE"),captchaContentNegotiation:e.getBoolean("CAPT_CONTENT_NGT",!1),secretKey:u,useCaptchaRelAssets:e.getBoolean("CAPT_REL_ASSETS",this.defaults.useCaptchaRelAssets)??!1,protoMitataVariableName:"PMUSER_NETACEA_PROTO_MITATA",encryptedCookieNames:[]},p=e.getString("MITIGATION_URL");h.mitigationServiceUrl=void 0!==p?p:this.defaults.mitigationServiceUrl??"https://mitigations.netacea.net";const f=e.getString("INGEST_URL");return h.ingestServiceUrl=void 0!==f?f:this.defaults.ingestServiceUrl??"https://ingest.netacea.net",void 0===h.netaceaCookieName&&(h.netaceaCookieName="_mitata"),void 0===h.netaceaCaptchaCookieName&&(h.netaceaCaptchaCookieName="_mitatacaptcha"),h.encryptedCookieNames.push(h.netaceaCookieName),h.encryptedCookieNames.push(h.netaceaCaptchaCookieName),void 0!==h.netaceaCaptchaHeaderKey&&void 0===h.netaceaCaptchaHeaderValue&&(h.netaceaCaptchaHeaderValue="true"),h}}function st(t,e){const i=t.netaceaCookieExpirySeconds??t.mitataCookieExpirySeconds;return void 0===i?e===l.NetaceaMitigationType.INGEST?3600:60:i}const ct=/\.(js|css)$/i;function ut(t,e,i){if(!i)return!1;const a=t.toLowerCase();return/\/?mitigations\//.test(a)&&ht(t,e)}function ht(t,e){const i=t.toLowerCase();return ct.test(i)&&"get"===e.toLowerCase()}function pt(t,e){return/\/?ataverifycaptcha$/.test(t.toLowerCase())&&"post"===e.toLowerCase()}var ft=i.crypto??i;const lt=s.TextEncoder??global.TextEncoder,dt=s.TextDecoder??global.TextDecoder;function gt(t){return"string"==typeof t?(new lt).encode(t):t}async function yt(t,e){const i=await mt(gt(e));return new Uint8Array(await ft.subtle.sign("HMAC",i,t))}async function mt(t){return await ft.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}for(var wt={},It={byteLength:function(t){var e=kt(t),i=e[0],a=e[1];return 3*(i+a)/4-a},toByteArray:function(t){var e,i,a=kt(t),n=a[0],r=a[1],o=new St(function(t,e,i){return 3*(e+i)/4-i}(0,n,r)),s=0,c=r>0?n-4:n;for(i=0;i<c;i+=4)e=vt[t.charCodeAt(i)]<<18|vt[t.charCodeAt(i+1)]<<12|vt[t.charCodeAt(i+2)]<<6|vt[t.charCodeAt(i+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=255&e;2===r&&(e=vt[t.charCodeAt(i)]<<2|vt[t.charCodeAt(i+1)]>>4,o[s++]=255&e);1===r&&(e=vt[t.charCodeAt(i)]<<10|vt[t.charCodeAt(i+1)]<<4|vt[t.charCodeAt(i+2)]>>2,o[s++]=e>>8&255,o[s++]=255&e);return o},fromByteArray:function(t){for(var e,i=t.length,a=i%3,n=[],r=16383,o=0,s=i-a;o<s;o+=r)n.push(At(t,o,o+r>s?s:o+r));1===a?(e=t[i-1],n.push(Ct[e>>2]+Ct[e<<4&63]+"==")):2===a&&(e=(t[i-2]<<8)+t[i-1],n.push(Ct[e>>10]+Ct[e>>4&63]+Ct[e<<2&63]+"="));return n.join("")}},Ct=[],vt=[],St="undefined"!=typeof Uint8Array?Uint8Array:Array,bt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Et=0;Et<64;++Et)Ct[Et]=bt[Et],vt[bt.charCodeAt(Et)]=Et;function kt(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=t.indexOf("=");return-1===i&&(i=e),[i,i===e?0:4-i%4]}function At(t,e,i){for(var a,n,r=[],o=e;o<i;o+=3)a=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),r.push(Ct[(n=a)>>18&63]+Ct[n>>12&63]+Ct[n>>6&63]+Ct[63&n]);return r.join("")}vt["-".charCodeAt(0)]=62,vt["_".charCodeAt(0)]=63;var Nt={
1
+ import{httpRequest as t}from"http-request";import{logger as e}from"log";import*as i from"crypto";import a from"crypto";import n from"buffer";import r from"querystring";import o from"url";import*as s from"encoding";var c,u,h,p,f="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},l={},d={},g={};c=g,Object.defineProperty(c,"__esModule",{value:!0}),c.NetaceaCookieV3IssueReason=c.NetaceaMitigationType=c.NetaceaLogVersion=c.NetaceaIngestType=void 0,(u=c.NetaceaIngestType||(c.NetaceaIngestType={})).ORIGIN="ORIGIN",u.HTTP="HTTP",u.KINESIS="KINESIS",u.NATIVE="NATIVE",(h=c.NetaceaLogVersion||(c.NetaceaLogVersion={})).V1="V1",h.V2="V2",function(t){t.MITIGATE="MITIGATE",t.INJECT="INJECT",t.INGEST="INGEST"}(c.NetaceaMitigationType||(c.NetaceaMitigationType={})),(p=c.NetaceaCookieV3IssueReason||(c.NetaceaCookieV3IssueReason={})).NO_SESSION="no_session",p.EXPIRED_SESSION="expired_session",p.INVALID_SESSION="invalid_session",p.IP_CHANGE="ip_change";var y={};!function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.netaceaSettingsMap=t.netaceaCookieV3OptionalKeyMap=t.netaceaCookieV3KeyMap=t.bestMitigationCaptchaMap=t.bestMitigationMap=t.captchaStatusCodes=t.captchaMap=t.mitigateMap=t.matchMap=t.netaceaHeaders=t.mitigationTypes=t.COOKIEDELIMITER=void 0,t.COOKIEDELIMITER="_/@#/",t.mitigationTypes={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},t.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"},t.matchMap={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},t.mitigateMap={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},t.captchaMap={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},t.captchaStatusCodes={"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},t.bestMitigationMap={0:t.mitigationTypes.none,1:t.mitigationTypes.block,2:t.mitigationTypes.none,3:t.mitigationTypes.block,4:t.mitigationTypes.block},t.bestMitigationCaptchaMap={1:t.mitigationTypes.captcha,2:t.mitigationTypes.captchaPass,3:t.mitigationTypes.captcha,4:t.mitigationTypes.allow,5:t.mitigationTypes.captcha},t.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},t.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},t.netaceaSettingsMap={checkAllPostRequests:"checkAllPostRequests"}}(y);var m={};Object.defineProperty(m,"__esModule",{value:!0}),m.checkMitataCookie=m.warmupCookie=m.hexSha256=m.createMitataCookie=m.generateId=m.matchMitataCookie=m.ingestIgnoredIpValue=void 0;const w=a,C=y,I=n;m.ingestIgnoredIpValue="ignored";const v="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),S=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function b(t){if(void 0===t)return;const e=t.match(S);if(null!=e){const[,t,i,a,n,r,o,s,c]=e;return{signature:t,expiry:i,userId:a,ipHash:n,mitigationType:r,match:parseInt(o),mitigate:parseInt(s),captcha:parseInt(c)}}}function E(t=16,e=v){const i=w.randomBytes(t-1);return`c${Array.from(i).map((t=>e[t%e.length])).join("")}`}function k(t,e){const i=w.createHmac("sha256",e);return i.update(t),I.Buffer.from(i.digest("hex")).toString("base64")}m.matchMitataCookie=b,m.generateId=E,m.createMitataCookie=function(t,e,i,a,n="000"){void 0===e&&(e=E());const r=[i,e,k(t+"|"+String(i),a),n].join(C.COOKIEDELIMITER);return`${k(r,a)}${C.COOKIEDELIMITER}${r}`},m.hexSha256=k,m.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"},m.checkMitataCookie=function(t,e,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof t||""===t)return a;const n=b(t);if(void 0!==n){const t=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(C.COOKIEDELIMITER),a=Math.floor(Date.now()/1e3),r=parseInt(n.expiry)<a,o=[1,3,5].includes(n.captcha),s=k(e+"|"+n.expiry,i),c=n.ipHash===s;return{mitata:n,requiresReissue:r||!c,isExpired:r,shouldExpire:o,isSameIP:c,isPrimaryHashValid:n.signature===k(t,i),match:n.match,mitigate:n.mitigate,captcha:n.captcha}}return a};var A={},N={},T={},M={},x=function(t){return new P(t)};function P(t){this.capacity=0|t,this.map=Object.create(null),this.list=new _}function _(){this.firstNode=null,this.lastNode=null}function R(t,e){this.key=t,this.val=e,this.prev=null,this.next=null}P.prototype.get=function(t){var e=this.map[t];if(null!=e)return this.used(e),e.val},P.prototype.set=function(t,e){var i=this.map[t];if(null!=i)i.val=e;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new R(t,e),this.map[t]=i,this.capacity--}return this.used(i),!0},P.prototype.used=function(t){this.list.moveToFront(t)},P.prototype.prune=function(){var t=this.list.pop();null!=t&&(delete this.map[t.key],this.capacity++)},_.prototype.moveToFront=function(t){this.firstNode!=t&&(this.remove(t),null==this.firstNode?(this.firstNode=t,this.lastNode=t,t.prev=null,t.next=null):(t.prev=null,t.next=this.firstNode,t.next.prev=t,this.firstNode=t))},_.prototype.pop=function(){var t=this.lastNode;return null!=t&&this.remove(t),t},_.prototype.remove=function(t){this.firstNode==t?this.firstNode=t.next:null!=t.prev&&(t.prev.next=t.next),this.lastNode==t?this.lastNode=t.prev:null!=t.next&&(t.next.prev=t.prev)},function(t){var e=M,i=o,n=r,s=a,c=x(1e3);function u(t,e,i){return s.createHmac("sha256",t).update(e,"utf8").digest(i)}function h(t,e){return s.createHash("sha256").update(t,"utf8").digest(e)}function p(t){return t.replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}function f(t){return p(encodeURIComponent(t))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function d(t,e){"string"==typeof t&&(t=i.parse(t));var a=t.headers=t.headers||{},n=(!this.service||!this.region)&&this.matchHost(t.hostname||t.host||a.Host||a.host);this.request=t,this.credentials=e||this.defaultCredentials(),this.service=t.service||n[0]||"",this.region=t.region||n[1]||"us-east-1","email"===this.service&&(this.service="ses"),!t.method&&t.body&&(t.method="POST"),a.Host||a.host||(a.Host=t.hostname||t.host||this.createHost(),t.port&&(a.Host+=":"+t.port)),t.hostname||t.host||(t.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===t.method}d.prototype.matchHost=function(t){var e=((t||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===e[1]&&(e=e.reverse()),"s3"==e[1])e[0]="s3",e[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(e[i])){e[1]=e[i].slice(3),e[0]="s3";break}return e},d.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},d.prototype.createHost=function(){var t=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+t+".amazonaws.com"},d.prototype.prepareRequest=function(){this.parsePath();var t,e=this.request,i=e.headers;e.signQuery?(this.parsedPath.query=t=this.parsedPath.query||{},this.credentials.sessionToken&&(t["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||t["X-Amz-Expires"]||(t["X-Amz-Expires"]=86400),t["X-Amz-Date"]?this.datetime=t["X-Amz-Date"]:t["X-Amz-Date"]=this.getDateTime(),t["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",t["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),t["X-Amz-SignedHeaders"]=this.signedHeaders()):(e.doNotModifyHeaders||this.isCodeCommitGit||(!e.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!e.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(e.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=h(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},d.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},d.prototype.getDateTime=function(){if(!this.datetime){var t=this.request.headers,e=new Date(t.Date||t.date||new Date);this.datetime=e.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},d.prototype.getDate=function(){return this.getDateTime().substr(0,8)},d.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},d.prototype.signature=function(){var t,e,i,a=this.getDate(),n=[this.credentials.secretAccessKey,a,this.region,this.service].join(),r=c.get(n);return r||(t=u("AWS4"+this.credentials.secretAccessKey,a),e=u(t,this.region),i=u(e,this.service),r=u(i,"aws4_request"),c.set(n,r)),u(r,this.stringToSign(),"hex")},d.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),h(this.canonicalString(),"hex")].join("\n")},d.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var t,e=this.parsedPath.path,i=this.parsedPath.query,a=this.request.headers,n="",r="s3"!==this.service,o="s3"===this.service||this.request.doNotEncodePath,s="s3"===this.service,c="s3"===this.service;if(t="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||h(this.request.body||"","hex"),i){var u=Object.keys(i).reduce((function(t,e){return e?(t[f(e)]=Array.isArray(i[e])&&c?i[e][0]:i[e],t):t}),{}),p=[];Object.keys(u).sort().forEach((function(t){Array.isArray(u[t])?u[t].map(f).sort().forEach((function(e){p.push(t+"="+e)})):p.push(t+"="+f(u[t]))})),n=p.join("&")}return"/"!==e&&(r&&(e=e.replace(/\/{2,}/g,"/")),"/"!==(e=e.split("/").reduce((function(t,e){return r&&".."===e?t.pop():r&&"."===e||(o&&(e=decodeURIComponent(e.replace(/\+/g," "))),t.push(f(e))),t}),[]).join("/"))[0]&&(e="/"+e),s&&(e=e.replace(/%2F/g,"/"))),[this.request.method||"GET",e,n,this.canonicalHeaders()+"\n",this.signedHeaders(),t].join("\n")},d.prototype.canonicalHeaders=function(){var t=this.request.headers;return Object.keys(t).filter((function(t){return null==l[t.toLowerCase()]})).sort((function(t,e){return t.toLowerCase()<e.toLowerCase()?-1:1})).map((function(e){return e.toLowerCase()+":"+t[e].toString().trim().replace(/\s+/g," ")})).join("\n")},d.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(t){return t.toLowerCase()})).filter((function(t){return null==l[t]})).sort().join(";")},d.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},d.prototype.defaultCredentials=function(){var t=process.env;return{accessKeyId:t.AWS_ACCESS_KEY_ID||t.AWS_ACCESS_KEY,secretAccessKey:t.AWS_SECRET_ACCESS_KEY||t.AWS_SECRET_KEY,sessionToken:t.AWS_SESSION_TOKEN}},d.prototype.parsePath=function(){var t=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(t)&&(t=encodeURI(decodeURI(t)));var e=t.indexOf("?"),i=null;e>=0&&(i=n.parse(t.slice(e+1)),t=t.slice(0,e)),this.parsedPath={path:t,query:i}},d.prototype.formatPath=function(){var t=this.parsedPath.path,e=this.parsedPath.query;return e?(null!=e[""]&&delete e[""],t+"?"+p(n.stringify(e))):t},e.RequestSigner=d,e.sign=function(t,e){return new d(t,e).sign()}}();var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.API_VERSION=O.REGION=O.PAYLOAD_TYPE=O.STATE=void 0,O.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},O.PAYLOAD_TYPE="string",O.REGION="eu-west-1",O.API_VERSION="2013-12-02",Object.defineProperty(T,"__esModule",{value:!0});const B=M,U=O;T.default=class{static batchArrayForKinesis(t,e){const i=[];for(let a=0;a<t.length;a+=e){const n=t.slice(a,a+e);i.push({Data:Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}static signRequest(t,e,i){const{accessKeyId:a,secretAccessKey:n}=t,r={Records:this.batchArrayForKinesis(e,i),PartitionKey:Date.now().toString(),StreamName:t.streamName};return B.sign({service:"kinesis",body:JSON.stringify(r),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:U.REGION},{accessKeyId:a,secretAccessKey:n})}},Object.defineProperty(N,"__esModule",{value:!0});const K=T;N.default=class{constructor({kinesisStreamName:t,kinesisAccessKey:e,kinesisSecretKey:i,maxLogAgeSeconds:a,logBatchSize:n}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=t,this.kinesisAccessKey=e,this.kinesisSecretKey=i,void 0!==a&&a<this.maxLogAgeSeconds&&a>0&&(this.maxLogAgeSeconds=a),void 0!==n&&(this.logBatchSize=n)}async putToKinesis(t){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const i=K.default.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await t({headers:i.headers,host:`https://${i.hostname}`,method:i.method,path:i.path,body:i.body})}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(t,e){if(this.logCache.push(t),this.intervalSet||(this.intervalSet=!0,await async function(t){await new Promise((e=>{setTimeout(e,t)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(e),this.intervalSet=!1),this.logCache.length>=this.logBatchSize)return await this.putToKinesis(e)}},Object.defineProperty(A,"__esModule",{value:!0});const V=N;A.default=V.default,Object.defineProperty(d,"__esModule",{value:!0}),d.configureMitataExpiry=d.safeParseInt=d.correctTimeout=void 0;const H=g,j=y,$=m,L=A;function D(t){return t<=0?z:t}function q(t,e=0){return isNaN(t)?e:parseInt(t)}d.correctTimeout=D,d.safeParseInt=q;const z=3e3;function X(t,e){return void 0===e?t===H.NetaceaMitigationType.INGEST?3600:60:e}d.configureMitataExpiry=X;d.default=class{constructor({apiKey:t,secretKey:e,timeout:i=z,mitigationServiceUrl:a="https://mitigations.netacea.net",ingestServiceUrl:n="https://ingest.netacea.net",mitigationType:r=H.NetaceaMitigationType.INGEST,captchaSiteKey:o,captchaSecretKey:s,ingestType:c=H.NetaceaIngestType.HTTP,kinesis:u,logVersion:h,mitataCookieExpirySeconds:p,netaceaCookieExpirySeconds:f,netaceaCookieName:l,netaceaCaptchaCookieName:d}){if(this.encryptedCookies=[],null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=e,this.mitigationServiceUrl=a,this.ingestServiceUrl=n,this.mitigationType=r,this.ingestType=null!=c?c:H.NetaceaIngestType.HTTP,this.logVersion=null!=h?h:H.NetaceaLogVersion.V1,this.ingestType===H.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new L.default({...u,apiKey:this.apiKey})),void 0===o&&void 0===s||(this.captchaSiteKey=o,this.captchaSecretKey=s),this.timeout=D(i),this.netaceaCookieName=null!=l?l:"_mitata",this.netaceaCaptchaCookieName=null!=d?d:"_mitatacaptcha",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=X(r,null!=f?f:p)}async runMitigation(t){try{switch(this.mitigationType){case H.NetaceaMitigationType.MITIGATE:return await this.mitigate(t);case H.NetaceaMitigationType.INJECT:return await this.inject(t);case H.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(t,e){if(null==e)return;if("string"==typeof e)return await this.readCookie(t,e.split(";"));const i=`${t}=`;for(const a of e){const e=a.split(";")[0].trimStart();if(e.startsWith(i)){const a=e.slice(i.length);if(this.encryptedCookies.includes(t))try{return await this.decryptCookieValue(a)}catch(t){return}return a}}}async callIngest(t){const e=this.constructWebLog(t);if(this.ingestType===H.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({...e,apiKey:this.apiKey},this.makeRequest.bind(this))}catch(t){console.error("NETACEA Error: ",t.message)}}else{const t={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(t,e);if(200!==i.status)throw this.APIError(i)}}async makeIngestApiCall(t,e){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:t,body:JSON.stringify(e),timeout:this.timeout})}constructV2WebLog({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){var l;const d=new Date;let g;"/"!==n[0]&&(n=`/${n}`);const y=n.split("?");y.length>1&&(g=`?${y[1]}`);const m=y[0],w=null===(l=$.matchMitataCookie(u))||void 0===l?void 0:l.userId;return{status:i,method:a,bytes_sent:q(s),referrer:""===o?void 0:o,request:`${a} ${m}${null!=g?g:""} ${r}`,request_time:q(c),integration_type:p,integration_version:f,client:t,user_agent:e,bc_type:""===h?void 0:h,hour:d.getUTCHours(),minute:d.getUTCMinutes(),"@timestamp":d.toISOString().replace("Z","+00:00"),path:m,protocol:r,query:g,user_id:w}}constructV1WebLog({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){return{Request:`${a} ${n} ${r}`,TimeLocal:(new Date).toUTCString(),RealIp:t,UserAgent:e,Status:i,RequestTime:null==c?void 0:c.toString(),BytesSent:null==s?void 0:s.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:null!=u?u:"",NetaceaMitigationApplied:null!=h?h:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=f?f:""}}constructWebLog(t){return t.bytesSent=""===t.bytesSent?"0":t.bytesSent,this.logVersion===H.NetaceaLogVersion.V2?this.constructV2WebLog(t):this.constructV1WebLog(t)}async check(t,e,i,a){var n,r;let o,s,c,u,h,p,f;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const l=$.checkMitataCookie(t,e,this.secretKey);if(!l.isPrimaryHashValid||l.requiresReissue){const t=await this.makeMitigateAPICall(null===(n=l.mitata)||void 0===n?void 0:n.userId,e,i,a);o=t.status,s=t.match,c=t.mitigate,u=t.captcha,h=t.body,p=[await this.createMitata(e,null===(r=l.mitata)||void 0===r?void 0:r.userId,s,c,u,t.mitataMaxAge)],f=t.eventId}else o=-1,s=l.match,c=l.mitigate,u=l.captcha,h=void 0,p=[];return this.composeResult(h,p,o,s,c,u,!1,f)}async createMitata(t,e,i,a,n,r=86400,o=void 0){const s=[1,3,5].includes(n)?-this.mitataCookieExpirySeconds:this.mitataCookieExpirySeconds,c=null!=o?o:Math.floor(Date.now()/1e3)+s;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join(""),h=$.createMitataCookie(t,e,c,this.secretKey,u);return await this.buildCookieFromValues(this.netaceaCookieName,h,r,"/")}async processCaptcha(t,e,i,a){const{status:n,match:r,mitigate:o,captcha:s,body:c,setCookie:u}=await this.makeCaptchaAPICall(t,e,i,a);return this.composeResult(c,u,n,r,o,s,!0)}async getMitataCaptchaFromHeaders(t){if(Object.prototype.hasOwnProperty.call(t,j.netaceaHeaders.mitataCaptcha)){const e=t[j.netaceaHeaders.mitataCaptcha],i=parseInt(t[j.netaceaHeaders.mitataCaptchaExpiry]),a=await this.buildCookieFromValues(this.netaceaCaptchaCookieName,e,i);if(void 0!==a)return a}}async makeCaptchaAPICall(t,e,i,a){const n={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},r=$.matchMitataCookie(t);void 0!==r&&(n["X-Netacea-UserId"]=r.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const o=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:n,method:"POST",body:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(o,null==r?void 0:r.userId,e)}async getApiCallResponseFromResponse(t,e,i){if(200!==t.status)throw this.APIError(t);const a=parseInt(t.headers[j.netaceaHeaders.match]),n=parseInt(t.headers[j.netaceaHeaders.mitigate]),r=parseInt(t.headers[j.netaceaHeaders.captcha]);let o=parseInt(t.headers[j.netaceaHeaders.mitataExpiry]);isNaN(o)&&(o=86400);const s=[await this.createMitata(i,e,a,n,r),await this.getMitataCaptchaFromHeaders(t.headers)].filter((t=>void 0!==t)),c=t.headers[j.netaceaHeaders.eventId];return{status:t.status,match:a,mitigate:n,captcha:r,setCookie:s,body:t.body,eventId:c,mitataMaxAge:o}}async buildCookieFromValues(t,e,i,a="/"){if(this.encryptedCookies.includes(t)){return`${t}=${await this.encryptCookieValue(e)}; Max-Age=${i}; Path=${a}`}return`${t}=${e}; Max-Age=${i}; Path=${a}`}buildCookieHeader(t){let e="",i="";for(const a in t){const n=t[a];void 0!==n&&(e=`${e}${i}${a}=${n}`,i="; ")}return e}async makeMitigateAPICall(t,e,i,a){const n={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":e,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==t&&(n["X-Netacea-UserId"]=t),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const r=await this.makeRequest({host:this.mitigationServiceUrl,path:"/",headers:n,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(r,t,e)}composeResult(t,e,i,a,n,r,o,s){const c=this.findBestMitigation(a,n,r,o),u={body:t,apiCallStatus:i,setCookie:e,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[j.mitigationTypes.block,j.mitigationTypes.captcha,j.mitigationTypes.captchaPass].includes(c.mitigation)};if(this.mitigationType===H.NetaceaMitigationType.INJECT){const t={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==s&&(t["x-netacea-event-id"]=s),u.injectHeaders=t}return u}findBestMitigation(t,e,i,a){var n,r,o;const s="unknown";a||(2===i?i=4:3===i&&(i=5));let c=null!==(n=j.matchMap[t])&&void 0!==n?n:s+"_";c+=null!==(r=j.mitigateMap[e])&&void 0!==r?r:s;let u=j.bestMitigationMap[e];if(0!==i){c+=","+(null!==(o=j.captchaMap[i])&&void 0!==o?o:s);const t=j.bestMitigationCaptchaMap[i];void 0!==t&&(u=t)}return this.mitigationType===H.NetaceaMitigationType.INJECT&&(u=j.mitigationTypes.none),{sessionStatus:c,mitigation:u,parts:{match:t,mitigate:e,captcha:i}}}APIError(t){let e="Unknown error";switch(t.status){case 403:e="Invalid credentials";break;case 500:e="Server error";break;case 502:e="Bad Gateway";break;case 503:e="Service Unavailable";break;case 400:e="Invalid request"}return new Error(`Error reaching Netacea API (${e}), status: ${t.status}`)}isUrlCaptchaPost(t,e){return t.includes("/AtaVerifyCaptcha")&&"post"===e.toLowerCase()}async processMitigateRequest(t){const e=this.isUrlCaptchaPost(t.url,t.method);return await(e?this.processCaptcha(t.mitata,t.clientIp,t.userAgent,await t.getBodyFn()):this.check(t.mitata,t.clientIp,t.userAgent,t.mitataCaptcha))}async setIngestOnlyMitataCookie(t){return{sessionStatus:"",setCookie:[await this.createMitata($.ingestIgnoredIpValue,t,0,0,0,86400)]}}async processIngest(t){var e;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const i=this.getCookieHeader(t),a=await this.readCookie(this.netaceaCookieName,i),n=$.checkMitataCookie(a,$.ingestIgnoredIpValue,this.secretKey);return n.isPrimaryHashValid?n.requiresReissue?await this.setIngestOnlyMitataCookie(null===(e=n.mitata)||void 0===e?void 0:e.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}async encryptCookieValue(t){return t}async decryptCookieValue(t){return t}};var G={};Object.defineProperty(G,"__esModule",{value:!0});var F={};Object.defineProperty(F,"__esModule",{value:!0}),F.defaultInvalidResponse=F.matchNetaceaCookieV3=F.checkNetaceaCookieV3=F.objectIsNetaceaCookieV3=F.cookieIsNetaceaV3Format=F.createNetaceaCookieV3=void 0;const Y=y;function W(t){if(void 0===t||""===t)return;const e=t.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const t of e){const[e,a]=t.split("="),n=decodeURIComponent(a);let r=Object.keys(Y.netaceaCookieV3KeyMap).find((t=>Y.netaceaCookieV3KeyMap[t]===e));void 0===r&&(r=Object.keys(Y.netaceaCookieV3OptionalKeyMap).find((t=>Y.netaceaCookieV3OptionalKeyMap[t]===e)));let o=""===n?void 0:Number(n);void 0!==o&&isNaN(o)&&(o=n),i[r]=o}return i}function J(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0}}F.createNetaceaCookieV3=function(t){return Object.entries(t).filter((([t,e])=>void 0!==e)).map((([t,e])=>t in Y.netaceaCookieV3OptionalKeyMap?`${Y.netaceaCookieV3OptionalKeyMap[t]}=${encodeURIComponent(e)}`:`${Y.netaceaCookieV3KeyMap[t]}=${encodeURIComponent(e)}`)).join("&")},F.cookieIsNetaceaV3Format=function(t){return void 0!==t&&t.split("&").map((t=>t.split("=")[0])).filter((t=>!Object.values(Y.netaceaCookieV3OptionalKeyMap).includes(t))).every((t=>Object.values(Y.netaceaCookieV3KeyMap).includes(t)))},F.objectIsNetaceaCookieV3=function(t){if("object"!=typeof t||null===t)return!1;for(const e of Object.keys(Y.netaceaCookieV3KeyMap)){if(!(e in t))return!1;if(void 0===t[e])return!1}return!0},F.checkNetaceaCookieV3=function(t,e){if(void 0===t||""===t)return J();const i=W(t);if(void 0!==i){const t=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<t,n=e===i.clientIP;return{mitata:i,requiresReissue:a||!n,isExpired:a,shouldExpire:[1,3,5].includes(i.captcha),isSameIP:n,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha}}return J()},F.matchNetaceaCookieV3=W,F.defaultInvalidResponse=J;var Z={},Q={};function tt(t,e){const i=t.split(";").map((t=>t.trim())).filter((t=>t.toLowerCase().startsWith(e.toLowerCase())))[0];return void 0!==i&&i.length>0?null==i?void 0:i.replace(`${e}=`,""):void 0}function et(t,e=!1){if(""===t)return"";return t.replace(/ /g,"").split(";").map((t=>t.charAt(0).toUpperCase()+t.slice(1))).filter(((t,i,a)=>{const n=t=>t.split("=")[0],r=n(t),o=a.map(n);return e?i===o.lastIndexOf(r):i===o.indexOf(r)})).join("; ")}Object.defineProperty(Q,"__esModule",{value:!0}),Q.removeDuplicateAttrs=Q.extractCookieAttr=Q.extractAndRemoveCookieAttr=Q.configureCookiesDomain=void 0,Q.configureCookiesDomain=function(t,e){let i=t=et(null!=t?t:"",!0),a=e=et(null!=e?e:"",!0);if(void 0!==t&&void 0!==e){const n=tt(t,"Domain"),r=tt(e,"Domain");void 0!==n&&void 0!==r?a=e.replace(r,n):void 0!==n&&void 0===r?a=e+(""!==e?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==r&&(i=t+(""!==t?`; Domain=${r}`:`Domain=${r}`))}else if(void 0!==t&&void 0===e){const e=tt(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}else if(void 0===t&&void 0!==e){const t=tt(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},Q.extractAndRemoveCookieAttr=function(t,e){const i=tt(t,e);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:t.replace(/ /g,"").replace(`${e}=${i}`,"").split(";").filter((t=>t.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:t}},Q.extractCookieAttr=tt,Q.removeDuplicateAttrs=et,Object.defineProperty(Z,"__esModule",{value:!0}),Z.lib=void 0;const it=Q;Z.lib={cookieAttributes:it},function(t){var e=f&&f.__createBinding||(Object.create?function(t,e,i,a){void 0===a&&(a=i),Object.defineProperty(t,a,{enumerable:!0,get:function(){return e[i]}})}:function(t,e,i,a){void 0===a&&(a=i),t[a]=e[i]}),i=f&&f.__exportStar||function(t,i){for(var a in t)"default"===a||i.hasOwnProperty(a)||e(i,t,a)};Object.defineProperty(t,"__esModule",{value:!0});const a=d;i(d,t),i(g,t),i(G,t);var n=m;Object.defineProperty(t,"matchMitataCookie",{enumerable:!0,get:function(){return n.matchMitataCookie}}),Object.defineProperty(t,"checkMitataCookie",{enumerable:!0,get:function(){return n.checkMitataCookie}}),Object.defineProperty(t,"createMitataCookie",{enumerable:!0,get:function(){return n.createMitataCookie}}),Object.defineProperty(t,"generateId",{enumerable:!0,get:function(){return n.generateId}}),Object.defineProperty(t,"hexSha256",{enumerable:!0,get:function(){return n.hexSha256}}),Object.defineProperty(t,"ingestIgnoredIpValue",{enumerable:!0,get:function(){return n.ingestIgnoredIpValue}}),Object.defineProperty(t,"warmupCookie",{enumerable:!0,get:function(){return n.warmupCookie}});var r=F;Object.defineProperty(t,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return r.matchNetaceaCookieV3}}),Object.defineProperty(t,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return r.cookieIsNetaceaV3Format}}),Object.defineProperty(t,"createNetaceaCookieV3",{enumerable:!0,get:function(){return r.createNetaceaCookieV3}}),Object.defineProperty(t,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return r.checkNetaceaCookieV3}}),Object.defineProperty(t,"defaultInvalidResponse",{enumerable:!0,get:function(){return r.defaultInvalidResponse}}),Object.defineProperty(t,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return r.objectIsNetaceaCookieV3}}),t.dictionary=y;var o=Z;Object.defineProperty(t,"lib",{enumerable:!0,get:function(){return o.lib}}),t.default=a.default}(l);const{configureCookiesDomain:at}=l.lib.cookieAttributes,nt="PMUSER_NETACEA_";class rt{constructor(t){this.getBoolean=(t,e)=>{const i=this.getString(t);return void 0!==i?"true"===(i?.toLowerCase()??"false"):e},this.request=t}getString(t,e){t.startsWith(nt)&&(t=t.slice(15));const i=`${nt}${t}`,a=this.request.getVariable(i)??e;return Boolean(a)?a:e}}class ot{constructor(t){this.defaults=t}loadConfig(t){const e=new rt(t),i=e.getString("MITIGATION_TYPE",this.defaults.mitigationType),a=e.getString("INGEST_TYPE",this.defaults.ingestType),n=e.getString("COOKIE_ATTR"),r=e.getString("CAP_COOKIE_ATTR"),{cookieAttributes:o,captchaCookieAttributes:s}=at(n,r);let c=e.getString("CAPT_PATH");void 0!==c&&c.length>0&&"/"!==c?.[0]&&(c=`/${c}`);const u=e.getString("SECRET_KEY",this.defaults.secretKey);if(void 0===u)throw new Error("A secret key is required to configure this integration.");const h={...this.defaults,apiKey:e.getString("API_KEY",this.defaults.apiKey),cookieEncryptionKey:e.getString("ENCRYPTION_KEY",this.defaults.cookieEncryptionKey),ingestType:a,mitigationType:i,netaceaCaptchaCookieAttributes:s??"",netaceaCaptchaCookieName:e.getString("CAPT_COOKIE_NAME",this.defaults.netaceaCaptchaCookieName),netaceaCookieAttributes:o??"",netaceaCookieExpirySeconds:st(this.defaults,i),netaceaCookieName:e.getString("COOKIE_NAME",this.defaults.netaceaCookieName),netaceaCaptchaPath:c,netaceaCaptchaHeaderKey:e.getString("CAPT_HEADER_KEY"),netaceaCaptchaHeaderValue:e.getString("CAPT_HEADER_VALUE"),captchaContentNegotiation:e.getBoolean("CAPT_CONTENT_NGT",!1),secretKey:u,useCaptchaRelAssets:e.getBoolean("CAPT_REL_ASSETS",this.defaults.useCaptchaRelAssets)??!1,protoMitataVariableName:"PMUSER_NETACEA_PROTO_MITATA",encryptedCookieNames:[]},p=e.getString("MITIGATION_URL");h.mitigationServiceUrl=void 0!==p?p:this.defaults.mitigationServiceUrl??"https://mitigations.netacea.net";const f=e.getString("INGEST_URL");return h.ingestServiceUrl=void 0!==f?f:this.defaults.ingestServiceUrl??"https://ingest.netacea.net",void 0===h.netaceaCookieName&&(h.netaceaCookieName="_mitata"),void 0===h.netaceaCaptchaCookieName&&(h.netaceaCaptchaCookieName="_mitatacaptcha"),h.encryptedCookieNames.push(h.netaceaCookieName),h.encryptedCookieNames.push(h.netaceaCaptchaCookieName),void 0!==h.netaceaCaptchaHeaderKey&&void 0===h.netaceaCaptchaHeaderValue&&(h.netaceaCaptchaHeaderValue="true"),h}}function st(t,e){const i=t.netaceaCookieExpirySeconds??t.mitataCookieExpirySeconds;return void 0===i?e===l.NetaceaMitigationType.INGEST?3600:60:i}const ct=/\.(js|css)$/i;function ut(t,e,i){if(!i)return!1;const a=t.toLowerCase();return/\/?mitigations\//.test(a)&&ht(t,e)}function ht(t,e){const i=t.toLowerCase();return ct.test(i)&&"get"===e.toLowerCase()}function pt(t,e){return/\/?ataverifycaptcha$/.test(t.toLowerCase())&&"post"===e.toLowerCase()}var ft=i.crypto??i;const lt=s.TextEncoder??global.TextEncoder,dt=s.TextDecoder??global.TextDecoder;function gt(t){return"string"==typeof t?(new lt).encode(t):t}async function yt(t,e){const i=await mt(gt(e));return new Uint8Array(await ft.subtle.sign("HMAC",i,t))}async function mt(t){return await ft.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}for(var wt={},Ct={byteLength:function(t){var e=kt(t),i=e[0],a=e[1];return 3*(i+a)/4-a},toByteArray:function(t){var e,i,a=kt(t),n=a[0],r=a[1],o=new St(function(t,e,i){return 3*(e+i)/4-i}(0,n,r)),s=0,c=r>0?n-4:n;for(i=0;i<c;i+=4)e=vt[t.charCodeAt(i)]<<18|vt[t.charCodeAt(i+1)]<<12|vt[t.charCodeAt(i+2)]<<6|vt[t.charCodeAt(i+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=255&e;2===r&&(e=vt[t.charCodeAt(i)]<<2|vt[t.charCodeAt(i+1)]>>4,o[s++]=255&e);1===r&&(e=vt[t.charCodeAt(i)]<<10|vt[t.charCodeAt(i+1)]<<4|vt[t.charCodeAt(i+2)]>>2,o[s++]=e>>8&255,o[s++]=255&e);return o},fromByteArray:function(t){for(var e,i=t.length,a=i%3,n=[],r=16383,o=0,s=i-a;o<s;o+=r)n.push(At(t,o,o+r>s?s:o+r));1===a?(e=t[i-1],n.push(It[e>>2]+It[e<<4&63]+"==")):2===a&&(e=(t[i-2]<<8)+t[i-1],n.push(It[e>>10]+It[e>>4&63]+It[e<<2&63]+"="));return n.join("")}},It=[],vt=[],St="undefined"!=typeof Uint8Array?Uint8Array:Array,bt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Et=0;Et<64;++Et)It[Et]=bt[Et],vt[bt.charCodeAt(Et)]=Et;function kt(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=t.indexOf("=");return-1===i&&(i=e),[i,i===e?0:4-i%4]}function At(t,e,i){for(var a,n,r=[],o=e;o<i;o+=3)a=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),r.push(It[(n=a)>>18&63]+It[n>>12&63]+It[n>>6&63]+It[63&n]);return r.join("")}vt["-".charCodeAt(0)]=62,vt["_".charCodeAt(0)]=63;var Nt={
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  read:function(t,e,i,a,n){var r,o,s=8*n-a-1,c=(1<<s)-1,u=c>>1,h=-7,p=i?n-1:0,f=i?-1:1,l=t[e+p];for(p+=f,r=l&(1<<-h)-1,l>>=-h,h+=s;h>0;r=256*r+t[e+p],p+=f,h-=8);for(o=r&(1<<-h)-1,r>>=-h,h+=a;h>0;o=256*o+t[e+p],p+=f,h-=8);if(0===r)r=1-u;else{if(r===c)return o?NaN:1/0*(l?-1:1);o+=Math.pow(2,a),r-=u}return(l?-1:1)*o*Math.pow(2,r-a)},write:function(t,e,i,a,n,r){var o,s,c,u=8*r-n-1,h=(1<<u)-1,p=h>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,l=a?0:r-1,d=a?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),(e+=o+p>=1?f/c:f*Math.pow(2,1-p))*c>=2&&(o++,c/=2),o+p>=h?(s=0,o=h):o+p>=1?(s=(e*c-1)*Math.pow(2,n),o+=p):(s=e*Math.pow(2,p-1)*Math.pow(2,n),o=0));n>=8;t[i+l]=255&s,l+=d,s/=256,n-=8);for(o=o<<n|s,u+=n;u>0;t[i+l]=255&o,l+=d,o/=256,u-=8);t[i+l-d]|=128*g}};
4
4
  /*!
@@ -7,4 +7,4 @@ read:function(t,e,i,a,n){var r,o,s=8*n-a-1,c=(1<<s)-1,u=c>>1,h=-7,p=i?n-1:0,f=i?
7
7
  * @author Feross Aboukhadijeh <https://feross.org>
8
8
  * @license MIT
9
9
  */
10
- !function(t){const e=It,i=Nt,a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=function(t){+t!=t&&(t=0);return o.alloc(+t)},t.INSPECT_MAX_BYTES=50;const n=2147483647;function r(t){if(t>n)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,o.prototype),e}function o(t,e,i){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return u(t)}return s(t,e,i)}function s(t,e,i){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const i=0|l(t,e);let a=r(i);const n=a.write(t,e);n!==i&&(a=a.slice(0,n));return a}(t,e);if(ArrayBuffer.isView(t))return function(t){if(G(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return h(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(G(t,ArrayBuffer)||t&&G(t.buffer,ArrayBuffer))return p(t,e,i);if("undefined"!=typeof SharedArrayBuffer&&(G(t,SharedArrayBuffer)||t&&G(t.buffer,SharedArrayBuffer)))return p(t,e,i);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=t.valueOf&&t.valueOf();if(null!=a&&a!==t)return o.from(a,e,i);const n=function(t){if(o.isBuffer(t)){const e=0|f(t.length),i=r(e);return 0===i.length||t.copy(i,0,0,e),i}if(void 0!==t.length)return"number"!=typeof t.length||F(t.length)?r(0):h(t);if("Buffer"===t.type&&Array.isArray(t.data))return h(t.data)}(t);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),e,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function u(t){return c(t),r(t<0?0:0|f(t))}function h(t){const e=t.length<0?0:0|f(t.length),i=r(e);for(let a=0;a<e;a+=1)i[a]=255&t[a];return i}function p(t,e,i){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(i||0))throw new RangeError('"length" is outside of buffer bounds');let a;return a=void 0===e&&void 0===i?new Uint8Array(t):void 0===i?new Uint8Array(t,e):new Uint8Array(t,e,i),Object.setPrototypeOf(a,o.prototype),a}function f(t){if(t>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|t}function l(t,e){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||G(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const i=t.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===i)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return z(t).length;default:if(n)return a?-1:q(t).length;e=(""+e).toLowerCase(),n=!0}}function d(t,e,i){let a=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return A(this,e,i);case"latin1":case"binary":return N(this,e,i);case"base64":return b(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,e,i);default:if(a)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),a=!0}}function g(t,e,i){const a=t[e];t[e]=t[i],t[i]=a}function y(t,e,i,a,n){if(0===t.length)return-1;if("string"==typeof i?(a=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),F(i=+i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=o.from(e,a)),o.isBuffer(e))return 0===e.length?-1:m(t,e,i,a,n);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):m(t,[e],i,a,n);throw new TypeError("val must be string, number or Buffer")}function m(t,e,i,a,n){let r,o=1,s=t.length,c=e.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,i/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(n){let a=-1;for(r=i;r<s;r++)if(u(t,r)===u(e,-1===a?0:r-a)){if(-1===a&&(a=r),r-a+1===c)return a*o}else-1!==a&&(r-=r-a),a=-1}else for(i+c>s&&(i=s-c),r=i;r>=0;r--){let i=!0;for(let a=0;a<c;a++)if(u(t,r+a)!==u(e,a)){i=!1;break}if(i)return r}return-1}function w(t,e,i,a){i=Number(i)||0;const n=t.length-i;a?(a=Number(a))>n&&(a=n):a=n;const r=e.length;let o;for(a>r/2&&(a=r/2),o=0;o<a;++o){const a=parseInt(e.substr(2*o,2),16);if(F(a))return o;t[i+o]=a}return o}function I(t,e,i,a){return X(q(e,t.length-i),t,i,a)}function C(t,e,i,a){return X(function(t){const e=[];for(let i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}(e),t,i,a)}function v(t,e,i,a){return X(z(e),t,i,a)}function S(t,e,i,a){return X(function(t,e){let i,a,n;const r=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),a=i>>8,n=i%256,r.push(n),r.push(a);return r}(e,t.length-i),t,i,a)}function b(t,i,a){return 0===i&&a===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(i,a))}function E(t,e,i){i=Math.min(t.length,i);const a=[];let n=e;for(;n<i;){const e=t[n];let r=null,o=e>239?4:e>223?3:e>191?2:1;if(n+o<=i){let i,a,s,c;switch(o){case 1:e<128&&(r=e);break;case 2:i=t[n+1],128==(192&i)&&(c=(31&e)<<6|63&i,c>127&&(r=c));break;case 3:i=t[n+1],a=t[n+2],128==(192&i)&&128==(192&a)&&(c=(15&e)<<12|(63&i)<<6|63&a,c>2047&&(c<55296||c>57343)&&(r=c));break;case 4:i=t[n+1],a=t[n+2],s=t[n+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(c=(15&e)<<18|(63&i)<<12|(63&a)<<6|63&s,c>65535&&c<1114112&&(r=c))}}null===r?(r=65533,o=1):r>65535&&(r-=65536,a.push(r>>>10&1023|55296),r=56320|1023&r),a.push(r),n+=o}return function(t){const e=t.length;if(e<=k)return String.fromCharCode.apply(String,t);let i="",a=0;for(;a<e;)i+=String.fromCharCode.apply(String,t.slice(a,a+=k));return i}(a)}t.kMaxLength=n,o.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(t,e,i){return s(t,e,i)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,e,i){return function(t,e,i){return c(t),t<=0?r(t):void 0!==e?"string"==typeof i?r(t).fill(e,i):r(t).fill(e):r(t)}(t,e,i)},o.allocUnsafe=function(t){return u(t)},o.allocUnsafeSlow=function(t){return u(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,e){if(G(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),G(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let i=t.length,a=e.length;for(let n=0,r=Math.min(i,a);n<r;++n)if(t[n]!==e[n]){i=t[n],a=e[n];break}return i<a?-1:a<i?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);let i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;const a=o.allocUnsafe(e);let n=0;for(i=0;i<t.length;++i){let e=t[i];if(G(e,Uint8Array))n+e.length>a.length?(o.isBuffer(e)||(e=o.from(e)),e.copy(a,n)):Uint8Array.prototype.set.call(a,e,n);else{if(!o.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(a,n)}n+=e.length}return a},o.byteLength=l,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},o.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},o.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},o.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?E(this,0,t):d.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){let e="";const i=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,i).replace(/(.{2})/g,"$1 ").trim(),this.length>i&&(e+=" ... "),"<Buffer "+e+">"},a&&(o.prototype[a]=o.prototype.inspect),o.prototype.compare=function(t,e,i,a,n){if(G(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===a&&(a=0),void 0===n&&(n=this.length),e<0||i>t.length||a<0||n>this.length)throw new RangeError("out of range index");if(a>=n&&e>=i)return 0;if(a>=n)return-1;if(e>=i)return 1;if(this===t)return 0;let r=(n>>>=0)-(a>>>=0),s=(i>>>=0)-(e>>>=0);const c=Math.min(r,s),u=this.slice(a,n),h=t.slice(e,i);for(let t=0;t<c;++t)if(u[t]!==h[t]){r=u[t],s=h[t];break}return r<s?-1:s<r?1:0},o.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},o.prototype.indexOf=function(t,e,i){return y(this,t,e,i,!0)},o.prototype.lastIndexOf=function(t,e,i){return y(this,t,e,i,!1)},o.prototype.write=function(t,e,i,a){if(void 0===e)a="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)a=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(i)?(i>>>=0,void 0===a&&(a="utf8")):(a=i,i=void 0)}const n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");let r=!1;for(;;)switch(a){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return I(this,t,e,i);case"ascii":case"latin1":case"binary":return C(this,t,e,i);case"base64":return v(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),r=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function A(t,e,i){let a="";i=Math.min(t.length,i);for(let n=e;n<i;++n)a+=String.fromCharCode(127&t[n]);return a}function N(t,e,i){let a="";i=Math.min(t.length,i);for(let n=e;n<i;++n)a+=String.fromCharCode(t[n]);return a}function T(t,e,i){const a=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>a)&&(i=a);let n="";for(let a=e;a<i;++a)n+=Y[t[a]];return n}function M(t,e,i){const a=t.slice(e,i);let n="";for(let t=0;t<a.length-1;t+=2)n+=String.fromCharCode(a[t]+256*a[t+1]);return n}function x(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function _(t,e,i,a,n,r){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<r)throw new RangeError('"value" argument is out of bounds');if(i+a>t.length)throw new RangeError("Index out of range")}function P(t,e,i,a,n){j(e,a,n,t,i,7);let r=Number(e&BigInt(4294967295));t[i++]=r,r>>=8,t[i++]=r,r>>=8,t[i++]=r,r>>=8,t[i++]=r;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[i++]=o,o>>=8,t[i++]=o,o>>=8,t[i++]=o,o>>=8,t[i++]=o,i}function R(t,e,i,a,n){j(e,a,n,t,i,7);let r=Number(e&BigInt(4294967295));t[i+7]=r,r>>=8,t[i+6]=r,r>>=8,t[i+5]=r,r>>=8,t[i+4]=r;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[i+3]=o,o>>=8,t[i+2]=o,o>>=8,t[i+1]=o,o>>=8,t[i]=o,i+8}function O(t,e,i,a,n,r){if(i+a>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function B(t,e,a,n,r){return e=+e,a>>>=0,r||O(t,0,a,4),i.write(t,e,a,n,23,4),a+4}function U(t,e,a,n,r){return e=+e,a>>>=0,r||O(t,0,a,8),i.write(t,e,a,n,52,8),a+8}o.prototype.slice=function(t,e){const i=this.length;(t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);const a=this.subarray(t,e);return Object.setPrototypeOf(a,o.prototype),a},o.prototype.readUintLE=o.prototype.readUIntLE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t],n=1,r=0;for(;++r<e&&(n*=256);)a+=this[t+r]*n;return a},o.prototype.readUintBE=o.prototype.readUIntBE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t+--e],n=1;for(;e>0&&(n*=256);)a+=this[t+--e]*n;return a},o.prototype.readUint8=o.prototype.readUInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),this[t]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readBigUInt64LE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,n=this[++t]+256*this[++t]+65536*this[++t]+i*2**24;return BigInt(a)+(BigInt(n)<<BigInt(32))})),o.prototype.readBigUInt64BE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=e*2**24+65536*this[++t]+256*this[++t]+this[++t],n=this[++t]*2**24+65536*this[++t]+256*this[++t]+i;return(BigInt(a)<<BigInt(32))+BigInt(n)})),o.prototype.readIntLE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t],n=1,r=0;for(;++r<e&&(n*=256);)a+=this[t+r]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*e)),a},o.prototype.readIntBE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=e,n=1,r=this[t+--a];for(;a>0&&(n*=256);)r+=this[t+--a]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},o.prototype.readInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){t>>>=0,e||x(t,2,this.length);const i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},o.prototype.readInt16BE=function(t,e){t>>>=0,e||x(t,2,this.length);const i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},o.prototype.readInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readBigInt64LE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=this[t+4]+256*this[t+5]+65536*this[t+6]+(i<<24);return(BigInt(a)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)})),o.prototype.readBigInt64BE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(a)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+i)})),o.prototype.readFloatLE=function(t,e){return t>>>=0,e||x(t,4,this.length),i.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return t>>>=0,e||x(t,4,this.length),i.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return t>>>=0,e||x(t,8,this.length),i.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return t>>>=0,e||x(t,8,this.length),i.read(this,t,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(t,e,i,a){if(t=+t,e>>>=0,i>>>=0,!a){_(this,t,e,i,Math.pow(2,8*i)-1,0)}let n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(t,e,i,a){if(t=+t,e>>>=0,i>>>=0,!a){_(this,t,e,i,Math.pow(2,8*i)-1,0)}let n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},o.prototype.writeUint8=o.prototype.writeUInt8=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,1,255,0),this[e]=255&t,e+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigUInt64LE=W((function(t,e=0){return P(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),o.prototype.writeBigUInt64BE=W((function(t,e=0){return R(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),o.prototype.writeIntLE=function(t,e,i,a){if(t=+t,e>>>=0,!a){const a=Math.pow(2,8*i-1);_(this,t,e,i,a-1,-a)}let n=0,r=1,o=0;for(this[e]=255&t;++n<i&&(r*=256);)t<0&&0===o&&0!==this[e+n-1]&&(o=1),this[e+n]=(t/r>>0)-o&255;return e+i},o.prototype.writeIntBE=function(t,e,i,a){if(t=+t,e>>>=0,!a){const a=Math.pow(2,8*i-1);_(this,t,e,i,a-1,-a)}let n=i-1,r=1,o=0;for(this[e+n]=255&t;--n>=0&&(r*=256);)t<0&&0===o&&0!==this[e+n+1]&&(o=1),this[e+n]=(t/r>>0)-o&255;return e+i},o.prototype.writeInt8=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeInt16BE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeInt32LE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},o.prototype.writeInt32BE=function(t,e,i){return t=+t,e>>>=0,i||_(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigInt64LE=W((function(t,e=0){return P(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),o.prototype.writeBigInt64BE=W((function(t,e=0){return R(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),o.prototype.writeFloatLE=function(t,e,i){return B(this,t,e,!0,i)},o.prototype.writeFloatBE=function(t,e,i){return B(this,t,e,!1,i)},o.prototype.writeDoubleLE=function(t,e,i){return U(this,t,e,!0,i)},o.prototype.writeDoubleBE=function(t,e,i){return U(this,t,e,!1,i)},o.prototype.copy=function(t,e,i,a){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),a||0===a||(a=this.length),e>=t.length&&(e=t.length),e||(e=0),a>0&&a<i&&(a=i),a===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),t.length-e<a-i&&(a=t.length-e+i);const n=a-i;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,i,a):Uint8Array.prototype.set.call(t,this.subarray(i,a),e),n},o.prototype.fill=function(t,e,i,a){if("string"==typeof t){if("string"==typeof e?(a=e,e=0,i=this.length):"string"==typeof i&&(a=i,i=this.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!o.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(1===t.length){const e=t.charCodeAt(0);("utf8"===a&&e<128||"latin1"===a)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;let n;if(e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0),"number"==typeof t)for(n=e;n<i;++n)this[n]=t;else{const r=o.isBuffer(t)?t:o.from(t,a),s=r.length;if(0===s)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(n=0;n<i-e;++n)this[n+e]=r[n%s]}return this};const K={};function H(t,e,i){K[t]=class extends i{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function V(t){let e="",i=t.length;const a="-"===t[0]?1:0;for(;i>=a+4;i-=3)e=`_${t.slice(i-3,i)}${e}`;return`${t.slice(0,i)}${e}`}function j(t,e,i,a,n,r){if(t>i||t<e){const a="bigint"==typeof e?"n":"";let n;throw n=r>3?0===e||e===BigInt(0)?`>= 0${a} and < 2${a} ** ${8*(r+1)}${a}`:`>= -(2${a} ** ${8*(r+1)-1}${a}) and < 2 ** ${8*(r+1)-1}${a}`:`>= ${e}${a} and <= ${i}${a}`,new K.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,i){$(e,"offset"),void 0!==t[e]&&void 0!==t[e+i]||L(e,t.length-(i+1))}(a,n,r)}function $(t,e){if("number"!=typeof t)throw new K.ERR_INVALID_ARG_TYPE(e,"number",t)}function L(t,e,i){if(Math.floor(t)!==t)throw $(t,i),new K.ERR_OUT_OF_RANGE(i||"offset","an integer",t);if(e<0)throw new K.ERR_BUFFER_OUT_OF_BOUNDS;throw new K.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${e}`,t)}H("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),H("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),H("ERR_OUT_OF_RANGE",(function(t,e,i){let a=`The value of "${t}" is out of range.`,n=i;return Number.isInteger(i)&&Math.abs(i)>2**32?n=V(String(i)):"bigint"==typeof i&&(n=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(n=V(n)),n+="n"),a+=` It must be ${e}. Received ${n}`,a}),RangeError);const D=/[^+/0-9A-Za-z-_]/g;function q(t,e){let i;e=e||1/0;const a=t.length;let n=null;const r=[];for(let o=0;o<a;++o){if(i=t.charCodeAt(o),i>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===a){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function z(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(D,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function X(t,e,i,a){let n;for(n=0;n<a&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function G(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function F(t){return t!=t}const Y=function(){const t="0123456789abcdef",e=new Array(256);for(let i=0;i<16;++i){const a=16*i;for(let n=0;n<16;++n)e[a+n]=t[i]+t[n]}return e}();function W(t){return"undefined"==typeof BigInt?J:t}function J(){throw new Error("BigInt not supported")}}(wt);const Tt="_/@#/",Mt="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");function xt(t=16,e=Mt){const i=new Uint16Array(t-1);ft.getRandomValues(i);return`c${Array.from(i).map((t=>e[t%e.length])).join("")}`}async function _t(t,e){const i=await yt(wt.Buffer.from(t),e),a=wt.Buffer.from(i).toString("hex");return wt.Buffer.from(a).toString("base64")}async function Pt(t,e,i){const a=wt.Buffer.from(t,"base64").toString("utf-8"),n=wt.Buffer.from(a,"hex");return await async function(t,e,i){const a=await mt(gt(i));return await ft.subtle.verify("HMAC",a,t,e)}(n,wt.Buffer.from(e),i)}async function Rt(t,e,i,a,n,r=86400){const o={clientIP:t,userId:e??xt(),match:i,mitigate:a,captcha:n,mitataMaxAge:r};return`_proto-mitata=${JSON.stringify(o)}`}async function Ot(t,e,i,a,n,r="/"){const o=[e.netaceaCookieName,e.netaceaCaptchaCookieName];if(void 0!==t.cachedEncryption&&o.includes(i)){return`${i}=${await t.cachedEncryption.encrypt(a)}; Max-Age=${n}; Path=${r}`}return`${i}=${a}; Max-Age=${n}; Path=${r}`}class Bt extends Error{static fromResponse(t){let e="Unknown error";switch(t.status){case 403:e="Invalid credentials";break;case 500:e="Server error";break;case 502:e="Bad Gateway";break;case 503:e="Service Unavailable";break;case 400:e="Invalid request"}return new Bt(e)}}async function Ut(t,e,i,a,n,r){if(200!==a.status)throw Bt.fromResponse(a);let o=parseInt(a.headers[l.dictionary.netaceaHeaders.match]),s=parseInt(a.headers[l.dictionary.netaceaHeaders.mitigate]),c=parseInt(a.headers[l.dictionary.netaceaHeaders.captcha]);isNaN(o)&&(o=i?.match??0),isNaN(s)&&(s=i?.mitigate??0),isNaN(c)&&(c=i?.captcha??0);let u=parseInt(a.headers[l.dictionary.netaceaHeaders.mitataExpiry]);isNaN(u)&&(u=86400);const h=await Rt(r,n,o,s,c),p=await async function(t,e,i){if(Object.prototype.hasOwnProperty.call(i,l.dictionary.netaceaHeaders.mitataCaptcha)){const a=i[l.dictionary.netaceaHeaders.mitataCaptcha],n=parseInt(i[l.dictionary.netaceaHeaders.mitataCaptchaExpiry]),r=await Ot(t,e,e.netaceaCaptchaCookieName,a,n);if(void 0!==r)return r}}(t,e,a.headers),f=[h,p].filter((t=>void 0!==t)),d=a.headers[l.dictionary.netaceaHeaders.eventId];return{status:a.status,match:o,mitigate:s,captcha:c,setCookie:f,body:a.body,eventId:d,mitataMaxAge:u}}function Kt(t){const e=Object.entries(t.getHeaders()),i={};for(const[t,a]of e)i[t]=a[0];return i}async function Ht(t,e,i){const{method:a,path:n,headers:r,body:o,timeout:s}=i;let{host:c}=i;c.endsWith("/")&&(c=c.slice(0,-1));const u=c+n,{httpRequest:h}=t,p=await h(u,{body:o,headers:r,method:a,timeout:s??3e3});return{status:p.status,body:await p.text(),headers:Kt(p)}}function Vt(t){return Object.entries(t).filter((([,t])=>void 0!==t)).map((t=>t.join("="))).join("; ")}function jt(t){const e=t?.toLowerCase()??"text/html",i=e?.includes("text/html")||e?.includes("application/html"),a=e?.includes("application/json");return a&&!i?"application/json":"text/html"}function $t(t,e,i){let a;if(void 0===t||""===t)return"";if("string"==typeof t&&(a=JSON.parse(t)),!function(t){if(null==t)return!1;const e=t;return void 0!==e?.captchaSiteKey&&void 0!==e?.trackingId&&void 0!==e?.captchaURL}(a))throw new Error("Body is not a Mitigation Service JSON response!");const n=`${i}?trackingId=${a.trackingId}`,r=`https://${e}${n}`;return JSON.stringify({captchaRelativeURL:n,captchaAbsoluteURL:r})}async function Lt(t,e,i,a){const n=void 0!==i.trackingId?`?trackingId=${i.trackingId}`:"";return await async function(t,e,i,a,n,r){const{userId:o,clientIP:s,host:c}=i,{mitigationServiceUrl:u,timeout:h}=e;if(void 0===u)throw new Error("Mitigation Service URL is not defined!");const p=function(t,e){const{apiKey:i,userId:a,userAgent:n,captchaCookie:r,clientIP:o,captchaSiteKey:s,captchaSecretKey:c,accept:u}=e,h={"X-Netacea-API-Key":i,"X-Netacea-Client-IP":o,"user-agent":n,cookie:Vt({_mitatacaptcha:r})};void 0!==a&&(h["X-Netacea-UserId"]=a);void 0!==s&&void 0!==c&&(h["X-Netacea-Captcha-Site-Key"]=s,h["X-Netacea-Captcha-Secret-Key"]=c);t.captchaContentNegotiation&&void 0!==t.netaceaCaptchaPath&&(h["X-Netacea-Captcha-Content-Type"]=jt(u));return h}(e,i),f="application/json"===p["X-Netacea-Captcha-Content-Type"],l={host:u,path:a,headers:p,method:n,timeout:h},d=await Ht(t,0,l);f&&void 0!==e.netaceaCaptchaPath&&void 0!==c&&(d.body=$t(d.body,c,e.netaceaCaptchaPath));return await Ut(t,e,r,d,o,s)}(t,e,i,`/captcha${n}`,"GET",a)}async function Dt(t,e,i,a){if(null==i)return;if("string"==typeof i)return await Dt(t,e,i.split(";"),a);const n=`${a}=`;for(const o of i){const i=o.split(";")[0].trimStart();if(i.startsWith(n)){const o=i.slice(n.length);if(e.encryptedCookieNames.includes(a)&&(5===(r=o).split(".").length&&r.includes("..")))try{return await(t.cachedEncryption?.decrypt(o))}catch(t){return}return o}}var r}function qt(t,e,i=""){const a=t.getHeader(e)?.[0]?.trim();return a??i}function zt(t,e,i=""){return t.getVariable(e)??i}async function Xt(t,e,i){return l.cookieIsNetaceaV3Format(t)?l.checkNetaceaCookieV3(t,e):await async function(t,e,i){if("string"!=typeof t||""===t)return l.defaultInvalidResponse();const a=l.matchMitataCookie(t);if(void 0!==a){const t=Math.floor(Date.now()/1e3),n=parseInt(a.expiry)<t,r=[1,3,5].includes(a.captcha),o=e+"|"+a.expiry,s=await Pt(a.ipHash,o,i),c=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(Tt);return{mitata:a,requiresReissue:n||!s,isExpired:n,shouldExpire:r,isSameIP:s,isPrimaryHashValid:await Pt(a.signature,c,i),match:a.match,mitigate:a.mitigate,captcha:a.captcha}}return l.defaultInvalidResponse()}(t,e,i??"")}function Gt(t,e){const i=t.split("&");for(const t of i){const[i,a]=t.split("=");if(i===e)return a}}async function Ft(t,e,{clientIP:i,userId:a,match:n,mitigate:r,captcha:o,issueReason:s,maxAge:c=86400,expiry:u}){const h=e.netaceaCookieExpirySeconds,p=[1,3,5].includes(o)?-h:h,f=u??Math.floor(Date.now()/1e3)+p,d=e.ingestType!==l.NetaceaIngestType.HTTP&&void 0!==t.cachedEncryption;if(!d&&void 0===e.secretKey)throw new Error("Cannot build cookie without secret key.");let g;if(d)g=l.createNetaceaCookieV3({clientIP:i,userId:a??"",match:n,mitigate:r,captcha:o,gracePeriod:p,cookieId:xt(),issueTimestamp:Math.floor(Date.now()/1e3),issueReason:s??l.NetaceaCookieV3IssueReason.NO_SESSION});else{const t=[n,r,o].join("");g=await async function(t,e,i,a,n="000"){void 0===e&&(e=xt());const r=[i,e,await _t(t+"|"+String(i),a),n].join(Tt);return`${await _t(r,a)}${Tt}${r}`}(i,a,f,e.secretKey,t)}return await Ot(t,e,e.netaceaCookieName,g,c)}function Yt(t,e){const i=e.getVariable(t.protoMitataVariableName);if(void 0!==i&&""!==i)try{return JSON.parse(i)}catch{return}}const{extractAndRemoveCookieAttr:Wt,removeDuplicateAttrs:Jt}=l.lib.cookieAttributes;async function Zt(t,e,i,a){const n=pt(i.path,i.method)?function(t,e){const i=(t,i)=>Number(e.getHeader(t)?.[0]??i),a=t.getHeader("x-netacea-client-ip")?.[0];if(null==a||""===a)throw new Error("Cannot build proto-mitata without Client IP");const n=t.getHeader("x-netacea-userid")?.[0]??"";return{clientIP:a,userId:""!==n?n:xt(),match:i("x-netacea-match",0),mitigate:i("x-netacea-mitigate",0),captcha:i("x-netacea-captcha",0),mitataMaxAge:i("x-netacea-mitata-expiry",86400)}}(i,a):Yt(e,i);if(void 0!==n){let i,{netaceaCookieAttributes:r}=e;if(""!==r){const{extractedAttribute:t,cookieAttributes:e}=Wt(r,"Max-Age");i=t,r=e}const o=await Ft(t,e,{clientIP:n.clientIP,userId:n.userId,match:n.match,mitigate:n.mitigate,captcha:n.captcha,maxAge:void 0!==i?parseInt(i,10):n.mitataMaxAge}),s=""!==r?Jt(`${o}; ${r}`,!0):o;a.addHeader("set-cookie",s)}}const{extractAndRemoveCookieAttr:Qt,removeDuplicateAttrs:te}=l.lib.cookieAttributes;async function ee(t,e,i,a){const n=a.getHeader("set-cookie")??void 0;if(a.removeHeader("set-cookie"),200===a.status){await async function(t,e,i,a){const n=a?.find((t=>t.startsWith("_mitatacaptcha=")));if(void 0!==n){const a=n.slice(n.indexOf("=")+1);let[r,...o]=a.split(/; ?/);void 0!==t.cachedEncryption&&(r=await t.cachedEncryption.encrypt(r));let s=[`${e.netaceaCaptchaCookieName}=${r}`,...o].join("; ");if(""!==e.netaceaCaptchaCookieAttributes){const{extractedAttribute:t,cookieAttributes:i}=Qt(te(e.netaceaCaptchaCookieAttributes,!0),"Max-Age"),{extractedAttribute:a}=Qt(s,"Max-Age");void 0!==t&&void 0!==a?(s=s.replace(`Max-Age=${a}`,`Max-Age=${t}`),s=te(`${s}; ${i}`,!0)):s=te(`${s}; ${i}`,!0)}i.addHeader("set-cookie",s)}}(t,e,a,n),await Zt(t,e,i,a);const r=String(l.dictionary.captchaStatusCodes.captchaPass),o=l.dictionary.netaceaHeaders.captcha,s=a.getHeader(o)?.[0];s!==r&&(a.status=403)}}function ie(t){return wt.Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64")}function ae(t,e){if("string"==typeof t&&void 0===e)throw new Error("Encoding should be provided to convert strings.");return function(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}(("string"==typeof t?wt.Buffer.from(t,e):wt.Buffer.from(t)).toString("base64"))}const ne=128,re=ae(JSON.stringify({alg:"dir",enc:"A128CBC-HS256"}),"utf-8"),oe=(new lt).encode(re);async function se(t){return await ft.subtle.importKey("raw",t,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async function ce({plaintext:t,secret:e,ivBase64Url:i}){const a=ie(e),n=a.subarray(ne>>3),r=a.subarray(0,ne>>3),o=await se(n),s=void 0!==i?ie(i):function(){const t=new Uint8Array(16);return ft.getRandomValues(t),t}(),c=(new lt).encode(t),u=await async function(t,e,i){const a=await ft.subtle.encrypt({name:"AES-CBC",length:ne,iv:t},e,i);return new Uint8Array(a)}(s,o,c),h=new Uint8Array(s),p=pe(oe,h,u),f=await he(p,r);return[re,"",ae(s),ae(u),ae(f)].join(".")}async function ue({jwe:t,secret:e}){const i=ie(e),a=i.subarray(ne>>3),n=i.subarray(0,ne>>3),{header:r,iv:o,payload:s,mac:c}=function(t){const e=t.split(".");if(5!==e.length)throw new Error(`JWE should have 5 parts, got ${e.length}`);const[i,a,n,r,o]=e;return{header:i,key:a,iv:n,payload:r,mac:o}}(t);if(r!==re)throw new Error("Incorrect JWE header");const u=ie(o),h=new Uint8Array(ie(s)),p=pe((new lt).encode(r),u,h);if(ae(await he(p,n))!==c)throw new Error("MAC does not match JWE data");const f=await se(a),l=await async function(t,e,i){const a=await ft.subtle.decrypt({name:"AES-CBC",length:ne,iv:t},e,i);return new Uint8Array(a)}(u,f,h);return(new dt).decode(l)}async function he(t,e){return(await yt(t,e)).slice(0,ne>>3)}function pe(t,e,i){return function(t){const e=t.reduce(((t,{length:e})=>t+e),0),i=new Uint8Array(e);let a=0;return t.forEach((t=>{i.set(t,a),a+=t.length})),i}([t,e,i,de(t.length<<3)])}const fe=2**32;function le(t,e,i){if(e<0||e>=fe)throw new RangeError(`value must be >= 0 and <= ${fe-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,255&e],i)}function de(t){const e=Math.floor(t/fe),i=t%fe,a=new Uint8Array(8);return le(a,e,0),le(a,i,4),a}class ge{constructor(t){this.maxSize=t,this.cachedItems=[]}getCacheSize(){return this.cachedItems.length}delete(t){this.cachedItems=this.cachedItems.filter((e=>e.key!==t))}add(t,e){this.delete(t),this.cachedItems.push({key:t,value:e}),this.cachedItems.length>this.maxSize&&this.cachedItems.shift()}get(t){return this.cachedItems.find((e=>e.key===t))}}class ye{constructor(t){this.encryptionKey=t.encryptionKey,this.cache=new ge(t.cacheMaxSize??5)}getCacheSize(){return this.cache.getCacheSize()}async memoizeFn(t,e){const i=this.cache.get(t);if(void 0!==i)return i.value;const a=await e();return this.cache.add(t,a),a}async encrypt(t){const e=`encrypt::${t}`;return await this.memoizeFn(e,(async()=>await ce({plaintext:t,secret:this.encryptionKey})))}async decrypt(t){const e=`encrypt::${t}`;return await this.memoizeFn(e,(async()=>await ue({jwe:t,secret:this.encryptionKey})))}}function me(t){return l.cookieIsNetaceaV3Format(t)?l.matchNetaceaCookieV3(t):l.matchMitataCookie(t)}function we(t,e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,t.logVersion===l.NetaceaLogVersion.V2?function({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){const d=new Date;"/"!==n[0]&&(n=`/${n}`);let g;const y=n.split("?");y.length>1&&(g=`?${y[1]}`);const m=y[0],w=me(u)?.userId;return{status:i,method:a,bytes_sent:l.safeParseInt(s),referrer:""===o?void 0:o,request:`${a} ${m}${g??""} ${r}`,request_time:l.safeParseInt(c),integration_type:p,integration_version:f,client:t,user_agent:e,bc_type:""===h?void 0:h,hour:d.getUTCHours(),minute:d.getUTCMinutes(),"@timestamp":d.toISOString().replace("Z","+00:00"),path:m,protocol:r,query:g,user_id:w}}(e):function({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){const l=(new Date).toUTCString();return{Request:`${a} ${n} ${r}`,TimeLocal:l,RealIp:t,UserAgent:e,Status:i,RequestTime:c?.toString(),BytesSent:s?.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:u??"",NetaceaMitigationApplied:h??"",IntegrationType:p??"",IntegrationVersion:f??""}}(e)}async function Ie(t,e,i){const a=we(e,i);if(e.ingestType!==l.NetaceaIngestType.KINESIS){const i={"X-Netacea-API-Key":e.apiKey??"","content-type":"application/json"},n=await async function(t,e,i,a){return await Ht(t,0,{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:JSON.stringify(a),timeout:e.timeout})}(t,e,i,a);if(200!==n.status)throw Bt.fromResponse(n)}}function Ce(t,e,i,a,n){const r="unknown";n||(2===a?a=4:3===a&&(a=5));let o=l.dictionary.matchMap[e]??r+"_";o+=l.dictionary.mitigateMap[i]??r;let s=l.dictionary.bestMitigationMap[i];if(0!==a){o+=","+(l.dictionary.captchaMap[a]??r);const t=l.dictionary.bestMitigationCaptchaMap[a];void 0!==t&&(s=t)}return t.mitigationType===l.NetaceaMitigationType.INJECT&&(s=l.dictionary.mitigationTypes.none),{sessionStatus:o,mitigation:s,parts:{match:e,mitigate:i,captcha:a}}}var ve="@netacea/akamai",Se="6.1.13";async function be(t,e,i,a){e.ingestType===l.NetaceaIngestType.HTTP&&await async function(t,e,i,a){const n=a.getHeader("set-cookie")??[],r=0!==n.length?n?.join("; "):qt(i,"cookie");let o=await Dt(t,e,r,e.netaceaCookieName)??"";if(void 0===o||""===o){const a=qt(i,"cookie");o=await Dt(t,e,a,e.netaceaCookieName)??""}const{match:s,mitigate:c,captcha:u}=me(o)??{match:0,mitigate:0,captcha:0},{sessionStatus:h}=Ce(e,s,c,u,pt(i.path,i.method));try{Ie(t,e,{bytesSent:qt(a,"content-length","0"),ip:zt(i,"PMUSER_CLIENT_IP",""),method:i.method,path:i.url,protocol:qt(i,"protocol","HTTP/1.1"),referer:qt(i,"referer",""),requestTime:"0",sessionStatus:h,status:String(a.status),userAgent:qt(i,"user-agent","-"),mitataCookie:o,integrationType:ve.replace("@netacea/",""),integrationVersion:Se})}catch(e){const{logger:i}=t;i.log("Error in callIngest():",e)}}(t,e,i,a)}async function Ee(t){const e=function(t){return Object.keys(t).filter((t=>{const e=t.toLowerCase();return"cookie"!==e&&"referer"!==e&&!e.startsWith("x-netacea-")})).join(",")}(t);return await ke(e)}async function ke(t){let e="";try{e=await async function(t,e){const i=(new lt).encode(e),a=await ft.subtle.digest(t,i);return Array.from(new Uint8Array(a)).map((t=>t.toString(16).padStart(2,"0"))).join("")}("SHA-256",t)}catch(t){e=""}return e}async function Ae(t){const e=t.getHeaders(),i=await Ee(e),a=function(t,e){const i=t.getHeader(e);return null==i?[]:i}(t,"cookie").map((t=>t.split(/; ?/).map((t=>t.split("=")[0])))).flat(),n=await async function(t){const e=t.join(",");return await ke(e)}(a);return[""===i?i:`h_${i.substring(1,15)}`,""===n?n:`c_${n.substring(1,15)}`]}const Ne={mitigationStatusCode:void 0,sessionReason:void 0,sessionStartTime:void 0};async function Te(t,e,i,a){try{const t=Yt(e,i),n=t?.userId??a?.userId??"",r=function(t,e,i,a){const n=a?.match??i?.match??0,r=a?.mitigate??i?.mitigate??0,o=a?.captcha??i?.captcha??0,{sessionStatus:s}=Ce(t,n,r,o,pt(e.path,e.method));return s}(e,i,a,t),[o,s]=await Ae(i),{mitigationType:c}=e,u=[n,r,Se,o,s,Ne.sessionReason??"",Ne.sessionStartTime??"",c,Ne.mitigationStatusCode??""].join(";");i.setVariable("PMUSER_NETACEA_DS2_CUSTOM_FIELD",u),function(){for(const t in Ne)Ne[t]=void 0}()}catch(e){const{logger:i}=t;i.log(`Error setting PMUSER_NETACEA_DS2_CUSTOM_FIELD ${e}`)}}function Me(t,e){!function(t){for(const e in Ne)void 0!==t[e]&&(Ne[e]=t[e])}({sessionReason:t,sessionStartTime:e??Math.floor(Date.now()/1e3)})}function xe(t){t.route({origin:"mitigations"})}var _e;!function(t){t[t.NO_SESSION=0]="NO_SESSION",t[t.NEW_SESSION=1]="NEW_SESSION",t[t.EXISTING_SESSION=2]="EXISTING_SESSION",t[t.RENEW_SESSION=3]="RENEW_SESSION"}(_e||(_e={}));const{mitigationTypes:Pe}=l.dictionary,Re=[Pe.block,Pe.captcha,Pe.captchaPass];async function Oe(t,e,i,a,n){let r={status:-1,match:(o=i.netaceaCookieInfo).match,mitigate:o.mitigate,captcha:o.captcha,mitataMaxAge:86400,setCookie:[]};var o;if(void 0===e.secretKey)throw new Error("Secret key is required to mitigate");const{netaceaCookieInfo:s}=i;if(!s.isPrimaryHashValid||s.requiresReissue){r=await async function(t,e,i,a,n){const r={"X-Netacea-API-Key":e.apiKey,"X-Netacea-Client-IP":i.clientIp,"user-agent":i.userAgent,cookie:Vt({_mitatacaptcha:i.netaceaSession.captchaToken})};void 0!==i.netaceaSession.userId&&(r["X-Netacea-UserId"]=i.netaceaSession.userId),void 0!==e.captchaSiteKey&&void 0!==e.captchaSecretKey&&(r["X-Netacea-Captcha-Site-Key"]=e.captchaSiteKey,r["X-Netacea-Captcha-Secret-Key"]=e.captchaSecretKey),e.captchaContentNegotiation&&void 0!==e.netaceaCaptchaPath&&(r["X-Netacea-Captcha-Content-Type"]=jt(a));const o="application/json"===r["X-Netacea-Captcha-Content-Type"],s=await Ht(t,0,{host:e.mitigationServiceUrl,path:"/",headers:r,method:"GET",timeout:e.timeout});return o&&void 0!==e.netaceaCaptchaPath&&(s.body=$t(s.body,n,e.netaceaCaptchaPath)),await Ut(t,e,void 0,s,i.netaceaSession.userId,i.clientIp)}(t,e,i,a,n),r.setCookie=[await Rt(i.clientIp,i.netaceaSession.userId,r.match,r.mitigate,r.captcha,r.mitataMaxAge)];Me(void 0===s.mitata?_e.NEW_SESSION:_e.RENEW_SESSION)}else{const t=s.mitata,e=(c=t,l.objectIsNetaceaCookieV3(c)?c.issueTimestamp:Number.parseInt(c.expiry,10)-60);Me(_e.EXISTING_SESSION,e)}var c;const u=Ce(e,r.match,r.mitigate,r.captcha,!1);return{body:r.body,apiCallStatus:r.status,setCookie:r.setCookie,sessionStatus:u.sessionStatus,mitigation:u.mitigation,mitigated:Re.includes(u.mitigation),bestMitigation:u,eventId:r.eventId}}async function Be(t){return{sessionStatus:"",setCookie:[await Rt(l.ingestIgnoredIpValue,t,0,0,0,86400)]}}async function Ue(t,e,i,a){try{switch(e.mitigationType){case l.NetaceaMitigationType.MITIGATE:return await async function(t,e,i,a){const n=qt(i,"accept","text/html"),r=await Oe(t,e,a,n,i.host),o={};let s,c;return r.mitigated&&(c=403,"captcha"===r.mitigation?(o["content-type"]="text/html; charset=UTF-8",s=r.body):s="Forbidden"),{response:{body:s,status:c,statusText:c?.toString(),headers:o,mitigation:r.mitigation},sessionStatus:r.sessionStatus,setCookie:r.setCookie}}(t,e,i,a);case l.NetaceaMitigationType.INJECT:return await async function(t,e,i,a){const n=qt(i,"accept","text/html"),r=await Oe(t,e,a,n,i.host),o={};o["set-cookie"]=r.setCookie.join("; ");const s={"x-netacea-match":r.bestMitigation.parts.match.toString(),"x-netacea-mitigate":r.bestMitigation.parts.mitigate.toString(),"x-netacea-captcha":r.bestMitigation.parts.captcha.toString()};return void 0!==r.eventId&&(s["x-netacea-event-id"]=r.eventId),{injectHeaders:s,sessionStatus:r.sessionStatus,setCookie:r.setCookie,response:{headers:o}}}(t,e,i,a);case l.NetaceaMitigationType.INGEST:return await async function(t,e,i){if(void 0===e.secretKey)throw new Error("Secret key is required for ingest");const a=qt(i,"cookie"),n=await Dt(t,e,a,e.netaceaCookieName),r=await Xt(n,l.ingestIgnoredIpValue,e.secretKey);return r.isPrimaryHashValid?r.requiresReissue?await Be(r.mitata?.userId):{sessionStatus:"",setCookie:[]}:await Be(void 0)}(t,e,i);default:throw new Error(`Netacea Error: Mitigation type ${e.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async function Ke(t,e,i,a){let n={};if(void 0!==i?.setCookie){const n=await Dt(t,e,i.setCookie,"_proto-mitata");void 0!==n&&a.setVariable(e.protoMitataVariableName,n)}if(e.mitigationType===l.NetaceaMitigationType.INJECT){n=i.injectHeaders??{}}let r={};e.ingestType===l.NetaceaIngestType.ORIGIN&&(r=await async function(t,e,i){const a=qt(i,"cookie"),n=me(await Dt(t,e,a,e.netaceaCookieName)??""),r=Yt(e,i),{match:o,mitigate:s,captcha:c,userId:u}=r??n??{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:h}=Ce(e,o,s,c,pt(i.path,i.method));return{"X-Netacea-UserId":u,"X-Netacea-BC-Type":h,"X-Netacea-Integration-Type":ve.replace("@netacea/",""),"X-Netacea-Integration-Version":Se}}(t,e,a));for(const[t,e]of Object.entries({...n,...r}))a.addHeader(t,e)}class He{constructor(i){this.configLoader=new ot(i),this.defaultDeps={httpRequest:t,logger:e,cachedEncryption:void 0}}async requestHandler(t){const e=this.configLoader.loadConfig(t);void 0!==e.cookieEncryptionKey&&void 0===this.defaultDeps.cachedEncryption&&(this.defaultDeps.cachedEncryption=new ye({encryptionKey:e.cookieEncryptionKey}));const i=await async function(t,e,i){const a=zt(i,"PMUSER_CLIENT_IP"),n=qt(i,"user-agent"),r=qt(i,"cookie"),o=await Dt(t,e,r,e.netaceaCookieName),s=await Xt(o,a,e.secretKey),c=await Dt(t,e,r,e.netaceaCaptchaCookieName);return{clientIp:a,userAgent:n,netaceaCookieInfo:s,netaceaSession:{userId:s.mitata?.userId,captchaToken:c,match:s.match,mitigate:s.mitigate,captcha:s.captcha}}}(this.defaultDeps,e,t);var a,n,r;a=t.path,n=t.method,void 0!==(r=e.netaceaCaptchaPath)&&r.length>0&&a===r&&"get"===n.toLowerCase()?await async function(t,e,i){const a=qt(i,"cookie"),n=await Dt(t,e,a,e.netaceaCookieName),r=await Dt(t,e,a,e.netaceaCaptchaCookieName),o=zt(i,"PMUSER_CLIENT_IP"),s=qt(i,"user-agent"),c=await Xt(n,o,e.secretKey),u=await Lt(t,e,{apiKey:e.apiKey??"",clientIP:o,userAgent:s,userId:c.mitata?.userId,captchaCookie:r,trackingId:Gt(i.query,"trackingId"),captchaSiteKey:e.captchaSiteKey,captchaSecretKey:e.captchaSecretKey,accept:qt(i,"accept","text/html"),host:i.host},{match:0,mitigate:0,captcha:1}),h=await Dt(t,e,u.setCookie,"_proto-mitata");void 0!==h&&i.setVariable(e.protoMitataVariableName,h);const p={};void 0!==e.netaceaCaptchaHeaderKey&&(p[e.netaceaCaptchaHeaderKey]=e.netaceaCaptchaHeaderValue),i.respondWith(403,p,u.body)}(this.defaultDeps,e,t):pt(t.path,t.method)?await async function(t,e,i){const a=i.getVariable("PMUSER_CLIENT_IP")??"";i.setHeader("x-netacea-api-key",e.apiKey),i.setHeader("x-netacea-client-ip",a);const n=qt(i,"cookie"),r=await Dt(t,e,n,e.netaceaCookieName)??"";let o="";const s=await Xt(r,a,e.secretKey??"");s.isPrimaryHashValid&&(o=s.mitata?.userId??""),i.setHeader("x-netacea-userid",o),xe(i)}(this.defaultDeps,e,t):ut(t.path,t.method,e.useCaptchaRelAssets)?xe(t):await async function(t,e,i,a){const n=await Ue(t,e,i,a);if(void 0===n)throw new Error('Mitigation Service response "mitResult" was undefined.');const r=n.response?.mitigation;if("block"===r||"captcha"===r){const a=n.response?.status??403,o={},s=await Dt(t,e,n.setCookie,"_proto-mitata");void 0!==s&&i.setVariable(e.protoMitataVariableName,s);const c=n.response?.body??"";(function(t){return t.includes("captchaRelativeURL")&&t.includes("captchaAbsoluteURL")})(c)&&(o["content-type"]="application/json"),"captcha"===r&&void 0!==e.netaceaCaptchaHeaderKey&&(o[e.netaceaCaptchaHeaderKey]=e.netaceaCaptchaHeaderValue),i.respondWith(a,o,c)}else await Ke(t,e,n,i)}(this.defaultDeps,e,t,i),await Te(this.defaultDeps,e,t,i.netaceaSession)}async responseHandler(t,e){const i=this.configLoader.loadConfig(t);if(pt(t.path,t.method))await ee(this.defaultDeps,i,t,e);else if(ht(t.path,t.method)&&!ut(t.path,t.method,i.useCaptchaRelAssets)){qt(t,"cookie").includes(i.netaceaCookieName)&&await Zt(this.defaultDeps,i,t,e)}else ut(t.path,t.method,i.useCaptchaRelAssets)||await Zt(this.defaultDeps,i,t,e);!function(t){t.removeHeader("x-netacea-match"),t.removeHeader("x-netacea-mitigate"),t.removeHeader("x-netacea-captcha"),t.removeHeader("x-netacea-mitata-expiry"),t.removeHeader("x-netacea-mitata-value"),t.removeHeader("x-netacea-mitatacaptcha-expiry"),t.removeHeader("x-netacea-mitatacaptcha-value"),t.removeHeader("x-netacea-event-id")}(e),await be(this.defaultDeps,i,t,e)}}var Ve=l.NetaceaMitigationType;export{Ve as NetaceaMitigationType,He as default};
10
+ !function(t){const e=Ct,i=Nt,a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=function(t){+t!=t&&(t=0);return o.alloc(+t)},t.INSPECT_MAX_BYTES=50;const n=2147483647;function r(t){if(t>n)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,o.prototype),e}function o(t,e,i){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return u(t)}return s(t,e,i)}function s(t,e,i){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const i=0|l(t,e);let a=r(i);const n=a.write(t,e);n!==i&&(a=a.slice(0,n));return a}(t,e);if(ArrayBuffer.isView(t))return function(t){if(G(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return h(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(G(t,ArrayBuffer)||t&&G(t.buffer,ArrayBuffer))return p(t,e,i);if("undefined"!=typeof SharedArrayBuffer&&(G(t,SharedArrayBuffer)||t&&G(t.buffer,SharedArrayBuffer)))return p(t,e,i);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=t.valueOf&&t.valueOf();if(null!=a&&a!==t)return o.from(a,e,i);const n=function(t){if(o.isBuffer(t)){const e=0|f(t.length),i=r(e);return 0===i.length||t.copy(i,0,0,e),i}if(void 0!==t.length)return"number"!=typeof t.length||F(t.length)?r(0):h(t);if("Buffer"===t.type&&Array.isArray(t.data))return h(t.data)}(t);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),e,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function u(t){return c(t),r(t<0?0:0|f(t))}function h(t){const e=t.length<0?0:0|f(t.length),i=r(e);for(let a=0;a<e;a+=1)i[a]=255&t[a];return i}function p(t,e,i){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(i||0))throw new RangeError('"length" is outside of buffer bounds');let a;return a=void 0===e&&void 0===i?new Uint8Array(t):void 0===i?new Uint8Array(t,e):new Uint8Array(t,e,i),Object.setPrototypeOf(a,o.prototype),a}function f(t){if(t>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|t}function l(t,e){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||G(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const i=t.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===i)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return z(t).length;default:if(n)return a?-1:q(t).length;e=(""+e).toLowerCase(),n=!0}}function d(t,e,i){let a=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return A(this,e,i);case"latin1":case"binary":return N(this,e,i);case"base64":return b(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,e,i);default:if(a)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),a=!0}}function g(t,e,i){const a=t[e];t[e]=t[i],t[i]=a}function y(t,e,i,a,n){if(0===t.length)return-1;if("string"==typeof i?(a=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),F(i=+i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=o.from(e,a)),o.isBuffer(e))return 0===e.length?-1:m(t,e,i,a,n);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):m(t,[e],i,a,n);throw new TypeError("val must be string, number or Buffer")}function m(t,e,i,a,n){let r,o=1,s=t.length,c=e.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,i/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(n){let a=-1;for(r=i;r<s;r++)if(u(t,r)===u(e,-1===a?0:r-a)){if(-1===a&&(a=r),r-a+1===c)return a*o}else-1!==a&&(r-=r-a),a=-1}else for(i+c>s&&(i=s-c),r=i;r>=0;r--){let i=!0;for(let a=0;a<c;a++)if(u(t,r+a)!==u(e,a)){i=!1;break}if(i)return r}return-1}function w(t,e,i,a){i=Number(i)||0;const n=t.length-i;a?(a=Number(a))>n&&(a=n):a=n;const r=e.length;let o;for(a>r/2&&(a=r/2),o=0;o<a;++o){const a=parseInt(e.substr(2*o,2),16);if(F(a))return o;t[i+o]=a}return o}function C(t,e,i,a){return X(q(e,t.length-i),t,i,a)}function I(t,e,i,a){return X(function(t){const e=[];for(let i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}(e),t,i,a)}function v(t,e,i,a){return X(z(e),t,i,a)}function S(t,e,i,a){return X(function(t,e){let i,a,n;const r=[];for(let o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),a=i>>8,n=i%256,r.push(n),r.push(a);return r}(e,t.length-i),t,i,a)}function b(t,i,a){return 0===i&&a===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(i,a))}function E(t,e,i){i=Math.min(t.length,i);const a=[];let n=e;for(;n<i;){const e=t[n];let r=null,o=e>239?4:e>223?3:e>191?2:1;if(n+o<=i){let i,a,s,c;switch(o){case 1:e<128&&(r=e);break;case 2:i=t[n+1],128==(192&i)&&(c=(31&e)<<6|63&i,c>127&&(r=c));break;case 3:i=t[n+1],a=t[n+2],128==(192&i)&&128==(192&a)&&(c=(15&e)<<12|(63&i)<<6|63&a,c>2047&&(c<55296||c>57343)&&(r=c));break;case 4:i=t[n+1],a=t[n+2],s=t[n+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(c=(15&e)<<18|(63&i)<<12|(63&a)<<6|63&s,c>65535&&c<1114112&&(r=c))}}null===r?(r=65533,o=1):r>65535&&(r-=65536,a.push(r>>>10&1023|55296),r=56320|1023&r),a.push(r),n+=o}return function(t){const e=t.length;if(e<=k)return String.fromCharCode.apply(String,t);let i="",a=0;for(;a<e;)i+=String.fromCharCode.apply(String,t.slice(a,a+=k));return i}(a)}t.kMaxLength=n,o.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(t,e,i){return s(t,e,i)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,e,i){return function(t,e,i){return c(t),t<=0?r(t):void 0!==e?"string"==typeof i?r(t).fill(e,i):r(t).fill(e):r(t)}(t,e,i)},o.allocUnsafe=function(t){return u(t)},o.allocUnsafeSlow=function(t){return u(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,e){if(G(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),G(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let i=t.length,a=e.length;for(let n=0,r=Math.min(i,a);n<r;++n)if(t[n]!==e[n]){i=t[n],a=e[n];break}return i<a?-1:a<i?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);let i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;const a=o.allocUnsafe(e);let n=0;for(i=0;i<t.length;++i){let e=t[i];if(G(e,Uint8Array))n+e.length>a.length?(o.isBuffer(e)||(e=o.from(e)),e.copy(a,n)):Uint8Array.prototype.set.call(a,e,n);else{if(!o.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(a,n)}n+=e.length}return a},o.byteLength=l,o.prototype._isBuffer=!0,o.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},o.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},o.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},o.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?E(this,0,t):d.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){let e="";const i=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,i).replace(/(.{2})/g,"$1 ").trim(),this.length>i&&(e+=" ... "),"<Buffer "+e+">"},a&&(o.prototype[a]=o.prototype.inspect),o.prototype.compare=function(t,e,i,a,n){if(G(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===a&&(a=0),void 0===n&&(n=this.length),e<0||i>t.length||a<0||n>this.length)throw new RangeError("out of range index");if(a>=n&&e>=i)return 0;if(a>=n)return-1;if(e>=i)return 1;if(this===t)return 0;let r=(n>>>=0)-(a>>>=0),s=(i>>>=0)-(e>>>=0);const c=Math.min(r,s),u=this.slice(a,n),h=t.slice(e,i);for(let t=0;t<c;++t)if(u[t]!==h[t]){r=u[t],s=h[t];break}return r<s?-1:s<r?1:0},o.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},o.prototype.indexOf=function(t,e,i){return y(this,t,e,i,!0)},o.prototype.lastIndexOf=function(t,e,i){return y(this,t,e,i,!1)},o.prototype.write=function(t,e,i,a){if(void 0===e)a="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)a=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(i)?(i>>>=0,void 0===a&&(a="utf8")):(a=i,i=void 0)}const n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");let r=!1;for(;;)switch(a){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return C(this,t,e,i);case"ascii":case"latin1":case"binary":return I(this,t,e,i);case"base64":return v(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),r=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const k=4096;function A(t,e,i){let a="";i=Math.min(t.length,i);for(let n=e;n<i;++n)a+=String.fromCharCode(127&t[n]);return a}function N(t,e,i){let a="";i=Math.min(t.length,i);for(let n=e;n<i;++n)a+=String.fromCharCode(t[n]);return a}function T(t,e,i){const a=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>a)&&(i=a);let n="";for(let a=e;a<i;++a)n+=Y[t[a]];return n}function M(t,e,i){const a=t.slice(e,i);let n="";for(let t=0;t<a.length-1;t+=2)n+=String.fromCharCode(a[t]+256*a[t+1]);return n}function x(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,i,a,n,r){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<r)throw new RangeError('"value" argument is out of bounds');if(i+a>t.length)throw new RangeError("Index out of range")}function _(t,e,i,a,n){j(e,a,n,t,i,7);let r=Number(e&BigInt(4294967295));t[i++]=r,r>>=8,t[i++]=r,r>>=8,t[i++]=r,r>>=8,t[i++]=r;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[i++]=o,o>>=8,t[i++]=o,o>>=8,t[i++]=o,o>>=8,t[i++]=o,i}function R(t,e,i,a,n){j(e,a,n,t,i,7);let r=Number(e&BigInt(4294967295));t[i+7]=r,r>>=8,t[i+6]=r,r>>=8,t[i+5]=r,r>>=8,t[i+4]=r;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[i+3]=o,o>>=8,t[i+2]=o,o>>=8,t[i+1]=o,o>>=8,t[i]=o,i+8}function O(t,e,i,a,n,r){if(i+a>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function B(t,e,a,n,r){return e=+e,a>>>=0,r||O(t,0,a,4),i.write(t,e,a,n,23,4),a+4}function U(t,e,a,n,r){return e=+e,a>>>=0,r||O(t,0,a,8),i.write(t,e,a,n,52,8),a+8}o.prototype.slice=function(t,e){const i=this.length;(t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);const a=this.subarray(t,e);return Object.setPrototypeOf(a,o.prototype),a},o.prototype.readUintLE=o.prototype.readUIntLE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t],n=1,r=0;for(;++r<e&&(n*=256);)a+=this[t+r]*n;return a},o.prototype.readUintBE=o.prototype.readUIntBE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t+--e],n=1;for(;e>0&&(n*=256);)a+=this[t+--e]*n;return a},o.prototype.readUint8=o.prototype.readUInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),this[t]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readBigUInt64LE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,n=this[++t]+256*this[++t]+65536*this[++t]+i*2**24;return BigInt(a)+(BigInt(n)<<BigInt(32))})),o.prototype.readBigUInt64BE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=e*2**24+65536*this[++t]+256*this[++t]+this[++t],n=this[++t]*2**24+65536*this[++t]+256*this[++t]+i;return(BigInt(a)<<BigInt(32))+BigInt(n)})),o.prototype.readIntLE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=this[t],n=1,r=0;for(;++r<e&&(n*=256);)a+=this[t+r]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*e)),a},o.prototype.readIntBE=function(t,e,i){t>>>=0,e>>>=0,i||x(t,e,this.length);let a=e,n=1,r=this[t+--a];for(;a>0&&(n*=256);)r+=this[t+--a]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},o.prototype.readInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){t>>>=0,e||x(t,2,this.length);const i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},o.prototype.readInt16BE=function(t,e){t>>>=0,e||x(t,2,this.length);const i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},o.prototype.readInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readBigInt64LE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=this[t+4]+256*this[t+5]+65536*this[t+6]+(i<<24);return(BigInt(a)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)})),o.prototype.readBigInt64BE=W((function(t){$(t>>>=0,"offset");const e=this[t],i=this[t+7];void 0!==e&&void 0!==i||L(t,this.length-8);const a=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(a)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+i)})),o.prototype.readFloatLE=function(t,e){return t>>>=0,e||x(t,4,this.length),i.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return t>>>=0,e||x(t,4,this.length),i.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return t>>>=0,e||x(t,8,this.length),i.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return t>>>=0,e||x(t,8,this.length),i.read(this,t,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(t,e,i,a){if(t=+t,e>>>=0,i>>>=0,!a){P(this,t,e,i,Math.pow(2,8*i)-1,0)}let n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(t,e,i,a){if(t=+t,e>>>=0,i>>>=0,!a){P(this,t,e,i,Math.pow(2,8*i)-1,0)}let n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},o.prototype.writeUint8=o.prototype.writeUInt8=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,1,255,0),this[e]=255&t,e+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigUInt64LE=W((function(t,e=0){return _(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),o.prototype.writeBigUInt64BE=W((function(t,e=0){return R(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),o.prototype.writeIntLE=function(t,e,i,a){if(t=+t,e>>>=0,!a){const a=Math.pow(2,8*i-1);P(this,t,e,i,a-1,-a)}let n=0,r=1,o=0;for(this[e]=255&t;++n<i&&(r*=256);)t<0&&0===o&&0!==this[e+n-1]&&(o=1),this[e+n]=(t/r>>0)-o&255;return e+i},o.prototype.writeIntBE=function(t,e,i,a){if(t=+t,e>>>=0,!a){const a=Math.pow(2,8*i-1);P(this,t,e,i,a-1,-a)}let n=i-1,r=1,o=0;for(this[e+n]=255&t;--n>=0&&(r*=256);)t<0&&0===o&&0!==this[e+n+1]&&(o=1),this[e+n]=(t/r>>0)-o&255;return e+i},o.prototype.writeInt8=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},o.prototype.writeInt16BE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},o.prototype.writeInt32LE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},o.prototype.writeInt32BE=function(t,e,i){return t=+t,e>>>=0,i||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},o.prototype.writeBigInt64LE=W((function(t,e=0){return _(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),o.prototype.writeBigInt64BE=W((function(t,e=0){return R(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),o.prototype.writeFloatLE=function(t,e,i){return B(this,t,e,!0,i)},o.prototype.writeFloatBE=function(t,e,i){return B(this,t,e,!1,i)},o.prototype.writeDoubleLE=function(t,e,i){return U(this,t,e,!0,i)},o.prototype.writeDoubleBE=function(t,e,i){return U(this,t,e,!1,i)},o.prototype.copy=function(t,e,i,a){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),a||0===a||(a=this.length),e>=t.length&&(e=t.length),e||(e=0),a>0&&a<i&&(a=i),a===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),t.length-e<a-i&&(a=t.length-e+i);const n=a-i;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,i,a):Uint8Array.prototype.set.call(t,this.subarray(i,a),e),n},o.prototype.fill=function(t,e,i,a){if("string"==typeof t){if("string"==typeof e?(a=e,e=0,i=this.length):"string"==typeof i&&(a=i,i=this.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!o.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(1===t.length){const e=t.charCodeAt(0);("utf8"===a&&e<128||"latin1"===a)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;let n;if(e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0),"number"==typeof t)for(n=e;n<i;++n)this[n]=t;else{const r=o.isBuffer(t)?t:o.from(t,a),s=r.length;if(0===s)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(n=0;n<i-e;++n)this[n+e]=r[n%s]}return this};const K={};function V(t,e,i){K[t]=class extends i{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function H(t){let e="",i=t.length;const a="-"===t[0]?1:0;for(;i>=a+4;i-=3)e=`_${t.slice(i-3,i)}${e}`;return`${t.slice(0,i)}${e}`}function j(t,e,i,a,n,r){if(t>i||t<e){const a="bigint"==typeof e?"n":"";let n;throw n=r>3?0===e||e===BigInt(0)?`>= 0${a} and < 2${a} ** ${8*(r+1)}${a}`:`>= -(2${a} ** ${8*(r+1)-1}${a}) and < 2 ** ${8*(r+1)-1}${a}`:`>= ${e}${a} and <= ${i}${a}`,new K.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,i){$(e,"offset"),void 0!==t[e]&&void 0!==t[e+i]||L(e,t.length-(i+1))}(a,n,r)}function $(t,e){if("number"!=typeof t)throw new K.ERR_INVALID_ARG_TYPE(e,"number",t)}function L(t,e,i){if(Math.floor(t)!==t)throw $(t,i),new K.ERR_OUT_OF_RANGE(i||"offset","an integer",t);if(e<0)throw new K.ERR_BUFFER_OUT_OF_BOUNDS;throw new K.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${e}`,t)}V("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),V("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),V("ERR_OUT_OF_RANGE",(function(t,e,i){let a=`The value of "${t}" is out of range.`,n=i;return Number.isInteger(i)&&Math.abs(i)>2**32?n=H(String(i)):"bigint"==typeof i&&(n=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(n=H(n)),n+="n"),a+=` It must be ${e}. Received ${n}`,a}),RangeError);const D=/[^+/0-9A-Za-z-_]/g;function q(t,e){let i;e=e||1/0;const a=t.length;let n=null;const r=[];for(let o=0;o<a;++o){if(i=t.charCodeAt(o),i>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===a){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function z(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(D,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function X(t,e,i,a){let n;for(n=0;n<a&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function G(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function F(t){return t!=t}const Y=function(){const t="0123456789abcdef",e=new Array(256);for(let i=0;i<16;++i){const a=16*i;for(let n=0;n<16;++n)e[a+n]=t[i]+t[n]}return e}();function W(t){return"undefined"==typeof BigInt?J:t}function J(){throw new Error("BigInt not supported")}}(wt);const Tt="_/@#/",Mt="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");function xt(t=16,e=Mt){const i=new Uint16Array(t-1);ft.getRandomValues(i);return`c${Array.from(i).map((t=>e[t%e.length])).join("")}`}async function Pt(t,e){const i=await yt(wt.Buffer.from(t),e),a=wt.Buffer.from(i).toString("hex");return wt.Buffer.from(a).toString("base64")}async function _t(t,e,i){const a=wt.Buffer.from(t,"base64").toString("utf-8"),n=wt.Buffer.from(a,"hex");return await async function(t,e,i){const a=await mt(gt(i));return await ft.subtle.verify("HMAC",a,t,e)}(n,wt.Buffer.from(e),i)}async function Rt(t,e,i,a,n,r,o=86400){const s={clientIP:t,userId:e??xt(),match:i,mitigate:a,captcha:n,mitataMaxAge:o,netaceaSettings:r??{}};return`_proto-mitata=${JSON.stringify(s)}`}async function Ot(t,e,i,a,n,r="/"){const o=[e.netaceaCookieName,e.netaceaCaptchaCookieName];if(void 0!==t.cachedEncryption&&o.includes(i)){return`${i}=${await t.cachedEncryption.encrypt(a)}; Max-Age=${n}; Path=${r}`}return`${i}=${a}; Max-Age=${n}; Path=${r}`}class Bt extends Error{static fromResponse(t){let e="Unknown error";switch(t.status){case 403:e="Invalid credentials";break;case 500:e="Server error";break;case 502:e="Bad Gateway";break;case 503:e="Service Unavailable";break;case 400:e="Invalid request"}return new Bt(e)}}async function Ut(t,e,i,a,n,r,o){if(200!==a.status)throw Bt.fromResponse(a);let s=parseInt(a.headers[l.dictionary.netaceaHeaders.match]),c=parseInt(a.headers[l.dictionary.netaceaHeaders.mitigate]),u=parseInt(a.headers[l.dictionary.netaceaHeaders.captcha]);isNaN(s)&&(s=i?.match??0),isNaN(c)&&(c=i?.mitigate??0),isNaN(u)&&(u=i?.captcha??0);let h=parseInt(a.headers[l.dictionary.netaceaHeaders.mitataExpiry]);isNaN(h)&&(h=86400);const p=await Rt(r,n,s,c,u,o),f=await async function(t,e,i){if(Object.prototype.hasOwnProperty.call(i,l.dictionary.netaceaHeaders.mitataCaptcha)){const a=i[l.dictionary.netaceaHeaders.mitataCaptcha],n=parseInt(i[l.dictionary.netaceaHeaders.mitataCaptchaExpiry]),r=await Ot(t,e,e.netaceaCaptchaCookieName,a,n);if(void 0!==r)return r}}(t,e,a.headers),d=[p,f].filter((t=>void 0!==t)),g=a.headers[l.dictionary.netaceaHeaders.eventId];return{status:a.status,match:s,mitigate:c,captcha:u,setCookie:d,body:a.body,eventId:g,mitataMaxAge:h,netaceaSettings:o??{}}}function Kt(t){const e=Object.entries(t.getHeaders()),i={};for(const[t,a]of e)i[t]=a[0];return i}async function Vt(t,e,i){const{method:a,path:n,headers:r,body:o,timeout:s}=i;let{host:c}=i;c.endsWith("/")&&(c=c.slice(0,-1));const u=c+n,{httpRequest:h}=t,p=await h(u,{body:o,headers:r,method:a,timeout:s??3e3});return{status:p.status,body:await p.text(),headers:Kt(p)}}function Ht(t){return Object.entries(t).filter((([,t])=>void 0!==t)).map((t=>t.join("="))).join("; ")}function jt(t){const e=t?.toLowerCase()??"text/html",i=e?.includes("text/html")||e?.includes("application/html"),a=e?.includes("application/json");return a&&!i?"application/json":"text/html"}function $t(t,e,i){let a;if(void 0===t||""===t)return"";if("string"==typeof t&&(a=JSON.parse(t)),!function(t){if(null==t)return!1;const e=t;return void 0!==e?.captchaSiteKey&&void 0!==e?.trackingId&&void 0!==e?.captchaURL}(a))throw new Error("Body is not a Mitigation Service JSON response!");const n=`${i}?trackingId=${a.trackingId}`,r=`https://${e}${n}`;return JSON.stringify({captchaRelativeURL:n,captchaAbsoluteURL:r})}async function Lt(t,e,i,a){const n=void 0!==i.trackingId?`?trackingId=${i.trackingId}`:"";return await async function(t,e,i,a,n,r){const{userId:o,clientIP:s,host:c}=i,{mitigationServiceUrl:u,timeout:h}=e;if(void 0===u)throw new Error("Mitigation Service URL is not defined!");const p=function(t,e){const{apiKey:i,userId:a,userAgent:n,captchaCookie:r,clientIP:o,captchaSiteKey:s,captchaSecretKey:c,accept:u}=e,h={"X-Netacea-API-Key":i,"X-Netacea-Client-IP":o,"user-agent":n,cookie:Ht({_mitatacaptcha:r})};void 0!==a&&(h["X-Netacea-UserId"]=a);void 0!==s&&void 0!==c&&(h["X-Netacea-Captcha-Site-Key"]=s,h["X-Netacea-Captcha-Secret-Key"]=c);t.captchaContentNegotiation&&void 0!==t.netaceaCaptchaPath&&(h["X-Netacea-Captcha-Content-Type"]=jt(u));return h}(e,i),f="application/json"===p["X-Netacea-Captcha-Content-Type"],l={host:u,path:a,headers:p,method:n,timeout:h},d=await Vt(t,0,l);f&&void 0!==e.netaceaCaptchaPath&&void 0!==c&&(d.body=$t(d.body,c,e.netaceaCaptchaPath));return await Ut(t,e,r,d,o,s)}(t,e,i,`/captcha${n}`,"GET",a)}async function Dt(t,e,i,a){if(null==i)return;if("string"==typeof i)return await Dt(t,e,i.split(";"),a);const n=`${a}=`;for(const o of i){const i=o.split(";")[0].trimStart();if(i.startsWith(n)){const o=i.slice(n.length);if(e.encryptedCookieNames.includes(a)&&(5===(r=o).split(".").length&&r.includes("..")))try{return await(t.cachedEncryption?.decrypt(o))}catch(t){return}return o}}var r}function qt(t,e,i=""){const a=t.getHeader(e)?.[0]?.trim();return a??i}function zt(t,e,i=""){return t.getVariable(e)??i}async function Xt(t,e,i){return l.cookieIsNetaceaV3Format(t)?l.checkNetaceaCookieV3(t,e):await async function(t,e,i){if("string"!=typeof t||""===t)return l.defaultInvalidResponse();const a=l.matchMitataCookie(t);if(void 0!==a){const t=Math.floor(Date.now()/1e3),n=parseInt(a.expiry)<t,r=[1,3,5].includes(a.captcha),o=e+"|"+a.expiry,s=await _t(a.ipHash,o,i),c=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(Tt);return{mitata:a,requiresReissue:n||!s,isExpired:n,shouldExpire:r,isSameIP:s,isPrimaryHashValid:await _t(a.signature,c,i),match:a.match,mitigate:a.mitigate,captcha:a.captcha}}return l.defaultInvalidResponse()}(t,e,i??"")}function Gt(t,e){const i=t.split("&");for(const t of i){const[i,a]=t.split("=");if(i===e)return a}}async function Ft(t,e,{clientIP:i,userId:a,match:n,mitigate:r,captcha:o,issueReason:s,netaceaSettings:c,maxAge:u=86400,expiry:h}){const p=e.netaceaCookieExpirySeconds,f=[1,3,5].includes(o)?-p:p,d=h??Math.floor(Date.now()/1e3)+f,g=e.ingestType!==l.NetaceaIngestType.HTTP&&void 0!==t.cachedEncryption;if(!g&&void 0===e.secretKey)throw new Error("Cannot build cookie without secret key.");let y;if(g)y=l.createNetaceaCookieV3({clientIP:i,userId:a??"",match:n,mitigate:r,captcha:o,gracePeriod:f,cookieId:xt(),issueTimestamp:Math.floor(Date.now()/1e3),issueReason:s??l.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:c.checkAllPostRequests});else{const t=[n,r,o].join("");y=await async function(t,e,i,a,n="000"){void 0===e&&(e=xt());const r=[i,e,await Pt(t+"|"+String(i),a),n].join(Tt);return`${await Pt(r,a)}${Tt}${r}`}(i,a,d,e.secretKey,t)}return await Ot(t,e,e.netaceaCookieName,y,u)}function Yt(t,e){const i=e.getVariable(t.protoMitataVariableName);if(void 0!==i&&""!==i)try{return JSON.parse(i)}catch{return}}const{extractAndRemoveCookieAttr:Wt,removeDuplicateAttrs:Jt}=l.lib.cookieAttributes;async function Zt(t,e,i,a){const n=pt(i.path,i.method)?function(t,e){const i=(t,i)=>Number(e.getHeader(t)?.[0]??i),a=t.getHeader("x-netacea-client-ip")?.[0];if(null==a||""===a)throw new Error("Cannot build proto-mitata without Client IP");const n=t.getHeader("x-netacea-userid")?.[0]??"";let r={};const o=t.getHeader("x-netacea-settings")?.[0];return void 0!==o&&(r=JSON.parse(o)),{clientIP:a,userId:""!==n?n:xt(),match:i("x-netacea-match",0),mitigate:i("x-netacea-mitigate",0),captcha:i("x-netacea-captcha",0),mitataMaxAge:i("x-netacea-mitata-expiry",86400),netaceaSettings:r}}(i,a):Yt(e,i);if(void 0!==n){let i,{netaceaCookieAttributes:r}=e;if(""!==r){const{extractedAttribute:t,cookieAttributes:e}=Wt(r,"Max-Age");i=t,r=e}const o=await Ft(t,e,{clientIP:n.clientIP,userId:n.userId,match:n.match,mitigate:n.mitigate,captcha:n.captcha,maxAge:void 0!==i?parseInt(i,10):n.mitataMaxAge,netaceaSettings:n.netaceaSettings}),s=""!==r?Jt(`${o}; ${r}`,!0):o;a.addHeader("set-cookie",s)}}const{extractAndRemoveCookieAttr:Qt,removeDuplicateAttrs:te}=l.lib.cookieAttributes;async function ee(t,e,i,a){const n=a.getHeader("set-cookie")??void 0;if(a.removeHeader("set-cookie"),200===a.status){await async function(t,e,i,a){const n=a?.find((t=>t.startsWith("_mitatacaptcha=")));if(void 0!==n){const a=n.slice(n.indexOf("=")+1);let[r,...o]=a.split(/; ?/);void 0!==t.cachedEncryption&&(r=await t.cachedEncryption.encrypt(r));let s=[`${e.netaceaCaptchaCookieName}=${r}`,...o].join("; ");if(""!==e.netaceaCaptchaCookieAttributes){const{extractedAttribute:t,cookieAttributes:i}=Qt(te(e.netaceaCaptchaCookieAttributes,!0),"Max-Age"),{extractedAttribute:a}=Qt(s,"Max-Age");void 0!==t&&void 0!==a?(s=s.replace(`Max-Age=${a}`,`Max-Age=${t}`),s=te(`${s}; ${i}`,!0)):s=te(`${s}; ${i}`,!0)}i.addHeader("set-cookie",s)}}(t,e,a,n),await Zt(t,e,i,a);const r=String(l.dictionary.captchaStatusCodes.captchaPass),o=l.dictionary.netaceaHeaders.captcha,s=a.getHeader(o)?.[0];s!==r&&(a.status=403)}}function ie(t){return wt.Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64")}function ae(t,e){if("string"==typeof t&&void 0===e)throw new Error("Encoding should be provided to convert strings.");return function(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}(("string"==typeof t?wt.Buffer.from(t,e):wt.Buffer.from(t)).toString("base64"))}const ne=128,re=ae(JSON.stringify({alg:"dir",enc:"A128CBC-HS256"}),"utf-8"),oe=(new lt).encode(re);async function se(t){return await ft.subtle.importKey("raw",t,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async function ce({plaintext:t,secret:e,ivBase64Url:i}){const a=ie(e),n=a.subarray(ne>>3),r=a.subarray(0,ne>>3),o=await se(n),s=void 0!==i?ie(i):function(){const t=new Uint8Array(16);return ft.getRandomValues(t),t}(),c=(new lt).encode(t),u=await async function(t,e,i){const a=await ft.subtle.encrypt({name:"AES-CBC",length:ne,iv:t},e,i);return new Uint8Array(a)}(s,o,c),h=new Uint8Array(s),p=pe(oe,h,u),f=await he(p,r);return[re,"",ae(s),ae(u),ae(f)].join(".")}async function ue({jwe:t,secret:e}){const i=ie(e),a=i.subarray(ne>>3),n=i.subarray(0,ne>>3),{header:r,iv:o,payload:s,mac:c}=function(t){const e=t.split(".");if(5!==e.length)throw new Error(`JWE should have 5 parts, got ${e.length}`);const[i,a,n,r,o]=e;return{header:i,key:a,iv:n,payload:r,mac:o}}(t);if(r!==re)throw new Error("Incorrect JWE header");const u=ie(o),h=new Uint8Array(ie(s)),p=pe((new lt).encode(r),u,h);if(ae(await he(p,n))!==c)throw new Error("MAC does not match JWE data");const f=await se(a),l=await async function(t,e,i){const a=await ft.subtle.decrypt({name:"AES-CBC",length:ne,iv:t},e,i);return new Uint8Array(a)}(u,f,h);return(new dt).decode(l)}async function he(t,e){return(await yt(t,e)).slice(0,ne>>3)}function pe(t,e,i){return function(t){const e=t.reduce(((t,{length:e})=>t+e),0),i=new Uint8Array(e);let a=0;return t.forEach((t=>{i.set(t,a),a+=t.length})),i}([t,e,i,de(t.length<<3)])}const fe=2**32;function le(t,e,i){if(e<0||e>=fe)throw new RangeError(`value must be >= 0 and <= ${fe-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,255&e],i)}function de(t){const e=Math.floor(t/fe),i=t%fe,a=new Uint8Array(8);return le(a,e,0),le(a,i,4),a}class ge{constructor(t){this.maxSize=t,this.cachedItems=[]}getCacheSize(){return this.cachedItems.length}delete(t){this.cachedItems=this.cachedItems.filter((e=>e.key!==t))}add(t,e){this.delete(t),this.cachedItems.push({key:t,value:e}),this.cachedItems.length>this.maxSize&&this.cachedItems.shift()}get(t){return this.cachedItems.find((e=>e.key===t))}}class ye{constructor(t){this.encryptionKey=t.encryptionKey,this.cache=new ge(t.cacheMaxSize??5)}getCacheSize(){return this.cache.getCacheSize()}async memoizeFn(t,e){const i=this.cache.get(t);if(void 0!==i)return i.value;const a=await e();return this.cache.add(t,a),a}async encrypt(t){const e=`encrypt::${t}`;return await this.memoizeFn(e,(async()=>await ce({plaintext:t,secret:this.encryptionKey})))}async decrypt(t){const e=`encrypt::${t}`;return await this.memoizeFn(e,(async()=>await ue({jwe:t,secret:this.encryptionKey})))}}function me(t){return l.cookieIsNetaceaV3Format(t)?l.matchNetaceaCookieV3(t):l.matchMitataCookie(t)}function we(t,e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,t.logVersion===l.NetaceaLogVersion.V2?function({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){const d=new Date;"/"!==n[0]&&(n=`/${n}`);let g;const y=n.split("?");y.length>1&&(g=`?${y[1]}`);const m=y[0],w=me(u)?.userId;return{status:i,method:a,bytes_sent:l.safeParseInt(s),referrer:""===o?void 0:o,request:`${a} ${m}${g??""} ${r}`,request_time:l.safeParseInt(c),integration_type:p,integration_version:f,client:t,user_agent:e,bc_type:""===h?void 0:h,hour:d.getUTCHours(),minute:d.getUTCMinutes(),"@timestamp":d.toISOString().replace("Z","+00:00"),path:m,protocol:r,query:g,user_id:w}}(e):function({ip:t,userAgent:e,status:i,method:a,path:n,protocol:r,referer:o,bytesSent:s,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:f}){const l=(new Date).toUTCString();return{Request:`${a} ${n} ${r}`,TimeLocal:l,RealIp:t,UserAgent:e,Status:i,RequestTime:c?.toString(),BytesSent:s?.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:u??"",NetaceaMitigationApplied:h??"",IntegrationType:p??"",IntegrationVersion:f??""}}(e)}async function Ce(t,e,i){const a=we(e,i);if(e.ingestType!==l.NetaceaIngestType.KINESIS){const i={"X-Netacea-API-Key":e.apiKey??"","content-type":"application/json"},n=await async function(t,e,i,a){return await Vt(t,0,{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:JSON.stringify(a),timeout:e.timeout})}(t,e,i,a);if(200!==n.status)throw Bt.fromResponse(n)}}function Ie(t,e,i,a,n){const r="unknown";n||(2===a?a=4:3===a&&(a=5));let o=l.dictionary.matchMap[e]??r+"_";o+=l.dictionary.mitigateMap[i]??r;let s=l.dictionary.bestMitigationMap[i];if(0!==a){o+=","+(l.dictionary.captchaMap[a]??r);const t=l.dictionary.bestMitigationCaptchaMap[a];void 0!==t&&(s=t)}return t.mitigationType===l.NetaceaMitigationType.INJECT&&(s=l.dictionary.mitigationTypes.none),{sessionStatus:o,mitigation:s,parts:{match:e,mitigate:i,captcha:a}}}var ve="@netacea/akamai",Se="6.1.14";async function be(t,e,i,a){e.ingestType===l.NetaceaIngestType.HTTP&&await async function(t,e,i,a){const n=a.getHeader("set-cookie")??[],r=0!==n.length?n?.join("; "):qt(i,"cookie");let o=await Dt(t,e,r,e.netaceaCookieName)??"";if(void 0===o||""===o){const a=qt(i,"cookie");o=await Dt(t,e,a,e.netaceaCookieName)??""}const{match:s,mitigate:c,captcha:u}=me(o)??{match:0,mitigate:0,captcha:0},{sessionStatus:h}=Ie(e,s,c,u,pt(i.path,i.method));try{Ce(t,e,{bytesSent:qt(a,"content-length","0"),ip:zt(i,"PMUSER_CLIENT_IP",""),method:i.method,path:i.url,protocol:qt(i,"protocol","HTTP/1.1"),referer:qt(i,"referer",""),requestTime:"0",sessionStatus:h,status:String(a.status),userAgent:qt(i,"user-agent","-"),mitataCookie:o,integrationType:ve.replace("@netacea/",""),integrationVersion:Se})}catch(e){const{logger:i}=t;i.log("Error in callIngest():",e)}}(t,e,i,a)}async function Ee(t){const e=function(t){return Object.keys(t).filter((t=>{const e=t.toLowerCase();return"cookie"!==e&&"referer"!==e&&!e.startsWith("x-netacea-")})).join(",")}(t);return await ke(e)}async function ke(t){let e="";try{e=await async function(t,e){const i=(new lt).encode(e),a=await ft.subtle.digest(t,i);return Array.from(new Uint8Array(a)).map((t=>t.toString(16).padStart(2,"0"))).join("")}("SHA-256",t)}catch(t){e=""}return e}async function Ae(t){const e=t.getHeaders(),i=await Ee(e),a=function(t,e){const i=t.getHeader(e);return null==i?[]:i}(t,"cookie").map((t=>t.split(/; ?/).map((t=>t.split("=")[0])))).flat(),n=await async function(t){const e=t.join(",");return await ke(e)}(a);return[""===i?i:`h_${i.substring(1,15)}`,""===n?n:`c_${n.substring(1,15)}`]}const Ne={mitigationStatusCode:void 0,sessionReason:void 0,sessionStartTime:void 0};async function Te(t,e,i,a){try{const t=Yt(e,i),n=t?.userId??a?.userId??"",r=function(t,e,i,a){const n=a?.match??i?.match??0,r=a?.mitigate??i?.mitigate??0,o=a?.captcha??i?.captcha??0,{sessionStatus:s}=Ie(t,n,r,o,pt(e.path,e.method));return s}(e,i,a,t),[o,s]=await Ae(i),{mitigationType:c}=e,u=[n,r,Se,o,s,Ne.sessionReason??"",Ne.sessionStartTime??"",c,Ne.mitigationStatusCode??""].join(";");i.setVariable("PMUSER_NETACEA_DS2_CUSTOM_FIELD",u),function(){for(const t in Ne)Ne[t]=void 0}()}catch(e){const{logger:i}=t;i.log(`Error setting PMUSER_NETACEA_DS2_CUSTOM_FIELD ${e}`)}}function Me(t){for(const e in Ne)void 0!==t[e]&&(Ne[e]=t[e])}function xe(t,e){Me({sessionReason:t,sessionStartTime:e??Math.floor(Date.now()/1e3)})}function Pe(t){t.route({origin:"mitigations"})}var _e;async function Re(t,e,i,a,n,r){const o={"X-Netacea-API-Key":e.apiKey,"X-Netacea-Client-IP":i.clientIp,"user-agent":i.userAgent,cookie:Ht({_mitatacaptcha:i.netaceaSession.captchaToken})};void 0!==i.netaceaSession.userId&&(o["X-Netacea-UserId"]=i.netaceaSession.userId),void 0!==e.captchaSiteKey&&void 0!==e.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=e.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=e.captchaSecretKey),e.captchaContentNegotiation&&void 0!==e.netaceaCaptchaPath&&(o["X-Netacea-Captcha-Content-Type"]=jt(a));const s=function(t){let e="";const i=[];for(const e in l.dictionary.netaceaSettingsMap)void 0===t[e]&&i.push(e);i.length>0&&(e=`?getSettings=${i.join(",")}`);return e}(r),c="application/json"===o["X-Netacea-Captcha-Content-Type"],u=await Vt(t,0,{host:e.mitigationServiceUrl,path:"/"+s,headers:o,method:"GET",timeout:e.timeout});Me({mitigationStatusCode:u.status}),c&&void 0!==e.netaceaCaptchaPath&&(u.body=$t(u.body,n,e.netaceaCaptchaPath));let h={};return void 0!==u.headers["x-netacea-settings"]&&(h=function(t){const e={},{netaceaSettingsMap:i}=l.dictionary;return decodeURIComponent(t).split("&").map((t=>t.split("="))).forEach((([t,a])=>{if(void 0!==a&&t in i){const n=parseInt(a,10);e[i[t]]=isNaN(n)?void 0:n}})),Object.entries(e).reduce(((t,[e,i])=>(void 0!==i&&(t[e]=i),t)),{})}(u.headers["x-netacea-settings"])),await Ut(t,e,void 0,u,i.netaceaSession.userId,i.clientIp,{...r,...h})}!function(t){t[t.NO_SESSION=0]="NO_SESSION",t[t.NEW_SESSION=1]="NEW_SESSION",t[t.EXISTING_SESSION=2]="EXISTING_SESSION",t[t.RENEW_SESSION=3]="RENEW_SESSION"}(_e||(_e={}));const{mitigationTypes:Oe}=l.dictionary,Be=[Oe.block,Oe.captcha,Oe.captchaPass];async function Ue(t,e,i,a,n){const{netaceaCookieInfo:r,clientIp:o,netaceaSession:s}=i;let c={status:-1,match:(u=r).match,mitigate:u.mitigate,captcha:u.captcha,mitataMaxAge:86400,netaceaSettings:{},setCookie:[]};var u;if(void 0===e.secretKey)throw new Error("Secret key is required to mitigate");const h=!r.isPrimaryHashValid||r.requiresReissue,p="post"===i.method.toLowerCase(),f=function(t){const e={};if(l.objectIsNetaceaCookieV3(t)){const{netaceaSettingsMap:i}=l.dictionary;for(const a in i){const n=t[i[a]];void 0!==n&&(e[a]=n)}}return e}(r.mitata),d=p&&1===f.checkAllPostRequests;if(h||d){c=await Re(t,e,i,a,n,f),c.setCookie=[await Rt(o,s.userId,c.match,c.mitigate,c.captcha,c.netaceaSettings,c.mitataMaxAge)];xe(void 0===r.mitata?_e.NEW_SESSION:_e.RENEW_SESSION)}else{const t=r.mitata,e=(g=t,l.objectIsNetaceaCookieV3(g)?g.issueTimestamp:Number.parseInt(g.expiry,10)-60);xe(_e.EXISTING_SESSION,e)}var g;const y=Ie(e,c.match,c.mitigate,c.captcha,!1);return{body:c.body,apiCallStatus:c.status,setCookie:c.setCookie,sessionStatus:y.sessionStatus,mitigation:y.mitigation,mitigated:Be.includes(y.mitigation),bestMitigation:y,eventId:c.eventId}}async function Ke(t){return{sessionStatus:"",setCookie:[await Rt(l.ingestIgnoredIpValue,t,0,0,0,void 0,86400)]}}async function Ve(t,e,i,a){try{switch(e.mitigationType){case l.NetaceaMitigationType.MITIGATE:return await async function(t,e,i,a){const n=qt(i,"accept","text/html"),r=await Ue(t,e,a,n,i.host),o={};let s,c;return r.mitigated&&(c=403,"captcha"===r.mitigation?(o["content-type"]="text/html; charset=UTF-8",s=r.body):s="Forbidden"),{response:{body:s,status:c,statusText:c?.toString(),headers:o,mitigation:r.mitigation},sessionStatus:r.sessionStatus,setCookie:r.setCookie}}(t,e,i,a);case l.NetaceaMitigationType.INJECT:return await async function(t,e,i,a){const n=qt(i,"accept","text/html"),r=await Ue(t,e,a,n,i.host),o={};o["set-cookie"]=r.setCookie.join("; ");const s={"x-netacea-match":r.bestMitigation.parts.match.toString(),"x-netacea-mitigate":r.bestMitigation.parts.mitigate.toString(),"x-netacea-captcha":r.bestMitigation.parts.captcha.toString()};return void 0!==r.eventId&&(s["x-netacea-event-id"]=r.eventId),{injectHeaders:s,sessionStatus:r.sessionStatus,setCookie:r.setCookie,response:{headers:o}}}(t,e,i,a);case l.NetaceaMitigationType.INGEST:return await async function(t,e,i){if(void 0===e.secretKey)throw new Error("Secret key is required for ingest");const a=qt(i,"cookie"),n=await Dt(t,e,a,e.netaceaCookieName),r=await Xt(n,l.ingestIgnoredIpValue,e.secretKey);return r.isPrimaryHashValid?r.requiresReissue?await Ke(r.mitata?.userId):{sessionStatus:"",setCookie:[]}:await Ke(void 0)}(t,e,i);default:throw new Error(`Netacea Error: Mitigation type ${e.mitigationType} not recognised`)}}catch(t){return console.error("Netacea FAILOPEN Error:",t),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async function He(t,e,i,a){let n={};if(void 0!==i?.setCookie){const n=await Dt(t,e,i.setCookie,"_proto-mitata");void 0!==n&&a.setVariable(e.protoMitataVariableName,n)}if(e.mitigationType===l.NetaceaMitigationType.INJECT){n=i.injectHeaders??{}}let r={};e.ingestType===l.NetaceaIngestType.ORIGIN&&(r=await async function(t,e,i){const a=qt(i,"cookie"),n=me(await Dt(t,e,a,e.netaceaCookieName)??""),r=Yt(e,i),{match:o,mitigate:s,captcha:c,userId:u}=r??n??{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:h}=Ie(e,o,s,c,pt(i.path,i.method));return{"X-Netacea-UserId":u,"X-Netacea-BC-Type":h,"X-Netacea-Integration-Type":ve.replace("@netacea/",""),"X-Netacea-Integration-Version":Se}}(t,e,a));for(const[t,e]of Object.entries({...n,...r}))a.addHeader(t,e)}class je{constructor(i){this.configLoader=new ot(i),this.defaultDeps={httpRequest:t,logger:e,cachedEncryption:void 0}}async requestHandler(t){const e=this.configLoader.loadConfig(t);void 0!==e.cookieEncryptionKey&&void 0===this.defaultDeps.cachedEncryption&&(this.defaultDeps.cachedEncryption=new ye({encryptionKey:e.cookieEncryptionKey}));const i=await async function(t,e,i){const a=zt(i,"PMUSER_CLIENT_IP"),n=qt(i,"user-agent"),r=qt(i,"cookie"),o=await Dt(t,e,r,e.netaceaCookieName),s=await Xt(o,a,e.secretKey),c=await Dt(t,e,r,e.netaceaCaptchaCookieName);return{clientIp:a,userAgent:n,method:i.method,netaceaCookieInfo:s,netaceaSession:{userId:s.mitata?.userId,captchaToken:c,match:s.match,mitigate:s.mitigate,captcha:s.captcha}}}(this.defaultDeps,e,t);var a,n,r;a=t.path,n=t.method,void 0!==(r=e.netaceaCaptchaPath)&&r.length>0&&a===r&&"get"===n.toLowerCase()?await async function(t,e,i){const a=qt(i,"cookie"),n=await Dt(t,e,a,e.netaceaCookieName),r=await Dt(t,e,a,e.netaceaCaptchaCookieName),o=zt(i,"PMUSER_CLIENT_IP"),s=qt(i,"user-agent"),c=await Xt(n,o,e.secretKey),u=await Lt(t,e,{apiKey:e.apiKey??"",clientIP:o,userAgent:s,userId:c.mitata?.userId,captchaCookie:r,trackingId:Gt(i.query,"trackingId"),captchaSiteKey:e.captchaSiteKey,captchaSecretKey:e.captchaSecretKey,accept:qt(i,"accept","text/html"),host:i.host},{match:0,mitigate:0,captcha:1}),h=await Dt(t,e,u.setCookie,"_proto-mitata");void 0!==h&&i.setVariable(e.protoMitataVariableName,h);const p={};void 0!==e.netaceaCaptchaHeaderKey&&(p[e.netaceaCaptchaHeaderKey]=e.netaceaCaptchaHeaderValue),i.respondWith(403,p,u.body)}(this.defaultDeps,e,t):pt(t.path,t.method)?await async function(t,e,i){const a=i.getVariable("PMUSER_CLIENT_IP")??"";i.setHeader("x-netacea-api-key",e.apiKey),i.setHeader("x-netacea-client-ip",a);const n=qt(i,"cookie"),r=await Dt(t,e,n,e.netaceaCookieName)??"";let o="";const s=await Xt(r,a,e.secretKey??"");if(l.objectIsNetaceaCookieV3(s.mitata)){const t={checkAllPostRequests:s.mitata.checkAllPostRequests};i.setHeader("x-netacea-settings",JSON.stringify(t))}s.isPrimaryHashValid&&(o=s.mitata?.userId??""),i.setHeader("x-netacea-userid",o),Pe(i)}(this.defaultDeps,e,t):ut(t.path,t.method,e.useCaptchaRelAssets)?Pe(t):await async function(t,e,i,a){const n=await Ve(t,e,i,a);if(void 0===n)throw new Error('Mitigation Service response "mitResult" was undefined.');const r=n.response?.mitigation;if("block"===r||"captcha"===r){const a=n.response?.status??403,o={},s=await Dt(t,e,n.setCookie,"_proto-mitata");void 0!==s&&i.setVariable(e.protoMitataVariableName,s);const c=n.response?.body??"";(function(t){return t.includes("captchaRelativeURL")&&t.includes("captchaAbsoluteURL")})(c)&&(o["content-type"]="application/json"),"captcha"===r&&void 0!==e.netaceaCaptchaHeaderKey&&(o[e.netaceaCaptchaHeaderKey]=e.netaceaCaptchaHeaderValue),i.respondWith(a,o,c)}else await He(t,e,n,i)}(this.defaultDeps,e,t,i),await Te(this.defaultDeps,e,t,i.netaceaSession)}async responseHandler(t,e){const i=this.configLoader.loadConfig(t);if(pt(t.path,t.method))await ee(this.defaultDeps,i,t,e);else if(ht(t.path,t.method)&&!ut(t.path,t.method,i.useCaptchaRelAssets)){qt(t,"cookie").includes(i.netaceaCookieName)&&await Zt(this.defaultDeps,i,t,e)}else ut(t.path,t.method,i.useCaptchaRelAssets)||await Zt(this.defaultDeps,i,t,e);!function(t){t.removeHeader("x-netacea-match"),t.removeHeader("x-netacea-mitigate"),t.removeHeader("x-netacea-captcha"),t.removeHeader("x-netacea-mitata-expiry"),t.removeHeader("x-netacea-mitata-value"),t.removeHeader("x-netacea-mitatacaptcha-expiry"),t.removeHeader("x-netacea-mitatacaptcha-value"),t.removeHeader("x-netacea-event-id"),t.removeHeader("x-netacea-settings")}(e),await be(this.defaultDeps,i,t,e)}}var $e=l.NetaceaMitigationType;export{$e as NetaceaMitigationType,je as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/akamai",
3
- "version": "6.1.13",
3
+ "version": "6.1.14",
4
4
  "description": "Netacea Akamai CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "license": "UNLICENSED",
22
22
  "dependencies": {
23
- "@netacea/netaceaintegrationbase": "^1.17.13",
23
+ "@netacea/netaceaintegrationbase": "^1.17.14",
24
24
  "buffer": "^6.0.3"
25
25
  },
26
26
  "files": [
@@ -73,5 +73,5 @@
73
73
  "tslib": "^2.0.3",
74
74
  "typescript": "^4.0.3"
75
75
  },
76
- "gitHead": "8ca2649a23c78c377bce6c2cd6f14f7f70ed1ede"
76
+ "gitHead": "fd9a755ef39e4dfc576eb16513685702867927d2"
77
77
  }