@netacea/vercel 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -16,9 +16,28 @@ Within your Vercel project, run:
16
16
 
17
17
  ## Netacea Config
18
18
 
19
- A NetaceaConfig.json file will need to be created within your project,
20
- alongside the middleware described below. The Netacea Solutions Engineering team
21
- can assist in providing this config.
19
+ This integration is best configured using Vercel environment variables.
20
+
21
+ Please consult the following table for the environment variables which must be set.
22
+ The Netacea Solutions Engineering team can assist in providing this config.
23
+
24
+ | Name | Description |
25
+ |-----------------------------------|-------------------------------------------------|
26
+ | NETACEA_COOKIE_NAME | Name of the Netacea session cookie. |
27
+ | NETACEA_CAPTCHA_COOKIE_NAME | Name of the Netacea captcha cookie. |
28
+ | NETACEA_PROTECTOR_API_URL | URL for the Netacea Protector API. |
29
+ | NETACEA_PROTECTION_MODE | The Protection Mode for the integration. |
30
+
31
+ The following variables should be set as **sensitive**:
32
+
33
+ | Name | Description |
34
+ |-----------------------------------|-------------------------------------------------|
35
+ | NETACEA_API_KEY | API Key to contact Netacea services. |
36
+ | NETACEA_COOKIE_ENCRYPTION_KEY | Key used to secure the session cookie. |
37
+ | NETACEA_SECRET_KEY | Additional key for securing the session cookie. |
38
+ | NETACEA_KINESIS_ACCESS_KEY | Key to write to Netacea Kinesis ingest. |
39
+ | NETACEA_KINESIS_SECRET_KEY | Key to write to Netacea Kinesis ingest. |
40
+ | NETACEA_KINESIS_STREAM_NAME | Name of the stream to write ingested logs. |
22
41
 
23
42
  ## Middleware Setup
24
43
 
@@ -27,17 +46,23 @@ The following code should be placed in the `middleware.ts` file within your proj
27
46
  ```TypeScript
28
47
  import { NextRequest, NextResponse } from 'next/server'
29
48
  import { waitUntil } from '@vercel/functions'
30
- import * as netaceaConfig from './NetaceaConfig.json'
31
- import NetaceaVercelIntegration from '@netacea/vercel'
32
- import type { NetaceaVercelIntegrationArgs } from '@netacea/vercel'
49
+ import {
50
+ NetaceaVercelIntegration,
51
+ getNetaceaArgsFromEnv,
52
+ type NetaceaVercelIntegrationArgs
53
+ } from '@netacea/vercel'
33
54
 
34
55
  let netaceaWorker: NetaceaVercelIntegration | undefined = undefined
35
56
 
36
57
  export default async function middleware(req: NextRequest) {
37
58
  try {
38
- // Initialize Netacea worker
59
+ /**
60
+ * Initialize the Netacea worker.
61
+ */
39
62
  if (netaceaWorker === undefined) {
40
- netaceaWorker = new NetaceaVercelIntegration(netaceaConfig as NetaceaVercelIntegrationArgs)
63
+ netaceaWorker = new NetaceaVercelIntegration({
64
+ ...getNetaceaArgsFromEnv(process.env)
65
+ } as NetaceaVercelIntegrationArgs)
41
66
  }
42
67
 
43
68
  // Run Netacea integration
package/dist/index.d.ts CHANGED
@@ -315,20 +315,20 @@ interface NetaceaRequestDetails {
315
315
  };
316
316
  }
317
317
 
318
- type NetaceaVercelIntegrationArgs$1 = NetaceaBaseArgs & {
318
+ type NetaceaVercelIntegrationArgs = NetaceaBaseArgs & {
319
319
  cookieEncryptionKey?: string;
320
320
  enableDynamicCaptchaContentType?: boolean | string;
321
321
  netaceaCaptchaPath?: string;
322
- captchaHeader?: CustomHeader$1 | undefined;
322
+ captchaHeader?: CustomHeader | undefined;
323
323
  netaceaCookieAttributes?: string;
324
324
  netaceaCaptchaCookieAttributes?: string;
325
325
  mitigationServiceTimeoutMs?: number | string;
326
326
  };
327
- interface CustomHeader$1 {
327
+ interface CustomHeader {
328
328
  name: string;
329
329
  value: string;
330
330
  }
331
- declare class VercelConfig {
331
+ declare class ValidatedConfig {
332
332
  readonly mitataCookieExpirySeconds: number;
333
333
  readonly apiKey: string;
334
334
  readonly secretKey: string;
@@ -347,10 +347,10 @@ declare class VercelConfig {
347
347
  readonly cookieEncryptionKey: string | undefined;
348
348
  readonly enableDynamicCaptchaContentType: boolean;
349
349
  readonly netaceaCaptchaPath: string | undefined;
350
- readonly captchaHeader: CustomHeader$1 | undefined;
350
+ readonly captchaHeader: CustomHeader | undefined;
351
351
  readonly netaceaCookieAttributes: string;
352
352
  readonly netaceaCaptchaCookieAttributes: string;
353
- constructor(args: NetaceaVercelIntegrationArgs$1);
353
+ constructor(args: Partial<NetaceaVercelIntegrationArgs>);
354
354
  }
355
355
 
356
356
  type KinesisMakeRequest = (args: {
@@ -401,18 +401,6 @@ declare class WebStandardKinesis {
401
401
  private signRequest;
402
402
  }
403
403
 
404
- type NetaceaVercelIntegrationArgs = NetaceaBaseArgs & {
405
- cookieEncryptionKey?: string;
406
- enableDynamicCaptchaContentType?: boolean | string;
407
- netaceaCaptchaPath?: string;
408
- captchaHeader?: CustomHeader | undefined;
409
- netaceaCookieAttributes?: string;
410
- netaceaCaptchaCookieAttributes?: string;
411
- };
412
- interface CustomHeader {
413
- name: string;
414
- value: string;
415
- }
416
404
  interface ComposeResultResponse {
417
405
  body?: string | ReadableStream<Uint8Array>;
418
406
  apiCallStatus?: number;
@@ -431,12 +419,12 @@ interface MakeRequestArgs {
431
419
  body?: string | ReadableStream<Uint8Array> | undefined;
432
420
  timeout?: number;
433
421
  }
434
- declare class Vercel {
435
- protected readonly config: VercelConfig;
422
+ declare class NetaceaVercelIntegration {
423
+ protected readonly config: ValidatedConfig;
436
424
  protected readonly kinesis?: WebStandardKinesis;
437
425
  private readonly requestAnalyser;
438
426
  private workerInstanceId;
439
- constructor(args: NetaceaVercelIntegrationArgs);
427
+ constructor(args: Partial<NetaceaVercelIntegrationArgs>);
440
428
  /**
441
429
  *
442
430
  * @param event Vercel's FetchEvent
@@ -490,4 +478,21 @@ declare class Vercel {
490
478
  protected processIngest(requestDetails: NetaceaRequestDetails): Promise<NetaceaResponseBase>;
491
479
  }
492
480
 
493
- export { NetaceaMitigationType, type NetaceaVercelIntegrationArgs, type NetaceaVercelResult, Vercel as default };
481
+ /**
482
+ * Extracts Netacea configuration options from environment variables.
483
+ *
484
+ * This function reads from a given environment object (such as `process.env`)
485
+ * and constructs a partial configuration object compatible with the Netacea
486
+ * Vercel integration. It uses a configurable prefix (defaulting to `NETACEA`)
487
+ * to locate relevant environment variables.
488
+ *
489
+ * All values are optionally defined, and only those that are present will be included
490
+ * in the returned configuration object.
491
+ *
492
+ * @param env - The environment variables object (typically `process.env`)
493
+ * @param prefix - An optional prefix for environment variable names (default is `'NETACEA'`)
494
+ * @returns A partial `NetaceaVercelIntegrationArgs` object containing only defined values
495
+ */
496
+ declare function getNetaceaArgsFromEnv(env: NodeJS.ProcessEnv, prefix?: string): Partial<NetaceaVercelIntegrationArgs>;
497
+
498
+ export { type KinesisIngestConfigArgs$1 as KinesisIngestConfigArgs, NetaceaIngestType, NetaceaMitigationType, NetaceaVercelIntegration, type NetaceaVercelIntegrationArgs, type NetaceaVercelResult, NetaceaVercelIntegration as default, getNetaceaArgsFromEnv };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function p(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function l(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(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 f=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=p(e,"Domain"),s=p(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=p(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=p(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=p(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:p,removeDuplicateAttrs:l});function g(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 g({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:g});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:f,netaceaSession:y}};var C="@netacea/vercel",k="0.1.2";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",E="x-netacea-mitatacaptcha-expiry",_="x-netacea-event-id",O={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"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},M={0:I.none,1:I.block,2:I.none,3:I.block,4:I.block},R={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha},K="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),j=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function L(e){if(void 0===e)return;const t=e.match(j);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function H(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var U;async function $(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 G(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}async function B(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:n}=e;return a.includes(i)&&n.includes("trackingId")&&"get"===t.toLowerCase()}function W(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function J(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(U||(U={}));class Y extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Z(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:n,integrationVersion:s,ip:o,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:h,netaceaCookieStatus:p,path:l,referer:d,requestHost:f,requestTime:g,sessionStatus:y,status:m,timeUnixMsUTC:S,userAgent:C,workerInstanceId:k,xForwardedFor:w}){return{Request:`${r} ${l}`,TimeLocal:new Date(S??Date.now()).toUTCString(),TimeUnixMsUTC:S,RealIp:o,UserAgent:C,Status:m,RequestTime:g?.toString(),BytesSent:e?.toString(),Referer:""===d?"-":d,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:y??"",ProtectorLatencyMs:u,ProtectorStatus:h,IntegrationType:n??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:f,XForwardedFor:w,WorkerInstanceId:k,NetaceaUserIdCookieStatus:p,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const Q="unknown";function ee(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s&&(s="5"));let o=O[a]??Q+"_";o+=x[n]??Q;let r=M[n];if("0"!==s){o+=","+(P[s]??Q);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function te(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class ie{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=(e.headers.get("x-forwarded-for")??"").split(/, ?/)[0],{sessionCookieDetails:o,sessionCookieStatus:r,sessionStatus:c,userId:u}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=L(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(K),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await F(t+"|"+n.expiry,i),h=n.ipHash===u,p=n.signature===await F(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:p,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?U.RENEW_SESSION:U.EXISTING_SESSION,{sessionStatus:u}=ee(e.mitigationType,s.protectorCheckCodes,W(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:H(),sessionCookieStatus:U.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await ae(e),method:i,protocol:void 0,url:t,userAgent:e.headers.get("user-agent")??"",sessionDetails:{sessionStatus:c,captchaToken:n,sessionCookieDetails:o,sessionCookieStatus:r,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await V(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ae(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await te(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await te(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}var ne="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},se={},oe={},re={},ce=ne&&ne.__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]}),ue=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),he=ne&&ne.__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)&&ce(t,e,i);return ue(t,e),t};Object.defineProperty(re,"__esModule",{value:!0}),re.isJweEncrypted=re.decrypt=re.encrypt=void 0;const pe=he(i);re.encrypt=async function(e,t){const i=pe.base64url.decode(t),a=(new TextEncoder).encode(e);return await new pe.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},re.decrypt=async function(e,t){const i=pe.base64url.decode(t),{plaintext:a}=await pe.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},re.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var le=ne&&ne.__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]}),de=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&le(t,e,i);return de(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0}),oe.jwe=void 0,oe.jwe=fe(re);var ge={},ye={};function me(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=Ce("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function Se(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...ke(s,t))}return i}function Ce(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ke(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ye,"__esModule",{value:!0}),ye.findAllInCookieString=ye.findFirstInCookieString=ye.findAllInHeaders=ye.findFirstInHeaders=ye.findOnlyValueInHeaders=ye.findAllValuesInHeaders=ye.findFirstValueInHeaders=void 0,ye.findFirstValueInHeaders=function(e,t){const i=me(e,t);if(void 0!==i)return i.slice(t.length+1)},ye.findAllValuesInHeaders=function(e,t){return Se(e,t).map((e=>e.slice(t.length+1)))},ye.findOnlyValueInHeaders=function(e,t){const i=Se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ye.findFirstInHeaders=me,ye.findAllInHeaders=Se,ye.findFirstInCookieString=Ce,ye.findAllInCookieString=ke;var we={};function Ie(e){return"set-cookie"===e||"Set-Cookie"===e}function ve(e,t){const i=t+"=";return e.startsWith(i)}function be(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Ne(e,t){for(const i of Object.keys(e)){if(!Ie(i))continue;const a=Ae(be(e,i),t);if(void 0!==a)return a}}function Ae(e,t){return e.map((e=>e.trimStart())).find((e=>ve(e,t)))}function Te(e,t){const i=[];for(const a of Object.keys(e)){if(!Ie(a))continue;const n=be(e,a);i.push(...Ee(n,t))}return i}function Ee(e,t){return e.map((e=>e.trimStart())).filter((e=>ve(e,t)))}Object.defineProperty(we,"__esModule",{value:!0}),we.findAllInSetCookieStrings=we.findAllInHeaders=we.findFirstInSetCookieStrings=we.findFirstInHeaders=we.findOnlyValueInHeaders=we.findFirstValueInHeaders=void 0,we.findFirstValueInHeaders=function(e,t){const i=Ne(e,t);return i?.slice(t.length+1)?.split(";")[0]},we.findOnlyValueInHeaders=function(e,t){const i=Te(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]},we.findFirstInHeaders=Ne,we.findFirstInSetCookieStrings=Ae,we.findAllInHeaders=Te,we.findAllInSetCookieStrings=Ee;var _e=ne&&ne.__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=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&_e(t,e,i);return Oe(t,e),t};Object.defineProperty(ge,"__esModule",{value:!0}),ge.setCookie=ge.cookie=void 0,ge.cookie=xe(ye),ge.setCookie=xe(we);var Pe={},Me={},Re={};Object.defineProperty(Re,"__esModule",{value:!0}),Re.KINESIS_URL=Re.API_VERSION=Re.REGION=Re.PAYLOAD_TYPE=Re.STATE=void 0,Re.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Re.PAYLOAD_TYPE="string",Re.REGION="eu-west-1",Re.API_VERSION="2013-12-02",Re.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com",Object.defineProperty(Me,"__esModule",{value:!0}),Me.WebStandardKinesis=void 0;const Ke=Re;async function De(e){await new Promise((t=>{setTimeout(t,e)}))}function je(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}Me.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e;const{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,maxLogAgeSeconds:s,logBatchSize:o,rampUpBatchSize:r,maxAwaitTimePerIngestCallMs:c}=t;if(void 0===a)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===n)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=i,this.kinesisAccessKey=a,this.kinesisSecretKey=n,this.maxAwaitTimePerIngestCallMs=c,void 0!==s&&s<this.maxLogAgeSeconds&&s>0&&(this.maxLogAgeSeconds=s),void 0!==o&&(this.maxLogBatchSize=o),this.logBatchSize=!0===r?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:je(i.headers),host:Ke.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(De(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=De(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const n=e.slice(a,a+t);i.push({Data:this.deps.Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}async signRequest(e,t,i,a){const n={Records:this.batchArrayForKinesis(i,a),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Ke.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebStandardKinesis=void 0;var t=Me;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}})}(Pe);var Le={};function He(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}return null===i&&(i=t.defaultValue),void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(Le,"__esModule",{value:!0}),Le.parseIntOrDefault=Le.parseNumberOrDefault=void 0,Le.parseNumberOrDefault=He,Le.parseIntOrDefault=function(e,t){return Math.floor(He(e,t))};var qe=ne&&ne.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Fe=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ue=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&qe(t,e,i);return Fe(t,e),t};Object.defineProperty(se,"__esModule",{value:!0});var $e=se.parsing=Ve=se.ingest=se.headers=se.webcrypto=void 0;se.webcrypto=Ue(oe),se.headers=Ue(ge);var Ve=se.ingest=Ue(Pe);$e=se.parsing=Ue(Le);const{configureCookiesDomain:Ge}=S.cookie.attributes;class Be{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;mitigationServiceTimeoutMs;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:p,ingestType:l=s.HTTP,kinesis:d,mitataCookieExpirySeconds:f,netaceaCookieExpirySeconds:g,netaceaCookieName:y,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:S=!1,captchaHeader:C,netaceaCaptchaPath: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=d,void 0===u&&void 0===p||(this.captchaSiteKey=u,this.captchaSecretKey=p),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=$e.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=y??"_mitata",this.netaceaCaptchaCookieName=m??"_mitatacaptcha";const{cookieAttributes:w,captchaCookieAttributes:I}=Ge(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,g??f),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(k)&&"string"==typeof k&&(this.netaceaCaptchaPath=k.startsWith("/")?k:`/${k}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof S?S:"true"===S),this.captchaHeader=C}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Be(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 ie({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{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);if(i.mitigated){const a=new Headers;if(!await B(t.url,e.method,this.config.netaceaCaptchaPath))for(const e of i.setCookie)a.append("set-cookie",e);let n="Forbidden";return"captcha"===i.mitigation&&(void 0!==this.config.captchaHeader&&a.append(this.config.captchaHeader.name,this.config.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),n=i.body),{response:new Response(n,{status:403,statusText:"Forbidden",headers:a}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}if(W(t.url,e.method)){const e=new Headers;for(const t of i.setCookie)e.append("set-cookie",t);return{response:new Response(i.body,{status:200,statusText:"OK",headers:e}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}return{setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=L(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ee(this.config.mitigationType,a,W(new URL(e.url),e.method));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:X(i.rawResponse.headers,"content-length","0"),cookieFingerprint:n.fingerprints.cookieFingerprint,headerFingerprint:n.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:n.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:X(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestTime:"0",sessionStatus:i.sessionStatus??n.sessionDetails.sessionStatus,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:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await w(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===s.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:z(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?G(e.headers.get("Accept")??void 0):G();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Y&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:W(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await 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=Z(e);if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([U.NEW_SESSION,U.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,p=await this.makeMitigateAPICall(e,t,!1,null);i=p.status,a=p.match,n=p.mitigate,s=p.captcha,o=p.body,u=p.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,p.mitataMaxAge)],c=p.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await F(e+"|"+String(i),a),n].join(K);return`${await F(s,a)}${K}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await $(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[T];const i=parseInt(e[E]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await $(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==U.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint);const s=Date.now(),o=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:t,timeout:this.config.mitigationServiceTimeoutMs}),r=Date.now()-s;return await this.getApiCallResponseFromResponse(o,e,r)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Y(e,i);const a=e.headers[v],n=e.headers[b],s=e.headers[N];let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[_];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:J({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==U.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=ee(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[I.block,I.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(await B(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(W(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===U.NEW_SESSION,a=t===U.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),u=n(a);exports.NetaceaIngestType=void 0,(s=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",s.HTTP="HTTP",s.KINESIS="KINESIS",s.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(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 p=3e3;function h(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function l(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(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 f=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=h(e,"Domain"),s=h(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=h(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=h(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=h(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:h,removeDuplicateAttrs:l});function g(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 g({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:g});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:f,netaceaSession:y}};var C="@netacea/vercel",k="0.1.4";const I=globalThis.fetch.bind(globalThis),w={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},E="x-netacea-match",v="x-netacea-mitigate",T="x-netacea-captcha",N="x-netacea-mitata-expiry",A="x-netacea-mitatacaptcha-value",_="x-netacea-mitatacaptcha-expiry",b="x-netacea-event-id",O={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},K={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},x={0:w.none,1:w.block,2:w.none,3:w.block,4:w.block},R={1:w.captcha,2:w.captchaPass,3:w.captcha,4:w.allow,5:w.captcha},M="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),j=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function H(e){if(void 0===e)return;const t=e.match(j);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function L(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function U(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 U(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var F;async function $(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 G(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}async function B(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:n}=e;return a.includes(i)&&n.includes("trackingId")&&"get"===t.toLowerCase()}function W(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function z(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function 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(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(F||(F={}));class J extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Z(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:n,integrationVersion:s,ip:o,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:p,netaceaCookieStatus:h,path:l,referer:d,requestHost:f,requestTime:g,sessionStatus:y,status:m,timeUnixMsUTC:S,userAgent:C,workerInstanceId:k,xForwardedFor:I}){return{Request:`${r} ${l}`,TimeLocal:new Date(S??Date.now()).toUTCString(),TimeUnixMsUTC:S,RealIp:o,UserAgent:C,Status:m,RequestTime:g?.toString(),BytesSent:e?.toString(),Referer:""===d?"-":d,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:y??"",ProtectorLatencyMs:u,ProtectorStatus:p,IntegrationType:n??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:f,XForwardedFor:I,WorkerInstanceId:k,NetaceaUserIdCookieStatus:h,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const Q="unknown";function ee(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s&&(s="5"));let o=O[a]??Q+"_";o+=K[n]??Q;let r=x[n];if("0"!==s){o+=","+(P[s]??Q);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=w.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function te(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class ie{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=(e.headers.get("x-forwarded-for")??"").split(/, ?/)[0],{sessionCookieDetails:o,sessionCookieStatus:r,sessionStatus:c,userId:u}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=H(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(M),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await q(t+"|"+n.expiry,i),p=n.ipHash===u,h=n.signature===await q(e,i);return{userId:n.userId,requiresReissue:s||!p,isExpired:s,shouldExpire:c,isSameIP:p,isPrimaryHashValid:h,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?F.RENEW_SESSION:F.EXISTING_SESSION,{sessionStatus:u}=ee(e.mitigationType,s.protectorCheckCodes,W(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:L(),sessionCookieStatus:F.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await ae(e),method:i,protocol:void 0,url:t,userAgent:e.headers.get("user-agent")??"",sessionDetails:{sessionStatus:c,captchaToken:n,sessionCookieDetails:o,sessionCookieStatus:r,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await V(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ae(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await te(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await te(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}var ne="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},se={},oe={},re={},ce=ne&&ne.__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]}),ue=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pe=ne&&ne.__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)&&ce(t,e,i);return ue(t,e),t};Object.defineProperty(re,"__esModule",{value:!0}),re.isJweEncrypted=re.decrypt=re.encrypt=void 0;const he=pe(i);re.encrypt=async function(e,t){const i=he.base64url.decode(t),a=(new TextEncoder).encode(e);return await new he.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},re.decrypt=async function(e,t){const i=he.base64url.decode(t),{plaintext:a}=await he.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},re.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var le=ne&&ne.__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]}),de=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&le(t,e,i);return de(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0}),oe.jwe=void 0,oe.jwe=fe(re);var ge={},ye={};function me(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=Ce("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function Se(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...ke(s,t))}return i}function Ce(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ke(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ye,"__esModule",{value:!0}),ye.findAllInCookieString=ye.findFirstInCookieString=ye.findAllInHeaders=ye.findFirstInHeaders=ye.findOnlyValueInHeaders=ye.findAllValuesInHeaders=ye.findFirstValueInHeaders=void 0,ye.findFirstValueInHeaders=function(e,t){const i=me(e,t);if(void 0!==i)return i.slice(t.length+1)},ye.findAllValuesInHeaders=function(e,t){return Se(e,t).map((e=>e.slice(t.length+1)))},ye.findOnlyValueInHeaders=function(e,t){const i=Se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ye.findFirstInHeaders=me,ye.findAllInHeaders=Se,ye.findFirstInCookieString=Ce,ye.findAllInCookieString=ke;var Ie={};function we(e){return"set-cookie"===e||"Set-Cookie"===e}function Ee(e,t){const i=t+"=";return e.startsWith(i)}function ve(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Te(e,t){for(const i of Object.keys(e)){if(!we(i))continue;const a=Ne(ve(e,i),t);if(void 0!==a)return a}}function Ne(e,t){return e.map((e=>e.trimStart())).find((e=>Ee(e,t)))}function Ae(e,t){const i=[];for(const a of Object.keys(e)){if(!we(a))continue;const n=ve(e,a);i.push(..._e(n,t))}return i}function _e(e,t){return e.map((e=>e.trimStart())).filter((e=>Ee(e,t)))}Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.findAllInSetCookieStrings=Ie.findAllInHeaders=Ie.findFirstInSetCookieStrings=Ie.findFirstInHeaders=Ie.findOnlyValueInHeaders=Ie.findFirstValueInHeaders=void 0,Ie.findFirstValueInHeaders=function(e,t){const i=Te(e,t);return i?.slice(t.length+1)?.split(";")[0]},Ie.findOnlyValueInHeaders=function(e,t){const i=Ae(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]},Ie.findFirstInHeaders=Te,Ie.findFirstInSetCookieStrings=Ne,Ie.findAllInHeaders=Ae,Ie.findAllInSetCookieStrings=_e;var be=ne&&ne.__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=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ke=ne&&ne.__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 Oe(t,e),t};Object.defineProperty(ge,"__esModule",{value:!0}),ge.setCookie=ge.cookie=void 0,ge.cookie=Ke(ye),ge.setCookie=Ke(Ie);var Pe={},xe={},Re={};Object.defineProperty(Re,"__esModule",{value:!0}),Re.KINESIS_URL=Re.API_VERSION=Re.REGION=Re.PAYLOAD_TYPE=Re.STATE=void 0,Re.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Re.PAYLOAD_TYPE="string",Re.REGION="eu-west-1",Re.API_VERSION="2013-12-02",Re.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com",Object.defineProperty(xe,"__esModule",{value:!0}),xe.WebStandardKinesis=void 0;const Me=Re;async function De(e){await new Promise((t=>{setTimeout(t,e)}))}function je(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}xe.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e;const{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,maxLogAgeSeconds:s,logBatchSize:o,rampUpBatchSize:r,maxAwaitTimePerIngestCallMs:c}=t;if(void 0===a)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===n)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=i,this.kinesisAccessKey=a,this.kinesisSecretKey=n,this.maxAwaitTimePerIngestCallMs=c,void 0!==s&&s<this.maxLogAgeSeconds&&s>0&&(this.maxLogAgeSeconds=s),void 0!==o&&(this.maxLogBatchSize=o),this.logBatchSize=!0===r?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:je(i.headers),host:Me.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(De(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=De(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const n=e.slice(a,a+t);i.push({Data:this.deps.Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}async signRequest(e,t,i,a){const n={Records:this.batchArrayForKinesis(i,a),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Me.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebStandardKinesis=void 0;var t=xe;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}})}(Pe);var He={};function Le(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(He,"__esModule",{value:!0}),He.parseIntOrDefault=He.parseNumberOrDefault=void 0,He.parseNumberOrDefault=Le,He.parseIntOrDefault=function(e,t){const i=Le(e,t);return"number"==typeof i?Math.floor(i):i};var Ue=ne&&ne.__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]}),qe=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Fe=ne&&ne.__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)&&Ue(t,e,i);return qe(t,e),t};Object.defineProperty(se,"__esModule",{value:!0});var $e=se.parsing=Ve=se.ingest=se.headers=se.webcrypto=void 0;se.webcrypto=Fe(oe),se.headers=Fe(ge);var Ve=se.ingest=Fe(Pe);$e=se.parsing=Fe(He);const{configureCookiesDomain:Ge}=S.cookie.attributes;class Be{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;mitigationServiceTimeoutMs;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?p:i,this.mitigationServiceTimeoutMs=$e.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=e.netaceaCookieName??"_mitata",this.netaceaCaptchaCookieName=e.netaceaCaptchaCookieName??"_mitatacaptcha";const{cookieAttributes:a,captchaCookieAttributes:n}=Ge(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var s,o;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=n??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(s=this.mitigationType,void 0===(o=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?s===exports.NetaceaMitigationType.INGEST?3600:60:o),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader}}class We{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Be(i),this.config.ingestType===exports.NetaceaIngestType.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new 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 ie({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{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);if(i.mitigated){const a=new Headers;if(!await B(t.url,e.method,this.config.netaceaCaptchaPath))for(const e of i.setCookie)a.append("set-cookie",e);let n="Forbidden";return"captcha"===i.mitigation&&(void 0!==this.config.captchaHeader&&a.append(this.config.captchaHeader.name,this.config.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),n=i.body),{response:new Response(n,{status:403,statusText:"Forbidden",headers:a}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}if(W(t.url,e.method)){const e=new Headers;for(const t of i.setCookie)e.append("set-cookie",t);return{response:new Response(i.body,{status:200,statusText:"OK",headers:e}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}return{setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=H(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ee(this.config.mitigationType,a,W(new URL(e.url),e.method));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:X(i.rawResponse.headers,"content-length","0"),cookieFingerprint:n.fingerprints.cookieFingerprint,headerFingerprint:n.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:n.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:X(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestTime:"0",sessionStatus:i.sessionStatus??n.sessionDetails.sessionStatus,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:"",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 I(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===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:z(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?G(e.headers.get("Accept")??void 0):G();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof J&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:W(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await 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=Z(e);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([F.NEW_SESSION,F.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const p=e.sessionDetails.userId,h=await this.makeMitigateAPICall(e,t,!1,null);i=h.status,a=h.match,n=h.mitigate,s=h.captcha,o=h.body,u=h.latency,r=[await this.createMitata(e.clientIp,p,a,n,s,h.mitataMaxAge)],c=h.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 p={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,p,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let p=await async function(e,t,i,a,n="000"){const s=[i,t,await q(e+"|"+String(i),a),n].join(M);return`${await q(s,a)}${M}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(p=await $(p,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:p,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[A];const i=parseInt(e[_]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await $(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==F.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint);const s=Date.now(),o=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:t,timeout:this.config.mitigationServiceTimeoutMs}),r=Date.now()-s;return await this.getApiCallResponseFromResponse(o,e,r)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new J(e,i);const a=e.headers[E],n=e.headers[v],s=e.headers[T];let o=parseInt(e.headers[N]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[b];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Y({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==F.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=ee(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[w.block,w.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(await B(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(W(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===F.NEW_SESSION,a=t===F.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}}const ze=e=>$e.parseIntOrDefault(e,{defaultValue:void 0});function Xe(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function Ye(e,t,i){if("string"==typeof i)return e[`${t}_${i}`];for(const a of i){const i=Ye(e,t,a);if(void 0!==i)return i}}function Je(e,t){const i=Ye(e,t,"CAPTCHA_HEADER_NAME"),a=Ye(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function Ze(e,t){const i=Ye(e,t,"KINESIS_STREAM_NAME"),a=Ye(e,t,"KINESIS_ACCESS_KEY"),n=Ye(e,t,"KINESIS_SECRET_KEY"),s=Xe({logBatchSize:ze(Ye(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:ze(Ye(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==n)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,...s}}exports.NetaceaVercelIntegration=We,exports.default=We,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return Xe({apiKey:Ye(e,t,"API_KEY"),secretKey:Ye(e,t,"SECRET_KEY"),captchaSiteKey:Ye(e,t,"CAPTCHA_SITE_KEY"),captchaSecretKey:Ye(e,t,"CAPTCHA_SECRET_KEY"),timeout:ze(Ye(e,t,"TIMEOUT")),ingestServiceUrl:Ye(e,t,"INGEST_SERVICE_URL"),mitigationServiceUrl:Ye(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:Ye(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),ingestType:Ye(e,t,"INGEST_TYPE"),kinesis:Ze(e,t),mitataCookieExpirySeconds:ze(Ye(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),netaceaCookieExpirySeconds:ze(Ye(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:Ye(e,t,"COOKIE_NAME"),netaceaCaptchaCookieName:Ye(e,t,"CAPTCHA_COOKIE_NAME"),cookieEncryptionKey:Ye(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:Ye(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),netaceaCaptchaPath:Ye(e,t,"CAPTCHA_PATH"),captchaHeader:Je(e,t),netaceaCookieAttributes:Ye(e,t,"COOKIE_ATTRIBUTES"),netaceaCaptchaCookieAttributes:Ye(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),mitigationServiceTimeoutMs:Ye(e,t,"MITIGATION_SERVICE_TIMEOUT_MS")})};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/vercel",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Netacea Vercel CDN Integration",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -22,5 +22,5 @@
22
22
  "jose": "^4.11.2",
23
23
  "uuid": "^10.0.0"
24
24
  },
25
- "gitHead": "2406302b62a3db0af442fb6cc1ce82345267ef6b"
25
+ "gitHead": "22dbe6cc56841d1caa585bf4e32a87298e28b938"
26
26
  }