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