@netacea/cloudflare 6.0.71 → 6.0.72

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
@@ -162,81 +162,6 @@ interface InjectHeaders {
162
162
  'x-netacea-captcha': string;
163
163
  'x-netacea-event-id'?: string;
164
164
  }
165
- interface IngestArgs {
166
- /**
167
- * Client IP Address
168
- */
169
- ip: string;
170
- /**
171
- * Client User-Agent header value
172
- */
173
- userAgent: string;
174
- /**
175
- * Response status code
176
- * Should be 403 if Netacea mitigated
177
- */
178
- status: string;
179
- /**
180
- * Request method
181
- */
182
- method: string;
183
- /**
184
- * Request path
185
- */
186
- path: string;
187
- /**
188
- * Request protocol
189
- */
190
- protocol: string | null;
191
- /**
192
- * Request referer header value
193
- */
194
- referer: string;
195
- /**
196
- * Request content-length header, or body size
197
- */
198
- bytesSent: string | number;
199
- /**
200
- * The time the request was started, in unix milliseconds format.
201
- */
202
- timeUnixMsUTC?: number;
203
- /**
204
- * Time taken to serve request
205
- */
206
- requestTime: string | number;
207
- /**
208
- * Netacea mitata cookie value.
209
- * Should be request's cookie value if Netacea was not called.
210
- */
211
- mitataCookie?: string;
212
- /**
213
- * Session status from `ComposeResultResponse`
214
- */
215
- sessionStatus?: string;
216
- /**
217
- * Type of the integration, for example "Cloudflare" or "Cloudfront"
218
- */
219
- integrationType?: string;
220
- /**
221
- * SEMVER string indicating the version of the integration
222
- * Example: 1.2.3
223
- */
224
- integrationVersion?: string;
225
- /**
226
- * IP values set by a CDN under "x-forwarded-for" header
227
- */
228
- cookieFingerprint?: string;
229
- headerFingerprint?: string;
230
- integrationMode?: string;
231
- ipHeader?: string;
232
- mitigationLatency?: number;
233
- mitigationStatus?: number;
234
- netaceaCookieStatus?: number;
235
- requestHost?: string;
236
- requestId?: string;
237
- workerInstanceId?: string;
238
- xForwardedFor?: string;
239
- }
240
165
  interface NetaceaResponseBase {
241
166
  /**
242
167
  * Cookies that should be set back to the user.
@@ -273,10 +198,11 @@ interface InjectResponse<T = any> extends MitigateResponse<T> {
273
198
  type NetaceaMitigationResponse<T> = MitigateResponse<T> | InjectResponse<T> | undefined;
274
199
 
275
200
  interface NetaceaCloudflareResult {
276
- response: Response;
277
- sessionStatus: string;
278
201
  protectorLatencyMs?: number;
279
202
  protectorStatus?: number;
203
+ requestDetails: NetaceaRequestDetails;
204
+ response: Response;
205
+ sessionStatus: string;
280
206
  }
281
207
  interface NetaceaSessionCookieDetails {
282
208
  userId: string | undefined;
@@ -300,12 +226,15 @@ interface ProtectorCheckCodes {
300
226
  }
301
227
  interface NetaceaSessionDetails {
302
228
  captchaToken: string | undefined;
303
- sessionStatus: string;
229
+ sessionCookie: string | undefined;
304
230
  sessionCookieDetails: NetaceaSessionCookieDetails | undefined;
305
231
  sessionCookieStatus: NetaceaSessionCookieStatus;
232
+ sessionStatus: string;
306
233
  userId: string;
307
234
  }
308
235
  interface NetaceaRequestDetails {
236
+ accept: string | undefined;
237
+ contentLength: number;
309
238
  clientIp: string;
310
239
  method: string;
311
240
  protocol: string | undefined;
@@ -314,6 +243,9 @@ interface NetaceaRequestDetails {
314
243
  userAgent: string;
315
244
  contentType: string | undefined;
316
245
  requestId: string;
246
+ xForwardedFor: string | undefined;
247
+ referer: string | undefined;
248
+ graphQL?: Record<string, string>;
317
249
  fingerprints: {
318
250
  headerFingerprint: string;
319
251
  cookieFingerprint: string;
@@ -331,36 +263,50 @@ type CloudflareConstructorArgs$1 = NetaceaBaseArgs & {
331
263
  mitigationServiceTimeoutMs?: number | string;
332
264
  netaceaCheckpointSignalPath?: string;
333
265
  netaceaBlockedResponseRedirectLocation?: string;
266
+ graphQL?: GraphQLParserArgs;
334
267
  };
335
268
  interface CustomHeader$1 {
336
269
  name: string;
337
270
  value: string;
338
271
  }
272
+ interface GraphQLParserConfig {
273
+ includePaths: string[];
274
+ parserRegex: RegExp;
275
+ maxParsableBytes: number;
276
+ maxValueLength: number;
277
+ }
278
+ interface GraphQLParserArgs extends Omit<GraphQLParserConfig, 'parserRegex'> {
279
+ parserRegex: RegExp | {
280
+ regex: string;
281
+ flags: string;
282
+ };
283
+ }
339
284
  declare class CloudflareConfig {
340
- readonly mitataCookieExpirySeconds: number;
341
285
  readonly apiKey: string;
342
- readonly secretKey: string;
343
- readonly mitigationServiceUrl: string;
286
+ readonly captchaHeader: CustomHeader$1 | undefined;
287
+ readonly captchaSecretKey?: string;
288
+ readonly captchaSiteKey?: string;
289
+ readonly cookieEncryptionKey: string | undefined;
290
+ readonly enableDynamicCaptchaContentType: boolean;
291
+ readonly encryptedCookies: string[];
292
+ readonly graphQL: GraphQLParserConfig;
344
293
  readonly ingestServiceUrl: string;
294
+ readonly ingestType: NetaceaIngestType;
345
295
  readonly kinesisConfigArgs?: KinesisIngestConfigArgs;
346
- readonly timeout: number;
296
+ readonly mitataCookieExpirySeconds: number;
347
297
  readonly mitigationServiceTimeoutMs: number;
348
- readonly captchaSiteKey?: string;
349
- readonly captchaSecretKey?: string;
350
- readonly ingestType: NetaceaIngestType;
298
+ readonly mitigationServiceUrl: string;
351
299
  readonly mitigationType: NetaceaMitigationType;
352
- readonly encryptedCookies: string[];
353
- readonly netaceaCookieName: string;
300
+ readonly netaceaBlockedResponseRedirectLocation?: string;
301
+ readonly netaceaCaptchaCookieAttributes: string;
354
302
  readonly netaceaCaptchaCookieName: string;
355
- readonly cookieEncryptionKey: string | undefined;
356
- readonly enableDynamicCaptchaContentType: boolean;
357
303
  readonly netaceaCaptchaPath: string | undefined;
304
+ readonly netaceaCaptchaVerificationPath: string;
358
305
  readonly netaceaCheckpointSignalPath?: string;
359
- readonly captchaHeader: CustomHeader$1 | undefined;
360
306
  readonly netaceaCookieAttributes: string;
361
- readonly netaceaCaptchaCookieAttributes: string;
362
- readonly netaceaCaptchaVerificationPath: string;
363
- readonly netaceaBlockedResponseRedirectLocation?: string;
307
+ readonly netaceaCookieName: string;
308
+ readonly secretKey: string;
309
+ readonly timeout: number;
364
310
  constructor(args: CloudflareConstructorArgs$1);
365
311
  }
366
312
 
@@ -481,8 +427,6 @@ declare class Cloudflare {
481
427
  protected readCookie(cookieName: string, cookies: string | string[] | null | undefined): Promise<string | undefined>;
482
428
  private getNetaceaCookieFromResponse;
483
429
  private getNetaceaCookieFromRequest;
484
- protected callIngest(args: IngestArgs): Promise<void>;
485
- private makeIngestApiCall;
486
430
  protected check(requestDetails: NetaceaRequestDetails, captchaPageContentType: string): Promise<ComposeResultResponse>;
487
431
  protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined): Promise<string>;
488
432
  private processCaptcha;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),h=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const u=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const n=d(e,"Domain"),s=d(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}};var C="@netacea/cloudflare",k="6.0.71";const w=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",b="x-netacea-mitigate",N="x-netacea-captcha",A="x-netacea-mitata-expiry",T="x-netacea-mitatacaptcha-value",_="x-netacea-mitatacaptcha-expiry",E="x-netacea-event-id",P={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},x={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},R={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"},O={0:I.none,1:I.block,2:I.none,3:I.block,4:I.block},K={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha,6:I.allow,7:I.captcha,a:I.captcha,b:I.captchaPass,c:I.captcha,d:I.allow,e:I.captcha},M="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),L=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function j(e){if(void 0===e)return;const t=e.match(L);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function q(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function H(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await H(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var B;async function U(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function V(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function $(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 z(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 G(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function W(e){return void 0!==e&&e.startsWith("/")&&e.length>=5?e:"/AtaVerifyCaptcha"}function J(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function Y(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}function Q(e){return void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)?function(e){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");const t=new Headers(e.responseHeaders);return t.append("Location",e.config.netaceaBlockedResponseRedirectLocation),new Response("Forbidden",{status:303,statusText:"",headers:t})}(e):function(e){return new Response("Forbidden",{status:403,statusText:"Forbidden",headers:e.responseHeaders})}(e)}function Z(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(B||(B={}));class ee extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function te(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:n,integrationVersion:s,ip:o,method:r,mitataCookie:c,mitigationLatency:h,mitigationStatus:u,netaceaCookieStatus:d,path:p,protocol:l,referer:g,requestHost:f,requestId:y,timeUnixMsUTC:m,requestTime:S,sessionStatus:C,status:k,userAgent:w,workerInstanceId:I,xForwardedFor:v}){return{Request:`${r} ${p} ${l}`,TimeLocal:new Date(m??Date.now()).toUTCString(),TimeUnixMsUTC:m,RealIp:o,UserAgent:w,Status:k,RequestTime:S?.toString(),BytesSent:e?.toString(),Referer:""===g?"-":g,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:C??"",ProtectorLatencyMs:h,ProtectorStatus:u,IntegrationType:n??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:f,RequestId:y,XForwardedFor:v,WorkerInstanceId:I,NetaceaUserIdCookieStatus:d,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const ie="unknown";function ae(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let o=P[a]??ie+"_";o+=x[n]??ie;let r=O[n];if("0"!==s){o+=","+(R[s]??ie);const e=K[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function ne(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class se{config;constructor(e){this.config=e,this.config.captchaVerificationPath=W(e.captchaVerificationPath)}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",{sessionCookieDetails:r,sessionCookieStatus:c,sessionStatus:h,userId:u}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=j(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(M),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5","a","c","e"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,h=await F(t+"|"+n.expiry,i),u=n.ipHash===h,d=n.signature===await F(e,i);return{userId:n.userId,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:d,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?B.RENEW_SESSION:B.EXISTING_SESSION,{sessionStatus:h}=ae(e.mitigationType,s.protectorCheckCodes,G(t,i,e.captchaVerificationPath));return{userId:a,sessionCookieStatus:c,sessionStatus:h,sessionCookieDetails:s}}return{sessionStatus:"",userId:q(),sessionCookieStatus:B.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await oe(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,requestId:o,sessionDetails:{sessionStatus:h,captchaToken:n,sessionCookieDetails:r,sessionCookieStatus:c,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await V(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function oe(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 ne(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await ne(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}var re="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ce={},he={},ue={},de=re&&re.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),pe=re&&re.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),le=re&&re.__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(ue,"__esModule",{value:!0}),ue.isJweEncrypted=ue.decrypt=ue.encrypt=void 0;const ge=le(i);ue.encrypt=async function(e,t){const i=ge.base64url.decode(t),a=(new TextEncoder).encode(e);return await new ge.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ue.decrypt=async function(e,t){const i=ge.base64url.decode(t),{plaintext:a}=await ge.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ue.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var fe=re&&re.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ye=re&&re.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),me=re&&re.__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(he,"__esModule",{value:!0}),he.jwe=void 0,he.jwe=me(ue);var Se={},Ce={};function ke(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=Ie("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function we(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...ve(s,t))}return i}function Ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ve(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.findAllInCookieString=Ce.findFirstInCookieString=Ce.findAllInHeaders=Ce.findFirstInHeaders=Ce.findOnlyValueInHeaders=Ce.findAllValuesInHeaders=Ce.findFirstValueInHeaders=void 0,Ce.findFirstValueInHeaders=function(e,t){const i=ke(e,t);if(void 0!==i)return i.slice(t.length+1)},Ce.findAllValuesInHeaders=function(e,t){return we(e,t).map((e=>e.slice(t.length+1)))},Ce.findOnlyValueInHeaders=function(e,t){const i=we(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Ce.findFirstInHeaders=ke,Ce.findAllInHeaders=we,Ce.findFirstInCookieString=Ie,Ce.findAllInCookieString=ve;var be={};function Ne(e){return"set-cookie"===e||"Set-Cookie"===e}function Ae(e,t){const i=t+"=";return e.startsWith(i)}function Te(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function _e(e,t){for(const i of Object.keys(e)){if(!Ne(i))continue;const a=Ee(Te(e,i),t);if(void 0!==a)return a}}function Ee(e,t){return e.map((e=>e.trimStart())).find((e=>Ae(e,t)))}function Pe(e,t){const i=[];for(const a of Object.keys(e)){if(!Ne(a))continue;const n=Te(e,a);i.push(...xe(n,t))}return i}function xe(e,t){return e.map((e=>e.trimStart())).filter((e=>Ae(e,t)))}Object.defineProperty(be,"__esModule",{value:!0}),be.findAllInSetCookieStrings=be.findAllInHeaders=be.findFirstInSetCookieStrings=be.findFirstInHeaders=be.findOnlyValueInHeaders=be.findFirstValueInHeaders=void 0,be.findFirstValueInHeaders=function(e,t){const i=_e(e,t);return i?.slice(t.length+1)?.split(";")[0]},be.findOnlyValueInHeaders=function(e,t){const i=Pe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},be.findFirstInHeaders=_e,be.findFirstInSetCookieStrings=Ee,be.findAllInHeaders=Pe,be.findAllInSetCookieStrings=xe;var Re=re&&re.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Oe=re&&re.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ke=re&&re.__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 Oe(t,e),t};Object.defineProperty(Se,"__esModule",{value:!0}),Se.setCookie=Se.cookie=void 0,Se.cookie=Ke(Ce),Se.setCookie=Ke(be);var Me={},De={},Le={};Object.defineProperty(Le,"__esModule",{value:!0}),Le.KINESIS_URL=Le.API_VERSION=Le.REGION=Le.PAYLOAD_TYPE=Le.STATE=void 0,Le.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Le.PAYLOAD_TYPE="string",Le.REGION="eu-west-1",Le.API_VERSION="2013-12-02",Le.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var je={};Object.defineProperty(je,"__esModule",{value:!0}),je.headersToRecord=je.increaseBatchSize=je.handleFailedLogs=je.batchArrayForKinesis=je.sleep=void 0,je.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},je.batchArrayForKinesis=function(e,t,i){const a=[];for(let n=0;n<e.length;n+=t){const s=e.slice(n,n+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},je.handleFailedLogs=function(e,t,i){const a=2*i,n=[...e,...t],s=n.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),n.splice(0,s)),n},je.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},je.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(De,"__esModule",{value:!0}),De.WebStandardKinesis=void 0;const qe=Le,He=je;De.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,He.headersToRecord)(i.headers),host:qe.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,He.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,He.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,He.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,He.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const n={Records:(0,He.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(qe.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Fe={};Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.Kinesis=void 0;const Be=Le,Ue=je;Fe.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,Ue.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ue.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,Ue.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ue.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:n}=e,s={Records:(0,Ue.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:Be.REGION},{accessKeyId:a,secretAccessKey:n})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=De;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Fe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Me);var Ve={};function $e(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(Ve,"__esModule",{value:!0}),Ve.stringOrDefault=Ve.parseIntOrDefault=Ve.parseNumberOrDefault=void 0,Ve.parseNumberOrDefault=$e,Ve.parseIntOrDefault=function(e,t){const i=$e(e,t);return"number"==typeof i?Math.floor(i):i},Ve.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t};var ze={};Object.defineProperty(ze,"__esModule",{value:!0}),ze.validateRedirectLocation=void 0,ze.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 Ge=re&&re.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),We=re&&re.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Je=re&&re.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Ge(t,e,i);return We(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0});var Xe=ce.configValidation=Qe=ce.parsing=Ye=ce.ingest=ce.headers=ce.webcrypto=void 0;ce.webcrypto=Je(he),ce.headers=Je(Se);var Ye=ce.ingest=Je(Me),Qe=ce.parsing=Je(Ve);Xe=ce.configValidation=Je(ze);const{validateRedirectLocation:Ze}=Xe,{configureCookiesDomain:et}=S.cookie.attributes;class tt{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;mitigationServiceTimeoutMs;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;netaceaCheckpointSignalPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;netaceaCaptchaVerificationPath;netaceaBlockedResponseRedirectLocation;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:h,captchaSecretKey:d,ingestType:p=s.HTTP,kinesis:l,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=p??s.HTTP,this.kinesisConfigArgs=l,void 0===h&&void 0===d||(this.captchaSiteKey=h,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?u:e}(a),this.mitigationServiceTimeoutMs=Qe.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Qe.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Qe.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:I}=et(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=I??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=W(C),this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=Ze(e.netaceaBlockedResponseRedirectLocation)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new tt(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 Ye.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new se({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,captchaVerificationPath:this.config.netaceaCaptchaVerificationPath}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=h.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=G(t.url,e.method,this.config.netaceaCaptchaVerificationPath),n=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&z(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!s&&!n)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!n?"captcha"===i.mitigation?{...i,response:Z({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:Q({config:this.config,request:e,responseHeaders:o()})}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=j(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ae(this.config.mitigationType,a,G(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=h.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e),s=i.sessionStatus??n.sessionDetails.sessionStatus;await this.callIngest({bytesSent:X(i.rawResponse.headers,"content-length","0"),cookieFingerprint:n.fingerprints.cookieFingerprint,headerFingerprint:n.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:X(e.headers,"cf-connecting-ip"),method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:n.protocol??null,referer:X(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestId:X(e.headers,"cf-ray"),requestTime:"0",sessionStatus:s,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:X(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:X(e.headers,"x-forwarded-for")})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await w(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===s.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:J(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?$(e.headers.get("Accept")??void 0):$();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof ee&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:G(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await V(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=X(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=te(e);if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,n,s,o,r,c,h;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([B.NEW_SESSION,B.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const u=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,n=d.mitigate,s=d.captcha,o=d.body,h=d.latency,r=[await this.createMitata(e.clientIp,u,a,n,s,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!1,h,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,n].join("");let u=await async function(e,t,i,a,n="000"){const s=[i,t,await F(e+"|"+String(i),a),n].join(M);return`${await F(s,a)}${M}${s}`}(e,t,c,this.config.secretKey,h);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(u=await U(u,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:u,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[T];const i=parseInt(e[_]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await U(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}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!==B.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),h=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,h)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new ee(e,i);const a=e.headers[v]??"0",n=e.headers[b]??"0",s=e.headers[N]??"0";let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),h=e.headers[E];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:h,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Y({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==B.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t,n["X-Netacea-Request-Id"]=e.requestId;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),h=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,h)}composeResult(e,t,i,a,n,s,o){const r=ae(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[I.block,I.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(z(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(G(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===B.NEW_SESSION,a=t===B.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 n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),h=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const u=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 l(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":p(e.split(";"),t).join("; ")}function p(e,t=!1){if(t)return p(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=l(e??"",!0),a=t=l(t??"",!0);if(void 0!==e&&void 0!==t){const n=d(e,"Domain"),s=d(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:l});function f(e){const t=l([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}},C=globalThis.fetch.bind(globalThis),k={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-match",v="x-netacea-mitigate",I="x-netacea-captcha",b="x-netacea-mitata-expiry",N="x-netacea-mitatacaptcha-value",A="x-netacea-mitatacaptcha-expiry",T="x-netacea-event-id",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},_={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},x={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},P={0:k.none,1:k.block,2:k.none,3:k.block,4:k.block},R={1:k.captcha,2:k.captchaPass,3:k.captcha,4:k.allow,5:k.captcha,6:k.allow,7:k.captcha,a:k.captcha,b:k.captchaPass,c:k.captcha,d:k.allow,e:k.captcha},O="_/@#/",K="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),L=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function D(e){if(void 0===e)return;const t=e.match(L);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function M(e=16,t=K){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function j(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function q(e,i){const a=await j(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var H;async function B(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function F(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function V(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 U(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,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function G(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}function W(e){return void 0!==e.config.netaceaBlockedResponseRedirectLocation&&function(e){if("GET"!==e.method?.toUpperCase())return!1;const t=e.headers.get("sec-fetch-mode");return(void 0===t||"navigate"===t)&&(e.headers.get("accept")?.split(/, ?/)??[]).includes("text/html")}(e.request)?function(e){if(void 0===e.config.netaceaBlockedResponseRedirectLocation)throw new Error("Cannot redirect without a configured location");const t=new Headers(e.responseHeaders);return t.append("Location",e.config.netaceaBlockedResponseRedirectLocation),new Response("Forbidden",{status:303,statusText:"",headers:t})}(e):function(e){return new Response("Forbidden",{status:403,statusText:"Forbidden",headers:e.responseHeaders})}(e)}function J(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(H||(H={}));class X extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}var Q="@netacea/cloudflare",Y="6.0.72",Z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ee={},te={},ie={},ae=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ne=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),se=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ae(t,e,i);return ne(t,e),t};Object.defineProperty(ie,"__esModule",{value:!0}),ie.isJweEncrypted=ie.decrypt=ie.encrypt=void 0;const oe=se(i);ie.encrypt=async function(e,t){const i=oe.base64url.decode(t),a=(new TextEncoder).encode(e);return await new oe.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ie.decrypt=async function(e,t){const i=oe.base64url.decode(t),{plaintext:a}=await oe.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ie.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var re=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ce=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),he=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&re(t,e,i);return ce(t,e),t};Object.defineProperty(te,"__esModule",{value:!0}),te.jwe=void 0,te.jwe=he(ie);var ue={},de={};function le(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=ge("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function pe(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...fe(s,t))}return i}function ge(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function fe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(de,"__esModule",{value:!0}),de.findAllInCookieString=de.findFirstInCookieString=de.findAllInHeaders=de.findFirstInHeaders=de.findOnlyValueInHeaders=de.findAllValuesInHeaders=de.findFirstValueInHeaders=void 0,de.findFirstValueInHeaders=function(e,t){const i=le(e,t);if(void 0!==i)return i.slice(t.length+1)},de.findAllValuesInHeaders=function(e,t){return pe(e,t).map((e=>e.slice(t.length+1)))},de.findOnlyValueInHeaders=function(e,t){const i=pe(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},de.findFirstInHeaders=le,de.findAllInHeaders=pe,de.findFirstInCookieString=ge,de.findAllInCookieString=fe;var ye={};function me(e){return"set-cookie"===e||"Set-Cookie"===e}function Se(e,t){const i=t+"=";return e.startsWith(i)}function Ce(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ke(e,t){for(const i of Object.keys(e)){if(!me(i))continue;const a=we(Ce(e,i),t);if(void 0!==a)return a}}function we(e,t){return e.map((e=>e.trimStart())).find((e=>Se(e,t)))}function ve(e,t){const i=[];for(const a of Object.keys(e)){if(!me(a))continue;const n=Ce(e,a);i.push(...Ie(n,t))}return i}function Ie(e,t){return e.map((e=>e.trimStart())).filter((e=>Se(e,t)))}Object.defineProperty(ye,"__esModule",{value:!0}),ye.findAllInSetCookieStrings=ye.findAllInHeaders=ye.findFirstInSetCookieStrings=ye.findFirstInHeaders=ye.findOnlyValueInHeaders=ye.findFirstValueInHeaders=void 0,ye.findFirstValueInHeaders=function(e,t){const i=ke(e,t);return i?.slice(t.length+1)?.split(";")[0]},ye.findOnlyValueInHeaders=function(e,t){const i=ve(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},ye.findFirstInHeaders=ke,ye.findFirstInSetCookieStrings=we,ye.findAllInHeaders=ve,ye.findAllInSetCookieStrings=Ie;var be=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ne=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ae=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&be(t,e,i);return Ne(t,e),t};Object.defineProperty(ue,"__esModule",{value:!0}),ue.setCookie=ue.cookie=void 0,ue.cookie=Ae(de),ue.setCookie=Ae(ye);var Te={},Ee={},_e={};Object.defineProperty(_e,"__esModule",{value:!0}),_e.KINESIS_URL=_e.API_VERSION=_e.REGION=_e.PAYLOAD_TYPE=_e.STATE=void 0,_e.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},_e.PAYLOAD_TYPE="string",_e.REGION="eu-west-1",_e.API_VERSION="2013-12-02",_e.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.headersToRecord=xe.increaseBatchSize=xe.handleFailedLogs=xe.batchArrayForKinesis=xe.sleep=void 0,xe.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},xe.batchArrayForKinesis=function(e,t,i){const a=[];for(let n=0;n<e.length;n+=t){const s=e.slice(n,n+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},xe.handleFailedLogs=function(e,t,i){const a=2*i,n=[...e,...t],s=n.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),n.splice(0,s)),n},xe.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},xe.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.WebStandardKinesis=void 0;const Pe=_e,Re=xe;Ee.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,Re.headersToRecord)(i.headers),host:Pe.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Re.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Re.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,Re.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Re.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const n={Records:(0,Re.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Pe.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Oe={};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.Kinesis=void 0;const Ke=_e,Le=xe;Oe.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,Le.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Le.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,Le.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Le.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:n}=e,s={Records:(0,Le.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:Ke.REGION},{accessKeyId:a,secretAccessKey:n})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=Ee;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Oe;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Te);var De={};function Me(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(De,"__esModule",{value:!0}),De.stringOrDefault=De.parseIntOrDefault=De.parseNumberOrDefault=void 0,De.parseNumberOrDefault=Me,De.parseIntOrDefault=function(e,t){const i=Me(e,t);return"number"==typeof i?Math.floor(i):i},De.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t};var je={};Object.defineProperty(je,"__esModule",{value:!0}),je.validateRedirectLocation=void 0,je.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 qe=Z&&Z.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),He=Z&&Z.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Be=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&qe(t,e,i);return He(t,e),t};Object.defineProperty(ee,"__esModule",{value:!0});var Fe=ee.configValidation=Ue=ee.parsing=Ve=ee.ingest=ee.headers=ee.webcrypto=void 0;ee.webcrypto=Be(te),ee.headers=Be(ue);var Ve=ee.ingest=Be(Te),Ue=ee.parsing=Be(De);Fe=ee.configValidation=Be(je);const $e="unknown";function ze(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let o=E[a]??$e+"_";o+=_[n]??$e;let r=P[n];if("0"!==s){o+=","+(x[s]??$e);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=k.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function Ge(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 We(e,t){const i=t.clone(),a=await async function(e,t){const i=t.body?.getReader();if(null==i)return"";let a=0;const n=[];for(;;){const{done:t,value:s}=await i.read();if(t)break;if(a+=s.length,a>e.maxParsableBytes)throw i.releaseLock(),new Je("Request body too large",a);if(!(s instanceof Uint8Array))throw new Error("Body must be read as Uint8Array chunks");n.push(s)}const s=new Uint8Array(a);let o=0;for(const e of n)s.set(e,o),o+=e.length;return(new TextDecoder).decode(s)}(e,i);if(""===a)throw new Error("Empty body received");const n=JSON.parse(a);if("object"!=typeof n)throw new Error("Invalid GraphQL JSON");const s=n?.query??"",o=s.match(e.parserRegex)?.groups??{},r={OpName:n?.operationName??"",...o};for(const t of Object.keys(r)){const i=r[t];r[t]=i.length<e.maxValueLength?i:i.slice(0,e.maxValueLength)+"..."}return{contentLength:a.length,graphQL:r}}class Je extends Error{bodySize;constructor(e,t){super(e),this.bodySize=t}}class Xe{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.netaceaCookieName),n=await this.readCookie(e,this.config.netaceaCaptchaCookieName),s=e.headers.get("cf-connecting-ip")??"",o=e.headers.get("cf-ray")??"",r=Ue.parseIntOrDefault(e.headers.get("content-length"),{defaultValue:0}),{sessionCookieDetails:c,sessionCookieStatus:h,sessionStatus:u,userId:d}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=D(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(O),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5","a","c","e"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,h=await q(t+"|"+n.expiry,i),u=n.ipHash===h,d=n.signature===await q(e,i);return{userId:n.userId,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:d,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?H.RENEW_SESSION:H.EXISTING_SESSION,{sessionStatus:h}=ze(e.mitigationType,s.protectorCheckCodes,$(t,i,e.netaceaCaptchaVerificationPath));return{sessionCookieDetails:s,sessionCookieStatus:c,sessionStatus:h,userId:a}}return{sessionStatus:"",userId:M(),sessionCookieStatus:H.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s),l={contentLength:r,clientIp:s,fingerprints:await Qe(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedFor:e.headers.get("x-forwarded-for")??void 0,referer:e.headers.get("referer")??void 0,accept:e.headers.get("accept")??void 0,requestId:o,sessionDetails:{captchaToken:n,sessionCookie:a,sessionCookieDetails:c,sessionCookieStatus:h,sessionStatus:u,userId:d}};try{if(p=this.config.graphQL,(g=l).contentLength<=p.maxParsableBytes&&p.includePaths.includes(g.url.pathname)&&"POST"===g.method&&void 0!==g.accept&&g.accept.toLocaleLowerCase().includes("graphql")&&"application/json"===g.contentType){const{contentLength:t,graphQL:i}=await We(this.config.graphQL,e);l.contentLength=t,l.graphQL=i}}catch(e){if(e instanceof Je){const t=e.bodySize;t>l.contentLength&&(l.contentLength=t)}}var p,g;return l}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await F(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function Qe(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 Ge(t)}(t),a=""===i?i:`h_${i.substring(1,15)}`,n=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await async function(e){const t=e.join(",");return await Ge(t)}(n);return{headerFingerprint:a,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{validateRedirectLocation:Ye}=Fe,{configureCookiesDomain:Ze}=S.cookie.attributes;class et{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];graphQL;ingestServiceUrl;ingestType;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaBlockedResponseRedirectLocation;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCaptchaVerificationPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:h,captchaSecretKey:d,ingestType:l=s.HTTP,kinesis:p,mitataCookieExpirySeconds:g,netaceaCookieExpirySeconds:f,enableDynamicCaptchaContentType:y=!1,captchaHeader:m,netaceaCaptchaPath:S,netaceaCaptchaVerificationPath:C,netaceaCheckpointSignalPath:k}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=l??s.HTTP,this.kinesisConfigArgs=p,void 0===h&&void 0===d||(this.captchaSiteKey=h,this.captchaSecretKey=d),this.timeout=function(e){return e<=0?u:e}(a),this.mitigationServiceTimeoutMs=Ue.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:w,captchaCookieAttributes:v}=Ze(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var I;this.netaceaCookieAttributes=w??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,f??g),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(S)&&"string"==typeof S&&(this.netaceaCaptchaPath=S.startsWith("/")?S:`/${S}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=m,this.netaceaCaptchaVerificationPath=void 0!==(I=C)&&I.startsWith("/")&&I.length>=5?I:"/AtaVerifyCaptcha",this.netaceaCheckpointSignalPath=k,this.netaceaBlockedResponseRedirectLocation=Ye(e.netaceaBlockedResponseRedirectLocation),this.graphQL=function(e){const t={includePaths:[],maxParsableBytes:Ue.parseIntOrDefault(e?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:Ue.parseIntOrDefault(e?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^(?<OpType>[^\s]+) /};if(Array.isArray(e?.includePaths))for(const i of e.includePaths)"string"==typeof i&&t.includePaths.push(i);try{if(e?.parserRegex instanceof RegExp)t.parserRegex=e?.parserRegex;else if("object"==typeof e?.parserRegex){const{regex:i,flags:a}=e?.parserRegex;"string"==typeof i&&(t.parserRegex=new RegExp(i,a))}}catch{}return t}(e.graphQL)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new et(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 Ve.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new Xe(this.config),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=h.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,a,e,t)}let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,a,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=$(t.url,e.method,this.config.netaceaCaptchaVerificationPath),n=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&U(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!s&&!n)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!n?"captcha"===i.mitigation?{...i,response:J({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:W({config:this.config,request:e,responseHeaders:o()})}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=D(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ze(this.config.mitigationType,a,$(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}async getResponseDetails(e){if(e instanceof Response){const t=e;return{rawResponse:t,sessionCookie:await this.getNetaceaCookieFromResponse(t)}}{const t=e;return{rawResponse:t.response,mitigationLatency:t.protectorLatencyMs,mitigationStatus:t.protectorStatus,sessionStatus:t.sessionStatus,sessionCookie:await this.getNetaceaCookieFromResponse(t.response)}}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=h.v4());const i=await this.getResponseDetails(t),a="requestDetails"in t?t.requestDetails:await this.requestAnalyser.getNetaceaRequestDetails(e),n=function(e,t,i,a){const n=i.sessionStatus??t.sessionDetails.sessionStatus,s=i.sessionCookie??t.sessionDetails.sessionCookie,o=t.method,r=t.url.pathname,c=t.protocol??null,h=Date.now(),u=t.referer??"",d=Ue.parseIntOrDefault(i.rawResponse.headers.get("content-length"),{defaultValue:0});return{BytesReceived:t.contentLength,BytesSent:d,Query:t.url.search.slice(1),GraphQL:t.graphQL,IntegrationType:Q?.replace("@netacea/","")??"",IntegrationVersion:Y,NetaceaMitigationApplied:n??"",NetaceaUserIdCookie:s??"",NetaceaUserIdCookieStatus:t.sessionDetails.sessionCookieStatus,ProtectionMode:e.mitigationType??"",ProtectorLatencyMs:i.mitigationLatency,ProtectorStatus:i.mitigationStatus,RealIp:t.clientIp,Referer:""===u?"-":u,Request:`${o} ${r} ${c}`,RequestHost:t.url.host,RequestId:t.requestId,RequestTime:"0",Status:i.rawResponse.status.toString(),TimeLocal:new Date(h).toUTCString(),TimeUnixMsUTC:h,UserAgent:t.userAgent,WorkerInstanceId:a,XForwardedFor:t.xForwardedFor,optional:{headerFingerprint:t.fingerprints.headerFingerprint,cookieFingerprint:t.fingerprints.cookieFingerprint}}}(this.config,a,i,this.workerInstanceId);try{if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");await this.kinesis.ingest({...n,apiKey:this.config.apiKey})}else{const e=function(e,t){const i={"X-Netacea-API-Key":e.apiKey,"content-type":"application/json"};return{host:e.ingestServiceUrl,method:"POST",path:"/",headers:i,body:t,timeout:e.timeout}}(this.config,JSON.stringify(n)),t=await this.makeRequest(e);if(200!==t.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(t)}}catch(e){console.error("NETACEA Error: ",e.message)}}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await C(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i,a){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==i?.response)return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:i.response,sessionStatus:i?.sessionStatus??""};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,i)),this.config.ingestType===s.ORIGIN){const{sessionStatus:t,userId:a}=await this.getNetaceaSession(e,i);!function(e,t,i){e.headers.set("x-netacea-integration-type",Q.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",Y),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,t,a)}const n=await a(e);return{protectorLatencyMs:i?.apiCallLatency,protectorStatus:i?.apiCallStatus,requestDetails:t,response:z(n,i),sessionStatus:i?.sessionStatus??""}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?V(e.headers.get("Accept")??void 0):V();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i,body:e.body})}async runMitigation(e,t){try{if(function(e,t){if(void 0===t)return!1;const i=new URL(e.url);if(t.startsWith("/"))return t===i.pathname;try{const e=new URL(t);return e.host===i.host&&e.pathname===i.pathname}catch{return!1}}(e,this.config.netaceaBlockedResponseRedirectLocation))return{sessionStatus:""};switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof X&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:$(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await F(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=function(e,t,i=""){return e.get(t)??i}(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async check(e,t){let i,a,n,s,o,r,c,h;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([H.NEW_SESSION,H.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const u=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,n=d.mitigate,s=d.captcha,o=d.body,h=d.latency,r=[await this.createMitata(e.clientIp,u,a,n,s,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!1,h,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,n].join("");let u=await async function(e,t,i,a,n="000"){const s=[i,t,await q(e+"|"+String(i),a),n].join(O);return`${await q(s,a)}${O}${s}`}(e,t,c,this.config.secretKey,h);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(u=await B(u,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:u,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[N];const i=parseInt(e[A]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await B(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id");const s=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",o=this.parseCaptchaAPICallBody(t,s),r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:o,timeout:this.config.mitigationServiceTimeoutMs}),h=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,h)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new X(e,i);const a=e.headers[w]??"0",n=e.headers[v]??"0",s=e.headers[I]??"0";let o=parseInt(e.headers[b]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),h=e.headers[T];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:h,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:G({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==H.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t,n["X-Netacea-Request-Id"]=e.requestId;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),h=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,h)}composeResult(e,t,i,a,n,s,o){const r=ze(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[k.block,k.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(U(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.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===H.NEW_SESSION,a=t===H.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "6.0.71",
3
+ "version": "6.0.72",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,10 +18,10 @@
18
18
  },
19
19
  "license": "ISC",
20
20
  "dependencies": {
21
- "@netacea/netaceaintegrationbase": "^2.0.114",
21
+ "@netacea/netaceaintegrationbase": "^2.0.115",
22
22
  "aws4fetch": "^1.0.20",
23
23
  "jose": "^4.11.2",
24
24
  "uuid": "^10.0.0"
25
25
  },
26
- "gitHead": "ed358a03a5bbcb78307205e72a95bfc513bf9e41"
26
+ "gitHead": "40fd25f0ba02ac8e704f76f8df6b963c684b2da8"
27
27
  }