@netacea/vercel 0.1.29 → 0.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +18 -61
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -162,79 +162,36 @@ interface InjectHeaders {
|
|
|
162
162
|
'x-netacea-event-id'?: string;
|
|
163
163
|
}
|
|
164
164
|
interface IngestArgs {
|
|
165
|
-
/**
|
|
166
|
-
* Client IP Address
|
|
167
|
-
*/
|
|
168
|
-
ip: string;
|
|
169
|
-
/**
|
|
170
|
-
* Client User-Agent header value
|
|
171
|
-
*/
|
|
172
|
-
userAgent: string;
|
|
173
|
-
/**
|
|
174
|
-
* Response status code
|
|
175
|
-
* Should be 403 if Netacea mitigated
|
|
176
|
-
*/
|
|
177
|
-
status: string;
|
|
178
|
-
/**
|
|
179
|
-
* Request method
|
|
180
|
-
*/
|
|
181
|
-
method: string;
|
|
182
|
-
/**
|
|
183
|
-
* Request path
|
|
184
|
-
*/
|
|
185
|
-
path: string;
|
|
186
|
-
/**
|
|
187
|
-
* Request protocol
|
|
188
|
-
*/
|
|
189
|
-
protocol: string | null;
|
|
190
|
-
/**
|
|
191
|
-
* Request referer header value
|
|
192
|
-
*/
|
|
193
|
-
referer: string;
|
|
194
|
-
/**
|
|
195
|
-
* Request content-length header, or body size
|
|
196
|
-
*/
|
|
197
165
|
bytesSent: string | number;
|
|
198
|
-
/**
|
|
199
|
-
* The time the request was started, in unix milliseconds format.
|
|
200
|
-
*/
|
|
201
|
-
timeUnixMsUTC?: number;
|
|
202
|
-
/**
|
|
203
|
-
* Time taken to serve request
|
|
204
|
-
*/
|
|
205
|
-
requestTime: string | number;
|
|
206
|
-
/**
|
|
207
|
-
* Netacea mitata cookie value.
|
|
208
|
-
* Should be request's cookie value if Netacea was not called.
|
|
209
|
-
*/
|
|
210
|
-
mitataCookie?: string;
|
|
211
|
-
/**
|
|
212
|
-
* Session status from `ComposeResultResponse`
|
|
213
|
-
*/
|
|
214
|
-
sessionStatus?: string;
|
|
215
|
-
/**
|
|
216
|
-
* Type of the integration, for example "Cloudflare" or "Cloudfront"
|
|
217
|
-
*/
|
|
218
|
-
integrationType?: string;
|
|
219
|
-
/**
|
|
220
|
-
* SEMVER string indicating the version of the integration
|
|
221
|
-
* Example: 1.2.3
|
|
222
|
-
*/
|
|
223
|
-
integrationVersion?: string;
|
|
224
|
-
/**
|
|
225
|
-
* IP values set by a CDN under "x-forwarded-for" header
|
|
226
|
-
*/
|
|
227
166
|
cookieFingerprint?: string;
|
|
228
167
|
gqlOpName?: string;
|
|
229
168
|
gqlOpType?: string;
|
|
230
169
|
headerFingerprint?: string;
|
|
231
170
|
integrationMode?: string;
|
|
171
|
+
integrationType?: string;
|
|
172
|
+
integrationVersion?: string;
|
|
173
|
+
ip: string;
|
|
232
174
|
ipHeader?: string;
|
|
175
|
+
method: string;
|
|
176
|
+
mitataCookie?: string;
|
|
233
177
|
mitigationLatency?: number;
|
|
234
178
|
mitigationStatus?: number;
|
|
235
179
|
netaceaCookieStatus?: number;
|
|
180
|
+
path: string;
|
|
181
|
+
protocol: string | null;
|
|
182
|
+
query?: string;
|
|
183
|
+
referer: string;
|
|
184
|
+
reqHandlerId?: string;
|
|
185
|
+
reqHandlerMs?: number;
|
|
236
186
|
requestHost?: string;
|
|
237
187
|
requestId?: string;
|
|
188
|
+
requestTime: string | number;
|
|
189
|
+
resHandlerId?: string;
|
|
190
|
+
resHandlerMs?: number;
|
|
191
|
+
sessionStatus?: string;
|
|
192
|
+
status: string;
|
|
193
|
+
timeUnixMsUTC?: number;
|
|
194
|
+
userAgent: string;
|
|
238
195
|
workerInstanceId?: string;
|
|
239
196
|
xForwardedFor?: string;
|
|
240
197
|
}
|
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),h=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 u=3e3;function d(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function p(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":l(e.split(";"),t).join("; ")}function l(e,t=!1){if(t)return l(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var g=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=p(e??"",!0),a=t=p(t??"",!0);if(void 0!==e&&void 0!==t){const 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(";");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.1.29";const I=globalThis.fetch.bind(globalThis),w={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",E="x-netacea-mitigate",N="x-netacea-captcha",A="x-netacea-mitata-expiry",T="x-netacea-mitatacaptcha-value",_="x-netacea-mitatacaptcha-expiry",b="x-netacea-event-id",O={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},K={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},x={0:w.none,1:w.block,2:w.none,3:w.block,4:w.block},R={1:w.captcha,2:w.captchaPass,3:w.captcha,4:w.allow,5:w.captcha,6:w.allow,7:w.captcha,a:w.captcha,b:w.captchaPass,c:w.captcha,d:w.allow,e:w.captcha},M="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function L(e){if(void 0===e)return;const t=e.match(H);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 j(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),s=t.Buffer.from(a).toString("hex");return t.Buffer.from(s).toString("base64")}var U;async function B(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function $(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function V(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}function z(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 G(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function W(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function J(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}function Y(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(U||(U={}));class Z 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 Q(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:h,mitigationStatus:u,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:h,ProtectorStatus:u,IntegrationType:s??"",IntegrationVersion:n??"",ProtectionMode:a??"",RequestHost:g,RequestId:f??"",XForwardedFor:w,IpHeader:v,WorkerInstanceId:I,NetaceaUserIdCookieStatus:d,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const ee="unknown";function te(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=O[a]??ee+"_";o+=K[s]??ee;let r=x[s];if("0"!==n){o+=","+(P[n]??ee);const e=R[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}}}async function ie(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 ae{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:h,sessionStatus:u,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=L(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(M),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,h=await F(t+"|"+s.expiry,i),u=s.ipHash===h,d=s.signature===await F(e,i);return{userId:s.userId,requiresReissue:n||!u,isExpired:n,shouldExpire:c,isSameIP:u,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?U.RENEW_SESSION:U.EXISTING_SESSION,{sessionStatus:h}=te(e.mitigationType,n.protectorCheckCodes,G(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:h,sessionCookieDetails:n}}return{sessionStatus:"",userId:j(),sessionCookieStatus:U.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:u,captchaToken:s,sessionCookieDetails:c,sessionCookieStatus:h,userId:d};return{clientIp:r,fingerprints:await se(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 $(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function se(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 ie(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 ie(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}var ne="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},oe={},re={},ce={},he=ne&&ne.__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]}),ue=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),de=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&he(t,e,i);return ue(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0}),ce.isJweEncrypted=ce.decrypt=ce.encrypt=void 0;const pe=de(i);ce.encrypt=async function(e,t){const i=pe.base64url.decode(t),a=(new TextEncoder).encode(e);return await new pe.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ce.decrypt=async function(e,t){const i=pe.base64url.decode(t),{plaintext:a}=await pe.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ce.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var le=ne&&ne.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var 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]}),ge=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&le(t,e,i);return ge(t,e),t};Object.defineProperty(re,"__esModule",{value:!0}),re.jwe=void 0,re.jwe=fe(ce);var ye={},me={};function Se(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=ke("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function Ce(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(...Ie(n,t))}return i}function ke(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function Ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(me,"__esModule",{value:!0}),me.findAllInCookieString=me.findFirstInCookieString=me.findAllInHeaders=me.findFirstInHeaders=me.findOnlyValueInHeaders=me.findAllValuesInHeaders=me.findFirstValueInHeaders=void 0,me.findFirstValueInHeaders=function(e,t){const i=Se(e,t);if(void 0!==i)return i.slice(t.length+1)},me.findAllValuesInHeaders=function(e,t){return Ce(e,t).map((e=>e.slice(t.length+1)))},me.findOnlyValueInHeaders=function(e,t){const i=Ce(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},me.findFirstInHeaders=Se,me.findAllInHeaders=Ce,me.findFirstInCookieString=ke,me.findAllInCookieString=Ie;var we={};function ve(e){return"set-cookie"===e||"Set-Cookie"===e}function Ee(e,t){const i=t+"=";return e.startsWith(i)}function Ne(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Ae(e,t){for(const i of Object.keys(e)){if(!ve(i))continue;const a=Te(Ne(e,i),t);if(void 0!==a)return a}}function Te(e,t){return e.map((e=>e.trimStart())).find((e=>Ee(e,t)))}function _e(e,t){const i=[];for(const a of Object.keys(e)){if(!ve(a))continue;const s=Ne(e,a);i.push(...be(s,t))}return i}function be(e,t){return e.map((e=>e.trimStart())).filter((e=>Ee(e,t)))}Object.defineProperty(we,"__esModule",{value:!0}),we.findAllInSetCookieStrings=we.findAllInHeaders=we.findFirstInSetCookieStrings=we.findFirstInHeaders=we.findOnlyValueInHeaders=we.findFirstValueInHeaders=void 0,we.findFirstValueInHeaders=function(e,t){const i=Ae(e,t);return i?.slice(t.length+1)?.split(";")[0]},we.findOnlyValueInHeaders=function(e,t){const i=_e(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},we.findFirstInHeaders=Ae,we.findFirstInSetCookieStrings=Te,we.findAllInHeaders=_e,we.findAllInSetCookieStrings=be;var Oe=ne&&ne.__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=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Pe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Oe(t,e,i);return Ke(t,e),t};Object.defineProperty(ye,"__esModule",{value:!0}),ye.setCookie=ye.cookie=void 0,ye.cookie=Pe(me),ye.setCookie=Pe(we);var xe={},Re={},Me={};Object.defineProperty(Me,"__esModule",{value:!0}),Me.KINESIS_URL=Me.API_VERSION=Me.REGION=Me.PAYLOAD_TYPE=Me.STATE=void 0,Me.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Me.PAYLOAD_TYPE="string",Me.REGION="eu-west-1",Me.API_VERSION="2013-12-02",Me.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var De={};Object.defineProperty(De,"__esModule",{value:!0}),De.headersToRecord=De.increaseBatchSize=De.handleFailedLogs=De.batchArrayForKinesis=De.sleep=void 0,De.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},De.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},De.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},De.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},De.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Re,"__esModule",{value:!0}),Re.WebStandardKinesis=void 0;const He=Me,Le=De;Re.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,Le.headersToRecord)(i.headers),host:He.KINESIS_URL,method:"POST",path:"/",body:i.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}}async signRequest(e,t,i,a){const s={Records:(0,Le.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(He.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var je={};Object.defineProperty(je,"__esModule",{value:!0}),je.Kinesis=void 0;const qe=Me,Fe=De;je.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,Fe.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Fe.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,Fe.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Fe.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,Fe.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:qe.REGION},{accessKeyId:a,secretAccessKey:s})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=Re;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=je;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(xe);var Ue={};function Be(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.stringOrDefault=Ue.parseIntOrDefault=Ue.parseNumberOrDefault=void 0,Ue.parseNumberOrDefault=Be,Ue.parseIntOrDefault=function(e,t){const i=Be(e,t);return"number"==typeof i?Math.floor(i):i},Ue.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t};var $e={};Object.defineProperty($e,"__esModule",{value:!0}),$e.validateRedirectLocation=void 0,$e.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 Ve=ne&&ne.__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]}),ze=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ge=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Ve(t,e,i);return ze(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0}),oe.configValidation=Xe=oe.parsing=We=oe.ingest=oe.headers=oe.webcrypto=void 0,oe.webcrypto=Ge(re),oe.headers=Ge(ye);var We=oe.ingest=Ge(xe),Xe=oe.parsing=Ge(Ue);oe.configValidation=Ge($e);const{configureCookiesDomain:Je}=S.cookie.attributes;class Ye{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?u:i,this.mitigationServiceTimeoutMs=Xe.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Xe.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Xe.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:s}=Je(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 Ze{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Ye(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 We.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ae({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=h.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let 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=G(t.url,e.method),s=a&&i.sessionStatus.includes("checkpoint_post"),n=!a&&z(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:Y({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:(r={config:this.config,request:e,responseHeaders:o()},new Response("Forbidden",{status:403,statusText:"Forbidden",headers:r.responseHeaders}))}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i;var r}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:s}=L(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:n}=te(this.config.mitigationType,a,G(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=h.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),s=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:X(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:X(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:X(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);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body: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.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:W(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?V(e.headers.get("Accept")??void 0):V();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}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 Z&&(s=i.latencyMs,a=i.protectorApiResponse?.status);return{response:G(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency: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 $(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=X(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Q(e);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,s,n,o,r,c,h;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([U.NEW_SESSION,U.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const u=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,s=d.mitigate,n=d.captcha,o=d.body,h=d.latency,r=[await this.createMitata(e.clientIp,u,a,s,n,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",s=t?.mitigate??"0",n=t?.captcha??"0",o=void 0,r=[]}const u={match:a,mitigate:s,captcha:n};return this.composeResult(o,r,i,u,!1,h,c)}async createMitata(e,t,i,a,s,n=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,s].join("");let u=await async function(e,t,i,a,s="000"){const n=[i,t,await F(e+"|"+String(i),a),s].join(M);return`${await F(n,a)}${M}${n}`}(e,t,c,this.config.secretKey,h);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(u=await B(u,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:u,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:s,captcha:n,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),h={match:a,mitigate:s,captcha:n};return this.composeResult(o,r,i,h,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[T];const i=parseInt(e[_]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await B(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==U.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),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}),h=Date.now()-n;return await this.getApiCallResponseFromResponse(c,e,h)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Z(e,i);const a=e.headers[v]??"0",s=e.headers[E]??"0",n=e.headers[N]??"0";let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,s,n,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),h=e.headers[b];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:s,captcha:n,setCookie:c,body:e.body,eventId:h,mitataMaxAge:o,latency:i}}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:J({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==U.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}),h=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,h)}composeResult(e,t,i,a,s,n,o){const r=te(this.config.mitigationType,a,s),c={body:e,apiCallStatus:i,apiCallLatency:n,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[w.block,w.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(z(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaPath)){const t=await async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}}(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if(G(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===U.NEW_SESSION,a=t===U.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}}const Qe=e=>Xe.parseIntOrDefault(e,{defaultValue:void 0});function et(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function tt(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=tt(e,t,a);if(void 0!==i)return i}}function it(e,t){const i=tt(e,t,"CAPTCHA_HEADER_NAME"),a=tt(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function at(e,t){const i=tt(e,t,"KINESIS_STREAM_NAME"),a=tt(e,t,"KINESIS_ACCESS_KEY"),s=tt(e,t,"KINESIS_SECRET_KEY"),n=et({logBatchSize:Qe(tt(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:Qe(tt(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=Ze,exports.default=Ze,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return et({apiKey:tt(e,t,"API_KEY"),captchaHeader:it(e,t),captchaSecretKey:tt(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:tt(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:tt(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:tt(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:tt(e,t,"INGEST_SERVICE_URL"),ingestType:tt(e,t,"INGEST_TYPE"),ipHeaderName:tt(e,t,"IP_HEADER_NAME"),kinesis:at(e,t),mitataCookieExpirySeconds:Qe(tt(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:tt(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:tt(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:tt(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:tt(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:tt(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:tt(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:tt(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:tt(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:Qe(tt(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:tt(e,t,"COOKIE_NAME"),secretKey:tt(e,t,"SECRET_KEY"),timeout:Qe(tt(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.1.31";const I=globalThis.fetch.bind(globalThis),w={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",N="x-netacea-mitigate",A="x-netacea-captcha",E="x-netacea-mitata-expiry",T="x-netacea-mitatacaptcha-value",_="x-netacea-mitatacaptcha-expiry",b="x-netacea-event-id",O={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},K={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},P={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},x={0:w.none,1:w.block,2:w.none,3:w.block,4:w.block},R={1:w.captcha,2:w.captchaPass,3:w.captcha,4:w.allow,5:w.captcha,6:w.allow,7:w.captcha,a:w.captcha,b:w.captchaPass,c:w.captcha,d:w.allow,e:w.captcha},M="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),H=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function j(e){if(void 0===e)return;const t=e.match(H);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 L(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),s=t.Buffer.from(a).toString("hex");return t.Buffer.from(s).toString("base64")}var U;async function B(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function $(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function V(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}function z(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 G(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function W(e,t){if(void 0===t)return e;const i=e.headers.get("set-cookie")??"",a=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)i.includes(e.split("=")[0])||a.append("set-cookie",e);return new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})}function X(e,t,i=""){return e.get(t)??i}function J(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}function Y(e){const t=new Headers(e.responseHeaders);return void 0!==e.config.captchaHeader&&t.append(e.config.captchaHeader.name,e.config.captchaHeader.value),t.append("content-type","text/html; charset=UTF-8"),new Response(e.body,{status:403,headers:t})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(U||(U={}));class Z 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 Q(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,IpHeader:v,WorkerInstanceId:I,NetaceaUserIdCookieStatus:d,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const ee="unknown";function te(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=O[a]??ee+"_";o+=K[s]??ee;let r=x[s];if("0"!==n){o+=","+(P[n]??ee);const e=R[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}}}async function ie(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 ae{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=j(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(M),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 F(t+"|"+s.expiry,i),h=s.ipHash===u,d=s.signature===await F(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?U.RENEW_SESSION:U.EXISTING_SESSION,{sessionStatus:u}=te(e.mitigationType,n.protectorCheckCodes,G(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:L(),sessionCookieStatus:U.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 se(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 $(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function se(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 ie(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 ie(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===s?s:`c_${s.substring(1,15)}`}}var ne="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},oe={},re={};Object.defineProperty(re,"__esModule",{value:!0}),re.validateRedirectLocation=void 0,re.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 ce={},ue={};function he(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",s=pe("string"==typeof a?a:a.join("; "),t);if(void 0!==s)return s}}function de(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(...le(n,t))}return i}function pe(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function le(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(ue,"__esModule",{value:!0}),ue.findAllInCookieString=ue.findFirstInCookieString=ue.findAllInHeaders=ue.findFirstInHeaders=ue.findOnlyValueInHeaders=ue.findAllValuesInHeaders=ue.findFirstValueInHeaders=void 0,ue.findFirstValueInHeaders=function(e,t){const i=he(e,t);if(void 0!==i)return i.slice(t.length+1)},ue.findAllValuesInHeaders=function(e,t){return de(e,t).map((e=>e.slice(t.length+1)))},ue.findOnlyValueInHeaders=function(e,t){const i=de(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},ue.findFirstInHeaders=he,ue.findAllInHeaders=de,ue.findFirstInCookieString=pe,ue.findAllInCookieString=le;var ge={};function fe(e){return"set-cookie"===e||"Set-Cookie"===e}function ye(e,t){const i=t+"=";return e.startsWith(i)}function me(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Se(e,t){for(const i of Object.keys(e)){if(!fe(i))continue;const a=Ce(me(e,i),t);if(void 0!==a)return a}}function Ce(e,t){return e.map((e=>e.trimStart())).find((e=>ye(e,t)))}function ke(e,t){const i=[];for(const a of Object.keys(e)){if(!fe(a))continue;const s=me(e,a);i.push(...Ie(s,t))}return i}function Ie(e,t){return e.map((e=>e.trimStart())).filter((e=>ye(e,t)))}Object.defineProperty(ge,"__esModule",{value:!0}),ge.findAllInSetCookieStrings=ge.findAllInHeaders=ge.findFirstInSetCookieStrings=ge.findFirstInHeaders=ge.findOnlyValueInHeaders=ge.findFirstValueInHeaders=void 0,ge.findFirstValueInHeaders=function(e,t){const i=Se(e,t);return i?.slice(t.length+1)?.split(";")[0]},ge.findOnlyValueInHeaders=function(e,t){const i=ke(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},ge.findFirstInHeaders=Se,ge.findFirstInSetCookieStrings=Ce,ge.findAllInHeaders=ke,ge.findAllInSetCookieStrings=Ie;var we=ne&&ne.__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]}),ve=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ne=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&we(t,e,i);return ve(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0}),ce.setCookie=ce.cookie=void 0,ce.cookie=Ne(ue),ce.setCookie=Ne(ge);var Ae={},Ee={},Te={};Object.defineProperty(Te,"__esModule",{value:!0}),Te.KINESIS_URL=Te.API_VERSION=Te.REGION=Te.PAYLOAD_TYPE=Te.STATE=void 0,Te.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Te.PAYLOAD_TYPE="string",Te.REGION="eu-west-1",Te.API_VERSION="2013-12-02",Te.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var _e={};Object.defineProperty(_e,"__esModule",{value:!0}),_e.headersToRecord=_e.increaseBatchSize=_e.handleFailedLogs=_e.batchArrayForKinesis=_e.sleep=void 0,_e.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},_e.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},_e.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},_e.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},_e.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.WebStandardKinesis=void 0;const be=Te,Oe=_e;Ee.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){if(this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e,void 0===t.kinesisAccessKey)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===t.kinesisSecretKey)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=t.kinesisStreamName,this.kinesisAccessKey=t.kinesisAccessKey,this.kinesisSecretKey=t.kinesisSecretKey,this.maxAwaitTimePerIngestCallMs=t.maxAwaitTimePerIngestCallMs,void 0!==t.maxLogAgeSeconds&&t.maxLogAgeSeconds<this.maxLogAgeSeconds&&t.maxLogAgeSeconds>0&&(this.maxLogAgeSeconds=t.maxLogAgeSeconds),void 0!==t.logBatchSize&&(this.maxLogBatchSize=t.logBatchSize),this.logBatchSize=!0===t.rampUpBatchSize?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:(0,Oe.headersToRecord)(i.headers),host:be.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Oe.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Oe.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,Oe.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Oe.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,Oe.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(be.KINESIS_URL,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.Kinesis=void 0;const Pe=Te,xe=_e;Ke.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,xe.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,xe.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,xe.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,xe.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,xe.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=Ee;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=Ke;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(Ae);var Re={};function Me(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}if(null===i){if("number"!=typeof t.defaultValue)return t.defaultValue;i=t.defaultValue}return void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(Re,"__esModule",{value:!0}),Re.parseHttpHeaderName=Re.stringOrDefault=Re.parseIntOrDefault=Re.parseNumberOrDefault=void 0,Re.parseNumberOrDefault=Me,Re.parseIntOrDefault=function(e,t){const i=Me(e,t);return"number"==typeof i?Math.floor(i):i},Re.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Re.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var De={};Object.defineProperty(De,"__esModule",{value:!0}),De.searchParamsFromRecord=void 0,De.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var He={},je={},Le=ne&&ne.__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]}),qe=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Fe=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Le(t,e,i);return qe(t,e),t};Object.defineProperty(je,"__esModule",{value:!0}),je.isJweEncrypted=je.decrypt=je.encrypt=void 0;const Ue=Fe(i);je.encrypt=async function(e,t){const i=Ue.base64url.decode(t),a=(new TextEncoder).encode(e);return await new Ue.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},je.decrypt=async function(e,t){const i=Ue.base64url.decode(t),{plaintext:a}=await Ue.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},je.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var Be=ne&&ne.__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]}),$e=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ve=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&Be(t,e,i);return $e(t,e),t};Object.defineProperty(He,"__esModule",{value:!0}),He.jwe=void 0,He.jwe=Ve(je);var ze=ne&&ne.__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]}),Ge=ne&&ne.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),We=ne&&ne.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ze(t,e,i);return Ge(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0}),oe.webcrypto=oe.url=Je=oe.parsing=Xe=oe.ingest=oe.headers=oe.configValidation=void 0,oe.configValidation=We(re),oe.headers=We(ce);var Xe=oe.ingest=We(Ae),Je=oe.parsing=We(Re);oe.url=We(De),oe.webcrypto=We(He);const{configureCookiesDomain:Ye}=S.cookie.attributes;class Ze{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=Je.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Je.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Je.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:s}=Ye(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 Qe{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Ze(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 Xe.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ae({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=G(t.url,e.method),s=a&&i.sessionStatus.includes("checkpoint_post"),n=!a&&z(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:Y({config:this.config,responseHeaders:o(),body:i.body})}:{...i,response:(r={config:this.config,request:e,responseHeaders:o()},new Response("Forbidden",{status:403,statusText:"Forbidden",headers:r.responseHeaders}))}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:o()})}:i;var r}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:s}=j(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:n}=te(this.config.mitigationType,a,G(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:X(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:X(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:X(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);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body: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.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:W(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?V(e.headers.get("Accept")??void 0):V();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}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 Z&&(s=i.latencyMs,a=i.protectorApiResponse?.status);return{response:G(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency: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 $(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=X(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Q(e);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,s,n,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([U.NEW_SESSION,U.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,d=await this.makeMitigateAPICall(e,t,!1,null);i=d.status,a=d.match,s=d.mitigate,n=d.captcha,o=d.body,u=d.latency,r=[await this.createMitata(e.clientIp,h,a,s,n,d.mitataMaxAge)],c=d.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",s=t?.mitigate??"0",n=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:s,captcha:n};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,s,n=86400,o=void 0){const r=["1","3","5","a","c","e"].includes(s)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,s].join("");let h=await async function(e,t,i,a,s="000"){const n=[i,t,await F(e+"|"+String(i),a),s].join(M);return`${await F(n,a)}${M}${n}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await B(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:s,captcha:n,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:s,captcha:n};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[T];const i=parseInt(e[_]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await B(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==U.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),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;return await this.getApiCallResponseFromResponse(c,e,u)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Z(e,i);const a=e.headers[v]??"0",s=e.headers[N]??"0",n=e.headers[A]??"0";let o=parseInt(e.headers[E]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,s,n,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[b];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:s,captcha:n,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}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:J({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==U.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;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,s,n,o){const r=te(this.config.mitigationType,a,s),c={body:e,apiCallStatus:i,apiCallLatency:n,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[w.block,w.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(z(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaPath)){const t=await async function(e){try{const{searchParams:t}=e;return t.get("trackingId")}catch(e){return null}}(e.requestDetails.url);return await this.handleGetCaptchaRequest(e.requestDetails,e.captchaPageContentType,t)}if(G(e.requestDetails.url,e.requestDetails.method)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===U.NEW_SESSION,a=t===U.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}}const et=e=>Je.parseIntOrDefault(e,{defaultValue:void 0});function tt(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function it(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=it(e,t,a);if(void 0!==i)return i}}function at(e,t){const i=it(e,t,"CAPTCHA_HEADER_NAME"),a=it(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function st(e,t){const i=it(e,t,"KINESIS_STREAM_NAME"),a=it(e,t,"KINESIS_ACCESS_KEY"),s=it(e,t,"KINESIS_SECRET_KEY"),n=tt({logBatchSize:et(it(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:et(it(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=Qe,exports.default=Qe,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return tt({apiKey:it(e,t,"API_KEY"),captchaHeader:at(e,t),captchaSecretKey:it(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:it(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:it(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:it(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:it(e,t,"INGEST_SERVICE_URL"),ingestType:it(e,t,"INGEST_TYPE"),ipHeaderName:it(e,t,"IP_HEADER_NAME"),kinesis:st(e,t),mitataCookieExpirySeconds:et(it(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:it(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:it(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:it(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:it(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:it(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:it(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:it(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:it(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:et(it(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:it(e,t,"COOKIE_NAME"),secretKey:it(e,t,"SECRET_KEY"),timeout:et(it(e,t,"TIMEOUT"))})};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/vercel",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.31",
|
|
4
4
|
"description": "Netacea Vercel CDN Integration",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
"jose": "^4.11.2",
|
|
23
23
|
"uuid": "^10.0.0"
|
|
24
24
|
},
|
|
25
|
-
"gitHead": "
|
|
25
|
+
"gitHead": "01505f0c270cd362402c71597c4d9ac25d0dbba7"
|
|
26
26
|
}
|