@netacea/cloudflare 5.2.48 → 5.2.49

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
@@ -1,4 +1,4 @@
1
- import { NetaceaBaseArgs, NetaceaIngestType, NetaceaLogVersion, NetaceaMitigationType, InjectResponse, NetaceaMitigationResponse, ComposeResultResponse, MakeRequestArgs, MakeRequestResponse, IngestArgs, WebLog, V2WebLog, APICallResponse, ProcessMitigateRequestArgs, NetaceaResponseBase, MitigateResponse } from '@netacea/netaceaintegrationbase';
1
+ import { NetaceaBaseArgs, NetaceaIngestType, NetaceaLogVersion, NetaceaMitigationType, InjectResponse, NetaceaMitigationResponse, MakeRequestResponse, IngestArgs, WebLog, V2WebLog, APICallResponse, NetaceaResponseBase, InjectHeaders, MitigateResponse } from '@netacea/netaceaintegrationbase';
2
2
  export { NetaceaMitigationType } from '@netacea/netaceaintegrationbase';
3
3
  import NetaceaKinesis from '@netacea/kinesisingest';
4
4
  import { Request as Request$1 } from '@cloudflare/workers-types/experimental';
@@ -26,6 +26,32 @@ interface CustomHeader {
26
26
  name: string;
27
27
  value: string;
28
28
  }
29
+ interface ComposeResultResponse {
30
+ body?: string | ReadableStream<Uint8Array>;
31
+ apiCallStatus: number;
32
+ setCookie: string[];
33
+ sessionStatus: string;
34
+ mitigation: string;
35
+ mitigated: boolean;
36
+ injectHeaders?: InjectHeaders;
37
+ }
38
+ interface ProcessMitigateRequestArgs {
39
+ url: string;
40
+ method: string;
41
+ mitata: string | undefined;
42
+ mitataCaptcha: string | undefined;
43
+ clientIp: string;
44
+ userAgent: string;
45
+ getBodyFn: () => Promise<string | ReadableStream<Uint8Array> | undefined>;
46
+ }
47
+ interface MakeRequestArgs {
48
+ host: string;
49
+ path: string;
50
+ headers: Record<string, string>;
51
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
52
+ body?: string | ReadableStream<Uint8Array> | undefined;
53
+ timeout?: number;
54
+ }
29
55
  type CloudflareMitigateResponse = MitigateResponse<Response>;
30
56
  declare class Cloudflare {
31
57
  protected mitataCookieExpirySeconds: number;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("crypto"),t=require("buffer"),a=require("url"),i=require("querystring"),s=require("jose");function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={},r={},c={};!function(a){var i,s,o,n,r=e,c=t;a.NetaceaIngestType=void 0,(i=a.NetaceaIngestType||(a.NetaceaIngestType={})).ORIGIN="ORIGIN",i.HTTP="HTTP",i.KINESIS="KINESIS",i.NATIVE="NATIVE",a.NetaceaLogVersion=void 0,(s=a.NetaceaLogVersion||(a.NetaceaLogVersion={})).V1="V1",s.V2="V2",a.NetaceaMitigationType=void 0,(o=a.NetaceaMitigationType||(a.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",a.NetaceaCookieV3IssueReason=void 0,(n=a.NetaceaCookieV3IssueReason||(a.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const h=3e3;const p="_/@#/",u={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:u.none,1:u.block,2:u.none,3:u.block,4:u.block},l={1:u.captcha,2:u.captchaPass,3:u.captcha,4:u.allow,5:u.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:u,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:parseInt(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function k(e=16,t=f){const a=r.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function S(e,t){const a=r.createHmac("sha256",t);return a.update(e),c.Buffer.from(a.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),a={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),a[o]=n}return a}function T(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:a.NetaceaCookieV3IssueReason.NO_SESSION}}function N(e,t){const a=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==a&&a.length>0?a?.replace(`${t}=`,""):void 0}function b(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":w(e.split(";"),t).join("; ")}function w(e,t=!1){if(t)return w(e.reverse()).reverse();const a=new Set,i=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();a.has(e)||(a.add(e),i.push(t))}return i}var A=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let a=e=b(e??"",!0),i=t=b(t??"",!0);if(void 0!==e&&void 0!==t){const s=N(e,"Domain"),o=N(t,"Domain");void 0!==s&&void 0!==o?i=t.replace(o,s):void 0!==s&&void 0===o?i=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(a=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=N(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=N(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},extractAndRemoveCookieAttr:function(e,t){const a=N(e,t);if(void 0!==a){return{extractedAttribute:a,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${a}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:N,removeDuplicateAttrs:b});function x(e){const t=b([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var P=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:x});var E=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const a=e.slice(0,t),i=e.slice(t+1),s=i.indexOf(";");return{name:a,value:i.slice(0,s),attributes:i.slice(s).trimStart()}}});const _={cookie:{parse:E,attributes:A,netaceaSession:P}};a.checkMitataCookie=function(e,t,a){const i={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return i;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=S(t+"|"+s.expiry,a),u=s.ipHash===h;return{mitata:s,requiresReissue:o||!u,isExpired:o,shouldExpire:c,isSameIP:u,isPrimaryHashValid:s.signature===S(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i},a.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return T();const a=I(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP,o=[1,3,5].includes(a.captcha),n=3===a.mitigate;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:a.issueReason}}return T()},a.configureMitataExpiry=function(e,t){return void 0===t?e===a.NetaceaMitigationType.INGEST?3600:60:t},a.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},a.correctTimeout=function(e){return e<=0?h:e},a.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=k());const o=[a,t,S(e+"|"+String(a),i),s].join(p);return`${S(o,i)}${p}${o}`},a.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},a.defaultInvalidResponse=T,a.dictionary=y,a.generateId=k,a.hexSha256=S,a.ingestIgnoredIpValue="ignored",a.lib=_,a.matchMitataCookie=v,a.matchNetaceaCookieV3=I,a.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},a.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},a.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(c);var h={},p={},u={},d={},l=function(e){return new g(e)};function g(e){this.capacity=0|e,this.map=Object.create(null),this.list=new m}function m(){this.firstNode=null,this.lastNode=null}function y(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}g.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},g.prototype.set=function(e,t){var a=this.map[e];if(null!=a)a.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;a=new y(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},g.prototype.used=function(e){this.list.moveToFront(e)},g.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},m.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},m.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},m.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=d,o=a,n=i,r=e,c=l(1e3);function h(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function p(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function u(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function g(e){return u(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var a=e.headers=e.headers||{},i=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||a.Host||a.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||i[0]||"",this.region=e.region||i[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),a.Host||a.host||(a.Host=e.hostname||e.host||this.createHost(),e.port&&(a.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var a=0;a<2;a++)if(/^s3-/.test(t[a])){t[1]=t[a].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,a=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||a["Content-Type"]||a["content-type"]||(a["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||a["Content-Length"]||a["content-length"]||(a["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||a["X-Amz-Security-Token"]||a["x-amz-security-token"]||(a["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||(a["X-Amz-Content-Sha256"]=p(this.request.body||"","hex")),a["X-Amz-Date"]||a["x-amz-date"]?this.datetime=a["X-Amz-Date"]||a["x-amz-date"]:a["X-Amz-Date"]=this.getDateTime()),delete a.Authorization,delete a.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,a,i=this.getDate(),s=[this.credentials.secretAccessKey,i,this.region,this.service].join(),o=c.get(s);return o||(e=h("AWS4"+this.credentials.secretAccessKey,i),t=h(e,this.region),a=h(t,this.service),o=h(a,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),p(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,a=this.parsedPath.query,i=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||p(this.request.body||"","hex"),a){var h=Object.keys(a).reduce((function(e,t){return t?(e[g(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),u=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(g).sort().forEach((function(t){u.push(e+"="+t)})):u.push(e+"="+g(h[e]))})),s=u.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(g(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),a=null;t>=0&&(a=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:a}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+u(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.API_VERSION=f.REGION=f.PAYLOAD_TYPE=f.STATE=void 0,f.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},f.PAYLOAD_TYPE="string",f.REGION="eu-west-1",f.API_VERSION="2013-12-02",Object.defineProperty(u,"__esModule",{value:!0}),u.signRequest=void 0;const C=d,v=f;function k(e,t){const a=[];for(let i=0;i<e.length;i+=t){const s=e.slice(i,i+t);a.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a}u.signRequest=function(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:k(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return C.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:i,secretAccessKey:s})},Object.defineProperty(p,"__esModule",{value:!0});const S=u;p.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=(0,S.signRequest)({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:a.headers,host:`https://${a.hostname}`,method:a.method,path:a.path,body:a.body})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize&&await this.putToKinesis(t)}},Object.defineProperty(h,"__esModule",{value:!0});const I=p;h.default=I.default;var T={name:"@netacea/cloudflare",version:"5.2.48",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"npx nyc tape -r ts-node/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup",postpack:"npx netacea-bundler postpack",prepack:"npx netacea-bundler prepack"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.48","@netacea/netaceaintegrationbase":"^2.0.30",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/bundler":"^1.0.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1","ts-node":"^10.9.1",typescript:"^5.2.2"},gitHead:"2250de7eb365e1817eccb58d19eea5b1dbf0a6a5"},N={};Object.defineProperty(N,"__esModule",{value:!0}),N.fetch=void 0,N.fetch=globalThis.fetch.bind(globalThis);var b,w={};var A={},x={};Object.defineProperty(x,"__esModule",{value:!0}),x.parseIntOrReturnUnparsed=void 0,x.parseIntOrReturnUnparsed=function(e){const t=parseInt(e,10);return isNaN(t)?e:t},Object.defineProperty(A,"__esModule",{value:!0}),A.checkMitataCookie=A.hexSha256=A.createMitataCookie=A.generateId=A.matchMitataCookie=A.ingestIgnoredIpValue=void 0;const P=e,E=t,_=x;A.ingestIgnoredIpValue="ignored";const M="_/@#/",R="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function O(e){if(void 0===e)return;const t=e.match(H);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:(0,_.parseIntOrReturnUnparsed)(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function j(e=16,t=R){const a=(0,P.randomBytes)(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function K(e,t){const a=(0,P.createHmac)("sha256",t);return a.update(e),E.Buffer.from(a.digest("hex")).toString("base64")}A.matchMitataCookie=O,A.generateId=j,A.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=j());const o=[a,t,K(e+"|"+String(a),i),s].join(M);return`${K(o,i)}${M}${o}`},A.hexSha256=K,A.checkMitataCookie=function(e,t,a){const i={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return i;const s=O(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(M),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=K(t+"|"+s.expiry,a),p=s.ipHash===h;return{mitata:s,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:s.signature===K(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i};var q={};Object.defineProperty(q,"__esModule",{value:!0}),q.decrypt=q.encrypt=void 0;const D=s;q.encrypt=async function(e,t){const a=D.base64url.decode(t),i=(new TextEncoder).encode(e);return await new D.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},q.decrypt=async function(e,t){const a=D.base64url.decode(t),{plaintext:i}=await D.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var V={};Object.defineProperty(V,"__esModule",{value:!0}),V.isUrlCaptchaGet=V.getTrackingId=V.modifyCaptchaJsonResponse=V.getCaptchaPageContentType=void 0,V.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),a=t.includes("application/html")||t.includes("text/html"),i=t.includes("application/json");return!a&&i?"application/json":"text/html"},V.modifyCaptchaJsonResponse=async function(e,t,a){const i=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(a);return t.length<2||void 0===i?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${i}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${i}`})},V.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},V.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||""===a)return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=new URL(e);return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()};var $={};async function F(e,t){const a=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,a);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function U(e){const t=[];return e.forEach(((e,a)=>{const i=a.toLowerCase();"cookie"===i||"referer"===i||i.startsWith("x-netacea-")||t.push(a)})),t.join(",")}async function L(e){let t="";try{t=await F("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty($,"__esModule",{value:!0}),$.hashCookieNames=$.hashHeaders=$.extractHeaderNames=$.hashString=void 0,$.hashString=F,$.extractHeaderNames=U,$.hashHeaders=async function(e){const t=U(e);return await L(t)},$.hashCookieNames=async function(e){const t=e.join(",");return await L(t)};var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.addIngestOriginHeaders=void 0;const G=T;z.addIngestOriginHeaders=function(e,t,a){e.headers.set("x-netacea-integration-type",G.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",G.version),e.headers.set("x-netacea-userid",a),e.headers.set("x-netacea-bc-type",t)},Object.defineProperty(r,"__esModule",{value:!0});const X=c,Y=h,W=T,B=N,J=function e(){return b||(b=1,t=w,Object.defineProperty(t,"__esModule",{value:!0}),t.dictionary=t.bestMitigationCaptchaMap=t.bestMitigationMap=t.captchaStatusCodes=t.captchaMap=t.mitigateMap=t.matchMap=t.netaceaHeaders=t.mitigationTypes=void 0,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_",b:"headerFP_"},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.dictionary=e()),w;var t}(),Z=A,Q=q,ee=V,te=$,ae=x,ie=z,{configureCookiesDomain:se}=X.lib.cookie.attributes;r.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:a,timeout:i=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=X.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=X.NetaceaIngestType.HTTP,kinesis:p,logVersion:u,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=a,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=h?h:X.NetaceaIngestType.HTTP,this.logVersion=null!=u?u:X.NetaceaLogVersion.V1,this.ingestType===X.NetaceaIngestType.KINESIS&&(void 0===p?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Y.default({...p,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,X.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=se(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=v?v:"",this.netaceaCaptchaCookieAttributes=null!=k?k:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===X.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f}async run(e,t){const a=new Request(e.request),i=await this.timeoutCheck(this.runMitigation(a),this.timeout);return await this.handleResponse(a,i,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const a=new Headers;if(!await(0,ee.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)a.append("set-cookie",e);let i="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&a.append(this.captchaHeader.name,this.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),i=t.body),{response:new Response(i,{status:403,statusText:"Forbidden",headers:a}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const a of t.setCookie)e.append("set-cookie",a);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async getNetaceaSession(e,t){var a;const i=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=i?i:await this.getNetaceaCookieFromRequest(e),{headers:o}=e,n=await(0,te.hashHeaders)(o),r=this.getHeaderValuesArray(o,"cookie").map((e=>e.split("=")[0])).flat(),c=await(0,te.hashCookieNames)(r),h=""===n?n:`h_${n.substring(1,15)}`,p=""===c?c:`c_${c.substring(1,15)}`,{match:u,mitigate:d,captcha:l,userId:g}=null!==(a=(0,Z.matchMitataCookie)(null!=s?s:""))&&void 0!==a?a:{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:m}=this.findBestMitigation(u,d,l,this.isUrlCaptchaPost(e.url,e.method));return{userId:g,sessionStatus:m,netaceaCookie:s,headerFingerprint:h,cookieFingerprint:p}}async ingest(e,t){var a;const{sessionStatus:i,netaceaCookie:s,headerFingerprint:o,cookieFingerprint:n}=await this.getNetaceaSession(e,t),r=String(null===(a=e.cf)||void 0===a?void 0:a.httpProtocol);await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:r,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:i,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:s,integrationType:W.name.replace("@netacea/",""),integrationVersion:W.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for"),headerFingerprint:o,cookieFingerprint:n})}async handleGetCaptchaRequest(e,t,a,i,s,o,n,r){var c;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const h=(0,Z.checkMitataCookie)(e,t,this.secretKey),p=await this.makeMitigateAPICall(null===(c=h.mitata)||void 0===c?void 0:c.userId,t,a,r,i,!0,s,o,n);return{body:p.body,apiCallStatus:p.status,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:a,headers:i,body:s}){const o=`${e}${a}`,n=new Request(o,{method:t,body:s,headers:i}),r=await(0,B.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(e,t){var a;if(void 0===t)return e;const i=null!==(a=e.headers.get("set-cookie"))&&void 0!==a?a:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})}addHeadersToRequest(e,t){if(void 0===t.injectHeaders)return e;const a=new Headers(e.headers);for(const[e,i]of Object.entries(t.injectHeaders))a.set(e,i);return new Request(e,{headers:a})}async handleResponse(e,t,a){if(void 0!==t)if(this.mitigationType===X.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===X.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));if(this.ingestType===X.NetaceaIngestType.ORIGIN){const{sessionStatus:a,userId:i}=await this.getNetaceaSession(e,t);(0,ie.addIngestOriginHeaders)(e,a,i)}const i=await a(e);return this.addHeadersToResponse(i,t)}getHeaderValueOrDefault(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a}getHeaderValuesArray(e,t){var a,i;return null!==(i=null===(a=e.get(t))||void 0===a?void 0:a.split(/; ?/))&&void 0!==i?i:[]}async getMitigationResponse(e){var t,a,i,s;const{headerFingerprint:o}=await this.getNetaceaSession(e,void 0),n=e.headers.get("cookie"),r=null!==(t=await this.readCookie(this.netaceaCookieName,n))&&void 0!==t?t:"",c=await this.readCookie(this.netaceaCaptchaCookieName,n),h=null!==(a=e.headers.get("cf-connecting-ip"))&&void 0!==a?a:"",p=null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",u=this.enableDynamicCaptchaContentType?(0,ee.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ee.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:h,getBodyFn:async()=>await Promise.resolve(e.body),method:e.method,mitata:r,mitataCaptcha:c,headerFingerprint:o,url:e.url,userAgent:p,captchaPageContentType:u})}async timeoutCheck(e,t){return await Promise.race([e,new Promise(((e,a)=>{setTimeout((()=>{e(void 0)}),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,Q.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,Q.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case X.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case X.NetaceaMitigationType.INJECT:return await this.inject(e);case X.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const a=`${e}=`;for(const i of t){const t=i.split(";")[0].trimStart();if(t.startsWith(a)){const i=t.slice(a.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const a of t)if(a.startsWith(e))return await this.readCookie(this.netaceaCookieName,a)}}async getNetaceaCookieFromRequest(e){var t;const a=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===X.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest)}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},a=await this.makeIngestApiCall(e,t);if(200!==a.status)throw this.APIError(a)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:p,integrationType:u,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){var y;const f=new Date;let C;"/"!==s[0]&&(s=`/${s}`);const v=s.split("?");v.length>1&&(C=`?${v[1]}`);const k=v[0],S=null===(y=(0,Z.matchMitataCookie)(h))||void 0===y?void 0:y.userId;return{status:a,method:i,bytes_sent:(0,X.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${k}${null!=C?C:""} ${o}`,request_time:(0,X.safeParseInt)(c),integration_type:u,integration_version:d,client:e,user_agent:t,bc_type:""===p?void 0:p,hour:f.getUTCHours(),minute:f.getUTCMinutes(),"@timestamp":f.toISOString().replace("Z","+00:00"),path:k,protocol:o,query:C,user_id:S,x_forwarded_for:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:p,integrationType:u,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){return{Request:`${i} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:a,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=h?h:"",NetaceaMitigationApplied:null!=p?p:"",IntegrationType:null!=u?u:"",IntegrationVersion:null!=d?d:"",XForwardedFor:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===X.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i,s,o,n){var r,c;let h,p,u,d,l,g,m;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const y=(0,Z.checkMitataCookie)(e,t,this.secretKey);if(!y.isPrimaryHashValid||y.requiresReissue){const e=await this.makeMitigateAPICall(null===(r=y.mitata)||void 0===r?void 0:r.userId,t,a,n,i,!1,null,s,o);h=e.status,p=e.match,u=e.mitigate,d=e.captcha,l=e.body,g=[await this.createMitata(t,null===(c=y.mitata)||void 0===c?void 0:c.userId,p,u,d,e.mitataMaxAge)],m=e.eventId}else h=-1,p=y.match,u=y.mitigate,d=y.captcha,l=void 0,g=[];return this.composeResult(l,g,h,p,u,d,!1,m)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)||3===i?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[a,i,s].join("");let p=(0,Z.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(p=await this.encryptCookieValue(p)),X.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:p,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t,a,i,s){const{status:o,match:n,mitigate:r,captcha:c,body:h,setCookie:p}=await this.makeCaptchaAPICall(e,t,a,i,s);return this.composeResult(h,p,o,n,r,c,!0)}async getMitataCaptchaFromHeaders(e){let t=e[J.dictionary.netaceaHeaders.mitataCaptcha];const a=parseInt(e[J.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),X.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(a),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t,a,i,s){const o={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},n=(0,Z.matchMitataCookie)(e);void 0!==n&&(o["X-Netacea-UserId"]=n.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const r=new URLSearchParams;r.append("headerFP",s);const c=await this.makeRequest({host:this.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${r.toString()}`,headers:o,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(c,null==n?void 0:n.userId,t,"")}async getApiCallResponseFromResponse(e,t,a,i){var s;if(200!==e.status)throw this.APIError(e);const o=(0,ae.parseIntOrReturnUnparsed)(e.headers[J.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[J.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[J.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[J.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(a,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),p=e.headers[J.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,ee.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,i)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:p,mitataMaxAge:c}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i,s,o,n,r,c){const h={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(h["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(h["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,h["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),h["X-Netacea-Captcha-Content-Type"]=s;let p="/";const u=new URLSearchParams;u.append("headerFP",r),o&&(p="/captcha",null!==n&&u.append("trackingId",n));const d=await this.makeRequest({host:this.mitigationServiceUrl,path:`${p}?${u.toString()}`,headers:h,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(d,e,t,c)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[J.dictionary.mitigationTypes.block,J.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===X.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=J.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=J.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=J.dictionary.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=J.dictionary.captchaMap[a])&&void 0!==n?n:r);const e=J.dictionary.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===X.NetaceaMitigationType.INJECT&&(h=J.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){if(await(0,ee.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ee.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.headerFingerprint,e.url,e.mitataCaptcha)}return this.isUrlCaptchaPost(e.url,e.method)?await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn(),e.headerFingerprint):await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.headerFingerprint,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(X.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=(0,Z.checkMitataCookie)(i,X.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=r;var a=c;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(n);var oe=o(n);module.exports=oe;
1
+ "use strict";var e=require("crypto"),t=require("buffer"),a=require("url"),i=require("querystring"),s=require("jose");function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={},r={},c={};!function(a){var i,s,o,n,r=e,c=t;a.NetaceaIngestType=void 0,(i=a.NetaceaIngestType||(a.NetaceaIngestType={})).ORIGIN="ORIGIN",i.HTTP="HTTP",i.KINESIS="KINESIS",i.NATIVE="NATIVE",a.NetaceaLogVersion=void 0,(s=a.NetaceaLogVersion||(a.NetaceaLogVersion={})).V1="V1",s.V2="V2",a.NetaceaMitigationType=void 0,(o=a.NetaceaMitigationType||(a.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",a.NetaceaCookieV3IssueReason=void 0,(n=a.NetaceaCookieV3IssueReason||(a.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const h=3e3;const p="_/@#/",u={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:u.none,1:u.block,2:u.none,3:u.block,4:u.block},l={1:u.captcha,2:u.captchaPass,3:u.captcha,4:u.allow,5:u.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:p,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:u,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:parseInt(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function k(e=16,t=f){const a=r.randomBytes(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function S(e,t){const a=r.createHmac("sha256",t);return a.update(e),c.Buffer.from(a.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),a={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,i]=e.split("="),s=decodeURIComponent(i);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),a[o]=n}return a}function T(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:a.NetaceaCookieV3IssueReason.NO_SESSION}}function N(e,t){const a=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==a&&a.length>0?a?.replace(`${t}=`,""):void 0}function b(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":w(e.split(";"),t).join("; ")}function w(e,t=!1){if(t)return w(e.reverse()).reverse();const a=new Set,i=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();a.has(e)||(a.add(e),i.push(t))}return i}var A=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let a=e=b(e??"",!0),i=t=b(t??"",!0);if(void 0!==e&&void 0!==t){const s=N(e,"Domain"),o=N(t,"Domain");void 0!==s&&void 0!==o?i=t.replace(o,s):void 0!==s&&void 0===o?i=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(a=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=N(e,"Domain");void 0!==t&&(i=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=N(t,"Domain");void 0!==e&&(a=`Domain=${e}`)}return{cookieAttributes:""!==a?a:void 0,captchaCookieAttributes:""!==i?i:void 0}},extractAndRemoveCookieAttr:function(e,t){const a=N(e,t);if(void 0!==a){return{extractedAttribute:a,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${a}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:N,removeDuplicateAttrs:b});function x(e){const t=b([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var P=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:x});var E=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const a=e.slice(0,t),i=e.slice(t+1),s=i.indexOf(";");return{name:a,value:i.slice(0,s),attributes:i.slice(s).trimStart()}}});const _={cookie:{parse:E,attributes:A,netaceaSession:P}};a.checkMitataCookie=function(e,t,a){const i={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return i;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(p),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=S(t+"|"+s.expiry,a),u=s.ipHash===h;return{mitata:s,requiresReissue:o||!u,isExpired:o,shouldExpire:c,isSameIP:u,isPrimaryHashValid:s.signature===S(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i},a.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return T();const a=I(e);if(void 0!==a){const e=Math.floor(Date.now()/1e3),i=a.issueTimestamp+a.gracePeriod<e,s=t===a.clientIP,o=[1,3,5].includes(a.captcha),n=3===a.mitigate;return{mitata:a,requiresReissue:i||!s,isExpired:i,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:a.issueReason}}return T()},a.configureMitataExpiry=function(e,t){return void 0===t?e===a.NetaceaMitigationType.INGEST?3600:60:t},a.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},a.correctTimeout=function(e){return e<=0?h:e},a.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=k());const o=[a,t,S(e+"|"+String(a),i),s].join(p);return`${S(o,i)}${p}${o}`},a.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},a.defaultInvalidResponse=T,a.dictionary=y,a.generateId=k,a.hexSha256=S,a.ingestIgnoredIpValue="ignored",a.lib=_,a.matchMitataCookie=v,a.matchNetaceaCookieV3=I,a.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},a.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},a.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(c);var h={},p={},u={},d={},l=function(e){return new g(e)};function g(e){this.capacity=0|e,this.map=Object.create(null),this.list=new m}function m(){this.firstNode=null,this.lastNode=null}function y(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}g.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},g.prototype.set=function(e,t){var a=this.map[e];if(null!=a)a.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;a=new y(e,t),this.map[e]=a,this.capacity--}return this.used(a),!0},g.prototype.used=function(e){this.list.moveToFront(e)},g.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},m.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},m.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},m.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=d,o=a,n=i,r=e,c=l(1e3);function h(e,t,a){return r.createHmac("sha256",e).update(t,"utf8").digest(a)}function p(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function u(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function g(e){return u(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var a=e.headers=e.headers||{},i=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||a.Host||a.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||i[0]||"",this.region=e.region||i[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),a.Host||a.host||(a.Host=e.hostname||e.host||this.createHost(),e.port&&(a.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=a.Host||a.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var a=0;a<2;a++)if(/^s3-/.test(t[a])){t[1]=t[a].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,a=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||a["Content-Type"]||a["content-type"]||(a["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||a["Content-Length"]||a["content-length"]||(a["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||a["X-Amz-Security-Token"]||a["x-amz-security-token"]||(a["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||(a["X-Amz-Content-Sha256"]=p(this.request.body||"","hex")),a["X-Amz-Date"]||a["x-amz-date"]?this.datetime=a["X-Amz-Date"]||a["x-amz-date"]:a["X-Amz-Date"]=this.getDateTime()),delete a.Authorization,delete a.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,a,i=this.getDate(),s=[this.credentials.secretAccessKey,i,this.region,this.service].join(),o=c.get(s);return o||(e=h("AWS4"+this.credentials.secretAccessKey,i),t=h(e,this.region),a=h(t,this.service),o=h(a,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),p(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,a=this.parsedPath.query,i=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||p(this.request.body||"","hex"),a){var h=Object.keys(a).reduce((function(e,t){return t?(e[g(t)]=Array.isArray(a[t])&&c?a[t][0]:a[t],e):e}),{}),u=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(g).sort().forEach((function(t){u.push(e+"="+t)})):u.push(e+"="+g(h[e]))})),s=u.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(g(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),a=null;t>=0&&(a=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:a}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+u(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.API_VERSION=f.REGION=f.PAYLOAD_TYPE=f.STATE=void 0,f.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},f.PAYLOAD_TYPE="string",f.REGION="eu-west-1",f.API_VERSION="2013-12-02",Object.defineProperty(u,"__esModule",{value:!0}),u.signRequest=void 0;const C=d,v=f;function k(e,t){const a=[];for(let i=0;i<e.length;i+=t){const s=e.slice(i,i+t);a.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a}u.signRequest=function(e,t,a){const{accessKeyId:i,secretAccessKey:s}=e,o={Records:k(t,a),PartitionKey:Date.now().toString(),StreamName:e.streamName};return C.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:i,secretAccessKey:s})},Object.defineProperty(p,"__esModule",{value:!0});const S=u;p.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:a,maxLogAgeSeconds:i,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=a,void 0!==i&&i<this.maxLogAgeSeconds&&i>0&&(this.maxLogAgeSeconds=i),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const a=(0,S.signRequest)({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:a.headers,host:`https://${a.hostname}`,method:a.method,path:a.path,body:a.body})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize&&await this.putToKinesis(t)}},Object.defineProperty(h,"__esModule",{value:!0});const I=p;h.default=I.default;var T={name:"@netacea/cloudflare",version:"5.2.49",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"npx nyc tape -r ts-node/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup",postpack:"npx netacea-bundler postpack",prepack:"npx netacea-bundler prepack"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.49","@netacea/netaceaintegrationbase":"^2.0.31",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/bundler":"^1.0.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1","ts-node":"^10.9.1",typescript:"^5.2.2"},gitHead:"976f2e93315b6dcbcfa076cc0345f341595e1520"},N={};Object.defineProperty(N,"__esModule",{value:!0}),N.fetch=void 0,N.fetch=globalThis.fetch.bind(globalThis);var b,w={};var A={},x={};Object.defineProperty(x,"__esModule",{value:!0}),x.parseIntOrReturnUnparsed=void 0,x.parseIntOrReturnUnparsed=function(e){const t=parseInt(e,10);return isNaN(t)?e:t},Object.defineProperty(A,"__esModule",{value:!0}),A.checkMitataCookie=A.hexSha256=A.createMitataCookie=A.generateId=A.matchMitataCookie=A.ingestIgnoredIpValue=void 0;const P=e,E=t,_=x;A.ingestIgnoredIpValue="ignored";const M="_/@#/",R="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function O(e){if(void 0===e)return;const t=e.match(H);if(null!=t){const[,e,a,i,s,o,n,r,c]=t;return{signature:e,expiry:a,userId:i,ipHash:s,mitigationType:o,match:(0,_.parseIntOrReturnUnparsed)(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function j(e=16,t=R){const a=(0,P.randomBytes)(e-1);return`c${Array.from(a).map((e=>t[e%t.length])).join("")}`}function K(e,t){const a=(0,P.createHmac)("sha256",t);return a.update(e),E.Buffer.from(a.digest("hex")).toString("base64")}A.matchMitataCookie=O,A.generateId=j,A.createMitataCookie=function(e,t,a,i,s="000"){void 0===t&&(t=j());const o=[a,t,K(e+"|"+String(a),i),s].join(M);return`${K(o,i)}${M}${o}`},A.hexSha256=K,A.checkMitataCookie=function(e,t,a){const i={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return i;const s=O(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(M),i=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<i,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=K(t+"|"+s.expiry,a),p=s.ipHash===h;return{mitata:s,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:s.signature===K(e,a),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return i};var q={};Object.defineProperty(q,"__esModule",{value:!0}),q.decrypt=q.encrypt=void 0;const D=s;q.encrypt=async function(e,t){const a=D.base64url.decode(t),i=(new TextEncoder).encode(e);return await new D.CompactEncrypt(i).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(a)},q.decrypt=async function(e,t){const a=D.base64url.decode(t),{plaintext:i}=await D.compactDecrypt(e,a,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(i)};var V={};Object.defineProperty(V,"__esModule",{value:!0}),V.isUrlCaptchaGet=V.getTrackingId=V.modifyCaptchaJsonResponse=V.getCaptchaPageContentType=void 0,V.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),a=t.includes("application/html")||t.includes("text/html"),i=t.includes("application/json");return!a&&i?"application/json":"text/html"},V.modifyCaptchaJsonResponse=async function(e,t,a){const i=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(a);return t.length<2||void 0===i?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${i}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${i}`})},V.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},V.isUrlCaptchaGet=async function(e,t,a){if(void 0===a||""===a)return!1;a.startsWith("/")||(a="/"+a);const{pathname:i,search:s}=new URL(e);return i.includes(a)&&s.includes("trackingId")&&"get"===t.toLowerCase()};var $={};async function F(e,t){const a=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,a);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function U(e){const t=[];return e.forEach(((e,a)=>{const i=a.toLowerCase();"cookie"===i||"referer"===i||i.startsWith("x-netacea-")||t.push(a)})),t.join(",")}async function L(e){let t="";try{t=await F("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty($,"__esModule",{value:!0}),$.hashCookieNames=$.hashHeaders=$.extractHeaderNames=$.hashString=void 0,$.hashString=F,$.extractHeaderNames=U,$.hashHeaders=async function(e){const t=U(e);return await L(t)},$.hashCookieNames=async function(e){const t=e.join(",");return await L(t)};var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.addIngestOriginHeaders=void 0;const G=T;z.addIngestOriginHeaders=function(e,t,a){e.headers.set("x-netacea-integration-type",G.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",G.version),e.headers.set("x-netacea-userid",a),e.headers.set("x-netacea-bc-type",t)},Object.defineProperty(r,"__esModule",{value:!0});const X=c,Y=h,W=T,B=N,J=function e(){return b||(b=1,t=w,Object.defineProperty(t,"__esModule",{value:!0}),t.dictionary=t.bestMitigationCaptchaMap=t.bestMitigationMap=t.captchaStatusCodes=t.captchaMap=t.mitigateMap=t.matchMap=t.netaceaHeaders=t.mitigationTypes=void 0,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_",b:"headerFP_"},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.dictionary=e()),w;var t}(),Z=A,Q=q,ee=V,te=$,ae=x,ie=z,{configureCookiesDomain:se}=X.lib.cookie.attributes;r.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:a,timeout:i=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=X.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=X.NetaceaIngestType.HTTP,kinesis:p,logVersion:u,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=a,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=h?h:X.NetaceaIngestType.HTTP,this.logVersion=null!=u?u:X.NetaceaLogVersion.V1,this.ingestType===X.NetaceaIngestType.KINESIS&&(void 0===p?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Y.default({...p,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,X.correctTimeout)(i),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=se(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=v?v:"",this.netaceaCaptchaCookieAttributes=null!=k?k:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===X.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f}async run(e,t){const a=new Request(e.request),i=await this.timeoutCheck(this.runMitigation(a),this.timeout);return await this.handleResponse(a,i,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const a=new Headers;if(!await(0,ee.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)a.append("set-cookie",e);let i="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&a.append(this.captchaHeader.name,this.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),i=t.body),{response:new Response(i,{status:403,statusText:"Forbidden",headers:a}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const a of t.setCookie)e.append("set-cookie",a);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async getNetaceaSession(e,t){var a;const i=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=i?i:await this.getNetaceaCookieFromRequest(e),{headers:o}=e,n=await(0,te.hashHeaders)(o),r=this.getHeaderValuesArray(o,"cookie").map((e=>e.split("=")[0])).flat(),c=await(0,te.hashCookieNames)(r),h=""===n?n:`h_${n.substring(1,15)}`,p=""===c?c:`c_${c.substring(1,15)}`,{match:u,mitigate:d,captcha:l,userId:g}=null!==(a=(0,Z.matchMitataCookie)(null!=s?s:""))&&void 0!==a?a:{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:m}=this.findBestMitigation(u,d,l,this.isUrlCaptchaPost(e.url,e.method));return{userId:g,sessionStatus:m,netaceaCookie:s,headerFingerprint:h,cookieFingerprint:p}}async ingest(e,t){var a;const{sessionStatus:i,netaceaCookie:s,headerFingerprint:o,cookieFingerprint:n}=await this.getNetaceaSession(e,t),r=String(null===(a=e.cf)||void 0===a?void 0:a.httpProtocol);await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:r,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:i,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:s,integrationType:W.name.replace("@netacea/",""),integrationVersion:W.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for"),headerFingerprint:o,cookieFingerprint:n})}async handleGetCaptchaRequest(e,t,a,i,s,o,n,r){var c;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const h=(0,Z.checkMitataCookie)(e,t,this.secretKey),p=await this.makeMitigateAPICall(null===(c=h.mitata)||void 0===c?void 0:c.userId,t,a,r,i,!0,s,o,n);return{body:p.body,apiCallStatus:p.status,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:a,headers:i,body:s}){const o=`${e}${a}`,n=new Request(o,{method:t,body:s,headers:i}),r=await(0,B.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(e,t){var a;if(void 0===t)return e;const i=null!==(a=e.headers.get("set-cookie"))&&void 0!==a?a:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})}addHeadersToRequest(e,t){if(void 0===t.injectHeaders)return e;const a=new Headers(e.headers);for(const[e,i]of Object.entries(t.injectHeaders))a.set(e,i);return new Request(e,{headers:a})}async handleResponse(e,t,a){if(void 0!==t)if(this.mitigationType===X.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===X.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));if(this.ingestType===X.NetaceaIngestType.ORIGIN){const{sessionStatus:a,userId:i}=await this.getNetaceaSession(e,t);(0,ie.addIngestOriginHeaders)(e,a,i)}const i=await a(e);return this.addHeadersToResponse(i,t)}getHeaderValueOrDefault(e,t,a=""){var i;return null!==(i=e.get(t))&&void 0!==i?i:a}getHeaderValuesArray(e,t){var a,i;return null!==(i=null===(a=e.get(t))||void 0===a?void 0:a.split(/; ?/))&&void 0!==i?i:[]}async getMitigationResponse(e){var t,a,i,s;const{headerFingerprint:o}=await this.getNetaceaSession(e,void 0),n=e.headers.get("cookie"),r=null!==(t=await this.readCookie(this.netaceaCookieName,n))&&void 0!==t?t:"",c=await this.readCookie(this.netaceaCaptchaCookieName,n),h=null!==(a=e.headers.get("cf-connecting-ip"))&&void 0!==a?a:"",p=null!==(i=e.headers.get("user-agent"))&&void 0!==i?i:"",u=this.enableDynamicCaptchaContentType?(0,ee.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ee.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:h,getBodyFn:async()=>{var t;return null!==(t=await Promise.resolve(e.body))&&void 0!==t?t:void 0},method:e.method,mitata:r,mitataCaptcha:c,headerFingerprint:o,url:e.url,userAgent:p,captchaPageContentType:u})}async timeoutCheck(e,t){const a=new Promise(((e,a)=>{setTimeout((()=>{e(void 0)}),t)}));return await Promise.race([e,a])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,Q.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,Q.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case X.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case X.NetaceaMitigationType.INJECT:return await this.inject(e);case X.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const a=`${e}=`;for(const i of t){const t=i.split(";")[0].trimStart();if(t.startsWith(a)){const i=t.slice(a.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(i)}catch(e){return}return i}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const a of t)if(a.startsWith(e))return await this.readCookie(this.netaceaCookieName,a)}}async getNetaceaCookieFromRequest(e){var t;const a=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,a))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===X.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest.bind(this))}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},a=await this.makeIngestApiCall(e,t);if(200!==a.status)throw this.APIError(a)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}constructV2WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:p,integrationType:u,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){var y;const f=new Date;let C;"/"!==s[0]&&(s=`/${s}`);const v=s.split("?");v.length>1&&(C=`?${v[1]}`);const k=v[0],S=null===(y=(0,Z.matchMitataCookie)(h))||void 0===y?void 0:y.userId;return{status:a,method:i,bytes_sent:(0,X.safeParseInt)(r),referrer:""===n?void 0:n,request:`${i} ${k}${null!=C?C:""} ${o}`,request_time:(0,X.safeParseInt)(c),integration_type:u,integration_version:d,client:e,user_agent:t,bc_type:""===p?void 0:p,hour:f.getUTCHours(),minute:f.getUTCMinutes(),"@timestamp":f.toISOString().replace("Z","+00:00"),path:k,protocol:o,query:C,user_id:S,x_forwarded_for:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructV1WebLog({ip:e,userAgent:t,status:a,method:i,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:p,integrationType:u,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){return{Request:`${i} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:a,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=h?h:"",NetaceaMitigationApplied:null!=p?p:"",IntegrationType:null!=u?u:"",IntegrationVersion:null!=d?d:"",XForwardedFor:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===X.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,a,i,s,o,n){var r,c;let h,p,u,d,l,g,m;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const y=(0,Z.checkMitataCookie)(e,t,this.secretKey);if(!y.isPrimaryHashValid||y.requiresReissue){const e=await this.makeMitigateAPICall(null===(r=y.mitata)||void 0===r?void 0:r.userId,t,a,n,i,!1,null,s,o);h=e.status,p=e.match,u=e.mitigate,d=e.captcha,l=e.body,g=[await this.createMitata(t,null===(c=y.mitata)||void 0===c?void 0:c.userId,p,u,d,e.mitataMaxAge)],m=e.eventId}else h=-1,p=y.match,u=y.mitigate,d=y.captcha,l=void 0,g=[];return this.composeResult(l,g,h,p,u,d,!1,m)}async createMitata(e,t,a,i,s,o=86400,n=void 0){const r=[1,3,5].includes(s)||3===i?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[a,i,s].join("");let p=(0,Z.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(p=await this.encryptCookieValue(p)),X.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:p,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t,a,i,s){const{status:o,match:n,mitigate:r,captcha:c,body:h,setCookie:p}=await this.makeCaptchaAPICall(e,t,a,i,s);return this.composeResult(h,p,o,n,r,c,!0)}async getMitataCaptchaFromHeaders(e){let t=e[J.dictionary.netaceaHeaders.mitataCaptcha];const a=parseInt(e[J.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),X.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(a),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t,a,i,s){const o={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},n=(0,Z.matchMitataCookie)(e);void 0!==n&&(o["X-Netacea-UserId"]=n.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const r=new URLSearchParams;r.append("headerFP",s);const c=await this.makeRequest({host:this.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${r.toString()}`,headers:o,method:"POST",body:i,timeout:this.timeout});return await this.getApiCallResponseFromResponse(c,null==n?void 0:n.userId,t,"")}async getApiCallResponseFromResponse(e,t,a,i){var s,o;if(200!==e.status)throw this.APIError(e);const n=(0,ae.parseIntOrReturnUnparsed)(e.headers[J.dictionary.netaceaHeaders.match]),r=parseInt(e.headers[J.dictionary.netaceaHeaders.mitigate]),c=parseInt(e.headers[J.dictionary.netaceaHeaders.captcha]);let h=parseInt(e.headers[J.dictionary.netaceaHeaders.mitataExpiry]);isNaN(h)&&(h=86400);const p=[await this.createMitata(a,t,n,r,c,h),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[J.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,ee.modifyCaptchaJsonResponse)(null!==(o=e.body)&&void 0!==o?o:"",this.netaceaCaptchaPath,i)}return{status:e.status,match:n,mitigate:r,captcha:c,setCookie:p,body:e.body,eventId:u,mitataMaxAge:h}}async buildCookieFromValues(e,t,a,i="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${a}; Path=${i}`}return`${e}=${t}; Max-Age=${a}; Path=${i}`}buildCookieHeader(e){let t="",a="";for(const i in e){const s=e[i];void 0!==s&&(t=`${t}${a}${i}=${s}`,a="; ")}return t}async makeMitigateAPICall(e,t,a,i,s,o,n,r,c){const h={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":a,cookie:this.buildCookieHeader({_mitatacaptcha:i})};void 0!==e&&(h["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(h["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,h["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),h["X-Netacea-Captcha-Content-Type"]=s;let p="/";const u=new URLSearchParams;u.append("headerFP",r),o&&(p="/captcha",null!==n&&u.append("trackingId",n));const d=await this.makeRequest({host:this.mitigationServiceUrl,path:`${p}?${u.toString()}`,headers:h,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(d,e,t,c)}composeResult(e,t,a,i,s,o,n,r){const c=this.findBestMitigation(i,s,o,n),h={body:e,apiCallStatus:a,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[J.dictionary.mitigationTypes.block,J.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===X.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,a,i){var s,o,n;const r="unknown";i||(2===a?a=4:3===a&&(a=5));let c=null!==(s=J.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=J.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=J.dictionary.bestMitigationMap[t];if(0!==a){c+=","+(null!==(n=J.dictionary.captchaMap[a])&&void 0!==n?n:r);const e=J.dictionary.bestMitigationCaptchaMap[a];void 0!==e&&(h=e)}return this.mitigationType===X.NetaceaMitigationType.INJECT&&(h=J.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:a}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){var t;if(await(0,ee.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ee.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.headerFingerprint,e.url,e.mitataCaptcha)}if(this.isUrlCaptchaPost(e.url,e.method)){const a=null!==(t=await e.getBodyFn())&&void 0!==t?t:"";return await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,a,e.headerFingerprint)}return await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.headerFingerprint,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(X.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const a=this.getCookieHeader(e),i=await this.readCookie(this.netaceaCookieName,a),s=(0,Z.checkMitataCookie)(i,X.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=r;var a=c;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return a.NetaceaMitigationType}}),e.default=t.default}(n);var oe=o(n);module.exports=oe;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "5.2.48",
3
+ "version": "5.2.49",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -17,9 +17,9 @@
17
17
  },
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "@netacea/kinesisingest": "^1.5.48",
21
- "@netacea/netaceaintegrationbase": "^2.0.30",
20
+ "@netacea/kinesisingest": "^1.5.49",
21
+ "@netacea/netaceaintegrationbase": "^2.0.31",
22
22
  "jose": "^4.11.2"
23
23
  },
24
- "gitHead": "2250de7eb365e1817eccb58d19eea5b1dbf0a6a5"
24
+ "gitHead": "976f2e93315b6dcbcfa076cc0345f341595e1520"
25
25
  }