@netacea/vercel 0.9.14 → 0.9.15
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 +13 -0
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -250,9 +250,18 @@ declare class WebStandardKinesis {
|
|
|
250
250
|
private signRequest;
|
|
251
251
|
}
|
|
252
252
|
|
|
253
|
+
interface HttpMsgSignature {
|
|
254
|
+
computedInput?: string;
|
|
255
|
+
signature?: string;
|
|
256
|
+
signatureSha256?: string;
|
|
257
|
+
signatureInput?: string;
|
|
258
|
+
signatureAgent?: string;
|
|
259
|
+
}
|
|
260
|
+
|
|
253
261
|
interface NetaceaVercelResult {
|
|
254
262
|
response: Response;
|
|
255
263
|
sessionStatus: string;
|
|
264
|
+
signatureStatus?: string;
|
|
256
265
|
protectorLatencyMs?: number;
|
|
257
266
|
protectorStatus?: number;
|
|
258
267
|
}
|
|
@@ -300,6 +309,7 @@ interface NetaceaRequestDetails {
|
|
|
300
309
|
headerFingerprint: string;
|
|
301
310
|
cookieFingerprint: string;
|
|
302
311
|
};
|
|
312
|
+
httpMessageSignatures: HttpMsgSignature;
|
|
303
313
|
}
|
|
304
314
|
|
|
305
315
|
interface KinesisIngestConfigArgs {
|
|
@@ -356,6 +366,7 @@ interface ComposeResultResponse {
|
|
|
356
366
|
body?: string | ReadableStream<Uint8Array>;
|
|
357
367
|
apiCallStatus?: number;
|
|
358
368
|
apiCallLatency?: number;
|
|
369
|
+
signatureStatus?: string;
|
|
359
370
|
setCookie: string[];
|
|
360
371
|
sessionStatus: string;
|
|
361
372
|
mitigation: string;
|
|
@@ -381,6 +392,7 @@ declare class NetaceaVercelIntegration {
|
|
|
381
392
|
protected readonly kinesis?: WebStandardKinesis;
|
|
382
393
|
private readonly requestAnalyser;
|
|
383
394
|
private readonly cookieFactory;
|
|
395
|
+
private readonly protectorApiClient;
|
|
384
396
|
private workerInstanceId;
|
|
385
397
|
constructor(args: Partial<NetaceaVercelIntegrationArgs>);
|
|
386
398
|
/**
|
|
@@ -423,6 +435,7 @@ declare class NetaceaVercelIntegration {
|
|
|
423
435
|
protected check(requestDetails: NetaceaRequestDetails, captchaPageContentType: string): Promise<ComposeResultResponse>;
|
|
424
436
|
protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined, issueReason?: NetaceaCookieV3IssueReason$1): Promise<string>;
|
|
425
437
|
private processCaptcha;
|
|
438
|
+
private getMitataCaptchaFromResponseView;
|
|
426
439
|
private getMitataCaptchaFromHeaders;
|
|
427
440
|
private parseCaptchaAPICallBody;
|
|
428
441
|
private makeCaptchaAPICall;
|
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 o(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,n,r,c=o(i),u=o(a);exports.NetaceaIngestType=void 0,(s=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",s.HTTP="HTTP",s.KINESIS="KINESIS",s.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(n=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",n.INJECT="INJECT",n.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 d=3e3;function h(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 o=h(e,"Domain"),s=h(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=h(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=h(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=h(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:h,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var C=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),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const y={cookie:{parse:m,attributes:g,netaceaSession:C}},S=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",monetise:"monetise",flag:"flag"},v="x-netacea-mitatacaptcha-value",k="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"customer_session_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},N={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"},_={0:I.none,1:I.block,2:I.none,3:I.block,4:I.flag,5:I.monetise},w={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha,6:I.allow,7:I.captcha,a:I.captcha,b:I.captchaPass,c:I.captcha,d:I.allow,e:I.captcha},O="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),b=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function T(e=16,t=O){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function P(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))}var R,M,K,x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},H={},V={};Object.defineProperty(V,"__esModule",{value:!0}),V.MitigateCode=V.MatchCode=V.CaptchaCode=void 0,function(e){e.NONE="0",e.SERVE="1",e.PASS="2",e.FAIL="3",e.COOKIE_PASS="4",e.COOKIE_FAIL="5",e.CHECKPOINT_SIGNAL="6",e.CHECKPOINT_POST="7",e.CHECKPOINT_SERVE="a",e.CHECKPOINT_PASS="b",e.CHECKPOINT_FAIL="c",e.CHECKPOINT_COOKIE_PASS="d",e.CHECKPOINT_COOKIE_FAIL="e"}(R||(V.CaptchaCode=R={})),function(e){e.NONE="0",e.USER_AGENT="1",e.IP="2",e.VISITOR="3",e.DATACENTER="4",e.CUSTOMER_SESSION="5",e.ORGANISATION="6",e.ASN="7",e.COUNTRY="8",e.COMBINATION="9",e.HEADER_FINGERPRINT="b",e.VENDOR_FAMILY="c",e.VENDOR_NAME="d",e.VENDOR="e",e.VENDOR_CRAWLER_CLASSIFICATION="f"}(M||(V.MatchCode=M={})),function(e){e.NONE="0",e.BLOCK="1",e.ALLOW="2",e.HARDBLOCK="3",e.FLAG="4",e.MONETISE="5"}(K||(V.MitigateCode=K={}));var L,j={};Object.defineProperty(j,"__esModule",{value:!0}),j.NetaceaCookieV3IssueReason=void 0,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",e.UNKNOWN="unknown"}(L||(j.NetaceaCookieV3IssueReason=L={}));var D={},F={},q={};Object.defineProperty(q,"__esModule",{value:!0}),q.netaceaCookieV3OptionalKeyMap=q.netaceaCookieV3KeyMap=q.COOKIEDELIMITER=void 0,q.COOKIEDELIMITER="_/@#/",q.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},q.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(F,"__esModule",{value:!0}),F.defaultInvalidResponse=F.matchNetaceaCookieV3=F.checkNetaceaCookieV3=F.objectIsNetaceaCookieV3=F.cookieIsNetaceaV3Format=F.createNetaceaCookieV3=void 0;const $=j,U=q;function B(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(U.netaceaCookieV3KeyMap).find((e=>U.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(U.netaceaCookieV3OptionalKeyMap).find((e=>U.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function G(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:$.NetaceaCookieV3IssueReason.NO_SESSION}}F.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in U.netaceaCookieV3OptionalKeyMap?`${U.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${U.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},F.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(U.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(U.netaceaCookieV3KeyMap).includes(e)))},F.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(U.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},F.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return G();let i;try{i=B(e)}catch{return G()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return G()},F.matchNetaceaCookieV3=B,F.defaultInvalidResponse=G;var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.AbstractCookieFactory=void 0;const W=j,X=F,J=q,Y="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),Q=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;z.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,X.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??this.generateUserId(),match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??W.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,X.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,X.cookieIsNetaceaV3Format)(i)?(0,X.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(J.COOKIEDELIMITER);return`${await this.hash(s,a)}${J.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(Q);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,X.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(J.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:W.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>Y[e%Y.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=F;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=z;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=q;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=j;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(D);var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),Z.validateRedirectLocation=void 0,Z.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 ee={},te={};function ie(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=oe("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function ae(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...se(s,t))}return i}function oe(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(te,"__esModule",{value:!0}),te.findAllInCookieString=te.findFirstInCookieString=te.findAllInHeaders=te.findFirstInHeaders=te.findOnlyValueInHeaders=te.findAllValuesInHeaders=te.findFirstValueInHeaders=void 0,te.findFirstValueInHeaders=function(e,t){const i=ie(e,t);if(void 0!==i)return i.slice(t.length+1)},te.findAllValuesInHeaders=function(e,t){return ae(e,t).map((e=>e.slice(t.length+1)))},te.findOnlyValueInHeaders=function(e,t){const i=ae(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},te.findFirstInHeaders=ie,te.findAllInHeaders=ae,te.findFirstInCookieString=oe,te.findAllInCookieString=se;var ne={};function re(e){return"set-cookie"===e||"Set-Cookie"===e}function ce(e,t){const i=t+"=";return e.startsWith(i)}function ue(e,t){if(!ce(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function de(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function he(e,t){for(const i of Object.keys(e)){if(!re(i))continue;const a=pe(de(e,i),t);if(void 0!==a)return a}}function pe(e,t){return e.map((e=>e.trimStart())).find((e=>ce(e,t)))}function le(e,t){const i=[];for(const a of Object.keys(e)){if(!re(a))continue;const o=de(e,a);i.push(...ge(o,t))}return i}function ge(e,t){return e.map((e=>e.trimStart())).filter((e=>ce(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=ue,ne.findFirstValueInHeaders=function(e,t){const i=he(e,t);return void 0!==i?ue(i,t):void 0},ne.findOnlyValueInHeaders=function(e,t){const i=le(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?ue(i[0],t):void 0},ne.findFirstInHeaders=he,ne.findFirstInSetCookieStrings=pe,ne.findValueInSetCookieStrings=function(e,t){const i=pe(e,t);if(void 0!==i)return ue(i,t)},ne.findAllInHeaders=le,ne.findAllInSetCookieStrings=ge;var fe=x&&x.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ce=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),me=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)&&fe(t,e,i);return Ce(t,e),t};Object.defineProperty(ee,"__esModule",{value:!0}),ee.setCookie=ee.cookie=void 0,ee.cookie=me(te),ee.setCookie=me(ne);var ye={},Se={},Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.KINESIS_URL=Ie.API_VERSION=Ie.REGION=Ie.PAYLOAD_TYPE=Ie.STATE=void 0,Ie.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ie.PAYLOAD_TYPE="string",Ie.REGION="eu-west-1",Ie.API_VERSION="2013-12-02",Ie.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.headersToRecord=ve.increaseBatchSize=ve.handleFailedLogs=ve.batchArrayForKinesis=ve.sleep=void 0,ve.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ve.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ve.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},ve.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ve.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 ke=Ie,Ee=ve;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,Ee.headersToRecord)(i.headers),host:ke.KINESIS_URL,method:"POST",path:"/",body:i.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}}async signRequest(e,t,i,a){const o={Records:(0,Ee.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ke.KINESIS_URL,{body:JSON.stringify(o),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 Ae=Ie,_e=ve;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,_e.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,_e.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,_e.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,_e.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:o}=e,s={Records:(0,_e.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:Ae.REGION},{accessKeyId:a,secretAccessKey:o})}},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=Ne;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ye);var we={};function Oe(e,t){let i=null;if("number"==typeof e&&Number.isFinite(e))i=e;else if("string"==typeof e&&""!==e.trim()){const t=Number(e);Number.isFinite(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(we,"__esModule",{value:!0}),we.parseUrl=we.parseHttpHeaderName=we.stringOrDefault=we.parseIntOrDefault=we.parseNumberOrDefault=void 0,we.parseNumberOrDefault=Oe,we.parseIntOrDefault=function(e,t){const i=Oe(e,t);return"number"==typeof i?Math.floor(i):i},we.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},we.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0},we.parseUrl=function(e){const t=/^[a-z][a-z\d+.-]*:\/\/([^/?#]+)([^?#]*)?(?:[?#].*)?$/i.exec(e);if(null===t)return;const[,i,a]=t;return{host:i.slice(i.lastIndexOf("@")+1),path:void 0===a||""===a?"/":a}};var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.searchParamsFromRecord=void 0,be.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Te={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.JweFactory=void 0;Pe.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Re=x&&x.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Me=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ke=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)&&Re(t,e,i);return Me(t,e),t};Object.defineProperty(Te,"__esModule",{value:!0}),Te.jwe=void 0,Te.jwe=Ke(Pe);var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.truncateLongFields=xe.parseGraphQl=xe.parseGraphQlRequestBody=xe.getGraphQLParserConfig=void 0;const He=we;function Ve(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function Le(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}xe.getGraphQLParserConfig=function(e){const t={includePaths:[],maxParsableBytes:(0,He.parseIntOrDefault)(e?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:(0,He.parseIntOrDefault)(e?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/,useStrictAcceptHeaderCheck:e?.useStrictAcceptHeaderCheck??!0};if(Array.isArray(e?.includePaths))for(const i of e.includePaths)"string"==typeof i&&t.includePaths.push(i);try{if(e?.parserRegex instanceof RegExp)t.parserRegex=e?.parserRegex;else if("object"==typeof e?.parserRegex){const{regex:i,flags:a}=e?.parserRegex;"string"==typeof i&&(t.parserRegex=new RegExp(i,a))}}catch{}return t},xe.parseGraphQlRequestBody=function(e,t){if(""===t)throw new Error("Netacea Error: Empty GraphQL body received");const i=JSON.parse(t);if("object"!=typeof i)throw new Error("Netacea Error: Invalid GraphQL JSON");const a={...Ve(e,i?.query??"")},o=(i?.operationName??"").trim();return""!==o&&(a.OpName=o),Le(e,a)},xe.parseGraphQl=Ve,xe.truncateLongFields=Le;var je={},De={};Object.defineProperty(De,"__esModule",{value:!0}),De.findBestMitigation=De.isCaptchaMitigation=void 0;const Fe=V;function qe(e){return`[${e}]`}const $e={[Fe.MatchCode.NONE]:"",[Fe.MatchCode.USER_AGENT]:"ua_",[Fe.MatchCode.IP]:"ip_",[Fe.MatchCode.VISITOR]:"visitor_",[Fe.MatchCode.DATACENTER]:"datacenter_",[Fe.MatchCode.CUSTOMER_SESSION]:"customer_session_",[Fe.MatchCode.ORGANISATION]:"organisation_",[Fe.MatchCode.ASN]:"asn_",[Fe.MatchCode.COUNTRY]:"country_",[Fe.MatchCode.COMBINATION]:"combination_",[Fe.MatchCode.HEADER_FINGERPRINT]:"headerFP_",[Fe.MatchCode.VENDOR_FAMILY]:"vendorFamily_",[Fe.MatchCode.VENDOR_NAME]:"vendorName_",[Fe.MatchCode.VENDOR]:"vendor_",[Fe.MatchCode.VENDOR_CRAWLER_CLASSIFICATION]:"vendorCrawlerClassification_"},Ue={[Fe.MitigateCode.NONE]:"",[Fe.MitigateCode.BLOCK]:"blocked",[Fe.MitigateCode.ALLOW]:"allow",[Fe.MitigateCode.HARDBLOCK]:"hardblocked",[Fe.MitigateCode.FLAG]:"flagged",[Fe.MitigateCode.MONETISE]:"monetised"},Be={[Fe.CaptchaCode.NONE]:"",[Fe.CaptchaCode.SERVE]:"captcha_serve",[Fe.CaptchaCode.PASS]:"captcha_pass",[Fe.CaptchaCode.FAIL]:"captcha_fail",[Fe.CaptchaCode.COOKIE_PASS]:"captcha_cookiepass",[Fe.CaptchaCode.COOKIE_FAIL]:"captcha_cookiefail",[Fe.CaptchaCode.CHECKPOINT_SIGNAL]:"checkpoint_signal",[Fe.CaptchaCode.CHECKPOINT_POST]:"checkpoint_post",[Fe.CaptchaCode.CHECKPOINT_SERVE]:"checkpoint_serve",[Fe.CaptchaCode.CHECKPOINT_PASS]:"checkpoint_pass",[Fe.CaptchaCode.CHECKPOINT_FAIL]:"checkpoint_fail",[Fe.CaptchaCode.CHECKPOINT_COOKIE_PASS]:"checkpoint_cookiepass",[Fe.CaptchaCode.CHECKPOINT_COOKIE_FAIL]:"checkpoint_cookiefail"};De.isCaptchaMitigation=function(e){return[Fe.CaptchaCode.SERVE,Fe.CaptchaCode.FAIL,Fe.CaptchaCode.COOKIE_FAIL,Fe.CaptchaCode.CHECKPOINT_POST,Fe.CaptchaCode.CHECKPOINT_SERVE,Fe.CaptchaCode.CHECKPOINT_FAIL,Fe.CaptchaCode.CHECKPOINT_COOKIE_FAIL].includes(e.captcha)},De.findBestMitigation=function(e,t,i,a,o=!1){i=function(e,t){return t?e:{[Fe.CaptchaCode.PASS]:Fe.CaptchaCode.COOKIE_PASS,[Fe.CaptchaCode.FAIL]:Fe.CaptchaCode.COOKIE_FAIL,[Fe.CaptchaCode.CHECKPOINT_PASS]:Fe.CaptchaCode.CHECKPOINT_COOKIE_PASS,[Fe.CaptchaCode.CHECKPOINT_FAIL]:Fe.CaptchaCode.CHECKPOINT_COOKIE_FAIL}[e]??e}(i,a),o&&(i=Fe.CaptchaCode.CHECKPOINT_SIGNAL);let s=$e[e]??qe(e)+"_";return s+=Ue[t]??qe(t),i!==Fe.CaptchaCode.NONE&&(s+=","+(Be[i]??qe(i))),{sessionStatus:s,codes:{match:e,mitigate:t,captcha:i}}},function(e){var t=x&&x.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=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}),i(De,e)}(je);var Ge={},ze={};Object.defineProperty(ze,"__esModule",{value:!0}),ze.ResponseView=ze.AbstractResponseView=void 0;class We{constructor(e){this.cacheStatus=e}get contentType(){return this.readHeader("content-type")?.[0]}get contentLength(){return this.readHeader("content-length")?.[0]}get location(){return this.readHeader("location")?.[0]}get setCookie(){return this.readHeader("set-cookie")}}ze.AbstractResponseView=We;ze.ResponseView=class extends We{constructor(e,t){super(t),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]:[]}readHeaders(){const e={};return this.response.headers.forEach(((t,i)=>{e[i]=[t]})),e["set-cookie"]=this.response.headers.getSetCookie(),e}},Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.HttpClient=Ge.AbstractHttpClient=void 0;const Xe=ze;class Je{constructor(e={}){this.cache=e.cache}async request(e,t){const i=this.cache?.get(e,t);if(void 0!==i)return this.createCachedResponseView(i);const a=await this.fetch(e,t);return await this.populateCache(e,t,a),a}async populateCache(e,t,i){void 0!==this.cache&&await this.cache.set(e,t,i).catch((()=>{}))}async get(e,t){return await this.request(e,{...t,method:"GET"})}async post(e,t,i){return await this.request(e,{...i,method:"POST",body:t})}}Ge.AbstractHttpClient=Je;Ge.HttpClient=class extends Je{constructor(e){super(e),this.fetchFn=e.fetch}async fetch(e,t){const i=await async function(e,t){if(void 0===t)return await e;let i;const a=new Promise(((e,a)=>{i=setTimeout((()=>{a(new Error(`HTTP request timed out after ${t}ms`))}),t)}));try{return await Promise.race([e,a])}finally{void 0!==i&&clearTimeout(i)}}(this.fetchFn(e,t),t?.timeoutMs);return new Xe.ResponseView(i,"MISS")}createCachedResponseView(e){const t=new Response(e.body,e);return new Xe.ResponseView(t,"HIT")}};var Ye={},Qe={};Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.LruCache=void 0;Qe.LruCache=class{constructor(e){if(this.capacity=e,this.entries=new Map,!Number.isInteger(e)||e<=0)throw new RangeError("LruCache capacity must be a positive integer")}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){if(this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.capacity){const e=Array.from(this.entries.keys());e.length>0&&this.entries.delete(e[0])}}find(e){for(const[t,i]of this.entries)if(e(i,t))return this.get(t)}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}},Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.HttpCache=void 0;const Ze=Qe,et=we,tt=1048576;function it(e){const t={};if(void 0===e)return t;for(const[i,a]of Object.entries(e))t[i.toLowerCase()]=a;return t}function at(e){if(void 0===e||""===e.trim())return{};const t={};for(const i of e.split(",")){const e=i.trim();if(""===e)continue;const a=e.indexOf("=");if(-1===a){t[e.toLowerCase()]=!0;continue}t[e.slice(0,a).trim().toLowerCase()]=e.slice(a+1).trim().replace(/^"(.+)"$/,"$1")}return t}function ot(e){const t=(0,et.parseNumberOrDefault)(e,{defaultValue:void 0});return"number"==typeof t&&t>=0?t:void 0}function st(e){if(void 0===e)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function nt(e,t){return{method:(i=t?.method,(i??"GET").toUpperCase()),url:e,headers:it(t?.headers)};var i}function rt(e){if("GET"!==e.method)return`method=${e.method}`;if(void 0!==e.headers.authorization)return"authorization header present";if(void 0!==e.headers.range)return"range header present";if(void 0!==e.headers["if-match"])return"if-match header present";if(void 0!==e.headers["if-none-match"])return"if-none-match header present";if(void 0!==e.headers["if-modified-since"])return"if-modified-since header present";if(void 0!==e.headers["if-unmodified-since"])return"if-unmodified-since header present";if(void 0!==e.headers["if-range"])return"if-range header present";return void 0!==at(e.headers["cache-control"])["no-store"]?"request cache-control=no-store":void 0}function ct(e,t){return!t.vary.includes("*")&&t.vary.every((i=>(e.headers[i]??"")===(t.varyRequestHeaders[i]??"")))}function ut(e){const t=ot(e.cacheControl["s-maxage"]);if(void 0!==t)return t;const i=ot(e.cacheControl["max-age"]);if(void 0!==i)return i;const a=st(e.headers.expires);return void 0===a?0:Math.max(0,Math.floor((a-(e.dateHeaderMs??e.storedAt))/1e3))}function dt(e){return JSON.stringify([e.url,e.vary.map((t=>[t,e.varyRequestHeaders[t]??""]))])}Ye.HttpCache=class{constructor(e={}){this.entries=new Ze.LruCache(10),this.defaultCacheControl=e.defaultCacheControl,this.now=e.now??(()=>Date.now())}get(e,t){const i=nt(e,t);if("GET"!==i.method)return{body:"Not Found",headers:{},status:404,storedAt:this.now(),url:i.url,vary:[],varyRequestHeaders:{},cacheControl:{},ageSeconds:0};if(void 0!==rt(i))return;const a=at(i.headers["cache-control"]);if(void 0!==a["no-cache"])return;const o=this.entries.find((e=>e.url===i.url&&ct(i,e)));if(void 0===o)return;if(void 0!==o.cacheControl["no-cache"])return;const s=ot(a["max-age"]),n=void 0===s?ut(o):Math.min(ut(o),s),r=function(e,t){return Math.max(0,Math.floor((t-e.storedAt)/1e3))+e.ageSeconds}(o,this.now());return r>=n?void 0:{...o,headers:{...o.headers,age:String(r)}}}async set(e,t,i){const a=nt(e,t);if(void 0!==rt(a))return;const o=this.entries.find((e=>e.url===a.url&&ct(a,e))),s=function(e){const t={};for(const[i,a]of Object.entries(e.readHeaders()))a.length>0&&(t[i.toLowerCase()]=a.join(", "));return t}(i),n=at(s["cache-control"]??this.defaultCacheControl);if(200!==i.status||void 0!==n["no-store"]||void 0!==n.private||i.setCookie.length>0)return void this.removeEntry(o);const r=function(e){return void 0===e.vary?[]:e.vary.split(",").map((e=>e.trim().toLowerCase())).filter((e=>""!==e))}(s);if(r.includes("*"))return void this.removeEntry(o);const c=Number(s["content-length"]);if(Number.isFinite(c)&&c>tt)return void this.removeEntry(o);const u=await i.getBody();if((new TextEncoder).encode(u).byteLength>tt)return void this.removeEntry(o);const d=this.now(),h=Number(s.age??"0"),p=st(s.date),l=void 0===p?0:Math.max(0,Math.floor((d-p)/1e3)),g={body:u,headers:s,status:i.status,storedAt:d,url:a.url,vary:r,varyRequestHeaders:Object.fromEntries(r.map((e=>[e,a.headers[e]??""]))),cacheControl:n,dateHeaderMs:p,ageSeconds:Math.max(Number.isFinite(h)&&h>=0?h:0,l)};void 0!==o&&this.entries.delete(dt(o)),this.entries.set(dt(g),g)}removeEntry(e){void 0!==e&&this.entries.delete(dt(e))}};var ht={},pt={};Object.defineProperty(pt,"__esModule",{value:!0}),pt.createComputedSignatureInputs=pt.createComputedSignatureInput=void 0;const lt=/^[a-z*][a-z0-9_.*-]{0,63}$/,gt=/^"(?:[^"\\]|\\.)*"$/,ft=/^[^;"\s]+$/,Ct=/^"[^"\\]+"(?:;[a-z*][a-z0-9_.*-]*(?:=(?:"(?:[^"\\]|\\.)*"|[^; ]+))?)*$/;function mt(e,t){const i=It(t);if(void 0===i)return;const a=[...i.componentIdentifiers.map((t=>{const i=function(e,t){const i=/^"([^"\\]+)"/.exec(t)?.[1];if(void 0===i)return;const a=yt(t,"name");let o;switch(i){case"@authority":o=e.url.host;break;case"@method":o=e.method;break;case"@path":o=e.url.path;break;case"@query":o=e.url.query;break;case"@query-param":o="string"==typeof a?function(e,t){const i=new URLSearchParams(e.slice(1)).getAll(t);return i.map(St).join(", ")}(e.url.query,a):void 0;break;case"@request-target":o=`${e.method.toLowerCase()} ${e.url.path}${e.url.query}`;break;case"@scheme":o=e.url.scheme;break;case"@target-uri":o=e.url.toString();break;default:o=function(e,t,i){const a=e.readHeader(t),o=0===a.length?void 0:a.map((e=>e.trim())).join(", ");return void 0!==o&&i?function(e){let t="",i=!1,a=!1,o=!1,s=!1;for(const n of e.trim())a?(t+=n,a=!1):i&&"\\"===n?(t+=n,a=!0):'"'===n?(t+=n,i=!i):i?t+=n:/\s/.test(n)?s||(o=!0):"="===n||";"===n?(t=t.trimEnd()+n,o=!1,s=!0):","===n?(t=t.trimEnd()+", ",o=!1,s=!1):(o&&""!==t&&!t.endsWith(" ")&&(t+=" "),t+=n,o=!1,s=!1);return t.trimEnd()}(o):o}(e,i,!0===yt(t,"sf"))}return o}(e,t);return void 0===i?void 0:`${t}: ${i}`})),`"@signature-params": ${i.parameters}`];return a.some((e=>void 0===e))?void 0:a.join("\n")}function yt(e,t){const i=e.indexOf('"',1),a=e.slice(i+1);if(a.startsWith(";"))for(const e of kt(a.slice(1),";")){const i=e.indexOf("=");if((-1===i?e:e.slice(0,i))!==t)continue;if(-1===i)return!0;const a=e.slice(i+1);return gt.test(a)?a.slice(1,-1).replace(/\\(.)/g,"$1"):a}}function St(e){return encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}function It(e){const t=e.indexOf("=");if(-1===t)return;const i=e.slice(0,t);if(!lt.test(i))return;const a=e.slice(t+1),o=vt(a,")",1);if(!a.startsWith("(")||-1===o)return;if(!function(e){if(""===e)return!0;return e.startsWith(";")&&kt(e.slice(1),";").every((e=>{const t=e.indexOf("=");if(-1===t)return!1;const i=e.slice(0,t),a=e.slice(t+1);return lt.test(i)&&function(e){return gt.test(e)||ft.test(e)}(a)}))}(a.slice(o+1)))return;const s=a.slice(1,o),n=""===s?[]:kt(s," ");return n.every((e=>Ct.test(e)))?{label:i,componentIdentifiers:n,parameters:a}:void 0}function vt(e,t,i=0){let a=!1,o=!1;for(let s=i;s<e.length;s++){const i=e[s];if(o)o=!1;else if(a&&"\\"===i)o=!0;else if('"'===i)a=!a;else if(!a&&i===t)return s}return-1}function kt(e,t){const i=[];let a=0,o=vt(e,t);for(;-1!==o;)i.push(e.slice(a,o)),a=o+1,o=vt(e,t,a);return i.push(e.slice(a)),i}pt.createComputedSignatureInput=mt,pt.createComputedSignatureInputs=function(e,t){const i=kt(t,","),a={};for(const t of i){const i=t.trim(),o=It(i),s=mt(e,i);if(void 0===o||void 0===s)return;a[o.label]=s}return a},Object.defineProperty(ht,"__esModule",{value:!0}),ht.AbstractRequestView=void 0;const Et=we,Nt=pt;ht.AbstractRequestView=class{constructor(e){this._httpMsgSignature=void 0,this._buffer=e}get contentLength(){return(0,Et.parseIntOrDefault)(this.readHeader("content-length")?.[0],{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get userAgent(){return this.readHeader("user-agent")?.[0]??""}get contentType(){return this.readHeader("content-type")?.[0]}get xForwardedFor(){return this.readHeader("x-forwarded-for")?.[0]}get referer(){return this.readHeader("referer")?.[0]}get accept(){return this.readHeader("accept")?.[0]}get host(){return this.readHeader("host")?.[0]}async getHttpMsgSignature(){const e=this.readJoinedHeader("Signature-Input"),t=this.readJoinedHeader("Signature"),i=void 0===e?void 0:this.createBase64SignatureInput(e);return void 0===this._httpMsgSignature&&(this._httpMsgSignature={signature:t,signatureSha256:void 0===t?void 0:(await this.sha256Hash(t)).toLowerCase().slice(0,12),signatureInput:e,signatureAgent:this.readJoinedHeader("Signature-Agent"),computedInput:i}),this._httpMsgSignature}readJoinedHeader(e){const t=this.readHeader(e).join(",");return""!==t?t:void 0}toBase64(e){if(void 0===e)return;return this._buffer.from(e).toString("base64")}createBase64SignatureInput(e){const t=(0,Nt.createComputedSignatureInputs)(this,e);if(void 0!==t)return Object.entries(t).map((([e,t])=>`${e}=:${this.toBase64(t)}:`)).join(", ")}};var At={};Object.defineProperty(At,"__esModule",{value:!0}),At.RequestUrl=void 0;class _t{constructor(e,t,i,a){this.scheme=e,this.host=t,this.path=i,this.query=a}static fromString(e){const t=/^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(?:#.*)?$/i.exec(e);if(null===t)throw new TypeError(`Invalid request URL: ${e}`);return new _t(t[1]??"",t[2],t[3]??"/",t[4]??"")}toString(){return`${""===this.scheme?"":`${this.scheme}://`}${this.host}${this.path}${this.query}`}}At.RequestUrl=_t;var wt={};Object.defineProperty(wt,"__esModule",{value:!0}),wt.ProtectorApiResponseView=void 0;const Ot=we;wt.ProtectorApiResponseView=class{constructor(e){this.responseView=e}get status(){return this.responseView.status}async getBody(){return await this.responseView.getBody()}readHeader(e){return this.responseView.readHeader(e)}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,Ot.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 signatureStatus(){return this.readHeader("x-netacea-signature-status")?.[0]}get netaceaSettings(){const e=this.readHeader("x-netacea-settings")?.[0];if(void 0===e)return{checkAllPostRequests:!1};try{const t=new URLSearchParams(e).get("checkAllPostRequests");return null===t?{checkAllPostRequests:!1}:{checkAllPostRequests:"1"===t}}catch{return{checkAllPostRequests:!1}}}get sessionCookieMaxAge(){return(0,Ot.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,Ot.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}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}};var bt={};Object.defineProperty(bt,"__esModule",{value:!0}),bt.acceptHeaderToNetaceaContentType=bt.APIError=bt.ProtectorApiClient=void 0;const Tt=wt;bt.ProtectorApiClient=class{constructor(e,t){this.httpClient=e.httpClient,this.timeoutMs=e.timeoutMs;const i=/^https:\/\/([^/?#]+)/i.exec(t.protectorApiUrl);if(null===i)throw new Error("Protector API URL must use HTTPS");this.protectorApiHost=i[1],this.apiKey=t.apiKey}async getDecisionResponse(e){return await this.getResponse("/",e)}async getChallengePage(e){return await this.getResponse("/captcha",e)}async getResponse(e,t){const i=[],a=new Mt,o={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t.clientIp};void 0===t.userId||t.isNewUser||(o["X-Netacea-UserId"]=t.userId);const{captchaSiteKey:s,captchaSecretKey:n}=t;if(void 0!==s&&void 0!==n&&(o["X-Netacea-Captcha-Site-Key"]=s,o["X-Netacea-Captcha-Secret-Key"]=n),void 0!==t.customerSessionId&&(o["X-Netacea-Customer-Session-ID"]=t.customerSessionId),void 0!==t.accept){o.Accept=t.accept;const e=Rt(t.accept);o["X-Netacea-Captcha-Content-Type"]=e}if(void 0!==t.headerFingerprint&&a.setQuery("headerFP",t.headerFingerprint),void 0===t.checkAllPostRequests&&a.setQuery("getSettings","checkAllPostRequests"),void 0!==t.challengeAssetsPath&&a.setQuery("challengeAssetsPath",t.challengeAssetsPath),void 0!==t.trackingId&&a.setQuery("trackingId",t.trackingId),void 0!==t.base64UserAgent?(o["X-Netacea-User-Agent"]=t.base64UserAgent,i.push("User-Agent")):void 0!==t.userAgent&&(o["User-Agent"]=t.userAgent),void 0!==t.requestId&&(o["X-Netacea-Request-Id"]=t.requestId,i.push("Request-Id")),void 0!==t.captchaCookie){let e=t.captchaCookie;e.startsWith("_mitatacaptcha=")||(e="_mitatacaptcha="+e),o.Cookie=e}void 0!==t.httpMsgSignature&&function(e,t,i){void 0!==i.signature&&(e.Signature=i.signature);void 0!==i.signatureInput&&(e["Signature-Input"]=i.signatureInput);void 0!==i.signatureAgent&&(e["Signature-Agent"]=i.signatureAgent);void 0!==i.computedInput&&(e["X-Netacea-Computed-Signature-Input"]=i.computedInput,t.push("Computed-Signature-Input"))}(o,i,t.httpMsgSignature),i.length>0&&a.setQuery("netaceaHeaders",i.join(","));const r=this.protectorApiHost,c=await this.httpClient.get(`https://${r}${e}`+a.buildQueryString(),{headers:o,timeoutMs:this.timeoutMs});if(200!==c.status)throw Pt.fromResponse(c);return new Tt.ProtectorApiResponseView(c)}};let Pt=class e extends Error{constructor(e,t){super(e),this.response=t}static fromResponse(t){let i="Unknown error";switch(t.status){case 403:i="Invalid credentials";break;case 500:i="Server error";break;case 502:i="Bad Gateway";break;case 503:i="Service Unavailable";break;case 400:i="Invalid request"}return new e(i,t)}};function Rt(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}bt.APIError=Pt,bt.acceptHeaderToNetaceaContentType=Rt;class Mt{constructor(){this.queries={}}setQuery(e,t){return this.queries[e]=encodeURIComponent(t),this}removeQuery(e){const{[e]:t,...i}=this.queries;return this.queries=i,this}buildQueryString(){const e=Object.entries(this.queries).map((([e,t])=>`${e}=${t}`)).join("&");return e.length>0?`?${e}`:""}}!function(e){var t=x&&x.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}: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 o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=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.mitigation=e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=e.MitigateCode=e.MatchCode=e.CaptchaCode=void 0;var s=V;Object.defineProperty(e,"CaptchaCode",{enumerable:!0,get:function(){return s.CaptchaCode}}),Object.defineProperty(e,"MatchCode",{enumerable:!0,get:function(){return s.MatchCode}}),Object.defineProperty(e,"MitigateCode",{enumerable:!0,get:function(){return s.MitigateCode}});var n=j;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return n.NetaceaCookieV3IssueReason}}),e.cookie=a(D),e.configValidation=a(Z),e.headers=a(ee),e.ingest=a(ye),e.parsing=a(we),e.url=a(be),e.webcrypto=a(Te),e.graphql=a(xe),e.mitigation=a(je),o(Ge,e),o(Ye,e),o(Qe,e),o(ht,e),o(At,e),o(ze,e),o(wt,e),o(bt,e)}(H);const Kt=new H.webcrypto.jwe.JweFactory(c);class xt extends H.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.encrypt called without a configured encryption key");return await Kt.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.decrypt called without a configured encryption key");return await Kt.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await P(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var Ht;function Vt(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 Lt(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:o}=e;return a.includes(i)&&o.includes("trackingId")&&"get"===t.toLowerCase()}function jt(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function Dt(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 Ft(e){let t="",i="";for(const a in e){const o=e[a];void 0!==o&&(t=`${t}${i}${a}=${o}`,i="; ")}return t}function qt(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function $t(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.has("content-type")||t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}function Ut(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ht||(Ht={}));var Bt="@netacea/vercel",Gt="0.9.14";class zt extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Wt(e){return`[${e}]`}function Xt(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=E[a]??Wt(a)+"_";n+=N[o]??Wt(o);let r=_[o];if("0"!==s){n+=","+(A[s]??Wt(s));const e=w[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function Jt(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 Yt(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class Qt{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),o=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("x-forwarded-for")??void 0;let n,r=s?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(n=e.headers.get(this.config.ipHeaderName)??void 0,r=n??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}=await async function(e,t,i,a,o){const s=await e.cookieFactory.retrieveCookieInfo(a,o),n={userId:void 0!==s.mitata?s.mitata.userId:void 0,requiresReissue:s.requiresReissue,isExpired:s.isExpired,shouldExpire:s.shouldExpire,isSameIP:s.isSameIP,isPrimaryHashValid:s.isPrimaryHashValid,protectorCheckCodes:{match:s.match,mitigate:s.mitigate,captcha:s.captcha},issueReason:s.issueReason};if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:o,shouldExpire:s,isSameIP:r}=n,c=o||s||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?Ht.RENEW_SESSION:Ht.EXISTING_SESSION,{sessionStatus:u}=Xt(e.mitigationType,n.protectorCheckCodes,jt(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:T(),sessionCookieStatus:Ht.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:d,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:u,userId:h},l=H.parsing.parseIntOrDefault(e.headers.get("x-vercel-id"),{defaultValue:void 0});return{clientIp:r,fingerprints:await Zt(e),ipHeader:void 0!==n?`${this.config.ipHeaderName}: ${n}`:void 0,method:i,protocol:void 0,requestId:e.headers.get("x-vercel-id")??"",sessionDetails:p,url:t,userAgent:e.headers.get("user-agent")??"",referer:e.headers.get("referer")??void 0,contentLength:l,contentType:e.headers.get("content-type")??void 0,xForwardedFor:s}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Kt.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function Zt(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 Yt(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),o=await async function(e){const t=e.join(",");return await Yt(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===o?o:`c_${o.substring(1,15)}`}}const{configureCookiesDomain:ei}=y.cookie.attributes;class ti{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?d:i,this.mitigationServiceTimeoutMs=H.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=H.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=H.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:o}=ei(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var s,n;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=o??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(s=this.mitigationType,void 0===(n=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?s===exports.NetaceaMitigationType.INGEST?3600:60:n),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class ii{config;kinesis;requestAnalyser;cookieFactory;workerInstanceId;constructor(i){this.config=new ti(i),this.cookieFactory=new xt({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===exports.NetaceaIngestType.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new H.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 Qt({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);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,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let o=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 o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,o,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=jt(t.url,e.method),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&Lt(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};if(i.mitigated&&!o){if("captcha"===i.mitigation){const e=n();return"application/json"===i.captchaPageContentType&&e.set("content-type","application/json"),{...i,response:$t({config:this.config,responseHeaders:e,body:i.body})}}return{...i,response:qt({responseHeaders:n()})}}return"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:qt({status:402,responseHeaders:n()})}:{...i,response:Ut({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=function(e){if(void 0===e)return;const t=e.match(b);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=Xt(this.config.mitigationType,a,jt(new URL(e.url),e.method));return{userId:o,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),a=await this.requestAnalyser.getNetaceaRequestDetails(e),o=function(e,t,i,a){const o=i.sessionStatus??t.sessionDetails.sessionStatus,s=t.method,n=t.url.pathname,r=t.protocol??null,c=Date.now(),u=t.referer??"",d=H.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),IntegrationType:Bt?.replace("@netacea/","")??"",IntegrationVersion:Gt,NetaceaMitigationApplied:o??"",UserId:t.sessionDetails.userId,NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===u?"-":u,Request:`${s} ${n} ${r}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(c).toUTCString(),TimeUnixMsUTC:c,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...o})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},t=await this.makeIngestApiCall(e,o);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)}}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:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n},captchaPageContentType:t}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await S(s,n),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){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(void 0!==t&&"injectHeaders"in t){e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)}if(this.config.ingestType===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",Bt.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Gt),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:Dt(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?Vt(e.headers.get("Accept")??void 0):Vt();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof zt&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:jt(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:Jt({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,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 Kt.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Ht.NEW_SESSION,Ht.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),o=a.responseView.getProtectorCodes(),{match:s,mitigate:n,captcha:r}=o,c=[await this.createMitata(e.clientIp,i,s,n,r,a.mitataMaxAge,void 0,ai(e))],u={match:s,mitigate:n,captcha:r},d=Xt(this.config.mitigationType,u,!1),h={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:c,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[I.block,I.captcha].includes(d.mitigation),redirect:"5"===n?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&d.mitigation!==I.flag||(h.injectHeaders=Jt(d.parts,a.eventId)),h}{const i=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,a={match:i?.match??"0",mitigate:i?.mitigate??"0",captcha:i?.captcha??"0"},o=Xt(this.config.mitigationType,a,!1),s={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:o.sessionStatus,mitigation:o.mitigation,mitigated:[I.block,I.captcha].includes(o.mitigation),redirect:void 0,protectorCheckCodes:o.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&o.mitigation!==I.flag||(s.injectHeaders=Jt(o.parts)),s}}async createMitata(e,t,i,a,o,s=86400,n=void 0,c=r.NO_SESSION){const u=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,d=void 0!==n?n-Math.floor(Date.now()/1e3):u,h=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:d,cookieId:"",issueReason:c});return y.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=Xt(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[I.block,I.captcha].includes(d.mitigation),protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromHeaders(e){let t=e[v];const i=parseInt(e[k]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Kt.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),y.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!==Ht.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 o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=Date.now(),n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,n),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-s;if(200!==c.status)throw new zt(c,u);const d=new H.ProtectorApiResponseView(new H.ResponseView(c.fetchResponse)),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,g,void 0,ai(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),C=d.eventId;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:f,body:c.body,eventId:C,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const o={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Ft({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Ht.NEW_SESSION&&(o["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),o["X-Netacea-Captcha-Content-Type"]=t,o["X-Netacea-Request-Id"]=e.requestId;let s="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&n.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${n.toString()}`,headers:o,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new zt(c,u);const d=new H.ProtectorApiResponseView(new H.ResponseView(c.fetchResponse)),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,d.sessionCookieMaxAge,void 0,ai(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e));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 d.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:d,status:c.status,setCookie:g,body:c.body,eventId:d.eventId,mitataMaxAge:d.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(Lt(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(jt(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e.sessionDetails.userId,"0","0","0",86400,void 0,ai(e))]}}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===Ht.NEW_SESSION,a=t===Ht.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}}function ai(e){if(void 0===e.sessionDetails.sessionCookieDetails)return r.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?r.EXPIRED_SESSION:r.NO_SESSION:r.IP_CHANGE}const oi=e=>H.parsing.parseIntOrDefault(e,{defaultValue:void 0});function si(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function ni(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=ni(e,t,a);if(void 0!==i)return i}}function ri(e,t){const i=ni(e,t,"CAPTCHA_HEADER_NAME"),a=ni(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function ci(e,t){const i=ni(e,t,"KINESIS_STREAM_NAME"),a=ni(e,t,"KINESIS_ACCESS_KEY"),o=ni(e,t,"KINESIS_SECRET_KEY"),s=si({logBatchSize:oi(ni(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:oi(ni(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==o)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:o,...s}}exports.NetaceaVercelIntegration=ii,exports.default=ii,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return si({apiKey:ni(e,t,"API_KEY"),captchaHeader:ri(e,t),captchaSecretKey:ni(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:ni(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:ni(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:ni(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:ni(e,t,"INGEST_SERVICE_URL"),ingestType:ni(e,t,"INGEST_TYPE"),ipHeaderName:ni(e,t,"IP_HEADER_NAME"),kinesis:ci(e,t),mitataCookieExpirySeconds:oi(ni(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:ni(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:ni(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:ni(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:ni(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:ni(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:ni(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:ni(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:ni(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:oi(ni(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:ni(e,t,"COOKIE_NAME"),secretKey:ni(e,t,"SECRET_KEY"),timeout:oi(ni(e,t,"TIMEOUT"))})};
|
|
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 o,n,r,c=s(i),u=s(a);exports.NetaceaIngestType=void 0,(o=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",o.HTTP="HTTP",o.KINESIS="KINESIS",o.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(n=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",n.INJECT="INJECT",n.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 d=3e3;function h(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=h(e,"Domain"),o=h(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=h(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=h(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=h(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:h,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var C=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 y=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 m={cookie:{parse:y,attributes:g,netaceaSession:C}},S=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",monetise:"monetise",flag:"flag"},v="x-netacea-mitatacaptcha-value",k="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"customer_session_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},N={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"},w={0:I.none,1:I.block,2:I.none,3:I.block,4:I.flag,5:I.monetise},_={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha,6:I.allow,7:I.captcha,a:I.captcha,b:I.captchaPass,c:I.captcha,d:I.allow,e:I.captcha},O="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),b=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function T(e=16,t=O){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function P(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))}var R,M,K,x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},H={},V={};Object.defineProperty(V,"__esModule",{value:!0}),V.MitigateCode=V.MatchCode=V.CaptchaCode=void 0,function(e){e.NONE="0",e.SERVE="1",e.PASS="2",e.FAIL="3",e.COOKIE_PASS="4",e.COOKIE_FAIL="5",e.CHECKPOINT_SIGNAL="6",e.CHECKPOINT_POST="7",e.CHECKPOINT_SERVE="a",e.CHECKPOINT_PASS="b",e.CHECKPOINT_FAIL="c",e.CHECKPOINT_COOKIE_PASS="d",e.CHECKPOINT_COOKIE_FAIL="e"}(R||(V.CaptchaCode=R={})),function(e){e.NONE="0",e.USER_AGENT="1",e.IP="2",e.VISITOR="3",e.DATACENTER="4",e.CUSTOMER_SESSION="5",e.ORGANISATION="6",e.ASN="7",e.COUNTRY="8",e.COMBINATION="9",e.HEADER_FINGERPRINT="b",e.VENDOR_FAMILY="c",e.VENDOR_NAME="d",e.VENDOR="e",e.VENDOR_CRAWLER_CLASSIFICATION="f"}(M||(V.MatchCode=M={})),function(e){e.NONE="0",e.BLOCK="1",e.ALLOW="2",e.HARDBLOCK="3",e.FLAG="4",e.MONETISE="5"}(K||(V.MitigateCode=K={}));var j,L={};Object.defineProperty(L,"__esModule",{value:!0}),L.NetaceaCookieV3IssueReason=void 0,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",e.UNKNOWN="unknown"}(j||(L.NetaceaCookieV3IssueReason=j={}));var D={},F={},q={};Object.defineProperty(q,"__esModule",{value:!0}),q.netaceaCookieV3OptionalKeyMap=q.netaceaCookieV3KeyMap=q.COOKIEDELIMITER=void 0,q.COOKIEDELIMITER="_/@#/",q.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},q.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(F,"__esModule",{value:!0}),F.defaultInvalidResponse=F.matchNetaceaCookieV3=F.checkNetaceaCookieV3=F.objectIsNetaceaCookieV3=F.cookieIsNetaceaV3Format=F.createNetaceaCookieV3=void 0;const U=L,$=q;function B(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),s=decodeURIComponent(a);let o,n=Object.keys($.netaceaCookieV3KeyMap).find((e=>$.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys($.netaceaCookieV3OptionalKeyMap).find((e=>$.netaceaCookieV3OptionalKeyMap[e]===t))),o=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===s?void 0:s:""===s?void 0:Number(s),void 0!==o&&"string"!=typeof o&&isNaN(o)&&(o=s),i[n]=o}return i}function G(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:U.NetaceaCookieV3IssueReason.NO_SESSION}}F.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in $.netaceaCookieV3OptionalKeyMap?`${$.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${$.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},F.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values($.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values($.netaceaCookieV3KeyMap).includes(e)))},F.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys($.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},F.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return G();let i;try{i=B(e)}catch{return G()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,s=t===i.clientIP,o=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!s,isExpired:a,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return G()},F.matchNetaceaCookieV3=B,F.defaultInvalidResponse=G;var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.AbstractCookieFactory=void 0;const W=L,X=F,J=q,Y="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),Q=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;z.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,X.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??this.generateUserId(),match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??W.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,X.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,X.cookieIsNetaceaV3Format)(i)?(0,X.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,s){const o=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),s].join(J.COOKIEDELIMITER);return`${await this.hash(o,a)}${J.COOKIEDELIMITER}${o}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(Q);if(null===t)return;const[,i,a,s,o,n,r,c,u]=t;return{signature:i,expiry:a,userId:s,ipHash:o,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,X.defaultInvalidResponse)();const s=Math.floor(Date.now()/1e3),o=parseInt(a.expiry)<s,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(J.COOKIEDELIMITER);return{mitata:a,requiresReissue:o||!u,isExpired:o,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:W.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>Y[e%Y.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=F;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=z;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=q;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var s=L;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return s.NetaceaCookieV3IssueReason}})}(D);var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),Z.validateRedirectLocation=void 0,Z.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 ee={},te={};function ie(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=se("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function ae(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const s=e[a]??"",o="string"==typeof s?s:s.join("; ");i.push(...oe(o,t))}return i}function se(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function oe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(te,"__esModule",{value:!0}),te.findAllInCookieString=te.findFirstInCookieString=te.findAllInHeaders=te.findFirstInHeaders=te.findOnlyValueInHeaders=te.findAllValuesInHeaders=te.findFirstValueInHeaders=void 0,te.findFirstValueInHeaders=function(e,t){const i=ie(e,t);if(void 0!==i)return i.slice(t.length+1)},te.findAllValuesInHeaders=function(e,t){return ae(e,t).map((e=>e.slice(t.length+1)))},te.findOnlyValueInHeaders=function(e,t){const i=ae(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},te.findFirstInHeaders=ie,te.findAllInHeaders=ae,te.findFirstInCookieString=se,te.findAllInCookieString=oe;var ne={};function re(e){return"set-cookie"===e||"Set-Cookie"===e}function ce(e,t){const i=t+"=";return e.startsWith(i)}function ue(e,t){if(!ce(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function de(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function he(e,t){for(const i of Object.keys(e)){if(!re(i))continue;const a=pe(de(e,i),t);if(void 0!==a)return a}}function pe(e,t){return e.map((e=>e.trimStart())).find((e=>ce(e,t)))}function le(e,t){const i=[];for(const a of Object.keys(e)){if(!re(a))continue;const s=de(e,a);i.push(...ge(s,t))}return i}function ge(e,t){return e.map((e=>e.trimStart())).filter((e=>ce(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=ue,ne.findFirstValueInHeaders=function(e,t){const i=he(e,t);return void 0!==i?ue(i,t):void 0},ne.findOnlyValueInHeaders=function(e,t){const i=le(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?ue(i[0],t):void 0},ne.findFirstInHeaders=he,ne.findFirstInSetCookieStrings=pe,ne.findValueInSetCookieStrings=function(e,t){const i=pe(e,t);if(void 0!==i)return ue(i,t)},ne.findAllInHeaders=le,ne.findAllInSetCookieStrings=ge;var fe=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]}),Ce=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)&&fe(t,e,i);return Ce(t,e),t};Object.defineProperty(ee,"__esModule",{value:!0}),ee.setCookie=ee.cookie=void 0,ee.cookie=ye(te),ee.setCookie=ye(ne);var me={},Se={},Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.KINESIS_URL=Ie.API_VERSION=Ie.REGION=Ie.PAYLOAD_TYPE=Ie.STATE=void 0,Ie.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ie.PAYLOAD_TYPE="string",Ie.REGION="eu-west-1",Ie.API_VERSION="2013-12-02",Ie.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.headersToRecord=ve.increaseBatchSize=ve.handleFailedLogs=ve.batchArrayForKinesis=ve.sleep=void 0,ve.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ve.batchArrayForKinesis=function(e,t,i){const a=[];for(let s=0;s<e.length;s+=t){const o=e.slice(s,s+t);a.push({Data:i.from(JSON.stringify(o)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ve.handleFailedLogs=function(e,t,i){const a=2*i,s=[...e,...t],o=s.length-a;return o>0&&(console.error(`Netacea Error :: failed to send ${o} log(s) to Kinesis ingest.`),s.splice(0,o)),s},ve.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ve.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 ke=Ie,Ee=ve;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,Ee.headersToRecord)(i.headers),host:ke.KINESIS_URL,method:"POST",path:"/",body:i.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}}async signRequest(e,t,i,a){const s={Records:(0,Ee.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ke.KINESIS_URL,{body:JSON.stringify(s),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 Ae=Ie,we=ve;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,we.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,we.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,we.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,we.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,o={Records:(0,we.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:Ae.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=Ne;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(me);var _e={};function Oe(e,t){let i=null;if("number"==typeof e&&Number.isFinite(e))i=e;else if("string"==typeof e&&""!==e.trim()){const t=Number(e);Number.isFinite(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(_e,"__esModule",{value:!0}),_e.parseUrl=_e.parseHttpHeaderName=_e.stringOrDefault=_e.parseIntOrDefault=_e.parseNumberOrDefault=void 0,_e.parseNumberOrDefault=Oe,_e.parseIntOrDefault=function(e,t){const i=Oe(e,t);return"number"==typeof i?Math.floor(i):i},_e.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},_e.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0},_e.parseUrl=function(e){const t=/^[a-z][a-z\d+.-]*:\/\/([^/?#]+)([^?#]*)?(?:[?#].*)?$/i.exec(e);if(null===t)return;const[,i,a]=t;return{host:i.slice(i.lastIndexOf("@")+1),path:void 0===a||""===a?"/":a}};var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.searchParamsFromRecord=void 0,be.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Te={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.JweFactory=void 0;Pe.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),s=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(s).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Re=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]}),Me=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ke=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)&&Re(t,e,i);return Me(t,e),t};Object.defineProperty(Te,"__esModule",{value:!0}),Te.jwe=void 0,Te.jwe=Ke(Pe);var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.truncateLongFields=xe.parseGraphQl=xe.parseGraphQlRequestBody=xe.getGraphQLParserConfig=void 0;const He=_e;function Ve(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function je(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const o=t[e];t[e]=(s=i,(a=o).length<=s?a:a.slice(0,s)+"…")}var a,s;return t}xe.getGraphQLParserConfig=function(e){const t={includePaths:[],maxParsableBytes:(0,He.parseIntOrDefault)(e?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:(0,He.parseIntOrDefault)(e?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/,useStrictAcceptHeaderCheck:e?.useStrictAcceptHeaderCheck??!0};if(Array.isArray(e?.includePaths))for(const i of e.includePaths)"string"==typeof i&&t.includePaths.push(i);try{if(e?.parserRegex instanceof RegExp)t.parserRegex=e?.parserRegex;else if("object"==typeof e?.parserRegex){const{regex:i,flags:a}=e?.parserRegex;"string"==typeof i&&(t.parserRegex=new RegExp(i,a))}}catch{}return t},xe.parseGraphQlRequestBody=function(e,t){if(""===t)throw new Error("Netacea Error: Empty GraphQL body received");const i=JSON.parse(t);if("object"!=typeof i)throw new Error("Netacea Error: Invalid GraphQL JSON");const a={...Ve(e,i?.query??"")},s=(i?.operationName??"").trim();return""!==s&&(a.OpName=s),je(e,a)},xe.parseGraphQl=Ve,xe.truncateLongFields=je;var Le={},De={},Fe={};Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.createComputedSignatureInputs=Fe.createComputedSignatureInput=void 0;const qe=/^[a-z*][a-z0-9_.*-]{0,63}$/,Ue=/^"(?:[^"\\]|\\.)*"$/,$e=/^[^;"\s]+$/,Be=/^"[^"\\]+"(?:;[a-z*][a-z0-9_.*-]*(?:=(?:"(?:[^"\\]|\\.)*"|[^; ]+))?)*$/;function Ge(e,t){const i=Xe(t);if(void 0===i)return;const a=[...i.componentIdentifiers.map((t=>{const i=function(e,t){const i=/^"([^"\\]+)"/.exec(t)?.[1];if(void 0===i)return;const a=ze(t,"name");let s;switch(i){case"@authority":s=e.url.host;break;case"@method":s=e.method;break;case"@path":s=e.url.path;break;case"@query":s=e.url.query;break;case"@query-param":s="string"==typeof a?function(e,t){const i=new URLSearchParams(e.slice(1)).getAll(t);return i.map(We).join(", ")}(e.url.query,a):void 0;break;case"@request-target":s=`${e.method.toLowerCase()} ${e.url.path}${e.url.query}`;break;case"@scheme":s=e.url.scheme;break;case"@target-uri":s=e.url.toString();break;default:s=function(e,t,i){const a=e.readHeader(t),s=0===a.length?void 0:a.map((e=>e.trim())).join(", ");return void 0!==s&&i?function(e){let t="",i=!1,a=!1,s=!1,o=!1;for(const n of e.trim())a?(t+=n,a=!1):i&&"\\"===n?(t+=n,a=!0):'"'===n?(t+=n,i=!i):i?t+=n:/\s/.test(n)?o||(s=!0):"="===n||";"===n?(t=t.trimEnd()+n,s=!1,o=!0):","===n?(t=t.trimEnd()+", ",s=!1,o=!1):(s&&""!==t&&!t.endsWith(" ")&&(t+=" "),t+=n,s=!1,o=!1);return t.trimEnd()}(s):s}(e,i,!0===ze(t,"sf"))}return s}(e,t);return void 0===i?void 0:`${t}: ${i}`})),`"@signature-params": ${i.parameters}`];return a.some((e=>void 0===e))?void 0:a.join("\n")}function ze(e,t){const i=e.indexOf('"',1),a=e.slice(i+1);if(a.startsWith(";"))for(const e of Ye(a.slice(1),";")){const i=e.indexOf("=");if((-1===i?e:e.slice(0,i))!==t)continue;if(-1===i)return!0;const a=e.slice(i+1);return Ue.test(a)?a.slice(1,-1).replace(/\\(.)/g,"$1"):a}}function We(e){return encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}function Xe(e){const t=e.indexOf("=");if(-1===t)return;const i=e.slice(0,t);if(!qe.test(i))return;const a=e.slice(t+1),s=Je(a,")",1);if(!a.startsWith("(")||-1===s)return;if(!function(e){if(""===e)return!0;return e.startsWith(";")&&Ye(e.slice(1),";").every((e=>{const t=e.indexOf("=");if(-1===t)return!1;const i=e.slice(0,t),a=e.slice(t+1);return qe.test(i)&&function(e){return Ue.test(e)||$e.test(e)}(a)}))}(a.slice(s+1)))return;const o=a.slice(1,s),n=""===o?[]:Ye(o," ");return n.every((e=>Be.test(e)))?{label:i,componentIdentifiers:n,parameters:a}:void 0}function Je(e,t,i=0){let a=!1,s=!1;for(let o=i;o<e.length;o++){const i=e[o];if(s)s=!1;else if(a&&"\\"===i)s=!0;else if('"'===i)a=!a;else if(!a&&i===t)return o}return-1}function Ye(e,t){const i=[];let a=0,s=Je(e,t);for(;-1!==s;)i.push(e.slice(a,s)),a=s+1,s=Je(e,t,a);return i.push(e.slice(a)),i}Fe.createComputedSignatureInput=Ge,Fe.createComputedSignatureInputs=function(e,t){const i=Ye(t,","),a={};for(const t of i){const i=t.trim(),s=Xe(i),o=Ge(e,i);if(void 0===s||void 0===o)return;a[s.label]=o}return a},Object.defineProperty(De,"__esModule",{value:!0}),De.AbstractRequestView=void 0;const Qe=_e,Ze=Fe;De.AbstractRequestView=class{constructor(e){this._httpMsgSignature=void 0,this._buffer=e}get contentLength(){return(0,Qe.parseIntOrDefault)(this.readHeader("content-length")?.[0],{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get userAgent(){return this.readHeader("user-agent")?.[0]??""}get contentType(){return this.readHeader("content-type")?.[0]}get xForwardedFor(){return this.readHeader("x-forwarded-for")?.[0]}get referer(){return this.readHeader("referer")?.[0]}get accept(){return this.readHeader("accept")?.[0]}get host(){return this.readHeader("host")?.[0]}async getHttpMsgSignature(){const e=this.readJoinedHeader("Signature-Input"),t=this.readJoinedHeader("Signature"),i=void 0===e?void 0:this.createBase64SignatureInput(e);return void 0===this._httpMsgSignature&&(this._httpMsgSignature={signature:t,signatureSha256:void 0===t?void 0:(await this.sha256Hash(t)).toLowerCase().slice(0,12),signatureInput:e,signatureAgent:this.readJoinedHeader("Signature-Agent"),computedInput:i}),this._httpMsgSignature}readJoinedHeader(e){const t=this.readHeader(e).join(",");return""!==t?t:void 0}toBase64(e){if(void 0===e)return;return this._buffer.from(e).toString("base64")}createBase64SignatureInput(e){const t=(0,Ze.createComputedSignatureInputs)(this,e);if(void 0!==t)return Object.entries(t).map((([e,t])=>`${e}=:${this.toBase64(t)}:`)).join(", ")}};var et={};Object.defineProperty(et,"__esModule",{value:!0}),et.RequestUrl=void 0;class tt{constructor(e,t,i,a){this.scheme=e,this.host=t,this.path=i,this.query=a}static fromString(e){const t=/^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)(\/[^?#]*)?(\?[^#]*)?(?:#.*)?$/i.exec(e);if(null===t)throw new TypeError(`Invalid request URL: ${e}`);return new tt(t[1]??"",t[2],t[3]??"/",t[4]??"")}toString(){return`${""===this.scheme?"":`${this.scheme}://`}${this.host}${this.path}${this.query}`}}et.RequestUrl=tt,Object.defineProperty(Le,"__esModule",{value:!0}),Le.RequestView=void 0;const it=t,at=De,st=et;class ot extends at.AbstractRequestView{constructor(e,t){super(it.Buffer),this.request=e,this.sha256Digest=t}get method(){return this.request.method}get url(){return st.RequestUrl.fromString(this.request.url)}async getBody(){return void 0===this._body&&(this._body=await this.request.clone().text()??""),this._body}readHeader(e){const t=this.request.headers.get(e)??void 0;return void 0!==t?[t]:[]}async sha256Hash(e){const t=(new TextEncoder).encode(e),i=await this.sha256Digest.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}Le.RequestView=ot;var nt={},rt={};Object.defineProperty(rt,"__esModule",{value:!0}),rt.findBestMitigation=rt.isCaptchaMitigation=void 0;const ct=V;function ut(e){return`[${e}]`}const dt={[ct.MatchCode.NONE]:"",[ct.MatchCode.USER_AGENT]:"ua_",[ct.MatchCode.IP]:"ip_",[ct.MatchCode.VISITOR]:"visitor_",[ct.MatchCode.DATACENTER]:"datacenter_",[ct.MatchCode.CUSTOMER_SESSION]:"customer_session_",[ct.MatchCode.ORGANISATION]:"organisation_",[ct.MatchCode.ASN]:"asn_",[ct.MatchCode.COUNTRY]:"country_",[ct.MatchCode.COMBINATION]:"combination_",[ct.MatchCode.HEADER_FINGERPRINT]:"headerFP_",[ct.MatchCode.VENDOR_FAMILY]:"vendorFamily_",[ct.MatchCode.VENDOR_NAME]:"vendorName_",[ct.MatchCode.VENDOR]:"vendor_",[ct.MatchCode.VENDOR_CRAWLER_CLASSIFICATION]:"vendorCrawlerClassification_"},ht={[ct.MitigateCode.NONE]:"",[ct.MitigateCode.BLOCK]:"blocked",[ct.MitigateCode.ALLOW]:"allow",[ct.MitigateCode.HARDBLOCK]:"hardblocked",[ct.MitigateCode.FLAG]:"flagged",[ct.MitigateCode.MONETISE]:"monetised"},pt={[ct.CaptchaCode.NONE]:"",[ct.CaptchaCode.SERVE]:"captcha_serve",[ct.CaptchaCode.PASS]:"captcha_pass",[ct.CaptchaCode.FAIL]:"captcha_fail",[ct.CaptchaCode.COOKIE_PASS]:"captcha_cookiepass",[ct.CaptchaCode.COOKIE_FAIL]:"captcha_cookiefail",[ct.CaptchaCode.CHECKPOINT_SIGNAL]:"checkpoint_signal",[ct.CaptchaCode.CHECKPOINT_POST]:"checkpoint_post",[ct.CaptchaCode.CHECKPOINT_SERVE]:"checkpoint_serve",[ct.CaptchaCode.CHECKPOINT_PASS]:"checkpoint_pass",[ct.CaptchaCode.CHECKPOINT_FAIL]:"checkpoint_fail",[ct.CaptchaCode.CHECKPOINT_COOKIE_PASS]:"checkpoint_cookiepass",[ct.CaptchaCode.CHECKPOINT_COOKIE_FAIL]:"checkpoint_cookiefail"};rt.isCaptchaMitigation=function(e){return[ct.CaptchaCode.SERVE,ct.CaptchaCode.FAIL,ct.CaptchaCode.COOKIE_FAIL,ct.CaptchaCode.CHECKPOINT_POST,ct.CaptchaCode.CHECKPOINT_SERVE,ct.CaptchaCode.CHECKPOINT_FAIL,ct.CaptchaCode.CHECKPOINT_COOKIE_FAIL].includes(e.captcha)},rt.findBestMitigation=function(e,t,i,a,s=!1){i=function(e,t){return t?e:{[ct.CaptchaCode.PASS]:ct.CaptchaCode.COOKIE_PASS,[ct.CaptchaCode.FAIL]:ct.CaptchaCode.COOKIE_FAIL,[ct.CaptchaCode.CHECKPOINT_PASS]:ct.CaptchaCode.CHECKPOINT_COOKIE_PASS,[ct.CaptchaCode.CHECKPOINT_FAIL]:ct.CaptchaCode.CHECKPOINT_COOKIE_FAIL}[e]??e}(i,a),s&&(i=ct.CaptchaCode.CHECKPOINT_SIGNAL);let o=dt[e]??ut(e)+"_";return o+=ht[t]??ut(t),i!==ct.CaptchaCode.NONE&&(o+=","+(pt[i]??ut(i))),{sessionStatus:o,codes:{match:e,mitigate:t,captcha:i}}},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.__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}),i(rt,e)}(nt);var lt={},gt={};Object.defineProperty(gt,"__esModule",{value:!0}),gt.ResponseView=gt.AbstractResponseView=void 0;class ft{constructor(e){this.cacheStatus=e}get contentType(){return this.readHeader("content-type")?.[0]}get contentLength(){return this.readHeader("content-length")?.[0]}get location(){return this.readHeader("location")?.[0]}get setCookie(){return this.readHeader("set-cookie")}}gt.AbstractResponseView=ft;gt.ResponseView=class extends ft{constructor(e,t){super(t),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]:[]}readHeaders(){const e={};return this.response.headers.forEach(((t,i)=>{e[i]=[t]})),e["set-cookie"]=this.response.headers.getSetCookie(),e}},Object.defineProperty(lt,"__esModule",{value:!0}),lt.HttpClient=lt.AbstractHttpClient=void 0;const Ct=gt;class yt{constructor(e={}){this.cache=e.cache}async request(e,t){const i=this.cache?.get(e,t);if(void 0!==i)return this.createCachedResponseView(i);const a=await this.fetch(e,t);return await this.populateCache(e,t,a),a}async populateCache(e,t,i){void 0!==this.cache&&await this.cache.set(e,t,i).catch((()=>{}))}async get(e,t){return await this.request(e,{...t,method:"GET"})}async post(e,t,i){return await this.request(e,{...i,method:"POST",body:t})}}lt.AbstractHttpClient=yt;lt.HttpClient=class extends yt{constructor(e){super(e),this.fetchFn=e.fetch}async fetch(e,t){const i=new AbortController,a=await async function(e,t,i){if(void 0===t)return await e;let a;const s=new Promise(((e,s)=>{a=setTimeout((()=>{i(),s(new Error(`HTTP request timed out after ${t}ms`))}),t)}));try{return await Promise.race([e,s])}finally{void 0!==a&&clearTimeout(a),Promise.resolve(e).catch((()=>{}))}}(this.fetchFn(e,{...t,signal:i.signal}),t?.timeoutMs,(()=>{i.abort()}));return new Ct.ResponseView(a,"MISS")}createCachedResponseView(e){const t=new Response(e.body,e);return new Ct.ResponseView(t,"HIT")}};var mt={},St={};Object.defineProperty(St,"__esModule",{value:!0}),St.LruCache=void 0;St.LruCache=class{constructor(e){if(this.capacity=e,this.entries=new Map,!Number.isInteger(e)||e<=0)throw new RangeError("LruCache capacity must be a positive integer")}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){if(this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.capacity){const e=Array.from(this.entries.keys());e.length>0&&this.entries.delete(e[0])}}find(e){for(const[t,i]of this.entries)if(e(i,t))return this.get(t)}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}},Object.defineProperty(mt,"__esModule",{value:!0}),mt.HttpCache=void 0;const It=St,vt=_e,kt=1048576;function Et(e){const t={};if(void 0===e)return t;for(const[i,a]of Object.entries(e))t[i.toLowerCase()]=a;return t}function Nt(e){if(void 0===e||""===e.trim())return{};const t={};for(const i of e.split(",")){const e=i.trim();if(""===e)continue;const a=e.indexOf("=");if(-1===a){t[e.toLowerCase()]=!0;continue}t[e.slice(0,a).trim().toLowerCase()]=e.slice(a+1).trim().replace(/^"(.+)"$/,"$1")}return t}function At(e){const t=(0,vt.parseNumberOrDefault)(e,{defaultValue:void 0});return"number"==typeof t&&t>=0?t:void 0}function wt(e){if(void 0===e)return;const t=Date.parse(e);return Number.isNaN(t)?void 0:t}function _t(e,t){return{method:(i=t?.method,(i??"GET").toUpperCase()),url:e,headers:Et(t?.headers)};var i}function Ot(e){if("GET"!==e.method)return`method=${e.method}`;if(void 0!==e.headers.authorization)return"authorization header present";if(void 0!==e.headers.range)return"range header present";if(void 0!==e.headers["if-match"])return"if-match header present";if(void 0!==e.headers["if-none-match"])return"if-none-match header present";if(void 0!==e.headers["if-modified-since"])return"if-modified-since header present";if(void 0!==e.headers["if-unmodified-since"])return"if-unmodified-since header present";if(void 0!==e.headers["if-range"])return"if-range header present";return void 0!==Nt(e.headers["cache-control"])["no-store"]?"request cache-control=no-store":void 0}function bt(e,t){return!t.vary.includes("*")&&t.vary.every((i=>(e.headers[i]??"")===(t.varyRequestHeaders[i]??"")))}function Tt(e){const t=At(e.cacheControl["s-maxage"]);if(void 0!==t)return t;const i=At(e.cacheControl["max-age"]);if(void 0!==i)return i;const a=wt(e.headers.expires);return void 0===a?0:Math.max(0,Math.floor((a-(e.dateHeaderMs??e.storedAt))/1e3))}function Pt(e){return JSON.stringify([e.url,e.vary.map((t=>[t,e.varyRequestHeaders[t]??""]))])}mt.HttpCache=class{constructor(e={}){this.entries=new It.LruCache(10),this.defaultCacheControl=e.defaultCacheControl,this.now=e.now??(()=>Date.now())}get(e,t){const i=_t(e,t);if("GET"!==i.method)return{body:"Not Found",headers:{},status:404,storedAt:this.now(),url:i.url,vary:[],varyRequestHeaders:{},cacheControl:{},ageSeconds:0};if(void 0!==Ot(i))return;const a=Nt(i.headers["cache-control"]);if(void 0!==a["no-cache"])return;const s=this.entries.find((e=>e.url===i.url&&bt(i,e)));if(void 0===s)return;if(void 0!==s.cacheControl["no-cache"])return;const o=At(a["max-age"]),n=void 0===o?Tt(s):Math.min(Tt(s),o),r=function(e,t){return Math.max(0,Math.floor((t-e.storedAt)/1e3))+e.ageSeconds}(s,this.now());return r>=n?void 0:{...s,headers:{...s.headers,age:String(r)}}}async set(e,t,i){const a=_t(e,t);if(void 0!==Ot(a))return;const s=this.entries.find((e=>e.url===a.url&&bt(a,e))),o=function(e){const t={};for(const[i,a]of Object.entries(e.readHeaders()))a.length>0&&(t[i.toLowerCase()]=a.join(", "));return t}(i),n=Nt(o["cache-control"]??this.defaultCacheControl);if(200!==i.status||void 0!==n["no-store"]||void 0!==n.private||i.setCookie.length>0)return void this.removeEntry(s);const r=function(e){return void 0===e.vary?[]:e.vary.split(",").map((e=>e.trim().toLowerCase())).filter((e=>""!==e))}(o);if(r.includes("*"))return void this.removeEntry(s);const c=Number(o["content-length"]);if(Number.isFinite(c)&&c>kt)return void this.removeEntry(s);const u=await i.getBody();if((new TextEncoder).encode(u).byteLength>kt)return void this.removeEntry(s);const d=this.now(),h=Number(o.age??"0"),p=wt(o.date),l=void 0===p?0:Math.max(0,Math.floor((d-p)/1e3)),g={body:u,headers:o,status:i.status,storedAt:d,url:a.url,vary:r,varyRequestHeaders:Object.fromEntries(r.map((e=>[e,a.headers[e]??""]))),cacheControl:n,dateHeaderMs:p,ageSeconds:Math.max(Number.isFinite(h)&&h>=0?h:0,l)};void 0!==s&&this.entries.delete(Pt(s)),this.entries.set(Pt(g),g)}removeEntry(e){void 0!==e&&this.entries.delete(Pt(e))}};var Rt={};Object.defineProperty(Rt,"__esModule",{value:!0}),Rt.ProtectorApiResponseView=void 0;const Mt=_e;Rt.ProtectorApiResponseView=class{constructor(e){this.responseView=e}get status(){return this.responseView.status}async getBody(){return await this.responseView.getBody()}readHeader(e){return this.responseView.readHeader(e)}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,Mt.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 signatureStatus(){return this.readHeader("x-netacea-signature-status")?.[0]}get netaceaSettings(){const e=this.readHeader("x-netacea-settings")?.[0];if(void 0===e)return{checkAllPostRequests:!1};try{const t=new URLSearchParams(e).get("checkAllPostRequests");return null===t?{checkAllPostRequests:!1}:{checkAllPostRequests:"1"===t}}catch{return{checkAllPostRequests:!1}}}get sessionCookieMaxAge(){return(0,Mt.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,Mt.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)}};var Kt={};Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.acceptHeaderToNetaceaContentType=Kt.APIError=Kt.ProtectorApiClient=void 0;const xt=Rt;Kt.ProtectorApiClient=class{constructor(e,t){this.httpClient=e.httpClient,this.timeoutMs=e.timeoutMs;const i=/^https:\/\/([^/?#]+)/i.exec(t.protectorApiUrl);if(null===i)throw new Error("Protector API URL must use HTTPS");this.protectorApiHost=i[1],this.apiKey=t.apiKey}async getDecisionResponse(e){return await this.getResponse("/",e)}async getChallengePage(e){return await this.getResponse("/captcha",e)}async getResponse(e,t){const i=[],a=new jt,s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t.clientIp};void 0===t.userId||t.isNewUser||(s["X-Netacea-UserId"]=t.userId);const{captchaSiteKey:o,captchaSecretKey:n}=t;if(void 0!==o&&void 0!==n&&(s["X-Netacea-Captcha-Site-Key"]=o,s["X-Netacea-Captcha-Secret-Key"]=n),void 0!==t.customerSessionId&&(s["X-Netacea-Customer-Session-ID"]=t.customerSessionId),void 0!==t.accept){s.Accept=t.accept;const e=Vt(t.accept);s["X-Netacea-Captcha-Content-Type"]=e}if(void 0!==t.headerFingerprint&&a.setQuery("headerFP",t.headerFingerprint),void 0===t.checkAllPostRequests&&a.setQuery("getSettings","checkAllPostRequests"),void 0!==t.challengeAssetsPath&&a.setQuery("challengeAssetsPath",t.challengeAssetsPath),void 0!==t.trackingId&&a.setQuery("trackingId",t.trackingId),void 0!==t.base64UserAgent?(s["X-Netacea-User-Agent"]=t.base64UserAgent,i.push("User-Agent")):void 0!==t.userAgent&&(s["User-Agent"]=t.userAgent),void 0!==t.requestId&&(s["X-Netacea-Request-Id"]=t.requestId,i.push("Request-Id")),void 0!==t.captchaCookie){let e=t.captchaCookie;e.startsWith("_mitatacaptcha=")||(e="_mitatacaptcha="+e),s.Cookie=e}void 0!==t.httpMsgSignature&&function(e,t,i){void 0!==i.signature&&(e.Signature=i.signature);void 0!==i.signatureInput&&(e["Signature-Input"]=i.signatureInput);void 0!==i.signatureAgent&&(e["Signature-Agent"]=i.signatureAgent);void 0!==i.computedInput&&(e["X-Netacea-Computed-Signature-Input"]=i.computedInput,t.push("Computed-Signature-Input"))}(s,i,t.httpMsgSignature),i.length>0&&a.setQuery("netaceaHeaders",i.join(","));const r=this.protectorApiHost,c=await this.httpClient.get(`https://${r}${e}`+a.buildQueryString(),{headers:s,timeoutMs:this.timeoutMs});if(200!==c.status)throw Ht.fromResponse(c);return new xt.ProtectorApiResponseView(c)}};let Ht=class e extends Error{constructor(e,t){super(e),this.response=t}static fromResponse(t){let i="Unknown error";switch(t.status){case 403:i="Invalid credentials";break;case 500:i="Server error";break;case 502:i="Bad Gateway";break;case 503:i="Service Unavailable";break;case 400:i="Invalid request"}return new e(i,t)}};function Vt(e){const t=e?.toLowerCase()??"text/html",i=t?.includes("text/html")||t?.includes("application/html"),a=t?.includes("application/json");return a&&!i?"application/json":"text/html"}Kt.APIError=Ht,Kt.acceptHeaderToNetaceaContentType=Vt;class jt{constructor(){this.queries={}}setQuery(e,t){return this.queries[e]=encodeURIComponent(t),this}removeQuery(e){const{[e]:t,...i}=this.queries;return this.queries=i,this}buildQueryString(){const e=Object.entries(this.queries).map((([e,t])=>`${e}=${t}`)).join("&");return e.length>0?`?${e}`:""}}!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.mitigation=e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=e.MitigateCode=e.MatchCode=e.CaptchaCode=void 0;var o=V;Object.defineProperty(e,"CaptchaCode",{enumerable:!0,get:function(){return o.CaptchaCode}}),Object.defineProperty(e,"MatchCode",{enumerable:!0,get:function(){return o.MatchCode}}),Object.defineProperty(e,"MitigateCode",{enumerable:!0,get:function(){return o.MitigateCode}});var n=L;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return n.NetaceaCookieV3IssueReason}}),e.cookie=a(D),e.configValidation=a(Z),e.headers=a(ee),e.ingest=a(me),e.parsing=a(_e),e.url=a(be),e.webcrypto=a(Te),e.graphql=a(xe),s(Le,e),e.mitigation=a(nt),s(lt,e),s(mt,e),s(St,e),s(De,e),s(et,e),s(gt,e),s(Rt,e),s(Kt,e)}(H);const Lt=new H.webcrypto.jwe.JweFactory(c);class Dt extends H.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.encrypt called without a configured encryption key");return await Lt.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.decrypt called without a configured encryption key");return await Lt.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await P(t.Buffer.from(e),i),s=t.Buffer.from(a).toString("hex");return t.Buffer.from(s).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var Ft;function qt(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 Ut(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:s}=e;return a.includes(i)&&s.includes("trackingId")&&"get"===t.toLowerCase()}function $t(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function Bt(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 Gt(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function zt(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.has("content-type")||t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}function Wt(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ft||(Ft={}));var Xt="@netacea/vercel",Jt="0.9.15";class Yt extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Qt(e){return`[${e}]`}function Zt(e,t,i){let{match:a,mitigate:s,captcha:o}=t;i||("2"===o?o="4":"3"===o?o="5":"b"===o?o="d":"c"===o&&(o="e"));let n=E[a]??Qt(a)+"_";n+=N[s]??Qt(s);let r=w[s];if("0"!==o){n+=","+(A[o]??Qt(o));const e=_[o];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:s,captcha:o}}}function ei(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 ti(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class ii{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),s=await this.readCookie(e,this.config.captchaCookieName),o=e.headers.get("x-forwarded-for")??void 0;let n,r=o?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(n=e.headers.get(this.config.ipHeaderName)??void 0,r=n??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}=await async function(e,t,i,a,s){const o=await e.cookieFactory.retrieveCookieInfo(a,s),n={userId:void 0!==o.mitata?o.mitata.userId:void 0,requiresReissue:o.requiresReissue,isExpired:o.isExpired,shouldExpire:o.shouldExpire,isSameIP:o.isSameIP,isPrimaryHashValid:o.isPrimaryHashValid,protectorCheckCodes:{match:o.match,mitigate:o.mitigate,captcha:o.captcha},issueReason:o.issueReason};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?Ft.RENEW_SESSION:Ft.EXISTING_SESSION,{sessionStatus:u}=Zt(e.mitigationType,n.protectorCheckCodes,$t(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:T(),sessionCookieStatus:Ft.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:d,captchaToken:s,sessionCookieDetails:c,sessionCookieStatus:u,userId:h},l=H.parsing.parseIntOrDefault(e.headers.get("x-vercel-id"),{defaultValue:void 0});return{clientIp:r,fingerprints:await si(e),httpMessageSignatures:await ai(e),ipHeader:void 0!==n?`${this.config.ipHeaderName}: ${n}`:void 0,method:i,protocol:void 0,requestId:e.headers.get("x-vercel-id")??"",sessionDetails:p,url:t,userAgent:e.headers.get("user-agent")??"",referer:e.headers.get("referer")??void 0,contentLength:l,contentType:e.headers.get("content-type")??void 0,xForwardedFor:o}}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 Lt.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ai(e){const t=new H.RequestView(e,crypto.subtle);return await t.getHttpMsgSignature()}async function si(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 ti(t)}(t),a=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 ti(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{configureCookiesDomain:oi}=m.cookie.attributes;class ni{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?d:i,this.mitigationServiceTimeoutMs=H.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=H.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=H.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:s}=oi(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var o,n;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=s??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(o=this.mitigationType,void 0===(n=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?o===exports.NetaceaMitigationType.INGEST?3600:60:n),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class ri{config;kinesis;requestAnalyser;cookieFactory;protectorApiClient;workerInstanceId;constructor(i){this.config=new ni(i),this.protectorApiClient=new H.ProtectorApiClient({httpClient:new H.HttpClient({fetch:S}),timeoutMs:this.config.mitigationServiceTimeoutMs},{apiKey:this.config.apiKey,protectorApiUrl:this.config.mitigationServiceUrl}),this.cookieFactory=new Dt({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===exports.NetaceaIngestType.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new H.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 ii({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);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,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);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,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=$t(t.url,e.method),s=a&&i.sessionStatus.includes("checkpoint_post"),o=!a&&Ut(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!o&&!s)for(const t of i.setCookie)e.append("set-cookie",t);return e};if(i.mitigated&&!s){if("captcha"===i.mitigation){const e=n();return"application/json"===i.captchaPageContentType&&e.set("content-type","application/json"),{...i,response:zt({config:this.config,responseHeaders:e,body:i.body})}}return{...i,response:Gt({responseHeaders:n()})}}return"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Gt({status:402,responseHeaders:n()})}:{...i,response:Wt({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:s}=function(e){if(void 0===e)return;const t=e.match(b);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:o}=Zt(this.config.mitigationType,a,$t(new URL(e.url),e.method));return{userId:s,sessionStatus:o,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus,signatureStatus:e.signatureStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),a=await this.requestAnalyser.getNetaceaRequestDetails(e),s=function(e,t,i,a){const s=i.sessionStatus??t.sessionDetails.sessionStatus,o=t.method,n=t.url.pathname,r=t.protocol??null,c=Date.now(),u=t.referer??"",d=H.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),IntegrationType:Xt?.replace("@netacea/","")??"",IntegrationVersion:Jt,NetaceaMitigationApplied:s??"",HttpMsgSigAgent:t.httpMessageSignatures.signatureAgent,HttpMsgSigInput:t.httpMessageSignatures.signatureInput,HttpMsgSigSha256:t.httpMessageSignatures.signatureSha256,HttpMsgSigStatus:i.signatureStatus,UserId:t.sessionDetails.userId,NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===u?"-":u,Request:`${o} ${n} ${r}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(c).toUTCString(),TimeUnixMsUTC:c,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...s})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},t=await this.makeIngestApiCall(e,s);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)}}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:o,captcha:n}=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:o,captcha:n},captchaPageContentType:t}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const o=`${e}${i}`,n=new Request(o,{...{method:t,body:s,headers:a},duplex:"half"}),r=await S(o,n),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){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",signatureStatus:t?.signatureStatus,response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(void 0!==t&&"injectHeaders"in t){e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)}if(this.config.ingestType===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",Xt.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Jt),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",signatureStatus:t?.signatureStatus,response:Bt(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?qt(e.headers.get("Accept")??void 0):qt();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,s;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Yt&&(s=i.latencyMs,a=i.protectorApiResponse?.status);return{response:$t(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:ei({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 Lt.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Ft.NEW_SESSION,Ft.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),s=a.responseView.getProtectorCodes(),{match:o,mitigate:n,captcha:r}=s,c=[await this.createMitata(e.clientIp,i,o,n,r,a.mitataMaxAge,void 0,ci(e))],u={match:o,mitigate:n,captcha:r},d=Zt(this.config.mitigationType,u,!1),h={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,signatureStatus:a.responseView.signatureStatus,setCookie:c,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[I.block,I.captcha].includes(d.mitigation),redirect:"5"===n?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&d.mitigation!==I.flag||(h.injectHeaders=ei(d.parts,a.eventId)),h}{const i=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,a={match:i?.match??"0",mitigate:i?.mitigate??"0",captcha:i?.captcha??"0"},s=Zt(this.config.mitigationType,a,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:s.sessionStatus,mitigation:s.mitigation,mitigated:[I.block,I.captcha].includes(s.mitigation),redirect:void 0,protectorCheckCodes:s.parts,captchaPageContentType:t};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&s.mitigation!==I.flag||(o.injectHeaders=ei(s.parts)),o}}async createMitata(e,t,i,a,s,o=86400,n=void 0,c=r.NO_SESSION){const u=["1","3","5","a","c","e"].includes(s)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,d=void 0!==n?n-Math.floor(Date.now()/1e3):u,h=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:s,gracePeriod:d,cookieId:"",issueReason:c});return m.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:s,captcha:o,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:s,captcha:o},d=Zt(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[I.block,I.captcha].includes(d.mitigation),protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromResponseView(e){const t={[v]:e.readHeader(v)?.[0],[k]:String(e.captchaCookieMaxAge)};return await this.getMitataCaptchaFromHeaders(t)}async getMitataCaptchaFromHeaders(e){let t=e[v];const i=parseInt(e[k]??"");if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Lt.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),m.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!==Ft.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 o=Date.now(),n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,n),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${s.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-o;if(200!==c.status)throw new Yt(c,u);const d=new H.ProtectorApiResponseView(new H.ResponseView(c.fetchResponse)),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,g,void 0,ci(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),C=d.eventId;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:f,body:c.body,eventId:C,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const s=e.sessionDetails.sessionCookieStatus===Ft.NEW_SESSION,o={accept:t,base64UserAgent:void 0,captchaCookie:e.sessionDetails.captchaToken,captchaSecretKey:this.config.captchaSecretKey,captchaSiteKey:this.config.captchaSiteKey,checkAllPostRequests:!0,clientIp:e.clientIp,customerSessionId:void 0,headerFingerprint:e.fingerprints.headerFingerprint,isNewUser:s,requestId:e.requestId,trackingId:i&&null!==a?a:void 0,userAgent:e.userAgent,userId:e.sessionDetails.userId,httpMsgSignature:e.httpMessageSignatures},n=Date.now();let r;try{r=i?await this.protectorApiClient.getChallengePage(o):await this.protectorApiClient.getDecisionResponse(o)}catch(e){if(e instanceof H.APIError)throw new Yt({headers:{},status:e.response.status},Date.now()-n);throw e}const c=Date.now()-n,{match:u,mitigate:d,captcha:h}=r.getProtectorCodes(),p=[await this.createMitata(e.clientIp,e.sessionDetails.userId,u,d,h,r.sessionCookieMaxAge,void 0,ci(e)),await this.getMitataCaptchaFromResponseView(r)].filter((e=>void 0!==e));let l=await r.getBody();if("application/json"===r.readHeader("content-type")?.[0]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");l=await r.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:r,status:r.status,setCookie:p,body:l,eventId:r.eventId,mitataMaxAge:r.sessionCookieMaxAge,latency:c}}async processMitigateRequest(e){if(Ut(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($t(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e.sessionDetails.userId,"0","0","0",86400,void 0,ci(e))]}}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===Ft.NEW_SESSION,a=t===Ft.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}}function ci(e){if(void 0===e.sessionDetails.sessionCookieDetails)return r.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?r.EXPIRED_SESSION:r.NO_SESSION:r.IP_CHANGE}const ui=e=>H.parsing.parseIntOrDefault(e,{defaultValue:void 0});function di(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function hi(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=hi(e,t,a);if(void 0!==i)return i}}function pi(e,t){const i=hi(e,t,"CAPTCHA_HEADER_NAME"),a=hi(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function li(e,t){const i=hi(e,t,"KINESIS_STREAM_NAME"),a=hi(e,t,"KINESIS_ACCESS_KEY"),s=hi(e,t,"KINESIS_SECRET_KEY"),o=di({logBatchSize:ui(hi(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:ui(hi(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==s)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:s,...o}}exports.NetaceaVercelIntegration=ri,exports.default=ri,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return di({apiKey:hi(e,t,"API_KEY"),captchaHeader:pi(e,t),captchaSecretKey:hi(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:hi(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:hi(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:hi(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:hi(e,t,"INGEST_SERVICE_URL"),ingestType:hi(e,t,"INGEST_TYPE"),ipHeaderName:hi(e,t,"IP_HEADER_NAME"),kinesis:li(e,t),mitataCookieExpirySeconds:ui(hi(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:hi(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:hi(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:hi(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:hi(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:hi(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:hi(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:hi(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:hi(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:ui(hi(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:hi(e,t,"COOKIE_NAME"),secretKey:hi(e,t,"SECRET_KEY"),timeout:ui(hi(e,t,"TIMEOUT"))})};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/vercel",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.15",
|
|
4
4
|
"description": "Netacea Vercel CDN Integration",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
"jose": "^4.15.9",
|
|
23
23
|
"uuid": "^10.0.0"
|
|
24
24
|
},
|
|
25
|
-
"gitHead": "
|
|
25
|
+
"gitHead": "0e34d53dd4bb95038b1e8bfd9fcf3035163246e5"
|
|
26
26
|
}
|