@netacea/vercel 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +25 -66
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.4.5";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 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.4.7";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"))})};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,67 +1,26 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
|
|
27
|
-
"author": "Netacea <npm@netacea.com> (https://netacea.com)",
|
|
28
|
-
"license": "ISC",
|
|
29
|
-
"dependencies": {
|
|
30
|
-
"aws4fetch": "^1.0.20",
|
|
31
|
-
"jose": "^4.15.9",
|
|
32
|
-
"uuid": "^10.0.0"
|
|
33
|
-
},
|
|
34
|
-
"devDependencies": {
|
|
35
|
-
"@netacea/bundler": "^1.3.6",
|
|
36
|
-
"@netacea/netaceaintegrationbase": "^2.3.6",
|
|
37
|
-
"@netacea/netaceaintegrationtestrunner": "^1.11.6",
|
|
38
|
-
"@netacea/test-runner-scenarios": "^1.3.6",
|
|
39
|
-
"@netacea/test-runner-transforms": "^1.3.6",
|
|
40
|
-
"@netacea/test-runner-types": "^1.3.6",
|
|
41
|
-
"@rollup/plugin-commonjs": "^25.0.0",
|
|
42
|
-
"@rollup/plugin-json": "^6.0.0",
|
|
43
|
-
"@rollup/plugin-node-resolve": "^15.1.0",
|
|
44
|
-
"@rollup/plugin-replace": "^5.0.2",
|
|
45
|
-
"@rollup/plugin-terser": "^0.4.4",
|
|
46
|
-
"@rollup/plugin-typescript": "^11.1.1",
|
|
47
|
-
"@types/chai": "^4.3.5",
|
|
48
|
-
"@types/mocha": "^10.0.1",
|
|
49
|
-
"@types/node": "^20.9.1",
|
|
50
|
-
"@types/node-fetch": "^2.5.7",
|
|
51
|
-
"@types/proxyquire": "^1.3.28",
|
|
52
|
-
"@types/sinon": "^9.0.8",
|
|
53
|
-
"@types/tape": "^4.13.0",
|
|
54
|
-
"@types/uuid": "^10.0.0",
|
|
55
|
-
"chai": "^4.3.7",
|
|
56
|
-
"mocha": "^10.2.0",
|
|
57
|
-
"nyc": "^15.1.0",
|
|
58
|
-
"proxyquire": "^2.1.3",
|
|
59
|
-
"rollup": "^3.23.0",
|
|
60
|
-
"rollup-plugin-dts": "^6.0.2",
|
|
61
|
-
"rollup-plugin-node-externals": "^6.1.1",
|
|
62
|
-
"sinon": "^9.1.0",
|
|
63
|
-
"tape": "^5.0.1",
|
|
64
|
-
"typescript": "^5.2.2"
|
|
65
|
-
},
|
|
66
|
-
"gitHead": "5d5586c4f97005c35a8b43590628473074503cbb"
|
|
67
|
-
}
|
|
2
|
+
"name": "@netacea/vercel",
|
|
3
|
+
"version": "0.4.7",
|
|
4
|
+
"description": "Netacea Vercel CDN Integration",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"main": "dist/index.js",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/index.js",
|
|
12
|
+
"dist/index.d.ts"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"prepack": "npx netacea-bundler prepack",
|
|
16
|
+
"postpack": "npx netacea-bundler postpack"
|
|
17
|
+
},
|
|
18
|
+
"author": "Netacea <npm@netacea.com> (https://netacea.com)",
|
|
19
|
+
"license": "ISC",
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"aws4fetch": "^1.0.20",
|
|
22
|
+
"jose": "^4.15.9",
|
|
23
|
+
"uuid": "^10.0.0"
|
|
24
|
+
},
|
|
25
|
+
"gitHead": "55130dcc13dbff893f593bc3f66c12c61e73ed1d"
|
|
26
|
+
}
|