@netacea/vercel 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -19
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,9 +4,12 @@
|
|
|
4
4
|
|
|
5
5
|
[](http://www.typescriptlang.org/)
|
|
6
6
|
|
|
7
|
-
`@netacea/vercel` is a package designed to add [Netacea](https://netacea.com)
|
|
7
|
+
`@netacea/vercel` is a package designed to add [Netacea](https://netacea.com)
|
|
8
|
+
functionality to
|
|
9
|
+
[Vercel edge middleware](https://vercel.com/docs/edge-middleware).
|
|
8
10
|
|
|
9
|
-
This package has been released for Beta testing and interfaces may change
|
|
11
|
+
This package has been released for Beta testing and interfaces may change
|
|
12
|
+
without warning.
|
|
10
13
|
|
|
11
14
|
## Installation
|
|
12
15
|
|
|
@@ -18,30 +21,31 @@ Within your Vercel project, run:
|
|
|
18
21
|
|
|
19
22
|
This integration is best configured using Vercel environment variables.
|
|
20
23
|
|
|
21
|
-
Please consult the following table for the environment variables which must be
|
|
22
|
-
The Netacea Solutions Engineering team can assist in providing this config.
|
|
24
|
+
Please consult the following table for the environment variables which must be
|
|
25
|
+
set. The Netacea Solutions Engineering team can assist in providing this config.
|
|
23
26
|
|
|
24
|
-
| Name
|
|
25
|
-
|
|
26
|
-
| NETACEA_COOKIE_NAME
|
|
27
|
-
| NETACEA_CAPTCHA_COOKIE_NAME
|
|
28
|
-
| NETACEA_PROTECTOR_API_URL
|
|
29
|
-
| NETACEA_PROTECTION_MODE
|
|
27
|
+
| Name | Description |
|
|
28
|
+
| --------------------------- | ---------------------------------------- |
|
|
29
|
+
| NETACEA_COOKIE_NAME | Name of the Netacea session cookie. |
|
|
30
|
+
| NETACEA_CAPTCHA_COOKIE_NAME | Name of the Netacea captcha cookie. |
|
|
31
|
+
| NETACEA_PROTECTOR_API_URL | URL for the Netacea Protector API. |
|
|
32
|
+
| NETACEA_PROTECTION_MODE | The Protection Mode for the integration. |
|
|
30
33
|
|
|
31
34
|
The following variables should be set as **sensitive**:
|
|
32
35
|
|
|
33
|
-
| Name
|
|
34
|
-
|
|
35
|
-
| NETACEA_API_KEY
|
|
36
|
-
| NETACEA_COOKIE_ENCRYPTION_KEY
|
|
37
|
-
| NETACEA_SECRET_KEY
|
|
38
|
-
| NETACEA_KINESIS_ACCESS_KEY
|
|
39
|
-
| NETACEA_KINESIS_SECRET_KEY
|
|
40
|
-
| NETACEA_KINESIS_STREAM_NAME
|
|
36
|
+
| Name | Description |
|
|
37
|
+
| ----------------------------- | ----------------------------------------------- |
|
|
38
|
+
| NETACEA_API_KEY | API Key to contact Netacea services. |
|
|
39
|
+
| NETACEA_COOKIE_ENCRYPTION_KEY | Key used to secure the session cookie. |
|
|
40
|
+
| NETACEA_SECRET_KEY | Additional key for securing the session cookie. |
|
|
41
|
+
| NETACEA_KINESIS_ACCESS_KEY | Key to write to Netacea Kinesis ingest. |
|
|
42
|
+
| NETACEA_KINESIS_SECRET_KEY | Key to write to Netacea Kinesis ingest. |
|
|
43
|
+
| NETACEA_KINESIS_STREAM_NAME | Name of the stream to write ingested logs. |
|
|
41
44
|
|
|
42
45
|
## Middleware Setup
|
|
43
46
|
|
|
44
|
-
The following code should be placed in the `middleware.ts` file within your
|
|
47
|
+
The following code should be placed in the `middleware.ts` file within your
|
|
48
|
+
project:
|
|
45
49
|
|
|
46
50
|
```TypeScript
|
|
47
51
|
import { NextRequest, NextResponse } from 'next/server'
|
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 s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n,o,r,c=s(i),u=s(a);exports.NetaceaIngestType=void 0,(n=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",n.HTTP="HTTP",n.KINESIS="KINESIS",n.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 h=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const s=d(e,"Domain"),n=d(t,"Domain");void 0!==s&&void 0!==n?a=t.replace(n,s):void 0!==s&&void 0===n?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==n&&(i=e+(""!==e?`; Domain=${n}`:`Domain=${n}`))}else if(void 0!==e&&void 0===t){const t=d(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=d(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=d(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:d,removeDuplicateAttrs:p});function f(e){const t=p([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),s=a.indexOf(";");if(s<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,s),attributes:a.slice(s).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}};var C="@netacea/vercel",k="0.5.0";const I=globalThis.fetch.bind(globalThis),w={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-mitatacaptcha-value",A="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},N={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},T={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},b={0:w.none,1:w.block,2:w.none,3:w.block,4:w.block},_={1:w.captcha,2:w.captchaPass,3:w.captcha,4:w.allow,5:w.captcha,6:w.allow,7:w.captcha,a:w.captcha,b:w.captchaPass,c:w.captcha,d:w.allow,e:w.captcha},x="_/@#/",O="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),P=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function R(e){if(void 0===e)return;const t=e.match(P);if(null!=t){const[,e,i,a,s,n,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:n,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function K(e=16,t=O){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function M(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function H(e,i){const a=await M(t.Buffer.from(e),i),s=t.Buffer.from(a).toString("hex");return t.Buffer.from(s).toString("base64")}var D;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(D||(D={}));var L="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},j={},F={};Object.defineProperty(F,"__esModule",{value:!0}),F.validateRedirectLocation=void 0,F.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 V={},q={};function U(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=$("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function B(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const s=e[a]??"",n="string"==typeof s?s:s.join("; ");i.push(...G(n,t))}return i}function $(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function G(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(q,"__esModule",{value:!0}),q.findAllInCookieString=q.findFirstInCookieString=q.findAllInHeaders=q.findFirstInHeaders=q.findOnlyValueInHeaders=q.findAllValuesInHeaders=q.findFirstValueInHeaders=void 0,q.findFirstValueInHeaders=function(e,t){const i=U(e,t);if(void 0!==i)return i.slice(t.length+1)},q.findAllValuesInHeaders=function(e,t){return B(e,t).map((e=>e.slice(t.length+1)))},q.findOnlyValueInHeaders=function(e,t){const i=B(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},q.findFirstInHeaders=U,q.findAllInHeaders=B,q.findFirstInCookieString=$,q.findAllInCookieString=G;var z={};function W(e){return"set-cookie"===e||"Set-Cookie"===e}function J(e,t){const i=t+"=";return e.startsWith(i)}function X(e,t){if(!J(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function Y(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Q(e,t){for(const i of Object.keys(e)){if(!W(i))continue;const a=Z(Y(e,i),t);if(void 0!==a)return a}}function Z(e,t){return e.map((e=>e.trimStart())).find((e=>J(e,t)))}function ee(e,t){const i=[];for(const a of Object.keys(e)){if(!W(a))continue;const s=Y(e,a);i.push(...te(s,t))}return i}function te(e,t){return e.map((e=>e.trimStart())).filter((e=>J(e,t)))}Object.defineProperty(z,"__esModule",{value:!0}),z.findAllInSetCookieStrings=z.findAllInHeaders=z.findValueInSetCookieStrings=z.findFirstInSetCookieStrings=z.findFirstInHeaders=z.findOnlyValueInHeaders=z.findFirstValueInHeaders=z.parseValueFromString=void 0,z.parseValueFromString=X,z.findFirstValueInHeaders=function(e,t){const i=Q(e,t);return void 0!==i?X(i,t):void 0},z.findOnlyValueInHeaders=function(e,t){const i=ee(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?X(i[0],t):void 0},z.findFirstInHeaders=Q,z.findFirstInSetCookieStrings=Z,z.findValueInSetCookieStrings=function(e,t){const i=Z(e,t);if(void 0!==i)return X(i,t)},z.findAllInHeaders=ee,z.findAllInSetCookieStrings=te;var ie=L&&L.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ae=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),se=L&&L.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ie(t,e,i);return ae(t,e),t};Object.defineProperty(V,"__esModule",{value:!0}),V.setCookie=V.cookie=void 0,V.cookie=se(q),V.setCookie=se(z);var ne={},oe={},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";var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.headersToRecord=ce.increaseBatchSize=ce.handleFailedLogs=ce.batchArrayForKinesis=ce.sleep=void 0,ce.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},ce.batchArrayForKinesis=function(e,t,i){const a=[];for(let s=0;s<e.length;s+=t){const n=e.slice(s,s+t);a.push({Data:i.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return a},ce.handleFailedLogs=function(e,t,i){const a=2*i,s=[...e,...t],n=s.length-a;return n>0&&(console.error(`Netacea Error :: failed to send ${n} log(s) to Kinesis ingest.`),s.splice(0,n)),s},ce.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},ce.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(oe,"__esModule",{value:!0}),oe.WebStandardKinesis=void 0;const ue=re,he=ce;oe.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:ue.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 s={Records:(0,he.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ue.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var de={};Object.defineProperty(de,"__esModule",{value:!0}),de.Kinesis=void 0;const pe=re,le=ce;de.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:s}=e,n={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(n),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:pe.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=oe;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=de;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ne);var ge={};function fe(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(ge,"__esModule",{value:!0}),ge.parseHttpHeaderName=ge.stringOrDefault=ge.parseIntOrDefault=ge.parseNumberOrDefault=void 0,ge.parseNumberOrDefault=fe,ge.parseIntOrDefault=function(e,t){const i=fe(e,t);return"number"==typeof i?Math.floor(i):i},ge.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},ge.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var ye={};Object.defineProperty(ye,"__esModule",{value:!0}),ye.searchParamsFromRecord=void 0,ye.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var me={},Se={};Object.defineProperty(Se,"__esModule",{value:!0}),Se.JweFactory=void 0;Se.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),s=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(s).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Ce=L&&L.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ke=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ie=L&&L.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Ce(t,e,i);return ke(t,e),t};Object.defineProperty(me,"__esModule",{value:!0}),me.jwe=void 0,me.jwe=Ie(Se);var we,ve={};var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.ProtectorApiResponseView=Ae.AbstractProtectorApiResponseView=void 0;const Ee=ge;class Ne{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Ee.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,Ee.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Ee.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,s=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:s})}(e,t,a)}}Ae.AbstractProtectorApiResponseView=Ne;var Te;function be(){return Te||(Te=1,function(e){var t=L&&L.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=L&&L.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=L&&L.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(a,e,s);return i(a,e),a},s=L&&L.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=void 0,e.configValidation=a(F),e.headers=a(V),e.ingest=a(ne),e.parsing=a(ge),e.url=a(ye),e.webcrypto=a(me),e.graphql=a(function(){if(we)return ve;we=1,Object.defineProperty(ve,"__esModule",{value:!0}),ve.truncateLongFields=ve.parseGraphQl=ve.parseGraphQlRequestBody=ve.getGraphQLParserConfig=void 0;const e=be();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const n=t[e];t[e]=(s=i,(a=n).length<=s?a:a.slice(0,s)+"…")}var a,s;return t}return ve.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},ve.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const s=JSON.parse(a);if("object"!=typeof s)throw new Error("Netacea Error: Invalid GraphQL JSON");const n={...t(e,s?.query??"")},o=(s?.operationName??"").trim();return""!==o&&(n.OpName=o),i(e,n)},ve.parseGraphQl=t,ve.truncateLongFields=i,ve}()),s(Ae,e)}(j)),j}Ae.ProtectorApiResponseView=class extends Ne{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var _e=be();const xe=new _e.webcrypto.jwe.JweFactory(c);function Oe(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 Pe(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:s}=e;return a.includes(i)&&s.includes("trackingId")&&"get"===t.toLowerCase()}function Re(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function Ke(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 Me(e,t,i=""){return e.get(t)??i}function He(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}function De(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Le(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 je(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}class Fe 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 Ve(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:s,integrationVersion:n,ip:o,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:h,netaceaCookieStatus:d,path:p,referer:l,requestHost:g,requestId:f,requestTime:y,sessionStatus:m,status:S,timeUnixMsUTC:C,userAgent:k,workerInstanceId:I,xForwardedFor:w,ipHeader:v}){return{Request:`${r} ${p}`,TimeLocal:new Date(C??Date.now()).toUTCString(),TimeUnixMsUTC:C,RealIp:o,UserAgent:k,Status:S,RequestTime:y?.toString(),BytesSent:e?.toString(),Referer:""===l?"-":l,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:m??"",ProtectorLatencyMs:u,ProtectorStatus:h,IntegrationType:s??"",IntegrationVersion:n??"",ProtectionMode:a??"",RequestHost:g,RequestId:f??"",XForwardedFor:w,IpFromHeader:v,WorkerInstanceId:I,NetaceaUserIdCookieStatus:d,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const qe="unknown";function Ue(e,t,i){let{match:a,mitigate:s,captcha:n}=t;i||("2"===n?n="4":"3"===n?n="5":"b"===n?n="d":"c"===n&&(n="e"));let o=E[a]??qe+"_";o+=N[s]??qe;let r=b[s];if("0"!==n){o+=","+(T[n]??qe);const e=_[n];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=w.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:s,captcha:n}}}function Be(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function $e(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 Ge{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),s=await this.readCookie(e,this.config.captchaCookieName),n=e.headers.get("x-forwarded-for")??void 0;let o,r=n?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(o=e.headers.get(this.config.ipHeaderName)??void 0,r=o??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:h,userId:d}=await async function(e,t,i,a,s){const n=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const s=R(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(x),a=Math.floor(Date.now()/1e3),n=parseInt(s.expiry)<a,o=["1","3","5","a","c","e"].includes(s.protectorCheckCodes.captcha),r="3"===s.protectorCheckCodes.mitigate,c=o||r,u=await H(t+"|"+s.expiry,i),h=s.ipHash===u,d=s.signature===await H(e,i);return{userId:s.userId,requiresReissue:n||!h,isExpired:n,shouldExpire:c,isSameIP:h,isPrimaryHashValid:d,protectorCheckCodes:s.protectorCheckCodes}}return a}(a,s,e.secretKey);if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:s,shouldExpire:o,isSameIP:r}=n,c=s||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?D.RENEW_SESSION:D.EXISTING_SESSION,{sessionStatus:u}=Ue(e.mitigationType,n.protectorCheckCodes,Re(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:K(),sessionCookieStatus:D.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:h,captchaToken:s,sessionCookieDetails:c,sessionCookieStatus:u,userId:d};return{clientIp:r,fingerprints:await ze(e),ipHeader:void 0!==o?`${this.config.ipHeaderName}: ${o}`:void 0,method:i,protocol:void 0,requestId:e.headers.get("x-vercel-id")??"",sessionDetails:p,url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedForHeaderValue:n}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),s=`${t}=`;for(const e of a)if(e.startsWith(s)){const i=e.slice(s.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await xe.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ze(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await $e(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),s=await async function(e){const t=e.join(",");return await $e(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}const{configureCookiesDomain:We}=S.cookie.attributes;class Je{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?h:i,this.mitigationServiceTimeoutMs=_e.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=_e.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=_e.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:s}=We(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var n,o;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=s??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(n=this.mitigationType,void 0===(o=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?n===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),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class Xe{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Je(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 _e.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new Ge({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let s=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof s&&(s={sessionStatus:"error_open",apiCallLatency:s}),await this.handleResponse(i,s,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=Re(t.url,e.method),s=a&&i.sessionStatus.includes("checkpoint_post"),n=!a&&Pe(t.url,e.method,this.config.netaceaCaptchaPath),o=()=>{const e=new Headers;if(!n&&!s)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!s?"captcha"===i.mitigation?{...i,response:Le({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:De({responseHeaders:o()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:De({status:402,responseHeaders:o()})}:{...i,response:je({config:this.config,responseHeaders:o()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:s}=R(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:n}=Ue(this.config.mitigationType,a,Re(new URL(e.url),e.method));return{userId:s,sessionStatus:n,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),s=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:Me(i.rawResponse.headers,"content-length","0"),cookieFingerprint:s.fingerprints.cookieFingerprint,headerFingerprint:s.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:s.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:s.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:Me(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestId:s.requestId,requestTime:"0",sessionStatus:i.sessionStatus??s.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:Me(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:s.xForwardedForHeaderValue,ipHeader:s.ipHeader})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match:s,mitigate:n,captcha:o}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:s,mitigate:n,captcha:o}}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const n=`${e}${i}`,o=new Request(n,{...{method:t,body:s,headers:a},duplex:"half"}),r=await I(n,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i){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:Ke(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?Oe(e.headers.get("Accept")??void 0):Oe();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,s;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Fe&&(s=i.latencyMs,a=i.protectorApiResponse?.status);return{response:Re(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:Be({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:s,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await xe.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=Me(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Ve(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){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([D.NEW_SESSION,D.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),s=a.responseView.getProtectorCodes(),{match:n,mitigate:o,captcha:r}=s,c=[await this.createMitata(e.clientIp,i,n,o,r,a.mitataMaxAge)],u={match:n,mitigate:o,captcha:r},h=Ue(this.config.mitigationType,u,!1),d={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:c,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[w.block,w.captcha].includes(h.mitigation),redirect:"5"===o?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:h.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(d.injectHeaders=Be(h.parts,a.eventId)),d}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=Ue(this.config.mitigationType,i,!1),s={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[w.block,w.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(s.injectHeaders=Be(a.parts)),s}}async createMitata(e,t,i,a,s,n=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,s].join("");let h=await async function(e,t,i,a,s="000"){const n=[i,t,await H(e+"|"+String(i),a),s].join(x);return`${await H(n,a)}${x}${n}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await xe.encrypt(h,this.config.cookieEncryptionKey,"A256GCM")),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:s,captcha:n,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:s,captcha:n},h=Ue(this.config.mitigationType,u,!0),d={body:o,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:h.sessionStatus,mitigation:h.mitigation,mitigated:[w.block,w.captcha].includes(h.mitigation),protectorCheckCodes:{match:h.parts.match.toString(),mitigate:h.parts.mitigate.toString(),captcha:h.parts.captcha.toString()}};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(d.injectHeaders=Be(h.parts)),d}async getMitataCaptchaFromHeaders(e){let t=e[v];const i=parseInt(e[A]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await xe.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),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!==D.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const s=new URLSearchParams;s.append("headerFP",e.fingerprints.headerFingerprint),s.append("netaceaHeaders","request-id");const n=Date.now(),o=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,o),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${s.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-n;if(200!==c.status)throw new Fe(c,u);const h=new _e.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=h.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,d,p,l,g),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),y=h.eventId;return{status:c.status,match:d,mitigate:p,captcha:l,setCookie:f,body:c.body,eventId:y,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:He({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==D.NEW_SESSION&&(s["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),s["X-Netacea-Captcha-Content-Type"]=t,s["X-Netacea-Request-Id"]=e.requestId;let n="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id"),i&&(n="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${n}?${o.toString()}`,headers:s,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new Fe(c,u);const h=new _e.ProtectorApiResponseView(c.fetchResponse),{match:d,mitigate:p,captcha:l}=h.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,d,p,l,h.sessionCookieMaxAge),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e));if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await h.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:h,status:c.status,setCookie:g,body:c.body,eventId:h.eventId,mitataMaxAge:h.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(Pe(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(Re(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===D.NEW_SESSION,a=t===D.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}}const Ye=e=>_e.parsing.parseIntOrDefault(e,{defaultValue:void 0});function Qe(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function Ze(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=Ze(e,t,a);if(void 0!==i)return i}}function et(e,t){const i=Ze(e,t,"CAPTCHA_HEADER_NAME"),a=Ze(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function tt(e,t){const i=Ze(e,t,"KINESIS_STREAM_NAME"),a=Ze(e,t,"KINESIS_ACCESS_KEY"),s=Ze(e,t,"KINESIS_SECRET_KEY"),n=Qe({logBatchSize:Ye(Ze(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:Ye(Ze(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==s)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:s,...n}}exports.NetaceaVercelIntegration=Xe,exports.default=Xe,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return Qe({apiKey:Ze(e,t,"API_KEY"),captchaHeader:et(e,t),captchaSecretKey:Ze(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:Ze(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:Ze(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:Ze(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:Ze(e,t,"INGEST_SERVICE_URL"),ingestType:Ze(e,t,"INGEST_TYPE"),ipHeaderName:Ze(e,t,"IP_HEADER_NAME"),kinesis:tt(e,t),mitataCookieExpirySeconds:Ye(Ze(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:Ze(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:Ze(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:Ze(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:Ze(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:Ze(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:Ze(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:Ze(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:Ze(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:Ye(Ze(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:Ze(e,t,"COOKIE_NAME"),secretKey:Ze(e,t,"SECRET_KEY"),timeout:Ye(Ze(e,t,"TIMEOUT"))})};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,n,r,c=o(i),u=o(a);exports.NetaceaIngestType=void 0,(s=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",s.HTTP="HTTP",s.KINESIS="KINESIS",s.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(n=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",n.INJECT="INJECT",n.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const d=3e3;function 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 h(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=h(e??"",!0),a=t=h(t??"",!0);if(void 0!==e&&void 0!==t){const o=p(e,"Domain"),s=p(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=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:h});function f(e){const t=h([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return f({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:f});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const C={cookie:{parse:m,attributes:g,netaceaSession:y}};var S="@netacea/vercel",k="0.6.0";const I=globalThis.fetch.bind(globalThis),v={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},w="x-netacea-mitatacaptcha-value",N="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},b={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},A={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},T={0:v.none,1:v.block,2:v.none,3:v.block,4:v.block},_={1:v.captcha,2:v.captchaPass,3:v.captcha,4:v.allow,5:v.captcha,6:v.allow,7:v.captcha,a:v.captcha,b:v.captchaPass,c:v.captcha,d:v.allow,e:v.captcha},O="_/@#/",P="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),R=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function x(e){if(void 0===e)return;const t=e.match(R);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}function K(e=16,t=P){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function M(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 V(e,i){const a=await M(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}var j;!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(j||(j={}));var D,H="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},L={},F={},q={},$={};Object.defineProperty($,"__esModule",{value:!0}),$.NetaceaCookieV3IssueReason=void 0,function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(D||($.NetaceaCookieV3IssueReason=D={}));var U={};Object.defineProperty(U,"__esModule",{value:!0}),U.netaceaCookieV3OptionalKeyMap=U.netaceaCookieV3KeyMap=U.COOKIEDELIMITER=void 0,U.COOKIEDELIMITER="_/@#/",U.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},U.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(q,"__esModule",{value:!0}),q.defaultInvalidResponse=q.matchNetaceaCookieV3=q.checkNetaceaCookieV3=q.objectIsNetaceaCookieV3=q.cookieIsNetaceaV3Format=q.createNetaceaCookieV3=void 0;const B=$,G=U;function z(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(G.netaceaCookieV3KeyMap).find((e=>G.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(G.netaceaCookieV3OptionalKeyMap).find((e=>G.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function W(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:B.NetaceaCookieV3IssueReason.NO_SESSION}}q.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in G.netaceaCookieV3OptionalKeyMap?`${G.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${G.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},q.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(G.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(G.netaceaCookieV3KeyMap).includes(e)))},q.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(G.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},q.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return W();let i;try{i=z(e)}catch{return W()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return W()},q.matchNetaceaCookieV3=z,q.defaultInvalidResponse=W;var J={};Object.defineProperty(J,"__esModule",{value:!0}),J.AbstractCookieFactory=void 0;const X=$,Y=q,Q=U,Z="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),ee=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;J.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,Y.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??"",match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??X.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,Y.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,Y.cookieIsNetaceaV3Format)(i)?(0,Y.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(Q.COOKIEDELIMITER);return`${await this.hash(s,a)}${Q.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(ee);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,Y.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(Q.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:X.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>Z[e%Z.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=q;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=J;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=U;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=$;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(F);var te={};Object.defineProperty(te,"__esModule",{value:!0}),te.validateRedirectLocation=void 0,te.validateRedirectLocation=function(e){if(""!==(e=e??""))try{return new URL(e).toString()}catch{if(/^https?:\/\//i.test(e))return;return e.startsWith("/")?e:`/${e}`}};var ie={},ae={};function oe(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=ne("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function se(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...re(s,t))}return i}function ne(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function re(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ae,"__esModule",{value:!0}),ae.findAllInCookieString=ae.findFirstInCookieString=ae.findAllInHeaders=ae.findFirstInHeaders=ae.findOnlyValueInHeaders=ae.findAllValuesInHeaders=ae.findFirstValueInHeaders=void 0,ae.findFirstValueInHeaders=function(e,t){const i=oe(e,t);if(void 0!==i)return i.slice(t.length+1)},ae.findAllValuesInHeaders=function(e,t){return se(e,t).map((e=>e.slice(t.length+1)))},ae.findOnlyValueInHeaders=function(e,t){const i=se(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ae.findFirstInHeaders=oe,ae.findAllInHeaders=se,ae.findFirstInCookieString=ne,ae.findAllInCookieString=re;var ce={};function ue(e){return"set-cookie"===e||"Set-Cookie"===e}function de(e,t){const i=t+"=";return e.startsWith(i)}function pe(e,t){if(!de(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function he(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function le(e,t){for(const i of Object.keys(e)){if(!ue(i))continue;const a=ge(he(e,i),t);if(void 0!==a)return a}}function ge(e,t){return e.map((e=>e.trimStart())).find((e=>de(e,t)))}function fe(e,t){const i=[];for(const a of Object.keys(e)){if(!ue(a))continue;const o=he(e,a);i.push(...ye(o,t))}return i}function ye(e,t){return e.map((e=>e.trimStart())).filter((e=>de(e,t)))}Object.defineProperty(ce,"__esModule",{value:!0}),ce.findAllInSetCookieStrings=ce.findAllInHeaders=ce.findValueInSetCookieStrings=ce.findFirstInSetCookieStrings=ce.findFirstInHeaders=ce.findOnlyValueInHeaders=ce.findFirstValueInHeaders=ce.parseValueFromString=void 0,ce.parseValueFromString=pe,ce.findFirstValueInHeaders=function(e,t){const i=le(e,t);return void 0!==i?pe(i,t):void 0},ce.findOnlyValueInHeaders=function(e,t){const i=fe(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?pe(i[0],t):void 0},ce.findFirstInHeaders=le,ce.findFirstInSetCookieStrings=ge,ce.findValueInSetCookieStrings=function(e,t){const i=ge(e,t);if(void 0!==i)return pe(i,t)},ce.findAllInHeaders=fe,ce.findAllInSetCookieStrings=ye;var me=H&&H.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ce=H&&H.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Se=H&&H.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&me(t,e,i);return Ce(t,e),t};Object.defineProperty(ie,"__esModule",{value:!0}),ie.setCookie=ie.cookie=void 0,ie.cookie=Se(ae),ie.setCookie=Se(ce);var ke={},Ie={},ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.KINESIS_URL=ve.API_VERSION=ve.REGION=ve.PAYLOAD_TYPE=ve.STATE=void 0,ve.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},ve.PAYLOAD_TYPE="string",ve.REGION="eu-west-1",ve.API_VERSION="2013-12-02",ve.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var we={};Object.defineProperty(we,"__esModule",{value:!0}),we.headersToRecord=we.increaseBatchSize=we.handleFailedLogs=we.batchArrayForKinesis=we.sleep=void 0,we.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},we.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},we.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},we.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},we.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.WebStandardKinesis=void 0;const Ne=ve,Ee=we;Ie.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:(0,Ee.headersToRecord)(i.headers),host:Ne.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ee.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ee.handleFailedLogs)(this.logCache,e,this.maxLogBatchSize)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push((0,Ee.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ee.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const o={Records:(0,Ee.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(Ne.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.Kinesis=void 0;const Ae=ve,Te=we;be.Kinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=this.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);if("POST"!==t.method)throw new Error(`Unexpected method. Expected POST but got ${t.method}`);await this.deps.makeRequest({headers:t.headers??{},host:`https://${t.hostname}`,method:t.method,path:t.path??"/",body:t.body}),this.logBatchSize=(0,Te.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Te.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,Te.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Te.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,Te.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:Ae.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=Ie;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=be;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ke);var _e={};function Oe(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(_e,"__esModule",{value:!0}),_e.parseHttpHeaderName=_e.stringOrDefault=_e.parseIntOrDefault=_e.parseNumberOrDefault=void 0,_e.parseNumberOrDefault=Oe,_e.parseIntOrDefault=function(e,t){const i=Oe(e,t);return"number"==typeof i?Math.floor(i):i},_e.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},_e.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.searchParamsFromRecord=void 0,Pe.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var Re={},xe={};Object.defineProperty(xe,"__esModule",{value:!0}),xe.JweFactory=void 0;xe.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Ke=H&&H.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Me=H&&H.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ve=H&&H.__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)&&Ke(t,e,i);return Me(t,e),t};Object.defineProperty(Re,"__esModule",{value:!0}),Re.jwe=void 0,Re.jwe=Ve(xe);var je,De={};var He={};Object.defineProperty(He,"__esModule",{value:!0}),He.ProtectorApiResponseView=He.AbstractProtectorApiResponseView=void 0;const Le=_e;class Fe{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Le.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,Le.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Le.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}}He.AbstractProtectorApiResponseView=Fe;var qe;function $e(){return qe||(qe=1,function(e){var t=H&&H.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=H&&H.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=H&&H.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=H&&H.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=void 0,e.cookie=a(F),e.configValidation=a(te),e.headers=a(ie),e.ingest=a(ke),e.parsing=a(_e),e.url=a(Pe),e.webcrypto=a(Re),e.graphql=a(function(){if(je)return De;je=1,Object.defineProperty(De,"__esModule",{value:!0}),De.truncateLongFields=De.parseGraphQl=De.parseGraphQlRequestBody=De.getGraphQLParserConfig=void 0;const e=$e();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}return De.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},De.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const o=JSON.parse(a);if("object"!=typeof o)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,o?.query??"")},n=(o?.operationName??"").trim();return""!==n&&(s.OpName=n),i(e,s)},De.parseGraphQl=t,De.truncateLongFields=i,De}()),o(He,e)}(L)),L}He.ProtectorApiResponseView=class extends Fe{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var Ue=$e();const Be=new Ue.webcrypto.jwe.JweFactory(c);function Ge(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 ze(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:o}=e;return a.includes(i)&&o.includes("trackingId")&&"get"===t.toLowerCase()}function We(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function Je(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 Xe(e,t,i=""){return e.get(t)??i}function Ye(e){let t="",i="";for(const a in e){const o=e[a];void 0!==o&&(t=`${t}${i}${a}=${o}`,i="; ")}return t}function Qe(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Ze(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 et(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}class tt 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 it(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:o,integrationVersion:s,ip:n,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:d,netaceaCookieStatus:p,path:h,referer:l,requestHost:g,requestId:f,requestTime:y,sessionStatus:m,status:C,timeUnixMsUTC:S,userAgent:k,workerInstanceId:I,xForwardedFor:v,ipHeader:w}){return{Request:`${r} ${h}`,TimeLocal:new Date(S??Date.now()).toUTCString(),TimeUnixMsUTC:S,RealIp:n,UserAgent:k,Status:C,RequestTime:y?.toString(),BytesSent:e?.toString(),Referer:""===l?"-":l,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:m??"",ProtectorLatencyMs:u,ProtectorStatus:d,IntegrationType:o??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:g,RequestId:f??"",XForwardedFor:v,IpFromHeader:w,WorkerInstanceId:I,NetaceaUserIdCookieStatus:p,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const at="unknown";function ot(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=E[a]??at+"_";n+=b[o]??at;let r=T[o];if("0"!==s){n+=","+(A[s]??at);const e=_[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=v.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function st(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function nt(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 rt{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),o=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("x-forwarded-for")??void 0;let n,r=s?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(n=e.headers.get(this.config.ipHeaderName)??void 0,r=n??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:p}=await async function(e,t,i,a,o){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const o=x(e);if(void 0!==o){const e=[o.expiry,o.userId,o.ipHash,o.mitigationType].join(O),a=Math.floor(Date.now()/1e3),s=parseInt(o.expiry)<a,n=["1","3","5","a","c","e"].includes(o.protectorCheckCodes.captcha),r="3"===o.protectorCheckCodes.mitigate,c=n||r,u=await V(t+"|"+o.expiry,i),d=o.ipHash===u,p=o.signature===await V(e,i);return{userId:o.userId,requiresReissue:s||!d,isExpired:s,shouldExpire:c,isSameIP:d,isPrimaryHashValid:p,protectorCheckCodes:o.protectorCheckCodes}}return a}(a,o,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:o,shouldExpire:n,isSameIP:r}=s,c=o||n||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?j.RENEW_SESSION:j.EXISTING_SESSION,{sessionStatus:u}=ot(e.mitigationType,s.protectorCheckCodes,We(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:K(),sessionCookieStatus:j.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),h={sessionStatus:d,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:u,userId:p};return{clientIp:r,fingerprints:await ct(e),ipHeader:void 0!==n?`${this.config.ipHeaderName}: ${n}`:void 0,method:i,protocol:void 0,requestId:e.headers.get("x-vercel-id")??"",sessionDetails:h,url:t,userAgent:e.headers.get("user-agent")??"",contentType:e.headers.get("content-type")??void 0,xForwardedForHeaderValue:s}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Be.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ct(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 nt(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),o=await async function(e){const t=e.join(",");return await nt(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===o?o:`c_${o.substring(1,15)}`}}const{configureCookiesDomain:ut}=C.cookie.attributes;class dt{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?d:i,this.mitigationServiceTimeoutMs=Ue.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:o}=ut(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var s,n;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=o??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(s=this.mitigationType,void 0===(n=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?s===exports.NetaceaMitigationType.INGEST?3600:60:n),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class pt{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new dt(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 Ue.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new rt({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,ipHeaderName:this.config.ipHeaderName}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let o=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,o,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=We(t.url,e.method),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&ze(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!o?"captcha"===i.mitigation?{...i,response:Ze({config:this.config,responseHeaders:n(),body:i.body})}:{...i,response:Qe({responseHeaders:n()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Qe({status:402,responseHeaders:n()})}:{...i,response:et({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=x(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=ot(this.config.mitigationType,a,We(new URL(e.url),e.method));return{userId:o,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),o=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:Xe(i.rawResponse.headers,"content-length","0"),cookieFingerprint:o.fingerprints.cookieFingerprint,headerFingerprint:o.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:S.replace("@netacea/",""),integrationVersion:k,ip:o.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:o.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:Xe(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestId:o.requestId,requestTime:"0",sessionStatus:i.sessionStatus??o.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:Xe(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:o.xForwardedForHeaderValue,ipHeader:o.ipHeader})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n}}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await I(s,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(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",S.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:Je(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?Ge(e.headers.get("Accept")??void 0):Ge();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof tt&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:We(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:st({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await Be.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=Xe(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=it(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){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([j.NEW_SESSION,j.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),o=a.responseView.getProtectorCodes(),{match:s,mitigate:n,captcha:r}=o,c=[await this.createMitata(e.clientIp,i,s,n,r,a.mitataMaxAge)],u={match:s,mitigate:n,captcha:r},d=ot(this.config.mitigationType,u,!1),p={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:c,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),redirect:"5"===n?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(p.injectHeaders=st(d.parts,a.eventId)),p}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=ot(this.config.mitigationType,i,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[v.block,v.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(o.injectHeaders=st(a.parts)),o}}async createMitata(e,t,i,a,o,s=86400,n=void 0){const r=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,c=n??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,o].join("");let d=await async function(e,t,i,a,o="000"){const s=[i,t,await V(e+"|"+String(i),a),o].join(O);return`${await V(s,a)}${O}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(d=await Be.encrypt(d,this.config.cookieEncryptionKey,"A256GCM")),C.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:d,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=ot(this.config.mitigationType,u,!0),p={body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}};return this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(p.injectHeaders=st(d.parts)),p}async getMitataCaptchaFromHeaders(e){let t=e[w];const i=parseInt(e[N]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Be.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),C.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==j.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=Date.now(),n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,n),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-s;if(200!==c.status)throw new tt(c,u);const d=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:p,mitigate:h,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,p,h,l,g),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),y=d.eventId;return{status:c.status,match:p,mitigate:h,captcha:l,setCookie:f,body:c.body,eventId:y,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const o={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Ye({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==j.NEW_SESSION&&(o["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),o["X-Netacea-Captcha-Content-Type"]=t,o["X-Netacea-Request-Id"]=e.requestId;let s="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&n.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${n.toString()}`,headers:o,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new tt(c,u);const d=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:p,mitigate:h,captcha:l}=d.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,p,h,l,d.sessionCookieMaxAge),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e));if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await d.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:d,status:c.status,setCookie:g,body:c.body,eventId:d.eventId,mitataMaxAge:d.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(ze(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(We(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===j.NEW_SESSION,a=t===j.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}}const ht=e=>Ue.parsing.parseIntOrDefault(e,{defaultValue:void 0});function lt(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function gt(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=gt(e,t,a);if(void 0!==i)return i}}function ft(e,t){const i=gt(e,t,"CAPTCHA_HEADER_NAME"),a=gt(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function yt(e,t){const i=gt(e,t,"KINESIS_STREAM_NAME"),a=gt(e,t,"KINESIS_ACCESS_KEY"),o=gt(e,t,"KINESIS_SECRET_KEY"),s=lt({logBatchSize:ht(gt(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:ht(gt(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==o)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:o,...s}}exports.NetaceaVercelIntegration=pt,exports.default=pt,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return lt({apiKey:gt(e,t,"API_KEY"),captchaHeader:ft(e,t),captchaSecretKey:gt(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:gt(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:gt(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:gt(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:gt(e,t,"INGEST_SERVICE_URL"),ingestType:gt(e,t,"INGEST_TYPE"),ipHeaderName:gt(e,t,"IP_HEADER_NAME"),kinesis:yt(e,t),mitataCookieExpirySeconds:ht(gt(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:gt(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:gt(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:gt(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:gt(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:gt(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:gt(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:gt(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:gt(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:ht(gt(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:gt(e,t,"COOKIE_NAME"),secretKey:gt(e,t,"SECRET_KEY"),timeout:ht(gt(e,t,"TIMEOUT"))})};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/vercel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Netacea Vercel CDN Integration",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
"jose": "^4.15.9",
|
|
23
23
|
"uuid": "^10.0.0"
|
|
24
24
|
},
|
|
25
|
-
"gitHead": "
|
|
25
|
+
"gitHead": "d43fe84b8bbac77a7592bac347c0e9721d1389d8"
|
|
26
26
|
}
|