@netacea/cloudflare 6.5.2 → 6.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -59,15 +59,6 @@ declare enum NetaceaMitigationType {
59
59
  */
60
60
  INGEST = "INGEST"
61
61
  }
62
- declare enum NetaceaCookieV3IssueReason {
63
- CAPTCHA_GET = "captcha_get",
64
- CAPTCHA_POST = "captcha_post",
65
- EXPIRED_SESSION = "expired_session",
66
- FORCED_REVALIDATION = "forced_revalidation",
67
- INVALID_SESSION = "invalid_session",
68
- IP_CHANGE = "ip_change",
69
- NO_SESSION = "no_session"
70
- }
71
62
  interface MakeRequestResponse {
72
63
  /**
73
64
  * Numerical status code of the response
@@ -197,61 +188,6 @@ interface InjectResponse<T = any> extends MitigateResponse<T> {
197
188
  }
198
189
  type NetaceaMitigationResponse<T> = MitigateResponse<T> | InjectResponse<T> | undefined;
199
190
 
200
- interface NetaceaCloudflareResult {
201
- protectorLatencyMs?: number;
202
- protectorStatus?: number;
203
- requestDetails: NetaceaRequestDetails;
204
- response: Response;
205
- sessionStatus: string;
206
- }
207
- interface NetaceaSessionCookieDetails {
208
- userId: string | undefined;
209
- requiresReissue: boolean;
210
- isExpired: boolean;
211
- shouldExpire: boolean;
212
- isSameIP: boolean;
213
- isPrimaryHashValid: boolean;
214
- protectorCheckCodes: ProtectorCheckCodes;
215
- issueReason?: NetaceaCookieV3IssueReason;
216
- }
217
- declare enum NetaceaSessionCookieStatus {
218
- NEW_SESSION = 1,
219
- EXISTING_SESSION = 2,
220
- RENEW_SESSION = 3
221
- }
222
- interface ProtectorCheckCodes {
223
- match: string;
224
- mitigate: string;
225
- captcha: string;
226
- }
227
- interface NetaceaSessionDetails {
228
- captchaToken: string | undefined;
229
- sessionCookie: string | undefined;
230
- sessionCookieDetails: NetaceaSessionCookieDetails | undefined;
231
- sessionCookieStatus: NetaceaSessionCookieStatus;
232
- sessionStatus: string;
233
- userId: string;
234
- }
235
- interface NetaceaRequestDetails {
236
- accept: string | undefined;
237
- contentLength: number;
238
- clientIp: string;
239
- method: string;
240
- protocol: string | undefined;
241
- sessionDetails: NetaceaSessionDetails;
242
- url: URL;
243
- userAgent: string;
244
- contentType: string | undefined;
245
- requestId: string;
246
- xForwardedFor: string | undefined;
247
- referer: string | undefined;
248
- graphQL?: Record<string, string>;
249
- fingerprints: {
250
- headerFingerprint: string;
251
- cookieFingerprint: string;
252
- };
253
- }
254
-
255
191
  interface GraphQLParserConfig {
256
192
  includePaths: string[];
257
193
  parserRegex: RegExp;
@@ -265,6 +201,17 @@ interface GraphQLParserArgs extends Omit<GraphQLParserConfig, 'parserRegex'> {
265
201
  };
266
202
  }
267
203
 
204
+ declare enum NetaceaCookieV3IssueReason {
205
+ CAPTCHA_GET = "captcha_get",
206
+ CAPTCHA_POST = "captcha_post",
207
+ EXPIRED_SESSION = "expired_session",
208
+ FORCED_REVALIDATION = "forced_revalidation",
209
+ INVALID_SESSION = "invalid_session",
210
+ IP_CHANGE = "ip_change",
211
+ NO_SESSION = "no_session",
212
+ UNKNOWN = "unknown"
213
+ }
214
+
268
215
  interface KinesisIngestWebLog {
269
216
  apiKey: string;
270
217
  }
@@ -311,6 +258,61 @@ declare class WebStandardKinesis {
311
258
  private signRequest;
312
259
  }
313
260
 
261
+ interface NetaceaCloudflareResult {
262
+ protectorLatencyMs?: number;
263
+ protectorStatus?: number;
264
+ requestDetails: NetaceaRequestDetails;
265
+ response: Response;
266
+ sessionStatus: string;
267
+ }
268
+ interface NetaceaSessionCookieDetails {
269
+ userId: string | undefined;
270
+ requiresReissue: boolean;
271
+ isExpired: boolean;
272
+ shouldExpire: boolean;
273
+ isSameIP: boolean;
274
+ isPrimaryHashValid: boolean;
275
+ protectorCheckCodes: ProtectorCheckCodes;
276
+ issueReason?: NetaceaCookieV3IssueReason;
277
+ }
278
+ declare enum NetaceaSessionCookieStatus {
279
+ NEW_SESSION = 1,
280
+ EXISTING_SESSION = 2,
281
+ RENEW_SESSION = 3
282
+ }
283
+ interface ProtectorCheckCodes {
284
+ match: string;
285
+ mitigate: string;
286
+ captcha: string;
287
+ }
288
+ interface NetaceaSessionDetails {
289
+ captchaToken: string | undefined;
290
+ sessionCookie: string | undefined;
291
+ sessionCookieDetails: NetaceaSessionCookieDetails | undefined;
292
+ sessionCookieStatus: NetaceaSessionCookieStatus;
293
+ sessionStatus: string;
294
+ userId: string;
295
+ }
296
+ interface NetaceaRequestDetails {
297
+ accept: string | undefined;
298
+ contentLength: number;
299
+ clientIp: string;
300
+ method: string;
301
+ protocol: string | undefined;
302
+ sessionDetails: NetaceaSessionDetails;
303
+ url: URL;
304
+ userAgent: string;
305
+ contentType: string | undefined;
306
+ requestId: string;
307
+ xForwardedFor: string | undefined;
308
+ referer: string | undefined;
309
+ graphQL?: Record<string, string>;
310
+ fingerprints: {
311
+ headerFingerprint: string;
312
+ cookieFingerprint: string;
313
+ };
314
+ }
315
+
314
316
  type CloudflareConstructorArgs$1 = NetaceaBaseArgs & {
315
317
  cookieEncryptionKey?: string;
316
318
  enableDynamicCaptchaContentType?: boolean | string;
@@ -397,6 +399,7 @@ declare class Cloudflare {
397
399
  protected readonly config: CloudflareConfig;
398
400
  protected readonly kinesis?: WebStandardKinesis;
399
401
  private readonly requestAnalyser;
402
+ private readonly cookieFactory;
400
403
  private workerInstanceId;
401
404
  constructor(args: CloudflareConstructorArgs);
402
405
  /**
@@ -438,7 +441,7 @@ declare class Cloudflare {
438
441
  private getNetaceaCookieFromResponse;
439
442
  private getNetaceaCookieFromRequest;
440
443
  protected check(requestDetails: NetaceaRequestDetails, captchaPageContentType: string): Promise<ComposeResultResponse>;
441
- protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined): Promise<string>;
444
+ protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined, issueReason?: NetaceaCookieV3IssueReason): Promise<string>;
442
445
  private processCaptcha;
443
446
  private getMitataCaptchaFromHeaders;
444
447
  private parseCaptchaAPICallBody;
@@ -450,7 +453,7 @@ declare class Cloudflare {
450
453
  requestDetails: NetaceaRequestDetails;
451
454
  body?: MakeRequestBody;
452
455
  }): Promise<ComposeResultResponse>;
453
- protected setIngestOnlyMitataCookie(userId: string): Promise<NetaceaResponseBase>;
456
+ protected setIngestOnlyMitataCookie(requestDetails: NetaceaRequestDetails): Promise<NetaceaResponseBase>;
454
457
  protected processIngest(requestDetails: NetaceaRequestDetails): Promise<NetaceaResponseBase>;
455
458
  }
456
459
 
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);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),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 h=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const o=d(e,"Domain"),s=d(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=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),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 C={cookie:{parse:m,attributes:g,netaceaSession:y}},S=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},I="x-netacea-mitatacaptcha-value",v="x-netacea-mitatacaptcha-expiry",w={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},b={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},N={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"},A={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},E={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},P="_/@#/",R="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),O=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function T(e){if(void 0===e)return;const t=e.match(O);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}}}}function _(e=16,t=R){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function x(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function M(e,i){const a=await x(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}var K;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(K||(K={}));var V,L="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},j={},D={},H={},q={};Object.defineProperty(q,"__esModule",{value:!0}),q.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"}(V||(q.NetaceaCookieV3IssueReason=V={}));var F={};Object.defineProperty(F,"__esModule",{value:!0}),F.netaceaCookieV3OptionalKeyMap=F.netaceaCookieV3KeyMap=F.COOKIEDELIMITER=void 0,F.COOKIEDELIMITER="_/@#/",F.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},F.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(H,"__esModule",{value:!0}),H.defaultInvalidResponse=H.matchNetaceaCookieV3=H.checkNetaceaCookieV3=H.objectIsNetaceaCookieV3=H.cookieIsNetaceaV3Format=H.createNetaceaCookieV3=void 0;const B=q,$=F;function U(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($.netaceaCookieV3KeyMap).find((e=>$.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys($.netaceaCookieV3OptionalKeyMap).find((e=>$.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 z(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:B.NetaceaCookieV3IssueReason.NO_SESSION}}H.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("&")},H.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)))},H.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},H.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return z();let i;try{i=U(e)}catch{return z()}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 z()},H.matchNetaceaCookieV3=U,H.defaultInvalidResponse=z;var G={};Object.defineProperty(G,"__esModule",{value:!0}),G.AbstractCookieFactory=void 0;const W=q,J=H,X=F,Q="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),Y=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;G.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,J.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??"",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,J.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,J.cookieIsNetaceaV3Format)(i)?(0,J.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(X.COOKIEDELIMITER);return`${await this.hash(s,a)}${X.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(Y);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,J.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,h=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(X.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(h,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=>Q[e%Q.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=H;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=G;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=F;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=q;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 he(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function de(e,t){for(const i of Object.keys(e)){if(!re(i))continue;const a=pe(he(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=he(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=de(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=de,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=L&&L.__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]}),ye=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),me=L&&L.__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 ye(t,e),t};Object.defineProperty(ee,"__esModule",{value:!0}),ee.setCookie=ee.cookie=void 0,ee.cookie=me(te),ee.setCookie=me(ne);var Ce={},Se={},ke={};Object.defineProperty(ke,"__esModule",{value:!0}),ke.KINESIS_URL=ke.API_VERSION=ke.REGION=ke.PAYLOAD_TYPE=ke.STATE=void 0,ke.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ke.PAYLOAD_TYPE="string",ke.REGION="eu-west-1",ke.API_VERSION="2013-12-02",ke.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.headersToRecord=Ie.increaseBatchSize=Ie.handleFailedLogs=Ie.batchArrayForKinesis=Ie.sleep=void 0,Ie.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ie.batchArrayForKinesis=function(e,t,i){const a=[];for(let 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},Ie.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},Ie.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ie.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Se,"__esModule",{value:!0}),Se.WebStandardKinesis=void 0;const ve=ke,we=Ie;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,we.headersToRecord)(i.headers),host:ve.KINESIS_URL,method:"POST",path:"/",body:i.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}}async signRequest(e,t,i,a){const o={Records:(0,we.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ve.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.Kinesis=void 0;const Ne=ke,Ae=Ie;be.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Ae.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ae.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ae.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ae.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,Ae.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:Ne.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=be;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Ce);var Ee={};function Pe(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.parseHttpHeaderName=Ee.stringOrDefault=Ee.parseIntOrDefault=Ee.parseNumberOrDefault=void 0,Ee.parseNumberOrDefault=Pe,Ee.parseIntOrDefault=function(e,t){const i=Pe(e,t);return"number"==typeof i?Math.floor(i):i},Ee.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Ee.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var Re={};Object.defineProperty(Re,"__esModule",{value:!0}),Re.searchParamsFromRecord=void 0,Re.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Oe={},Te={};Object.defineProperty(Te,"__esModule",{value:!0}),Te.JweFactory=void 0;Te.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 _e=L&&L.__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]}),xe=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Me=L&&L.__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)&&_e(t,e,i);return xe(t,e),t};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.jwe=void 0,Oe.jwe=Me(Te);var Ke,Ve={};var Le={};Object.defineProperty(Le,"__esModule",{value:!0}),Le.ProtectorApiResponseView=Le.AbstractProtectorApiResponseView=void 0;const je=Ee;class De{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,je.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,je.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,je.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)}}Le.AbstractProtectorApiResponseView=De;var He;function qe(){return He||(He=1,function(e){var t=L&&L.__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=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=L&&L.__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=L&&L.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=void 0,e.cookie=a(D),e.configValidation=a(Z),e.headers=a(ee),e.ingest=a(Ce),e.parsing=a(Ee),e.url=a(Re),e.webcrypto=a(Oe),e.graphql=a(function(){if(Ke)return Ve;Ke=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.truncateLongFields=Ve.parseGraphQl=Ve.parseGraphQlRequestBody=Ve.getGraphQLParserConfig=void 0;const e=qe();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}return Ve.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Ve.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const o=JSON.parse(a);if("object"!=typeof o)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,o?.query??"")},n=(o?.operationName??"").trim();return""!==n&&(s.OpName=n),i(e,s)},Ve.parseGraphQl=t,Ve.truncateLongFields=i,Ve}()),o(Le,e)}(j)),j}Le.ProtectorApiResponseView=class extends De{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var Fe=qe();const Be=new Fe.webcrypto.jwe.JweFactory(c);function $e(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 Ue(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function ze(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function Ge(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 We(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 Je(e){if(void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");return Qe(e,e.config.netaceaBlockedResponseRedirectLocation)}return Xe(e)}function Xe(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Qe(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}function Ye(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}class Ze extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var et="@netacea/cloudflare",tt="6.5.2";const it="unknown";function at(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=w[a]??it+"_";n+=b[o]??it;let r=A[o];if("0"!==s){n+=","+(N[s]??it);const e=E[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function ot(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 st(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}async function nt(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const o=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new rt("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");o.push(s)}const s=new Uint8Array(a);let n=0;for(const e of o)s.set(e,n),n+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:Fe.graphql.parseGraphQlRequestBody(e,a)}}class rt extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class ct{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.netaceaCookieName),o=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",n=e.headers.get("cf-ray")??"",r=Fe.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=await async function(e,t,i,a,o){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const o=T(e);if(void 0!==o){const e=[o.expiry,o.userId,o.ipHash,o.mitigationType].join(P),a=Math.floor(Date.now()/1e3),s=parseInt(o.expiry)<a,n=["1","3","5","a","c","e"].includes(o.protectorCheckCodes.captcha),r="3"===o.protectorCheckCodes.mitigate,c=n||r,u=await M(t+"|"+o.expiry,i),h=o.ipHash===u,d=o.signature===await M(e,i);return{userId:o.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,protectorCheckCodes:o.protectorCheckCodes}}return a}(a,o,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:o,shouldExpire:n,isSameIP:r}=s,c=o||n||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?K.RENEW_SESSION:K.EXISTING_SESSION,{sessionStatus:u}=at(e.mitigationType,s.protectorCheckCodes,ze(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:s,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:_(),sessionCookieStatus:K.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await ut(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:n,sessionDetails:{captchaToken:o,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await nt(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof rt){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),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 Be.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ut(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 st(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,o=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 st(t)}(o);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:ht}=Fe.configValidation,{configureCookiesDomain:dt}=C.cookie.attributes;class pt{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:o=1e3,mitigationServiceUrl:n="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:C,netaceaCaptchaVerificationPath:S,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=n.endsWith("/")?n.slice(0,-1):n,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Fe.parsing.parseIntOrDefault(o,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Fe.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Fe.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:I,captchaCookieAttributes:v}=dt(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var w;this.netaceaCookieAttributes=I??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(w=S)&&w.startsWith("/")&&w.length>=5?w:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=ht(e.netaceaBlockedResponseRedirectLocation),this.graphQL=Fe.graphql.getGraphQLParserConfig(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new pt(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Fe.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 ct(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let 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,a,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=ze(t.url,e.method,this.config.netaceaCaptchaVerificationPath),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&Ue(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};return i.mitigated&&!o?"captcha"===i.mitigation?{...i,response:Ye({config:this.config,responseHeaders:n(),body:i.body})}:{...i,response:Je({config:this.config,request:e,responseHeaders:n()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Xe({status:402,responseHeaders:n()})}:{...i,response:Qe({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}=T(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=at(this.config.mitigationType,a,ze(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:o,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),o=function(e,t,i,a){const o=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,n=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=Fe.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:et?.replace("@netacea/","")??"",IntegrationVersion:tt,NetaceaMitigationApplied:o??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${n} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...o,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(o)),t=await this.makeRequest(e);if(200!==t.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match: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}}}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,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",et.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",tt),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const o=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:Ge(o,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?$e(e.headers.get("Accept")??void 0):$e();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Ze&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:ze(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:ot({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 Be.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 check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([K.NEW_SESSION,K.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),{responseView:o}=a,s=o.getProtectorCodes(),{match:n,mitigate:r,captcha:c}=s,u=[await this.createMitata(e.clientIp,i,n,r,c,a.mitataMaxAge)],h={match:n,mitigate:r,captcha:c},d=at(this.config.mitigationType,h,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:u,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[k.block,k.captcha].includes(d.mitigation),redirect:"5"===r?o.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(p.injectHeaders=ot(d.parts,a.eventId)),p}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=at(this.config.mitigationType,i,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[k.block,k.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(o.injectHeaders=ot(a.parts)),o}}async createMitata(e,t,i,a,o,s=86400,n=void 0){const r=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,c=n??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,o].join("");let h=await async function(e,t,i,a,o="000"){const s=[i,t,await M(e+"|"+String(i),a),o].join(P);return`${await M(s,a)}${P}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await Be.encrypt(h,this.config.cookieEncryptionKey,"A256GCM")),C.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},h=at(this.config.mitigationType,u,!0),d={body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[k.block,k.captcha].includes(h.mitigation),redirect:void 0,protectorCheckCodes:{match:h.parts.match.toString(),mitigate:h.parts.mitigate.toString(),captcha:h.parts.captcha.toString()}};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(d.injectHeaders=ot(h.parts)),d}async getMitataCaptchaFromHeaders(e){let t=e[I];const i=parseInt(e[v]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Be.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),C.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!==K.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=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",n=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:n,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new Ze(c,u);const h=new Fe.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=h.sessionCookieMaxAge,f=e.sessionDetails.userId,y=await this.getMitataCaptchaFromHeaders(c.headers),m=[await this.createMitata(e.clientIp,f,d,p,l,g),y].filter((e=>void 0!==e)),C=h.eventId,S="5"===p?h.getMonetisationRedirect(e.url.pathname,e.url.search):void 0;return{status:c.status,match:d,mitigate:p,captcha:l,setCookie:m,body:c.body,eventId:C,mitataMaxAge:g,latency:u,redirect:S}}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:We({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==K.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 Ze(c,u);const h=new Fe.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,d,p,l,h.sessionCookieMaxAge),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),f=h.eventId;if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await h.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:h,status:c.status,setCookie:g,body:c.body,eventId:f,mitataMaxAge:h.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(Ue(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(ze(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===K.NEW_SESSION,a=t===K.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function 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);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),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 h=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const o=d(e,"Domain"),s=d(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=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),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 C={cookie:{parse:m,attributes:g,netaceaSession:y}},k=globalThis.fetch.bind(globalThis),S={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},I="x-netacea-mitatacaptcha-value",v="x-netacea-mitatacaptcha-expiry",w={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},b={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},N={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"},E={0:S.none,1:S.block,2:S.none,3:S.block,4:S.block},A={1:S.captcha,2:S.captchaPass,3:S.captcha,4:S.allow,5:S.captcha,6:S.allow,7:S.captcha,a:S.captcha,b:S.captchaPass,c:S.captcha,d:S.allow,e:S.captcha},R="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),P=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function O(e=16,t=R){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function _(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 T,x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},M={},K={};Object.defineProperty(K,"__esModule",{value:!0}),K.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"}(T||(K.NetaceaCookieV3IssueReason=T={}));var V={},L={},j={};Object.defineProperty(j,"__esModule",{value:!0}),j.netaceaCookieV3OptionalKeyMap=j.netaceaCookieV3KeyMap=j.COOKIEDELIMITER=void 0,j.COOKIEDELIMITER="_/@#/",j.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},j.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(L,"__esModule",{value:!0}),L.defaultInvalidResponse=L.matchNetaceaCookieV3=L.checkNetaceaCookieV3=L.objectIsNetaceaCookieV3=L.cookieIsNetaceaV3Format=L.createNetaceaCookieV3=void 0;const D=K,H=j;function F(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(H.netaceaCookieV3KeyMap).find((e=>H.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(H.netaceaCookieV3OptionalKeyMap).find((e=>H.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 q(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:D.NetaceaCookieV3IssueReason.NO_SESSION}}L.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in H.netaceaCookieV3OptionalKeyMap?`${H.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${H.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},L.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(H.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(H.netaceaCookieV3KeyMap).includes(e)))},L.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(H.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},L.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return q();let i;try{i=F(e)}catch{return q()}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 q()},L.matchNetaceaCookieV3=F,L.defaultInvalidResponse=q;var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.AbstractCookieFactory=void 0;const $=K,U=L,G=j,z="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),W=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;B.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,U.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??"",match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??$.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,U.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,U.cookieIsNetaceaV3Format)(i)?(0,U.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(G.COOKIEDELIMITER);return`${await this.hash(s,a)}${G.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(W);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,U.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,h=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(G.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(h,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:$.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>z[e%z.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=L;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=B;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=j;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=K;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(V);var J={};Object.defineProperty(J,"__esModule",{value:!0}),J.validateRedirectLocation=void 0,J.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 X={},Q={};function Y(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=ee("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function Z(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(...te(s,t))}return i}function ee(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function te(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Q,"__esModule",{value:!0}),Q.findAllInCookieString=Q.findFirstInCookieString=Q.findAllInHeaders=Q.findFirstInHeaders=Q.findOnlyValueInHeaders=Q.findAllValuesInHeaders=Q.findFirstValueInHeaders=void 0,Q.findFirstValueInHeaders=function(e,t){const i=Y(e,t);if(void 0!==i)return i.slice(t.length+1)},Q.findAllValuesInHeaders=function(e,t){return Z(e,t).map((e=>e.slice(t.length+1)))},Q.findOnlyValueInHeaders=function(e,t){const i=Z(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Q.findFirstInHeaders=Y,Q.findAllInHeaders=Z,Q.findFirstInCookieString=ee,Q.findAllInCookieString=te;var ie={};function ae(e){return"set-cookie"===e||"Set-Cookie"===e}function oe(e,t){const i=t+"=";return e.startsWith(i)}function se(e,t){if(!oe(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function ne(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function re(e,t){for(const i of Object.keys(e)){if(!ae(i))continue;const a=ce(ne(e,i),t);if(void 0!==a)return a}}function ce(e,t){return e.map((e=>e.trimStart())).find((e=>oe(e,t)))}function ue(e,t){const i=[];for(const a of Object.keys(e)){if(!ae(a))continue;const o=ne(e,a);i.push(...he(o,t))}return i}function he(e,t){return e.map((e=>e.trimStart())).filter((e=>oe(e,t)))}Object.defineProperty(ie,"__esModule",{value:!0}),ie.findAllInSetCookieStrings=ie.findAllInHeaders=ie.findValueInSetCookieStrings=ie.findFirstInSetCookieStrings=ie.findFirstInHeaders=ie.findOnlyValueInHeaders=ie.findFirstValueInHeaders=ie.parseValueFromString=void 0,ie.parseValueFromString=se,ie.findFirstValueInHeaders=function(e,t){const i=re(e,t);return void 0!==i?se(i,t):void 0},ie.findOnlyValueInHeaders=function(e,t){const i=ue(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?se(i[0],t):void 0},ie.findFirstInHeaders=re,ie.findFirstInSetCookieStrings=ce,ie.findValueInSetCookieStrings=function(e,t){const i=ce(e,t);if(void 0!==i)return se(i,t)},ie.findAllInHeaders=ue,ie.findAllInSetCookieStrings=he;var de=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]}),pe=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),le=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)&&de(t,e,i);return pe(t,e),t};Object.defineProperty(X,"__esModule",{value:!0}),X.setCookie=X.cookie=void 0,X.cookie=le(Q),X.setCookie=le(ie);var ge={},fe={},ye={};Object.defineProperty(ye,"__esModule",{value:!0}),ye.KINESIS_URL=ye.API_VERSION=ye.REGION=ye.PAYLOAD_TYPE=ye.STATE=void 0,ye.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ye.PAYLOAD_TYPE="string",ye.REGION="eu-west-1",ye.API_VERSION="2013-12-02",ye.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var me={};Object.defineProperty(me,"__esModule",{value:!0}),me.headersToRecord=me.increaseBatchSize=me.handleFailedLogs=me.batchArrayForKinesis=me.sleep=void 0,me.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},me.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},me.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},me.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},me.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(fe,"__esModule",{value:!0}),fe.WebStandardKinesis=void 0;const Ce=ye,ke=me;fe.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,ke.headersToRecord)(i.headers),host:Ce.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,ke.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,ke.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,ke.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,ke.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,ke.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Ce.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Se={};Object.defineProperty(Se,"__esModule",{value:!0}),Se.Kinesis=void 0;const Ie=ye,ve=me;Se.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,ve.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,ve.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,ve.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,ve.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,ve.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:Ie.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=fe;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Se;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ge);var we={};function be(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(we,"__esModule",{value:!0}),we.parseHttpHeaderName=we.stringOrDefault=we.parseIntOrDefault=we.parseNumberOrDefault=void 0,we.parseNumberOrDefault=be,we.parseIntOrDefault=function(e,t){const i=be(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};var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.searchParamsFromRecord=void 0,Ne.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Ee={},Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.JweFactory=void 0;Ae.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]}),Pe=x&&x.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Oe=x&&x.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Re(t,e,i);return Pe(t,e),t};Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.jwe=void 0,Ee.jwe=Oe(Ae);var _e,Te={};var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.ProtectorApiResponseView=xe.AbstractProtectorApiResponseView=void 0;const Me=we;class Ke{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,Me.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,Me.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,Me.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)}}xe.AbstractProtectorApiResponseView=Ke;var Ve;function Le(){return Ve||(Ve=1,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.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=void 0;var s=K;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return s.NetaceaCookieV3IssueReason}}),e.cookie=a(V),e.configValidation=a(J),e.headers=a(X),e.ingest=a(ge),e.parsing=a(we),e.url=a(Ne),e.webcrypto=a(Ee),e.graphql=a(function(){if(_e)return Te;_e=1,Object.defineProperty(Te,"__esModule",{value:!0}),Te.truncateLongFields=Te.parseGraphQl=Te.parseGraphQlRequestBody=Te.getGraphQLParserConfig=void 0;const e=Le();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}return Te.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Te.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const o=JSON.parse(a);if("object"!=typeof o)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,o?.query??"")},n=(o?.operationName??"").trim();return""!==n&&(s.OpName=n),i(e,s)},Te.parseGraphQl=t,Te.truncateLongFields=i,Te}()),o(xe,e)}(M)),M}xe.ProtectorApiResponseView=class extends Ke{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var je=Le();const De=new je.webcrypto.jwe.JweFactory(c);class He extends je.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.encrypt called without a configured encryption key");return await De.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("CloudflareCookieFactory.decrypt called without a configured encryption key");return await De.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await _(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 Fe;function qe(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 Be(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a}=e;return a===i&&"get"===t.toLowerCase()}function $e(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function Ue(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 Ge(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 ze(e){if(void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");return Je(e,e.config.netaceaBlockedResponseRedirectLocation)}return We(e)}function We(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Je(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}function Xe(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Fe||(Fe={}));class Qe extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var Ye="@netacea/cloudflare",Ze="6.6.0";const et="unknown";function tt(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=w[a]??et+"_";n+=b[o]??et;let r=E[o];if("0"!==s){n+=","+(N[s]??et);const e=A[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=S.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function it(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 at(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}async function ot(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const o=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new st("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");o.push(s)}const s=new Uint8Array(a);let n=0;for(const e of o)s.set(e,n),n+=e.length;return(new TextDecoder).decode(s)}(e,i);return{contentLength:a.length,graphQL:je.graphql.parseGraphQlRequestBody(e,a)}}class st extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class nt{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.netaceaCookieName),o=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",n=e.headers.get("cf-ray")??"",r=je.parsing.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=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?Fe.RENEW_SESSION:Fe.EXISTING_SESSION,{sessionStatus:u}=tt(e.mitigationType,n.protectorCheckCodes,$e(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:n,sessionCookieStatus:c,sessionStatus:u,userId:a}}return{sessionStatus:"",userId:O(),sessionCookieStatus:Fe.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),p={contentLength:r,clientIp:s,fingerprints:await rt(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:n,sessionDetails:{captchaToken:o,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}};try{if(function(e,t){const i=e.includePaths;return t.contentLength<=e.maxParsableBytes&&i.includes(t.url.pathname)&&"POST"===t.method&&void 0!==t.accept&&t.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===t.contentType}(this.config.graphQL,p)){const{contentLength:t,graphQL:i}=await ot(this.config.graphQL,e);p.contentLength=t,p.graphQL=i}}catch(e){if(e instanceof st){const t=e.bodySize;t>p.contentLength&&(p.contentLength=t)}}return p}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),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 De.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function rt(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 at(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,o=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 at(t)}(o);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:ct}=je.configValidation,{configureCookiesDomain:ut}=C.cookie.attributes;class ht{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:o=1e3,mitigationServiceUrl:n="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:C,netaceaCaptchaVerificationPath:k,netaceaCheckpointSignalPath:S}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=n.endsWith("/")?n.slice(0,-1):n,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===u&&void 0===d||(this.captchaSiteKey=u,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=je.parsing.parseIntOrDefault(o,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=je.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=je.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:I,captchaCookieAttributes:v}=ut(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var w;this.netaceaCookieAttributes=I??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(w=k)&&w.startsWith("/")&&w.length>=5?w:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=S,this.netaceaBlockedResponseRedirectLocation=ct(e.netaceaBlockedResponseRedirectLocation),this.graphQL=je.graphql.getGraphQLParserConfig(e.graphQL)}}function dt(e){if(void 0===e.sessionDetails.sessionCookieDetails)return je.NetaceaCookieV3IssueReason.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?je.NetaceaCookieV3IssueReason.EXPIRED_SESSION:je.NetaceaCookieV3IssueReason.UNKNOWN:je.NetaceaCookieV3IssueReason.IP_CHANGE}exports.default=class{config;kinesis;requestAnalyser;cookieFactory;workerInstanceId;constructor(i){this.config=new ht(i),this.cookieFactory=new He({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new je.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 nt({...this.config,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let 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,a,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=$e(t.url,e.method,this.config.netaceaCaptchaVerificationPath),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&Be(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};return i.mitigated&&!o?"captcha"===i.mitigation?{...i,response:Xe({config:this.config,responseHeaders:n(),body:i.body})}:{...i,response:ze({config:this.config,request:e,responseHeaders:n()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:We({status:402,responseHeaders:n()})}:{...i,response:Je({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(P);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}=tt(this.config.mitigationType,a,$e(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:o,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),o=function(e,t,i,a){const o=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,n=t.method,r=t.url.pathname,c=t.protocol??null,u=Date.now(),h=t.referer??"",d=je.parsing.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:Ye?.replace("@netacea/","")??"",IntegrationVersion:Ze,NetaceaMitigationApplied:o??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===h?"-":h,Request:`${n} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(u).toUTCString(),TimeUnixMsUTC:u,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...o,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(o)),t=await this.makeRequest(e);if(200!==t.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match: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}}}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 k(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,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",Ye.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Ze),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const o=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:Ue(o,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?qe(e.headers.get("Accept")??void 0):qe();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Qe&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:$e(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:it({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 De.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 check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Fe.NEW_SESSION,Fe.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),{responseView:o}=a,s=o.getProtectorCodes(),{match:n,mitigate:r,captcha:c}=s,u=[await this.createMitata(e.clientIp,i,n,r,c,a.mitataMaxAge,void 0,dt(e))],h={match:n,mitigate:r,captcha:c},d=tt(this.config.mitigationType,h,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:u,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[S.block,S.captcha].includes(d.mitigation),redirect:"5"===r?o.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(p.injectHeaders=it(d.parts,a.eventId)),p}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=tt(this.config.mitigationType,i,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[S.block,S.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(o.injectHeaders=it(a.parts)),o}}async createMitata(e,t,i,a,o,s=86400,n=void 0,r=je.NetaceaCookieV3IssueReason.NO_SESSION){const c=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,u=void 0!==n?n-Math.floor(Date.now()/1e3):c,h=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:u,cookieId:"",issueReason:r});return C.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},h=tt(this.config.mitigationType,u,!0),d={body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[S.block,S.captcha].includes(h.mitigation),redirect:void 0,protectorCheckCodes:{match:h.parts.match.toString(),mitigate:h.parts.mitigate.toString(),captcha:h.parts.captcha.toString()}};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(d.injectHeaders=it(h.parts)),d}async getMitataCaptchaFromHeaders(e){let t=e[I];const i=parseInt(e[v]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await De.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),C.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!==Fe.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=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",n=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:n,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new Qe(c,u);const h=new je.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=h.sessionCookieMaxAge,f=e.sessionDetails.userId,y=await this.getMitataCaptchaFromHeaders(c.headers),m=[await this.createMitata(e.clientIp,f,d,p,l,g,void 0,dt(e)),y].filter((e=>void 0!==e)),C=h.eventId,k="5"===p?h.getMonetisationRedirect(e.url.pathname,e.url.search):void 0;return{status:c.status,match:d,mitigate:p,captcha:l,setCookie:m,body:c.body,eventId:C,mitataMaxAge:g,latency:u,redirect:k}}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:Ge({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Fe.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 Qe(c,u);const h=new je.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,d,p,l,h.sessionCookieMaxAge,void 0,dt(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),f=h.eventId;if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await h.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:h,status:c.status,setCookie:g,body:c.body,eventId:f,mitataMaxAge:h.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(Be(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($e(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e.sessionDetails.userId,"0","0","0",86400,void 0,dt(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===Fe.NEW_SESSION,a=t===Fe.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "6.5.2",
3
+ "version": "6.6.0",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -23,5 +23,5 @@
23
23
  "jose": "^4.15.9",
24
24
  "uuid": "^10.0.0"
25
25
  },
26
- "gitHead": "d6fd3ad9004db93c213dc1e0058ba158643e432f"
26
+ "gitHead": "8e3b1e703719929d092e8915a79f2ae516be60cb"
27
27
  }