@netacea/cloudflare 6.0.89 → 6.1.1
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 +8 -3
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -378,6 +378,11 @@ interface ComposeResultResponse {
|
|
|
378
378
|
mitigation: string;
|
|
379
379
|
mitigated: boolean;
|
|
380
380
|
injectHeaders?: InjectHeaders;
|
|
381
|
+
redirect?: {
|
|
382
|
+
location: string;
|
|
383
|
+
statusCode: number;
|
|
384
|
+
};
|
|
385
|
+
protectorCheckCodes: ProtectorCheckCodes;
|
|
381
386
|
}
|
|
382
387
|
type MakeRequestBody = Record<string, any> | string | ReadableStream<Uint8Array> | undefined | null;
|
|
383
388
|
interface MakeRequestArgs {
|
|
@@ -412,7 +417,9 @@ declare class Cloudflare {
|
|
|
412
417
|
private getResponseDetails;
|
|
413
418
|
ingest(request: Request | Request$1, responseOrResult: Response | NetaceaCloudflareResult): Promise<void>;
|
|
414
419
|
protected handleGetCaptchaRequest(requestDetails: NetaceaRequestDetails, captchaPageContentType: string, trackingId: string | null): Promise<ComposeResultResponse>;
|
|
415
|
-
protected makeRequest({ host, method, path, headers, body }: MakeRequestArgs): Promise<MakeRequestResponse
|
|
420
|
+
protected makeRequest({ host, method, path, headers, body }: MakeRequestArgs): Promise<MakeRequestResponse & {
|
|
421
|
+
fetchResponse: Response;
|
|
422
|
+
}>;
|
|
416
423
|
private handleResponse;
|
|
417
424
|
private getMitigationResponse;
|
|
418
425
|
runMitigation(request: Request, requestDetails: NetaceaRequestDetails): Promise<NetaceaMitigationResponse<Response>>;
|
|
@@ -434,9 +441,7 @@ declare class Cloudflare {
|
|
|
434
441
|
private getMitataCaptchaFromHeaders;
|
|
435
442
|
private parseCaptchaAPICallBody;
|
|
436
443
|
private makeCaptchaAPICall;
|
|
437
|
-
private getApiCallResponseFromResponse;
|
|
438
444
|
private makeMitigateAPICall;
|
|
439
|
-
private composeResult;
|
|
440
445
|
protected processMitigateRequest(args: {
|
|
441
446
|
captchaPageContentType: string;
|
|
442
447
|
getBodyFn: () => Promise<string | ReadableStream<Uint8Array> | undefined>;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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 d(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 p(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=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const n=d(e,"Domain"),s=d(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=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(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=d(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:d,removeDuplicateAttrs:p});function f(e){const t=p([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(";");if(n<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}},C=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-match",v="x-netacea-mitigate",I="x-netacea-captcha",b="x-netacea-mitata-expiry",A="x-netacea-mitatacaptcha-value",N="x-netacea-mitatacaptcha-expiry",_="x-netacea-event-id",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},x={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},T={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},R={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},P={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},O="_/@#/",L="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),K=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function M(e){if(void 0===e)return;const t=e.match(K);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 D(e=16,t=L){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function j(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 H(e,i){const a=await j(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var q;async function V(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 F(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"}function $(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function U(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"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 G(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 W(e){return void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)?function(e){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");const t=new Headers(e.responseHeaders);return t.append("Location",e.config.netaceaBlockedResponseRedirectLocation),new Response("Forbidden",{status:303,statusText:"",headers:t})}(e):function(e){return new Response("Forbidden",{status:403,statusText:"Forbidden",headers:e.responseHeaders})}(e)}function J(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(q||(q={}));class X 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}}var Q="@netacea/cloudflare",Y="6.0.89",Z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ee={},te={};Object.defineProperty(te,"__esModule",{value:!0}),te.validateRedirectLocation=void 0,te.validateRedirectLocation=function(e){if(""!==(e=e??""))try{return new URL(e).toString()}catch{if(/^https?:\/\//i.test(e))return;return e.startsWith("/")?e:`/${e}`}};var ie={},ae={};function ne(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=oe("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function se(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(...re(s,t))}return i}function oe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function re(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ae,"__esModule",{value:!0}),ae.findAllInCookieString=ae.findFirstInCookieString=ae.findAllInHeaders=ae.findFirstInHeaders=ae.findOnlyValueInHeaders=ae.findAllValuesInHeaders=ae.findFirstValueInHeaders=void 0,ae.findFirstValueInHeaders=function(e,t){const i=ne(e,t);if(void 0!==i)return i.slice(t.length+1)},ae.findAllValuesInHeaders=function(e,t){return se(e,t).map((e=>e.slice(t.length+1)))},ae.findOnlyValueInHeaders=function(e,t){const i=se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ae.findFirstInHeaders=ne,ae.findAllInHeaders=se,ae.findFirstInCookieString=oe,ae.findAllInCookieString=re;var ce={};function ue(e){return"set-cookie"===e||"Set-Cookie"===e}function he(e,t){const i=t+"=";return e.startsWith(i)}function de(e,t){if(!he(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function pe(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function le(e,t){for(const i of Object.keys(e)){if(!ue(i))continue;const a=ge(pe(e,i),t);if(void 0!==a)return a}}function ge(e,t){return e.map((e=>e.trimStart())).find((e=>he(e,t)))}function fe(e,t){const i=[];for(const a of Object.keys(e)){if(!ue(a))continue;const n=pe(e,a);i.push(...ye(n,t))}return i}function ye(e,t){return e.map((e=>e.trimStart())).filter((e=>he(e,t)))}Object.defineProperty(ce,"__esModule",{value:!0}),ce.findAllInSetCookieStrings=ce.findAllInHeaders=ce.findValueInSetCookieStrings=ce.findFirstInSetCookieStrings=ce.findFirstInHeaders=ce.findOnlyValueInHeaders=ce.findFirstValueInHeaders=ce.parseValueFromString=void 0,ce.parseValueFromString=de,ce.findFirstValueInHeaders=function(e,t){const i=le(e,t);return void 0!==i?de(i,t):void 0},ce.findOnlyValueInHeaders=function(e,t){const i=fe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?de(i[0],t):void 0},ce.findFirstInHeaders=le,ce.findFirstInSetCookieStrings=ge,ce.findValueInSetCookieStrings=function(e,t){const i=ge(e,t);if(void 0!==i)return de(i,t)},ce.findAllInHeaders=fe,ce.findAllInSetCookieStrings=ye;var me=Z&&Z.__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]}),Se=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ce=Z&&Z.__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)&&me(t,e,i);return Se(t,e),t};Object.defineProperty(ie,"__esModule",{value:!0}),ie.setCookie=ie.cookie=void 0,ie.cookie=Ce(ae),ie.setCookie=Ce(ce);var ke={},we={},ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.KINESIS_URL=ve.API_VERSION=ve.REGION=ve.PAYLOAD_TYPE=ve.STATE=void 0,ve.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ve.PAYLOAD_TYPE="string",ve.REGION="eu-west-1",ve.API_VERSION="2013-12-02",ve.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.headersToRecord=Ie.increaseBatchSize=Ie.handleFailedLogs=Ie.batchArrayForKinesis=Ie.sleep=void 0,Ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let n=0;n<e.length;n+=t){const s=e.slice(n,n+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Ie.handleFailedLogs=function(e,t,i){const a=2*i,n=[...e,...t],s=n.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),n.splice(0,s)),n},Ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(we,"__esModule",{value:!0}),we.WebStandardKinesis=void 0;const be=ve,Ae=Ie;we.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?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:(0,Ae.headersToRecord)(i.headers),host:be.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ae.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ae.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}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((0,Ae.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ae.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const n={Records:(0,Ae.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(be.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.Kinesis=void 0;const _e=ve,Ee=Ie;Ne.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Ee.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ee.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}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((0,Ee.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ee.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:n}=e,s={Records:(0,Ee.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:_e.REGION},{accessKeyId:a,secretAccessKey:n})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=we;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Ne;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ke);var xe={};function Te(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(xe,"__esModule",{value:!0}),xe.parseHttpHeaderName=xe.stringOrDefault=xe.parseIntOrDefault=xe.parseNumberOrDefault=void 0,xe.parseNumberOrDefault=Te,xe.parseIntOrDefault=function(e,t){const i=Te(e,t);return"number"==typeof i?Math.floor(i):i},xe.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},xe.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var Re={};Object.defineProperty(Re,"__esModule",{value:!0}),Re.searchParamsFromRecord=void 0,Re.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Pe={},Oe={},Le=Z&&Z.__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]}),Ke=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Me=Z&&Z.__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)&&Le(t,e,i);return Ke(t,e),t};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.isJweEncrypted=Oe.decrypt=Oe.encrypt=void 0;const De=Me(i);Oe.encrypt=async function(e,t,i="A128CBC-HS256"){const a=De.base64url.decode(t),n=(new TextEncoder).encode(e);return await new De.CompactEncrypt(n).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)},Oe.decrypt=async function(e,t){const i=De.base64url.decode(t),{plaintext:a}=await De.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},Oe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var je=Z&&Z.__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]}),He=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),qe=Z&&Z.__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)&&je(t,e,i);return He(t,e),t};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.jwe=void 0,Pe.jwe=qe(Oe);var Ve,Fe={};var Be={};Object.defineProperty(Be,"__esModule",{value:!0}),Be.ProtectorApiResponseView=Be.AbstractProtectorApiResponseView=void 0;const $e=xe;class Ue{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,$e.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,$e.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,$e.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,n=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:n})}(e,t,a)}}Be.AbstractProtectorApiResponseView=Ue;var ze;function Ge(){return ze||(ze=1,function(e){var t=Z&&Z.__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]}),i=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(a,e,n);return i(a,e),a},n=Z&&Z.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=void 0,e.configValidation=a(te),e.headers=a(ie),e.ingest=a(ke),e.parsing=a(xe),e.url=a(Re),e.webcrypto=a(Pe),e.graphql=a(function(){if(Ve)return Fe;Ve=1,Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.truncateLongFields=Fe.parseGraphQl=Fe.parseGraphQlRequestBody=Fe.getGraphQLParserConfig=void 0;const e=Ge();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(n=i,(a=s).length<=n?a:a.slice(0,n)+"…")}var a,n;return t}return Fe.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Fe.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const n=JSON.parse(a);if("object"!=typeof n)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,n?.query??"")},o=(n?.operationName??"").trim();return""!==o&&(s.OpName=o),i(e,s)},Fe.parseGraphQl=t,Fe.truncateLongFields=i,Fe}()),n(Be,e)}(ee)),ee}Be.ProtectorApiResponseView=class extends Ue{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var We=Ge();const Je="unknown";function Xe(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let o=E[a]??Je+"_";o+=x[n]??Je;let r=R[n];if("0"!==s){o+=","+(T[s]??Je);const e=P[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function Qe(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}async function Ye(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const n=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new Ze("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");n.push(s)}const s=new Uint8Array(a);let o=0;for(const e of n)s.set(e,o),o+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:We.graphql.parseGraphQlRequestBody(e,a)}}class Ze extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class et{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.netaceaCookieName),n=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",r=We.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=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=M(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(O),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5","a","c","e"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await H(t+"|"+n.expiry,i),h=n.ipHash===u,d=n.signature===await H(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,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?q.RENEW_SESSION:q.EXISTING_SESSION,{sessionStatus:u}=Xe(e.mitigationType,s.protectorCheckCodes,U(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:s,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:D(),sessionCookieStatus:q.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await tt(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:o,sessionDetails:{captchaToken:n,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await Ye(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof Ze){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}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 F(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function tt(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 Qe(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,n=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await async function(e){const t=e.join(",");return await Qe(t)}(n);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:it}=We.configValidation,{configureCookiesDomain:at}=S.cookie.attributes;class nt{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=We.parsing.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=We.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=We.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:v}=at(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var I;this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(I=C)&&I.startsWith("/")&&I.length>=5?I:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=it(e.netaceaBlockedResponseRedirectLocation),this.graphQL=We.graphql.getGraphQLParserConfig(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new nt(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 We.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new et(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,a,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),a=U(t.url,e.method,this.config.netaceaCaptchaVerificationPath),n=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&$(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!s&&!n)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!n?"captcha"===i.mitigation?{...i,response:J({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:W({config:this.config,request:e,responseHeaders:o()})}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=M(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Xe(this.config.mitigationType,a,U(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),n=function(e,t,i,a){const n=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,o=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=We.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:Q?.replace("@netacea/","")??"",IntegrationVersion:Y,NetaceaMitigationApplied:n??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${o} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{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.");await this.kinesis.ingest({...n,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(n)),t=await this.makeRequest(e);if(200!==t.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}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}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:",captcha_serve",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 C(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,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};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,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",Q.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Y),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const n=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:z(n,i),sessionStatus:i?.sessionStatus??""}}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,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};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 X&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:U(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?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 F(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=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}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([q.NEW_SESSION,q.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,n=d.mitigate,s=d.captcha,o=d.body,u=d.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,d.mitataMaxAge)],c=d.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","a","c","e"].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 H(e+"|"+String(i),a),n].join(O);return`${await H(s,a)}${O}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await V(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[A];const i=parseInt(e[N]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await V(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}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":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==q.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),i["X-Netacea-Request-Id"]=e.requestId;const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new X(e,i);const a=e.headers[w]??"0",n=e.headers[v]??"0",s=e.headers[I]??"0";let o=parseInt(e.headers[b]);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:G({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==q.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,n["X-Netacea-Request-Id"]=e.requestId;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),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.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=Xe(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[k.block,k.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($(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(U(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){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===q.NEW_SESSION,a=t===q.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function s(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 n,o,r,c=s(i),u=s(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(n||(n={})),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 d(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 p(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=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const s=d(e,"Domain"),n=d(t,"Domain");void 0!==s&&void 0!==n?a=t.replace(n,s):void 0!==s&&void 0===n?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==n&&(i=e+(""!==e?`; Domain=${n}`:`Domain=${n}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(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=d(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:d,removeDuplicateAttrs:p});function f(e){const t=p([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),s=a.indexOf(";");if(s<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}},C=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-mitatacaptcha-value",v="x-netacea-mitatacaptcha-expiry",I={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},b={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},A={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},N={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},T={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},E="_/@#/",_="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),x=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function P(e){if(void 0===e)return;const t=e.match(x);if(null!=t){const[,e,i,a,s,n,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:n,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function R(e=16,t=_){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function O(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 L(e,i){const a=await O(t.Buffer.from(e),i),s=t.Buffer.from(a).toString("hex");return t.Buffer.from(s).toString("base64")}var M;async function K(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 D(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 j(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"}function H(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function q(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function V(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 B(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}function F(e){if(void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");return U(e,e.config.netaceaBlockedResponseRedirectLocation)}return $(e)}function $(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function U(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}function z(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(M||(M={}));class G 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}}var W="@netacea/cloudflare",J="6.1.1",X="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Q={},Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.validateRedirectLocation=void 0,Y.validateRedirectLocation=function(e){if(""!==(e=e??""))try{return new URL(e).toString()}catch{if(/^https?:\/\//i.test(e))return;return e.startsWith("/")?e:`/${e}`}};var Z={},ee={};function te(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=ae("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function ie(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const s=e[a]??"",n="string"==typeof s?s:s.join("; ");i.push(...se(n,t))}return i}function ae(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function se(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ee,"__esModule",{value:!0}),ee.findAllInCookieString=ee.findFirstInCookieString=ee.findAllInHeaders=ee.findFirstInHeaders=ee.findOnlyValueInHeaders=ee.findAllValuesInHeaders=ee.findFirstValueInHeaders=void 0,ee.findFirstValueInHeaders=function(e,t){const i=te(e,t);if(void 0!==i)return i.slice(t.length+1)},ee.findAllValuesInHeaders=function(e,t){return ie(e,t).map((e=>e.slice(t.length+1)))},ee.findOnlyValueInHeaders=function(e,t){const i=ie(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ee.findFirstInHeaders=te,ee.findAllInHeaders=ie,ee.findFirstInCookieString=ae,ee.findAllInCookieString=se;var ne={};function oe(e){return"set-cookie"===e||"Set-Cookie"===e}function re(e,t){const i=t+"=";return e.startsWith(i)}function ce(e,t){if(!re(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function ue(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function he(e,t){for(const i of Object.keys(e)){if(!oe(i))continue;const a=de(ue(e,i),t);if(void 0!==a)return a}}function de(e,t){return e.map((e=>e.trimStart())).find((e=>re(e,t)))}function pe(e,t){const i=[];for(const a of Object.keys(e)){if(!oe(a))continue;const s=ue(e,a);i.push(...le(s,t))}return i}function le(e,t){return e.map((e=>e.trimStart())).filter((e=>re(e,t)))}Object.defineProperty(ne,"__esModule",{value:!0}),ne.findAllInSetCookieStrings=ne.findAllInHeaders=ne.findValueInSetCookieStrings=ne.findFirstInSetCookieStrings=ne.findFirstInHeaders=ne.findOnlyValueInHeaders=ne.findFirstValueInHeaders=ne.parseValueFromString=void 0,ne.parseValueFromString=ce,ne.findFirstValueInHeaders=function(e,t){const i=he(e,t);return void 0!==i?ce(i,t):void 0},ne.findOnlyValueInHeaders=function(e,t){const i=pe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?ce(i[0],t):void 0},ne.findFirstInHeaders=he,ne.findFirstInSetCookieStrings=de,ne.findValueInSetCookieStrings=function(e,t){const i=de(e,t);if(void 0!==i)return ce(i,t)},ne.findAllInHeaders=pe,ne.findAllInSetCookieStrings=le;var ge=X&&X.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=X&&X.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ye=X&&X.__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(Z,"__esModule",{value:!0}),Z.setCookie=Z.cookie=void 0,Z.cookie=ye(ee),Z.setCookie=ye(ne);var me={},Se={},Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.KINESIS_URL=Ce.API_VERSION=Ce.REGION=Ce.PAYLOAD_TYPE=Ce.STATE=void 0,Ce.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ce.PAYLOAD_TYPE="string",Ce.REGION="eu-west-1",Ce.API_VERSION="2013-12-02",Ce.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var ke={};Object.defineProperty(ke,"__esModule",{value:!0}),ke.headersToRecord=ke.increaseBatchSize=ke.handleFailedLogs=ke.batchArrayForKinesis=ke.sleep=void 0,ke.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ke.batchArrayForKinesis=function(e,t,i){const a=[];for(let s=0;s<e.length;s+=t){const n=e.slice(s,s+t);a.push({Data:i.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ke.handleFailedLogs=function(e,t,i){const a=2*i,s=[...e,...t],n=s.length-a;return n>0&&(console.error(`Netacea Error :: failed to send ${n} log(s) to Kinesis ingest.`),s.splice(0,n)),s},ke.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ke.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Se,"__esModule",{value:!0}),Se.WebStandardKinesis=void 0;const we=Ce,ve=ke;Se.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?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:(0,ve.headersToRecord)(i.headers),host:we.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,ve.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,ve.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}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((0,ve.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,ve.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const s={Records:(0,ve.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(we.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.Kinesis=void 0;const be=Ce,Ae=ke;Ie.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Ae.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ae.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}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((0,Ae.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ae.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:s}=e,n={Records:(0,Ae.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(n),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:be.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=Se;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Ie;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(me);var Ne={};function Te(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.parseHttpHeaderName=Ne.stringOrDefault=Ne.parseIntOrDefault=Ne.parseNumberOrDefault=void 0,Ne.parseNumberOrDefault=Te,Ne.parseIntOrDefault=function(e,t){const i=Te(e,t);return"number"==typeof i?Math.floor(i):i},Ne.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Ne.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var Ee={};Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.searchParamsFromRecord=void 0,Ee.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var _e={},xe={},Pe=X&&X.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Re=X&&X.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Oe=X&&X.__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)&&Pe(t,e,i);return Re(t,e),t};Object.defineProperty(xe,"__esModule",{value:!0}),xe.isJweEncrypted=xe.decrypt=xe.encrypt=void 0;const Le=Oe(i);xe.encrypt=async function(e,t,i="A128CBC-HS256"){const a=Le.base64url.decode(t),s=(new TextEncoder).encode(e);return await new Le.CompactEncrypt(s).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)},xe.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)},xe.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var Me=X&&X.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ke=X&&X.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),De=X&&X.__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)&&Me(t,e,i);return Ke(t,e),t};Object.defineProperty(_e,"__esModule",{value:!0}),_e.jwe=void 0,_e.jwe=De(xe);var je,He={};var qe={};Object.defineProperty(qe,"__esModule",{value:!0}),qe.ProtectorApiResponseView=qe.AbstractProtectorApiResponseView=void 0;const Ve=Ne;class Be{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Ve.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,Ve.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Ve.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,s=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:s})}(e,t,a)}}qe.AbstractProtectorApiResponseView=Be;var Fe;function $e(){return Fe||(Fe=1,function(e){var t=X&&X.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=X&&X.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=X&&X.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(a,e,s);return i(a,e),a},s=X&&X.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=void 0,e.configValidation=a(Y),e.headers=a(Z),e.ingest=a(me),e.parsing=a(Ne),e.url=a(Ee),e.webcrypto=a(_e),e.graphql=a(function(){if(je)return He;je=1,Object.defineProperty(He,"__esModule",{value:!0}),He.truncateLongFields=He.parseGraphQl=He.parseGraphQlRequestBody=He.getGraphQLParserConfig=void 0;const e=$e();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const n=t[e];t[e]=(s=i,(a=n).length<=s?a:a.slice(0,s)+"…")}var a,s;return t}return He.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},He.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const s=JSON.parse(a);if("object"!=typeof s)throw new Error("Netacea Error: Invalid GraphQL JSON");const n={...t(e,s?.query??"")},o=(s?.operationName??"").trim();return""!==o&&(n.OpName=o),i(e,n)},He.parseGraphQl=t,He.truncateLongFields=i,He}()),s(qe,e)}(Q)),Q}qe.ProtectorApiResponseView=class extends Be{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var Ue=$e();const ze="unknown";function Ge(e,t,i){let{match:a,mitigate:s,captcha:n}=t;i||("2"===n?n="4":"3"===n?n="5":"b"===n?n="d":"c"===n&&(n="e"));let o=I[a]??ze+"_";o+=b[s]??ze;let r=N[s];if("0"!==n){o+=","+(A[n]??ze);const e=T[n];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:s,captcha:n}}}function We(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function Je(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}async function Xe(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const s=[];for(;;){const{done:t,value:n}=await i.read();if(t)break;if(a+=n.length,a>e.maxParsableBytes)throw i.releaseLock(),new Qe("Request body too large",a);if(!(n instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");s.push(n)}const n=new Uint8Array(a);let o=0;for(const e of s)n.set(e,o),o+=e.length;return(new TextDecoder).decode(n)}(e,i);return{contentLength:a.length,graphQL:Ue.graphql.parseGraphQlRequestBody(e,a)}}class Qe extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class Ye{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.netaceaCookieName),s=await this.readCookie(e,this.config.netaceaCaptchaCookieName),n=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",r=Ue.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=await async function(e,t,i,a,s){const n=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 s=P(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(E),a=Math.floor(Date.now()/1e3),n=parseInt(s.expiry)<a,o=["1","3","5","a","c","e"].includes(s.protectorCheckCodes.captcha),r="3"===s.protectorCheckCodes.mitigate,c=o||r,u=await L(t+"|"+s.expiry,i),h=s.ipHash===u,d=s.signature===await L(e,i);return{userId:s.userId,requiresReissue:n||!h,isExpired:n,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,protectorCheckCodes:s.protectorCheckCodes}}return a}(a,s,e.secretKey);if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:s,shouldExpire:o,isSameIP:r}=n,c=s||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?M.RENEW_SESSION:M.EXISTING_SESSION,{sessionStatus:u}=Ge(e.mitigationType,n.protectorCheckCodes,q(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:n,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:R(),sessionCookieStatus:M.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,n),p={contentLength:r,clientIp:n,fingerprints:await Ze(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:o,sessionDetails:{captchaToken:s,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await Xe(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof Qe){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),s=`${t}=`;for(const e of a)if(e.startsWith(s)){const i=e.slice(s.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await D(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function Ze(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 Je(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,s=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 Je(t)}(s);return{headerFingerprint:a,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}const{validateRedirectLocation:et}=Ue.configValidation,{configureCookiesDomain:tt}=S.cookie.attributes;class it{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:s=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=n.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??n.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Ue.parsing.parseIntOrDefault(s,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:v}=tt(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var I;this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(I=C)&&I.startsWith("/")&&I.length>=5?I:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=et(e.netaceaBlockedResponseRedirectLocation),this.graphQL=Ue.graphql.getGraphQLParserConfig(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new it(i),this.config.ingestType===n.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ue.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new Ye(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let s=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof s&&(s={sessionStatus:"error_open",apiCallLatency:s}),await this.handleResponse(i,a,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),a=q(t.url,e.method,this.config.netaceaCaptchaVerificationPath),s=a&&i.sessionStatus.includes("checkpoint_post"),n=!a&&H(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!n&&!s)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!s?"captcha"===i.mitigation?{...i,response:z({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:F({config:this.config,request:e,responseHeaders:o()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:$({status:402,responseHeaders:o()})}:{...i,response:U({config:this.config,responseHeaders:o()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:s}=P(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:n}=Ge(this.config.mitigationType,a,q(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:s,sessionStatus:n,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),s=function(e,t,i,a){const s=i.sessionStatus??t.sessionDetails.sessionStatus,n=i.sessionCookie??t.sessionDetails.sessionCookie,o=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=Ue.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:W?.replace("@netacea/","")??"",IntegrationVersion:J,NetaceaMitigationApplied:s??"",NetaceaUserIdCookie:n??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${o} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===n.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...s,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(s)),t=await this.makeRequest(e);if(200!==t.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}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}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),{match:s,mitigate:n,captcha:o}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:s,mitigate:n,captcha:o}}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const n=`${e}${i}`,o=new Request(n,{...{method:t,body:s,headers:a},duplex:"half"}),r=await C(n,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};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,i)),this.config.ingestType===n.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",W.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",J),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const s=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:V(s,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?j(e.headers.get("Accept")??void 0):j();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};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,s;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof G&&(s=i.latencyMs,a=i.protectorApiResponse?.status);return{response:q(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:We({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:s,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 D(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=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([M.NEW_SESSION,M.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),{responseView:s}=a,n=s.getProtectorCodes(),{match:o,mitigate:r,captcha:c}=n,u=[await this.createMitata(e.clientIp,i,o,r,c,a.mitataMaxAge)],h={match:o,mitigate:r,captcha:c},d=Ge(this.config.mitigationType,h,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:u,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[k.block,k.captcha].includes(d.mitigation),redirect:"5"===r?s.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(p.injectHeaders=We(d.parts,a.eventId)),p}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=Ge(this.config.mitigationType,i,!1),s={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[k.block,k.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(s.injectHeaders=We(a.parts)),s}}async createMitata(e,t,i,a,s,n=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a||"5"===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,s].join("");let h=await async function(e,t,i,a,s="000"){const n=[i,t,await L(e+"|"+String(i),a),s].join(E);return`${await L(n,a)}${E}${n}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await K(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:s,captcha:n,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:s,captcha:n},h=Ge(this.config.mitigationType,u,!0),d={body:o,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[k.block,k.captcha].includes(h.mitigation),redirect:void 0,protectorCheckCodes:{match:h.parts.match.toString(),mitigate:h.parts.mitigate.toString(),captcha:h.parts.captcha.toString()}};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(d.injectHeaders=We(h.parts)),d}async getMitataCaptchaFromHeaders(e){let t=e[w];const i=parseInt(e[v]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await K(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}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":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==M.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),i["X-Netacea-Request-Id"]=e.requestId;const s=new URLSearchParams;s.append("headerFP",e.fingerprints.headerFingerprint),s.append("netaceaHeaders","request-id");const n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,n),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${s.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new G(c,u);const h=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=h.sessionCookieMaxAge,f=e.sessionDetails.userId,y=await this.getMitataCaptchaFromHeaders(c.headers),m=[await this.createMitata(e.clientIp,f,d,p,l,g),y].filter((e=>void 0!==e)),S=h.eventId,C="5"===p?h.getMonetisationRedirect(e.url.pathname,e.url.search):void 0;return{status:c.status,match:d,mitigate:p,captcha:l,setCookie:m,body:c.body,eventId:S,mitataMaxAge:g,latency:u,redirect:C}}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:B({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==M.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,s["X-Netacea-Request-Id"]=e.requestId;let n="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(n="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${n}?${o.toString()}`,headers:s,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new G(c,u);const h=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,d,p,l,h.sessionCookieMaxAge),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),f=h.eventId;if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await h.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:h,status:c.status,setCookie:g,body:c.body,eventId:f,mitataMaxAge:h.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(H(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(q(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){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===M.NEW_SESSION,a=t===M.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudflare",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.1.1",
|
|
4
4
|
"description": "Netacea Cloudflare CDN Integration",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
},
|
|
19
19
|
"license": "ISC",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@netacea/netaceaintegrationbase": "^2.
|
|
21
|
+
"@netacea/netaceaintegrationbase": "^2.1.1",
|
|
22
22
|
"aws4fetch": "^1.0.20",
|
|
23
23
|
"jose": "^4.11.2",
|
|
24
24
|
"uuid": "^10.0.0"
|
|
25
25
|
},
|
|
26
|
-
"gitHead": "
|
|
26
|
+
"gitHead": "8e699f0ca7bfff2b26c361eb258b4993b83efe6d"
|
|
27
27
|
}
|