@netacea/cloudflare 6.0.22 → 6.0.24
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 +3 -2
- package/dist/index.js +2 -1
- package/package.json +6 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
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, { KinesisIngestConfigArgs } from '@netacea/kinesisingest';
|
|
4
3
|
import { Request as Request$1 } from '@cloudflare/workers-types/experimental';
|
|
4
|
+
import { KinesisIngestConfigArgs } from '@netacea/kinesisingest';
|
|
5
|
+
import * as sdk from '@netacea/integrations-sdk';
|
|
5
6
|
|
|
6
7
|
interface NetaceaCloudflareResult {
|
|
7
8
|
response: Response;
|
|
@@ -117,7 +118,7 @@ interface MakeRequestArgs {
|
|
|
117
118
|
}
|
|
118
119
|
declare class Cloudflare {
|
|
119
120
|
protected readonly config: CloudflareConfig;
|
|
120
|
-
protected readonly kinesis?:
|
|
121
|
+
protected readonly kinesis?: sdk.ingest.WebStandardKinesis;
|
|
121
122
|
private readonly requestAnalyser;
|
|
122
123
|
private workerInstanceId;
|
|
123
124
|
constructor(args: CloudflareConstructorArgs);
|
package/dist/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
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;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function p(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 d(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(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 g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=d(e??"",!0),a=t=d(t??"",!0);if(void 0!==e&&void 0!==t){const n=p(e,"Domain"),s=p(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=p(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=p(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=p(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:p,removeDuplicateAttrs:d});function f(e){const t=d([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=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),n=a.indexOf(";");return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}};var C="@netacea/cloudflare",k="6.0.24";const w=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",b="x-netacea-mitigate",N="x-netacea-captcha",A="x-netacea-mitata-expiry",E="x-netacea-mitatacaptcha-value",T="x-netacea-mitatacaptcha-expiry",_="x-netacea-event-id",P={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},O={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},x={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},R={0:I.none,1:I.block,2:I.none,3:I.block,4:I.block},K={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha},M="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),j=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function H(e){if(void 0===e)return;const t=e.match(j);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function L(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var $;async function U(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function G(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function B(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"}async function W(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:n}=e;return a.includes(i)&&n.includes("trackingId")&&"get"===t.toLowerCase()}function V(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function J(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}($||($={}));class Y extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Z(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({ip:e,userAgent:t,status:i,method:a,path:n,protocol:s,referer:o,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:d,integrationMode:l,xForwardedFor:g,headerFingerprint:f,cookieFingerprint:y,requestHost:m,mitigationLatency:S,mitigationStatus:C,netaceaCookieStatus:k,workerInstanceId:w}){return{Request:`${a} ${n} ${s}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,RequestTime:c?.toString(),BytesSent:r?.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:u??"",NetaceaMitigationApplied:h??"",ProtectorLatencyMs:S,ProtectorStatus:C,IntegrationType:p??"",IntegrationVersion:d??"",ProtectionMode:l??"",RequestHost:m,XForwardedFor:g,WorkerInstanceId:w,NetaceaUserIdCookieStatus:k,optional:{headerFingerprint:f,cookieFingerprint:y}}}(e)}const Q="unknown";function ee(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s&&(s="5"));let o=P[a]??Q+"_";o+=O[n]??Q;let r=R[n];if("0"!==s){o+=","+(x[s]??Q);const e=K[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function te(e){let t="";try{t=await async function(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("")}("SHA-256",e)}catch(e){t=""}return t}class ie{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("cf-connecting-ip")??"",{sessionCookieDetails:o,sessionCookieStatus:r,sessionStatus:c,userId:u}=await async function(e,t,i,a,n){const s=await async 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 n=H(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(M),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await F(t+"|"+n.expiry,i),h=n.ipHash===u,p=n.signature===await F(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:p,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?$.RENEW_SESSION:$.EXISTING_SESSION,{sessionStatus:u}=ee(e.mitigationType,s.protectorCheckCodes,V(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:L(),sessionCookieStatus:$.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await ae(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",sessionDetails:{sessionStatus:c,captchaToken:n,sessionCookieDetails:o,sessionCookieStatus:r,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await G(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ae(e){const{headers:t}=e,i=await async function(e){const t=function(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(",")}(e);return await te(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await te(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}const{configureCookiesDomain:ne}=S.cookie.attributes;class se{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceUrl:n="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:r=exports.NetaceaMitigationType.INGEST,captchaSiteKey:c,captchaSecretKey:u,ingestType:p=s.HTTP,kinesis:d,mitataCookieExpirySeconds:l,netaceaCookieExpirySeconds:g,netaceaCookieName:f,netaceaCaptchaCookieName:y,enableDynamicCaptchaContentType:m=!1,captchaHeader:S,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=n.endsWith("/")?n.slice(0,-1):n,this.ingestServiceUrl=o,this.mitigationType=r,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=d,void 0===c&&void 0===u||(this.captchaSiteKey=c,this.captchaSecretKey=u),this.timeout=function(e){return e<=0?h:e}(a),this.netaceaCookieName=f??"_mitata",this.netaceaCaptchaCookieName=y??"_mitatacaptcha";const{cookieAttributes:k,captchaCookieAttributes:w}=ne(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=k??"",this.netaceaCaptchaCookieAttributes=w??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(r,g??l),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof m?m:"true"===m),this.captchaHeader=S}}var oe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},re={},ce={},ue={},he=oe&&oe.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),pe=oe&&oe.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),de=oe&&oe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&he(t,e,i);return pe(t,e),t};Object.defineProperty(ue,"__esModule",{value:!0}),ue.isJweEncrypted=ue.decrypt=ue.encrypt=void 0;const le=de(i);ue.encrypt=async function(e,t){const i=le.base64url.decode(t),a=(new TextEncoder).encode(e);return await new le.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ue.decrypt=async function(e,t){const i=le.base64url.decode(t),{plaintext:a}=await le.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ue.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var ge=oe&&oe.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=oe&&oe.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ye=oe&&oe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ge(t,e,i);return fe(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0}),ce.jwe=void 0,ce.jwe=ye(ue);var me={},Se={};function Ce(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=we("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function ke(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...Ie(s,t))}return i}function we(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function Ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Se,"__esModule",{value:!0}),Se.findAllInCookieString=Se.findFirstInCookieString=Se.findAllInHeaders=Se.findFirstInHeaders=Se.findOnlyValueInHeaders=Se.findAllValuesInHeaders=Se.findFirstValueInHeaders=void 0,Se.findFirstValueInHeaders=function(e,t){const i=Ce(e,t);if(void 0!==i)return i.slice(t.length+1)},Se.findAllValuesInHeaders=function(e,t){return ke(e,t).map((e=>e.slice(t.length+1)))},Se.findOnlyValueInHeaders=function(e,t){const i=ke(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Se.findFirstInHeaders=Ce,Se.findAllInHeaders=ke,Se.findFirstInCookieString=we,Se.findAllInCookieString=Ie;var ve={};function be(e){return"set-cookie"===e||"Set-Cookie"===e}function Ne(e,t){const i=t+"=";return e.startsWith(i)}function Ae(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Ee(e,t){for(const i of Object.keys(e)){if(!be(i))continue;const a=Te(Ae(e,i),t);if(void 0!==a)return a}}function Te(e,t){return e.map((e=>e.trimStart())).find((e=>Ne(e,t)))}function _e(e,t){const i=[];for(const a of Object.keys(e)){if(!be(a))continue;const n=Ae(e,a);i.push(...Pe(n,t))}return i}function Pe(e,t){return e.map((e=>e.trimStart())).filter((e=>Ne(e,t)))}Object.defineProperty(ve,"__esModule",{value:!0}),ve.findAllInSetCookieStrings=ve.findAllInHeaders=ve.findFirstInSetCookieStrings=ve.findFirstInHeaders=ve.findOnlyValueInHeaders=ve.findFirstValueInHeaders=void 0,ve.findFirstValueInHeaders=function(e,t){const i=Ee(e,t);return i?.slice(t.length+1)?.split(";")[0]},ve.findOnlyValueInHeaders=function(e,t){const i=_e(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},ve.findFirstInHeaders=Ee,ve.findFirstInSetCookieStrings=Te,ve.findAllInHeaders=_e,ve.findAllInSetCookieStrings=Pe;var Oe=oe&&oe.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),xe=oe&&oe.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Re=oe&&oe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Oe(t,e,i);return xe(t,e),t};Object.defineProperty(me,"__esModule",{value:!0}),me.setCookie=me.cookie=void 0,me.cookie=Re(Se),me.setCookie=Re(ve);var Ke={},Me={},De={};Object.defineProperty(De,"__esModule",{value:!0}),De.KINESIS_URL=De.API_VERSION=De.REGION=De.PAYLOAD_TYPE=De.STATE=void 0,De.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},De.PAYLOAD_TYPE="string",De.REGION="eu-west-1",De.API_VERSION="2013-12-02",De.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com",Object.defineProperty(Me,"__esModule",{value:!0}),Me.WebStandardKinesis=void 0;const je=De;async function He(e){await new Promise((t=>{setTimeout(t,e)}))}function Le(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}Me.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e;const{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,maxLogAgeSeconds:s,logBatchSize:o,rampUpBatchSize:r,maxAwaitTimePerIngestCallMs:c}=t;if(void 0===a)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===n)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=i,this.kinesisAccessKey=a,this.kinesisSecretKey=n,this.maxAwaitTimePerIngestCallMs=c,void 0!==s&&s<this.maxLogAgeSeconds&&s>0&&(this.maxLogAgeSeconds=s),void 0!==o&&(this.maxLogBatchSize=o),this.logBatchSize=!0===r?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:Le(i.headers),host:je.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(He(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=He(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const n=e.slice(a,a+t);i.push({Data:this.deps.Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}async signRequest(e,t,i,a){const n={Records:this.batchArrayForKinesis(i,a),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(je.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebStandardKinesis=void 0;var t=Me;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}})}(Ke);var qe=oe&&oe.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Fe=oe&&oe.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$e=oe&&oe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&qe(t,e,i);return Fe(t,e),t};Object.defineProperty(re,"__esModule",{value:!0});var Ue=re.ingest=re.headers=re.webcrypto=void 0;re.webcrypto=$e(ce),re.headers=$e(me),Ue=re.ingest=$e(Ke);exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new se(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ue.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ie({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=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{setTimeout((()=>{e(void 0)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.timeout);return void 0===n&&(n={sessionStatus:"error_open"}),await this.handleResponse(i,n,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 W(t.url,e.method,this.config.netaceaCaptchaPath))for(const e of i.setCookie)a.append("set-cookie",e);let n="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"),n=i.body),{response:new Response(n,{status:403,statusText:"Forbidden",headers:a}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}if(V(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){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=H(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ee(this.config.mitigationType,a,V(new URL(e.url),e.method));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:X(i.rawResponse.headers,"content-length","0"),ip:X(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:n.protocol??null,referer:X(e.headers,"referer"),requestTime:"0",sessionStatus:i.sessionStatus??n.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),userAgent:X(e.headers,"user-agent","-"),mitataCookie:a,integrationType:C.replace("@netacea/",""),integrationVersion:k,xForwardedFor:X(e.headers,"x-forwarded-for"),headerFingerprint:n.fingerprints.headerFingerprint,cookieFingerprint:n.fingerprints.cookieFingerprint,integrationMode:this.config.mitigationType,requestHost:new URL(e.url).hostname,mitigationLatency:i.mitigationLatency,mitigationStatus:i.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:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await w(s,o),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){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=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})}(e,t)),this.config.ingestType===s.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:z(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?B(e.headers.get("Accept")??void 0):B();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Y&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:V(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}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 G(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){const t=X(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Z(e);if(this.config.ingestType===s.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})}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 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}`)}(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){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([$.NEW_SESSION,$.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,p=await this.makeMitigateAPICall(e,t,!1,null);i=p.status,a=p.match,n=p.mitigate,s=p.captcha,o=p.body,u=p.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,p.mitataMaxAge)],c=p.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??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,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await F(e+"|"+String(i),a),n].join(M);return`${await F(s,a)}${M}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await U(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[E];const i=parseInt(e[T]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await U(t,this.config.cookieEncryptionKey)),S.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!==$.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 n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint);const s=Date.now(),o=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:t,timeout:this.config.timeout}),r=Date.now()-s;return await this.getApiCallResponseFromResponse(o,e,r)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Y(e,i);const a=e.headers[v],n=e.headers[b],s=e.headers[N];let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[_];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:J({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==$.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.timeout}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=ee(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[I.block,I.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.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!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(await W(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaPath)){const t=await async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}}(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if(V(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",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===$.NEW_SESSION,a=t===$.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudflare",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.24",
|
|
4
4
|
"description": "Netacea Cloudflare CDN Integration",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"files": [
|
|
8
|
-
"dist/"
|
|
8
|
+
"dist/index.js",
|
|
9
|
+
"dist/index.d.ts"
|
|
9
10
|
],
|
|
10
11
|
"scripts": {
|
|
11
12
|
"prepack": "npx netacea-bundler prepack",
|
|
@@ -17,10 +18,10 @@
|
|
|
17
18
|
},
|
|
18
19
|
"license": "ISC",
|
|
19
20
|
"dependencies": {
|
|
20
|
-
"@netacea/
|
|
21
|
-
"
|
|
21
|
+
"@netacea/netaceaintegrationbase": "^2.0.67",
|
|
22
|
+
"aws4fetch": "^1.0.20",
|
|
22
23
|
"jose": "^4.11.2",
|
|
23
24
|
"uuid": "^10.0.0"
|
|
24
25
|
},
|
|
25
|
-
"gitHead": "
|
|
26
|
+
"gitHead": "02cd93e30cd3dced8c1fdf55dd93f950c5296f61"
|
|
26
27
|
}
|