@netacea/vercel 0.7.5 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +62 -48
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ declare enum NetaceaMitigationType {
|
|
|
50
50
|
*/
|
|
51
51
|
INGEST = "INGEST"
|
|
52
52
|
}
|
|
53
|
-
declare enum NetaceaCookieV3IssueReason {
|
|
53
|
+
declare enum NetaceaCookieV3IssueReason$1 {
|
|
54
54
|
CAPTCHA_GET = "captcha_get",
|
|
55
55
|
CAPTCHA_POST = "captcha_post",
|
|
56
56
|
EXPIRED_SESSION = "expired_session",
|
|
@@ -167,6 +167,9 @@ interface IngestArgs {
|
|
|
167
167
|
gqlOpName?: string;
|
|
168
168
|
gqlOpType?: string;
|
|
169
169
|
headerFingerprint?: string;
|
|
170
|
+
httpMsgSigAgent?: string;
|
|
171
|
+
httpMsgSigInput?: string;
|
|
172
|
+
httpMsgSigSha256?: string;
|
|
170
173
|
integrationMode?: string;
|
|
171
174
|
integrationType?: string;
|
|
172
175
|
integrationVersion?: string;
|
|
@@ -230,6 +233,63 @@ interface InjectResponse<T = any> extends MitigateResponse<T> {
|
|
|
230
233
|
}
|
|
231
234
|
type NetaceaMitigationResponse<T> = MitigateResponse<T> | InjectResponse<T> | undefined;
|
|
232
235
|
|
|
236
|
+
declare enum NetaceaCookieV3IssueReason {
|
|
237
|
+
CAPTCHA_GET = "captcha_get",
|
|
238
|
+
CAPTCHA_POST = "captcha_post",
|
|
239
|
+
EXPIRED_SESSION = "expired_session",
|
|
240
|
+
FORCED_REVALIDATION = "forced_revalidation",
|
|
241
|
+
INVALID_SESSION = "invalid_session",
|
|
242
|
+
IP_CHANGE = "ip_change",
|
|
243
|
+
NO_SESSION = "no_session",
|
|
244
|
+
UNKNOWN = "unknown"
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
interface KinesisIngestWebLog {
|
|
248
|
+
apiKey: string;
|
|
249
|
+
}
|
|
250
|
+
interface KinesisIngestArgs {
|
|
251
|
+
kinesisStreamName: string;
|
|
252
|
+
kinesisAccessKey?: string;
|
|
253
|
+
kinesisSecretKey?: string;
|
|
254
|
+
logBatchSize?: number;
|
|
255
|
+
maxLogAgeSeconds?: number;
|
|
256
|
+
apiKey: string;
|
|
257
|
+
rampUpBatchSize?: boolean;
|
|
258
|
+
maxAwaitTimePerIngestCallMs?: number;
|
|
259
|
+
}
|
|
260
|
+
type KinesisMakeRequest = (args: {
|
|
261
|
+
headers: Record<string, string>;
|
|
262
|
+
method: 'POST' | 'GET';
|
|
263
|
+
host: string;
|
|
264
|
+
path: string;
|
|
265
|
+
body?: any;
|
|
266
|
+
}) => Promise<any>;
|
|
267
|
+
|
|
268
|
+
interface WebStandardKinesisDependencies {
|
|
269
|
+
AwsClient: typeof AwsClient;
|
|
270
|
+
Buffer: typeof Buffer;
|
|
271
|
+
makeRequest: KinesisMakeRequest;
|
|
272
|
+
}
|
|
273
|
+
declare class WebStandardKinesis {
|
|
274
|
+
private readonly deps;
|
|
275
|
+
protected readonly kinesisStreamName: string;
|
|
276
|
+
protected readonly kinesisAccessKey: string;
|
|
277
|
+
protected readonly kinesisSecretKey: string;
|
|
278
|
+
protected readonly maxLogBatchSize: number;
|
|
279
|
+
protected readonly maxLogAgeSeconds: number;
|
|
280
|
+
protected logBatchSize: number;
|
|
281
|
+
protected maxAwaitTimePerIngestCallMs: undefined | number;
|
|
282
|
+
protected logCache: KinesisIngestWebLog[];
|
|
283
|
+
private intervalSet;
|
|
284
|
+
constructor({ deps, kinesisIngestArgs: args }: {
|
|
285
|
+
deps: WebStandardKinesisDependencies;
|
|
286
|
+
kinesisIngestArgs: KinesisIngestArgs;
|
|
287
|
+
});
|
|
288
|
+
putToKinesis(): Promise<void>;
|
|
289
|
+
ingest<LogFormat extends KinesisIngestWebLog>(log: LogFormat): Promise<void>;
|
|
290
|
+
private signRequest;
|
|
291
|
+
}
|
|
292
|
+
|
|
233
293
|
interface NetaceaVercelResult {
|
|
234
294
|
response: Response;
|
|
235
295
|
sessionStatus: string;
|
|
@@ -330,52 +390,6 @@ declare class ValidatedConfig {
|
|
|
330
390
|
constructor(args: Partial<NetaceaVercelIntegrationArgs>);
|
|
331
391
|
}
|
|
332
392
|
|
|
333
|
-
interface KinesisIngestWebLog {
|
|
334
|
-
apiKey: string;
|
|
335
|
-
}
|
|
336
|
-
interface KinesisIngestArgs {
|
|
337
|
-
kinesisStreamName: string;
|
|
338
|
-
kinesisAccessKey?: string;
|
|
339
|
-
kinesisSecretKey?: string;
|
|
340
|
-
logBatchSize?: number;
|
|
341
|
-
maxLogAgeSeconds?: number;
|
|
342
|
-
apiKey: string;
|
|
343
|
-
rampUpBatchSize?: boolean;
|
|
344
|
-
maxAwaitTimePerIngestCallMs?: number;
|
|
345
|
-
}
|
|
346
|
-
type KinesisMakeRequest = (args: {
|
|
347
|
-
headers: Record<string, string>;
|
|
348
|
-
method: 'POST' | 'GET';
|
|
349
|
-
host: string;
|
|
350
|
-
path: string;
|
|
351
|
-
body?: any;
|
|
352
|
-
}) => Promise<any>;
|
|
353
|
-
|
|
354
|
-
interface WebStandardKinesisDependencies {
|
|
355
|
-
AwsClient: typeof AwsClient;
|
|
356
|
-
Buffer: typeof Buffer;
|
|
357
|
-
makeRequest: KinesisMakeRequest;
|
|
358
|
-
}
|
|
359
|
-
declare class WebStandardKinesis {
|
|
360
|
-
private readonly deps;
|
|
361
|
-
protected readonly kinesisStreamName: string;
|
|
362
|
-
protected readonly kinesisAccessKey: string;
|
|
363
|
-
protected readonly kinesisSecretKey: string;
|
|
364
|
-
protected readonly maxLogBatchSize: number;
|
|
365
|
-
protected readonly maxLogAgeSeconds: number;
|
|
366
|
-
protected logBatchSize: number;
|
|
367
|
-
protected maxAwaitTimePerIngestCallMs: undefined | number;
|
|
368
|
-
protected logCache: KinesisIngestWebLog[];
|
|
369
|
-
private intervalSet;
|
|
370
|
-
constructor({ deps, kinesisIngestArgs: args }: {
|
|
371
|
-
deps: WebStandardKinesisDependencies;
|
|
372
|
-
kinesisIngestArgs: KinesisIngestArgs;
|
|
373
|
-
});
|
|
374
|
-
putToKinesis(): Promise<void>;
|
|
375
|
-
ingest<LogFormat extends KinesisIngestWebLog>(log: LogFormat): Promise<void>;
|
|
376
|
-
private signRequest;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
393
|
interface ComposeResultResponse {
|
|
380
394
|
body?: string | ReadableStream<Uint8Array>;
|
|
381
395
|
apiCallStatus?: number;
|
|
@@ -445,7 +459,7 @@ declare class NetaceaVercelIntegration {
|
|
|
445
459
|
protected callIngest(args: IngestArgs): Promise<void>;
|
|
446
460
|
private makeIngestApiCall;
|
|
447
461
|
protected check(requestDetails: NetaceaRequestDetails, captchaPageContentType: string): Promise<ComposeResultResponse>;
|
|
448
|
-
protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined, issueReason?: NetaceaCookieV3IssueReason): Promise<string>;
|
|
462
|
+
protected createMitata(clientIP: string, userId: string, match: string, mitigate: string, captcha: string, maxAge?: number, expiry?: number | undefined, issueReason?: NetaceaCookieV3IssueReason$1): Promise<string>;
|
|
449
463
|
private processCaptcha;
|
|
450
464
|
private getMitataCaptchaFromHeaders;
|
|
451
465
|
private parseCaptchaAPICallBody;
|
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 o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,n,r,c=o(i),u=o(a);exports.NetaceaIngestType=void 0,(s=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",s.HTTP="HTTP",s.KINESIS="KINESIS",s.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(n=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",n.INJECT="INJECT",n.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const d=3e3;function h(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function 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 o=h(e,"Domain"),s=h(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=h(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=h(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=h(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:h,removeDuplicateAttrs: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),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const C={cookie:{parse:m,attributes:g,netaceaSession:y}};var S="@netacea/vercel",k="0.7.5";const I=globalThis.fetch.bind(globalThis),v={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",monetise:"monetise",flag:"flag"},w="x-netacea-mitatacaptcha-value",N="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},b={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},A={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail",6:"checkpoint_signal",7:"checkpoint_post",a:"checkpoint_serve",b:"checkpoint_pass",c:"checkpoint_fail",d:"checkpoint_cookiepass",e:"checkpoint_cookiefail"},_={0:v.none,1:v.block,2:v.none,3:v.block,4:v.flag,5:v.monetise},T={1:v.captcha,2:v.captchaPass,3:v.captcha,4:v.allow,5:v.captcha,6:v.allow,7:v.captcha,a:v.captcha,b:v.captchaPass,c:v.captcha,d:v.allow,e:v.captcha},O="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),P=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function R(e=16,t=O){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function K(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))}var x,M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},V={},D={};Object.defineProperty(D,"__esModule",{value:!0}),D.NetaceaCookieV3IssueReason=void 0,function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session",e.UNKNOWN="unknown"}(x||(D.NetaceaCookieV3IssueReason=x={}));var j={},H={},L={};Object.defineProperty(L,"__esModule",{value:!0}),L.netaceaCookieV3OptionalKeyMap=L.netaceaCookieV3KeyMap=L.COOKIEDELIMITER=void 0,L.COOKIEDELIMITER="_/@#/",L.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},L.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(H,"__esModule",{value:!0}),H.defaultInvalidResponse=H.matchNetaceaCookieV3=H.checkNetaceaCookieV3=H.objectIsNetaceaCookieV3=H.cookieIsNetaceaV3Format=H.createNetaceaCookieV3=void 0;const F=D,q=L;function U(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(q.netaceaCookieV3KeyMap).find((e=>q.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(q.netaceaCookieV3OptionalKeyMap).find((e=>q.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function $(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:F.NetaceaCookieV3IssueReason.NO_SESSION}}H.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in q.netaceaCookieV3OptionalKeyMap?`${q.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${q.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},H.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(q.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(q.netaceaCookieV3KeyMap).includes(e)))},H.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(q.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},H.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return $();let i;try{i=U(e)}catch{return $()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return $()},H.matchNetaceaCookieV3=U,H.defaultInvalidResponse=$;var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.AbstractCookieFactory=void 0;const G=D,z=H,W=L,X="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),J=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;B.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,z.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??"",match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??G.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,z.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,z.cookieIsNetaceaV3Format)(i)?(0,z.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(W.COOKIEDELIMITER);return`${await this.hash(s,a)}${W.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(J);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,z.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(W.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:G.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>X[e%X.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=H;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=B;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=L;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=D;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(j);var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.validateRedirectLocation=void 0,Y.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 Q={},Z={};function ee(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=ie("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function te(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...ae(s,t))}return i}function ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ae(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Z,"__esModule",{value:!0}),Z.findAllInCookieString=Z.findFirstInCookieString=Z.findAllInHeaders=Z.findFirstInHeaders=Z.findOnlyValueInHeaders=Z.findAllValuesInHeaders=Z.findFirstValueInHeaders=void 0,Z.findFirstValueInHeaders=function(e,t){const i=ee(e,t);if(void 0!==i)return i.slice(t.length+1)},Z.findAllValuesInHeaders=function(e,t){return te(e,t).map((e=>e.slice(t.length+1)))},Z.findOnlyValueInHeaders=function(e,t){const i=te(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Z.findFirstInHeaders=ee,Z.findAllInHeaders=te,Z.findFirstInCookieString=ie,Z.findAllInCookieString=ae;var oe={};function se(e){return"set-cookie"===e||"Set-Cookie"===e}function ne(e,t){const i=t+"=";return e.startsWith(i)}function re(e,t){if(!ne(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function ce(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ue(e,t){for(const i of Object.keys(e)){if(!se(i))continue;const a=de(ce(e,i),t);if(void 0!==a)return a}}function de(e,t){return e.map((e=>e.trimStart())).find((e=>ne(e,t)))}function he(e,t){const i=[];for(const a of Object.keys(e)){if(!se(a))continue;const o=ce(e,a);i.push(...pe(o,t))}return i}function pe(e,t){return e.map((e=>e.trimStart())).filter((e=>ne(e,t)))}Object.defineProperty(oe,"__esModule",{value:!0}),oe.findAllInSetCookieStrings=oe.findAllInHeaders=oe.findValueInSetCookieStrings=oe.findFirstInSetCookieStrings=oe.findFirstInHeaders=oe.findOnlyValueInHeaders=oe.findFirstValueInHeaders=oe.parseValueFromString=void 0,oe.parseValueFromString=re,oe.findFirstValueInHeaders=function(e,t){const i=ue(e,t);return void 0!==i?re(i,t):void 0},oe.findOnlyValueInHeaders=function(e,t){const i=he(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?re(i[0],t):void 0},oe.findFirstInHeaders=ue,oe.findFirstInSetCookieStrings=de,oe.findValueInSetCookieStrings=function(e,t){const i=de(e,t);if(void 0!==i)return re(i,t)},oe.findAllInHeaders=he,oe.findAllInSetCookieStrings=pe;var le=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ge=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=M&&M.__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(Q,"__esModule",{value:!0}),Q.setCookie=Q.cookie=void 0,Q.cookie=fe(Z),Q.setCookie=fe(oe);var ye={},me={},Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.KINESIS_URL=Ce.API_VERSION=Ce.REGION=Ce.PAYLOAD_TYPE=Ce.STATE=void 0,Ce.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ce.PAYLOAD_TYPE="string",Ce.REGION="eu-west-1",Ce.API_VERSION="2013-12-02",Ce.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Se={};Object.defineProperty(Se,"__esModule",{value:!0}),Se.headersToRecord=Se.increaseBatchSize=Se.handleFailedLogs=Se.batchArrayForKinesis=Se.sleep=void 0,Se.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Se.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Se.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},Se.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Se.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(me,"__esModule",{value:!0}),me.WebStandardKinesis=void 0;const ke=Ce,Ie=Se;me.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,Ie.headersToRecord)(i.headers),host:ke.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ie.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ie.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,Ie.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ie.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const o={Records:(0,Ie.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ke.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.Kinesis=void 0;const we=Ce,Ne=Se;ve.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,Ne.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ne.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,Ne.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ne.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,Ne.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:we.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=me;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=ve;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ye);var Ee={};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(Ee,"__esModule",{value:!0}),Ee.parseHttpHeaderName=Ee.stringOrDefault=Ee.parseIntOrDefault=Ee.parseNumberOrDefault=void 0,Ee.parseNumberOrDefault=be,Ee.parseIntOrDefault=function(e,t){const i=be(e,t);return"number"==typeof i?Math.floor(i):i},Ee.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Ee.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var Ae={};Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.searchParamsFromRecord=void 0,Ae.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var _e={},Te={};Object.defineProperty(Te,"__esModule",{value:!0}),Te.JweFactory=void 0;Te.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Oe=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Pe=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Re=M&&M.__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 Pe(t,e),t};Object.defineProperty(_e,"__esModule",{value:!0}),_e.jwe=void 0,_e.jwe=Re(Te);var Ke,xe={};var Me={};Object.defineProperty(Me,"__esModule",{value:!0}),Me.ProtectorApiResponseView=Me.AbstractProtectorApiResponseView=void 0;const Ve=Ee;class De{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,Ve.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,Ve.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,Ve.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}}Me.AbstractProtectorApiResponseView=De;var je;function He(){return je||(je=1,function(e){var t=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=M&&M.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=M&&M.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=void 0;var s=D;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return s.NetaceaCookieV3IssueReason}}),e.cookie=a(j),e.configValidation=a(Y),e.headers=a(Q),e.ingest=a(ye),e.parsing=a(Ee),e.url=a(Ae),e.webcrypto=a(_e),e.graphql=a(function(){if(Ke)return xe;Ke=1,Object.defineProperty(xe,"__esModule",{value:!0}),xe.truncateLongFields=xe.parseGraphQl=xe.parseGraphQlRequestBody=xe.getGraphQLParserConfig=void 0;const e=He();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}return xe.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},xe.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const o=JSON.parse(a);if("object"!=typeof o)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,o?.query??"")},n=(o?.operationName??"").trim();return""!==n&&(s.OpName=n),i(e,s)},xe.parseGraphQl=t,xe.truncateLongFields=i,xe}()),o(Me,e)}(V)),V}Me.ProtectorApiResponseView=class extends De{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var Le=He();const Fe=new Le.webcrypto.jwe.JweFactory(c);class qe extends Le.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.encrypt called without a configured encryption key");return await Fe.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.decrypt called without a configured encryption key");return await Fe.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await K(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var Ue;function $e(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 Be(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:o}=e;return a.includes(i)&&o.includes("trackingId")&&"get"===t.toLowerCase()}function Ge(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function ze(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 We(e,t,i=""){return e.get(t)??i}function Xe(e){let t="",i="";for(const a in e){const o=e[a];void 0!==o&&(t=`${t}${i}${a}=${o}`,i="; ")}return t}function Je(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function Ye(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 Qe(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ue||(Ue={}));class Ze 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 et(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:o,integrationVersion:s,ip:n,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:d,netaceaCookieStatus:h,path:p,referer:l,requestHost:g,requestId:f,requestTime:y,sessionStatus:m,status:C,timeUnixMsUTC:S,userAgent:k,workerInstanceId:I,xForwardedFor:v,ipHeader:w}){return{Request:`${r} ${p}`,TimeLocal:new Date(S??Date.now()).toUTCString(),TimeUnixMsUTC:S,RealIp:n,UserAgent:k,Status:C,RequestTime:y?.toString(),BytesSent:e?.toString(),Referer:""===l?"-":l,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:m??"",ProtectorLatencyMs:u,ProtectorStatus:d,IntegrationType:o??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:g,RequestId:f??"",XForwardedFor:v,IpFromHeader:w,WorkerInstanceId:I,NetaceaUserIdCookieStatus:h,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const tt="unknown";function it(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=E[a]??tt+"_";n+=b[o]??tt;let r=_[o];if("0"!==s){n+=","+(A[s]??tt);const e=T[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=v.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function at(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function ot(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 st{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),o=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("x-forwarded-for")??void 0;let n,r=s?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(n=e.headers.get(this.config.ipHeaderName)??void 0,r=n??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}=await async function(e,t,i,a,o){const s=await e.cookieFactory.retrieveCookieInfo(a,o),n={userId:void 0!==s.mitata?s.mitata.userId:void 0,requiresReissue:s.requiresReissue,isExpired:s.isExpired,shouldExpire:s.shouldExpire,isSameIP:s.isSameIP,isPrimaryHashValid:s.isPrimaryHashValid,protectorCheckCodes:{match:s.match,mitigate:s.mitigate,captcha:s.captcha},issueReason:s.issueReason};if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:o,shouldExpire:s,isSameIP:r}=n,c=o||s||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?Ue.RENEW_SESSION:Ue.EXISTING_SESSION,{sessionStatus:u}=it(e.mitigationType,n.protectorCheckCodes,Ge(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:R(),sessionCookieStatus:Ue.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:d,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:u,userId:h};return{clientIp:r,fingerprints:await nt(e),ipHeader:void 0!==n?`${this.config.ipHeaderName}: ${n}`: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:s}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await Fe.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function nt(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 ot(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),o=await async function(e){const t=e.join(",");return await ot(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===o?o:`c_${o.substring(1,15)}`}}const{configureCookiesDomain:rt}=C.cookie.attributes;class ct{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?d:i,this.mitigationServiceTimeoutMs=Le.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Le.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Le.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:o}=rt(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var s,n;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=o??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(s=this.mitigationType,void 0===(n=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?s===exports.NetaceaMitigationType.INGEST?3600:60:n),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class ut{config;kinesis;requestAnalyser;cookieFactory;workerInstanceId;constructor(i){this.config=new ct(i),this.cookieFactory=new qe({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),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 Le.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new st({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,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let o=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,o,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=Ge(t.url,e.method),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&Be(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!o?"captcha"===i.mitigation?{...i,response:Ye({config:this.config,responseHeaders:n(),body:i.body})}:{...i,response:Je({responseHeaders:n()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Je({status:402,responseHeaders:n()})}:{...i,response:Qe({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=function(e){if(void 0===e)return;const t=e.match(P);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=it(this.config.mitigationType,a,Ge(new URL(e.url),e.method));return{userId:o,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),o=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:We(i.rawResponse.headers,"content-length","0"),cookieFingerprint:o.fingerprints.cookieFingerprint,headerFingerprint:o.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:S.replace("@netacea/",""),integrationVersion:k,ip:o.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:o.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:We(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestId:o.requestId,requestTime:"0",sessionStatus:i.sessionStatus??o.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:We(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:o.xForwardedForHeaderValue,ipHeader:o.ipHeader})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n}}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await I(s,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(void 0!==t&&"injectHeaders"in t){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)}if(this.config.ingestType===exports.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",S.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:ze(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?$e(e.headers.get("Accept")??void 0):$e();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Ze&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:Ge(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:at({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await Fe.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=We(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=et(e);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Ue.NEW_SESSION,Ue.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),o=a.responseView.getProtectorCodes(),{match:s,mitigate:n,captcha:r}=o,c=[await this.createMitata(e.clientIp,i,s,n,r,a.mitataMaxAge,void 0,dt(e))],u={match:s,mitigate:n,captcha:r},d=it(this.config.mitigationType,u,!1),h={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:c,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),redirect:"5"===n?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&d.mitigation!==v.flag||(h.injectHeaders=at(d.parts,a.eventId)),h}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=it(this.config.mitigationType,i,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[v.block,v.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&a.mitigation!==v.flag||(o.injectHeaders=at(a.parts)),o}}async createMitata(e,t,i,a,o,s=86400,n=void 0,c=r.NO_SESSION){const u=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,d=void 0!==n?n-Math.floor(Date.now()/1e3):u,h=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:d,cookieId:"",issueReason:c});return C.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=it(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromHeaders(e){let t=e[w];const i=parseInt(e[N]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await Fe.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),C.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==Ue.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=Date.now(),n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,n),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-s;if(200!==c.status)throw new Ze(c,u);const d=new Le.ProtectorApiResponseView(c.fetchResponse),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,g,void 0,dt(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),y=d.eventId;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:f,body:c.body,eventId:y,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const o={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Xe({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Ue.NEW_SESSION&&(o["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),o["X-Netacea-Captcha-Content-Type"]=t,o["X-Netacea-Request-Id"]=e.requestId;let s="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&n.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${n.toString()}`,headers:o,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new Ze(c,u);const d=new Le.ProtectorApiResponseView(c.fetchResponse),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,d.sessionCookieMaxAge,void 0,dt(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e));if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await d.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:d,status:c.status,setCookie:g,body:c.body,eventId:d.eventId,mitataMaxAge:d.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(Be(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(Ge(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.sessionDetails.userId,"0","0","0",86400,void 0,dt(e))]}}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===Ue.NEW_SESSION,a=t===Ue.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}}function dt(e){if(void 0===e.sessionDetails.sessionCookieDetails)return r.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?r.EXPIRED_SESSION:r.NO_SESSION:r.IP_CHANGE}const ht=e=>Le.parsing.parseIntOrDefault(e,{defaultValue:void 0});function pt(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function lt(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=lt(e,t,a);if(void 0!==i)return i}}function gt(e,t){const i=lt(e,t,"CAPTCHA_HEADER_NAME"),a=lt(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function ft(e,t){const i=lt(e,t,"KINESIS_STREAM_NAME"),a=lt(e,t,"KINESIS_ACCESS_KEY"),o=lt(e,t,"KINESIS_SECRET_KEY"),s=pt({logBatchSize:ht(lt(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:ht(lt(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==o)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:o,...s}}exports.NetaceaVercelIntegration=ut,exports.default=ut,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return pt({apiKey:lt(e,t,"API_KEY"),captchaHeader:gt(e,t),captchaSecretKey:lt(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:lt(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:lt(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:lt(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:lt(e,t,"INGEST_SERVICE_URL"),ingestType:lt(e,t,"INGEST_TYPE"),ipHeaderName:lt(e,t,"IP_HEADER_NAME"),kinesis:ft(e,t),mitataCookieExpirySeconds:ht(lt(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:lt(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:lt(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:lt(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:lt(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:lt(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:lt(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:lt(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:lt(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:ht(lt(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:lt(e,t,"COOKIE_NAME"),secretKey:lt(e,t,"SECRET_KEY"),timeout:ht(lt(e,t,"TIMEOUT"))})};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,n,r,c=o(i),u=o(a);exports.NetaceaIngestType=void 0,(s=exports.NetaceaIngestType||(exports.NetaceaIngestType={})).ORIGIN="ORIGIN",s.HTTP="HTTP",s.KINESIS="KINESIS",s.NATIVE="NATIVE",exports.NetaceaMitigationType=void 0,(n=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",n.INJECT="INJECT",n.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const d=3e3;function h(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function 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 o=h(e,"Domain"),s=h(t,"Domain");void 0!==o&&void 0!==s?a=t.replace(s,o):void 0!==o&&void 0===s?a=t+(""!==t?`; Domain=${o}`:`Domain=${o}`):void 0===o&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=h(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=h(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=h(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:h,removeDuplicateAttrs: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),o=a.indexOf(";");if(o<0){return{name:i,value:a,attributes:""}}return{name:i,value:a.slice(0,o),attributes:a.slice(o).trimStart()}}});const S={cookie:{parse:m,attributes:g,netaceaSession:y}};var C="@netacea/vercel",k="0.9.0";const I=globalThis.fetch.bind(globalThis),v={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass",monetise:"monetise",flag:"flag"},w="x-netacea-mitatacaptcha-value",N="x-netacea-mitatacaptcha-expiry",E={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_",c:"vendorFamily_",d:"vendorName_",e:"vendor_",f:"vendorCrawlerClassification_"},A={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"flagged",5:"monetised"},b={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"},_={0:v.none,1:v.block,2:v.none,3:v.block,4:v.flag,5:v.monetise},T={1:v.captcha,2:v.captchaPass,3:v.captcha,4:v.allow,5:v.captcha,6:v.allow,7:v.captcha,a:v.captcha,b:v.captchaPass,c:v.captcha,d:v.allow,e:v.captcha},O="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),P=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;function R(e=16,t=O){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function x(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))}var K,M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},V={},H={};Object.defineProperty(H,"__esModule",{value:!0}),H.NetaceaCookieV3IssueReason=void 0,function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session",e.UNKNOWN="unknown"}(K||(H.NetaceaCookieV3IssueReason=K={}));var D={},j={},L={};Object.defineProperty(L,"__esModule",{value:!0}),L.netaceaCookieV3OptionalKeyMap=L.netaceaCookieV3KeyMap=L.COOKIEDELIMITER=void 0,L.COOKIEDELIMITER="_/@#/",L.netaceaCookieV3KeyMap={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},L.netaceaCookieV3OptionalKeyMap={checkAllPostRequests:"fCAPR"},Object.defineProperty(j,"__esModule",{value:!0}),j.defaultInvalidResponse=j.matchNetaceaCookieV3=j.checkNetaceaCookieV3=j.objectIsNetaceaCookieV3=j.cookieIsNetaceaV3Format=j.createNetaceaCookieV3=void 0;const F=H,q=L;function U(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:"0",mitigate:"0",captcha:"0",issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),o=decodeURIComponent(a);let s,n=Object.keys(q.netaceaCookieV3KeyMap).find((e=>q.netaceaCookieV3KeyMap[e]===t));void 0===n&&(n=Object.keys(q.netaceaCookieV3OptionalKeyMap).find((e=>q.netaceaCookieV3OptionalKeyMap[e]===t))),s=void 0!==n&&["match","mitigate","captcha"].includes(n)?""===o?void 0:o:""===o?void 0:Number(o),void 0!==s&&"string"!=typeof s&&isNaN(s)&&(s=o),i[n]=s}return i}function $(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:"0",match:"0",mitigate:"0",issueReason:F.NetaceaCookieV3IssueReason.NO_SESSION}}j.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in q.netaceaCookieV3OptionalKeyMap?`${q.netaceaCookieV3OptionalKeyMap[e]}=${encodeURIComponent(t)}`:`${q.netaceaCookieV3KeyMap[e]}=${encodeURIComponent(t)}`)).join("&")},j.cookieIsNetaceaV3Format=function(e){if(void 0===e||""===e)return!1;const t=e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(q.netaceaCookieV3OptionalKeyMap).includes(e)));return 0!==t.length&&t.every((e=>Object.values(q.netaceaCookieV3KeyMap).includes(e)))},j.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(q.netaceaCookieV3KeyMap)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},j.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return $();let i;try{i=U(e)}catch{return $()}if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,o=t===i.clientIP,s=["1","3","5","a","c","e"].includes(i.captcha),n="3"===i.mitigate;return{mitata:i,requiresReissue:a||!o,isExpired:a,shouldExpire:s||n,isSameIP:o,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return $()},j.matchNetaceaCookieV3=U,j.defaultInvalidResponse=$;var B={};Object.defineProperty(B,"__esModule",{value:!0}),B.AbstractCookieFactory=void 0;const G=H,z=j,W=L,J="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),X=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d|[a-z])(\d)(\d|[a-z]))$/i;B.AbstractCookieFactory=class{constructor(e){this.config=e}isEncrypted(e){return 5===e.split(".").length}async createCookieValue(e){if(void 0!==this.config.cookieEncryptionKey){const t=(0,z.createNetaceaCookieV3)({clientIP:e.clientIP,userId:e.userId??"",match:e.match,mitigate:e.mitigate,captcha:e.captcha,gracePeriod:e.gracePeriod,cookieId:e.cookieId,issueTimestamp:Math.floor(Date.now()/1e3),issueReason:e.issueReason??G.NetaceaCookieV3IssueReason.NO_SESSION,checkAllPostRequests:e.checkAllPostRequests});return await this.encrypt(t)}if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const t=[e.match,e.mitigate,e.captcha].join(""),i=Math.floor(Date.now()/1e3)+e.gracePeriod;return await this.buildMitataCookie(e.clientIP,e.userId,i,this.config.secretKey,t)}async retrieveCookieInfo(e,t){if(void 0===e||""===e)return(0,z.defaultInvalidResponse)();let i=e;return this.isEncrypted(e)&&(i=await this.decrypt(e)),(0,z.cookieIsNetaceaV3Format)(i)?(0,z.checkNetaceaCookieV3)(i,t):await this.checkMitataCookie(i,t,this.config.secretKey??"")}async buildMitataCookie(e,t,i,a,o){const s=[i,t??this.generateUserId(),await this.hash(`${e}|${String(i)}`,a),o].join(W.COOKIEDELIMITER);return`${await this.hash(s,a)}${W.COOKIEDELIMITER}${s}`}async checkMitataCookie(e,t,i){const a=function(e){const t=e.match(X);if(null===t)return;const[,i,a,o,s,n,r,c,u]=t;return{signature:i,expiry:a,userId:o,ipHash:s,mitigationType:n,match:r,mitigate:c,captcha:u}}(e);if(void 0===a)return(0,z.defaultInvalidResponse)();const o=Math.floor(Date.now()/1e3),s=parseInt(a.expiry)<o,n=["1","3","5"].includes(a.captcha),r="3"===a.mitigate,c=n||r,u=await this.hash(`${t}|${a.expiry}`,i)===a.ipHash,d=[a.expiry,a.userId,a.ipHash,a.mitigationType].join(W.COOKIEDELIMITER);return{mitata:a,requiresReissue:s||!u,isExpired:s,shouldExpire:c,isSameIP:u,isPrimaryHashValid:await this.hash(d,i)===a.signature,match:a.match,mitigate:a.mitigate,captcha:a.captcha,issueReason:G.NetaceaCookieV3IssueReason.NO_SESSION}}generateUserId(e=16){const t=new Uint16Array(e-1);this.getRandomValues(t);return`c${Array.from(t).map((e=>J[e%J.length])).join("")}`}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaCookieV3IssueReason=e.COOKIEDELIMITER=e.netaceaCookieV3OptionalKeyMap=e.netaceaCookieV3KeyMap=e.AbstractCookieFactory=e.defaultInvalidResponse=e.objectIsNetaceaCookieV3=e.cookieIsNetaceaV3Format=e.matchNetaceaCookieV3=e.checkNetaceaCookieV3=e.createNetaceaCookieV3=void 0;var t=j;Object.defineProperty(e,"createNetaceaCookieV3",{enumerable:!0,get:function(){return t.createNetaceaCookieV3}}),Object.defineProperty(e,"checkNetaceaCookieV3",{enumerable:!0,get:function(){return t.checkNetaceaCookieV3}}),Object.defineProperty(e,"matchNetaceaCookieV3",{enumerable:!0,get:function(){return t.matchNetaceaCookieV3}}),Object.defineProperty(e,"cookieIsNetaceaV3Format",{enumerable:!0,get:function(){return t.cookieIsNetaceaV3Format}}),Object.defineProperty(e,"objectIsNetaceaCookieV3",{enumerable:!0,get:function(){return t.objectIsNetaceaCookieV3}}),Object.defineProperty(e,"defaultInvalidResponse",{enumerable:!0,get:function(){return t.defaultInvalidResponse}});var i=B;Object.defineProperty(e,"AbstractCookieFactory",{enumerable:!0,get:function(){return i.AbstractCookieFactory}});var a=L;Object.defineProperty(e,"netaceaCookieV3KeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3KeyMap}}),Object.defineProperty(e,"netaceaCookieV3OptionalKeyMap",{enumerable:!0,get:function(){return a.netaceaCookieV3OptionalKeyMap}}),Object.defineProperty(e,"COOKIEDELIMITER",{enumerable:!0,get:function(){return a.COOKIEDELIMITER}});var o=H;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return o.NetaceaCookieV3IssueReason}})}(D);var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.validateRedirectLocation=void 0,Y.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 Q={},Z={};function ee(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",o=ie("string"==typeof a?a:a.join("; "),t);if(void 0!==o)return o}}function te(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const o=e[a]??"",s="string"==typeof o?o:o.join("; ");i.push(...ae(s,t))}return i}function ie(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function ae(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(Z,"__esModule",{value:!0}),Z.findAllInCookieString=Z.findFirstInCookieString=Z.findAllInHeaders=Z.findFirstInHeaders=Z.findOnlyValueInHeaders=Z.findAllValuesInHeaders=Z.findFirstValueInHeaders=void 0,Z.findFirstValueInHeaders=function(e,t){const i=ee(e,t);if(void 0!==i)return i.slice(t.length+1)},Z.findAllValuesInHeaders=function(e,t){return te(e,t).map((e=>e.slice(t.length+1)))},Z.findOnlyValueInHeaders=function(e,t){const i=te(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},Z.findFirstInHeaders=ee,Z.findAllInHeaders=te,Z.findFirstInCookieString=ie,Z.findAllInCookieString=ae;var oe={};function se(e){return"set-cookie"===e||"Set-Cookie"===e}function ne(e,t){const i=t+"=";return e.startsWith(i)}function re(e,t){if(!ne(e,t))throw new Error(`Cookie '${t}' not found in '${e}'`);return e.slice(t.length+1).split(";")[0]}function ce(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function ue(e,t){for(const i of Object.keys(e)){if(!se(i))continue;const a=de(ce(e,i),t);if(void 0!==a)return a}}function de(e,t){return e.map((e=>e.trimStart())).find((e=>ne(e,t)))}function he(e,t){const i=[];for(const a of Object.keys(e)){if(!se(a))continue;const o=ce(e,a);i.push(...pe(o,t))}return i}function pe(e,t){return e.map((e=>e.trimStart())).filter((e=>ne(e,t)))}Object.defineProperty(oe,"__esModule",{value:!0}),oe.findAllInSetCookieStrings=oe.findAllInHeaders=oe.findValueInSetCookieStrings=oe.findFirstInSetCookieStrings=oe.findFirstInHeaders=oe.findOnlyValueInHeaders=oe.findFirstValueInHeaders=oe.parseValueFromString=void 0,oe.parseValueFromString=re,oe.findFirstValueInHeaders=function(e,t){const i=ue(e,t);return void 0!==i?re(i,t):void 0},oe.findOnlyValueInHeaders=function(e,t){const i=he(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return void 0!==i[0]?re(i[0],t):void 0},oe.findFirstInHeaders=ue,oe.findFirstInSetCookieStrings=de,oe.findValueInSetCookieStrings=function(e,t){const i=de(e,t);if(void 0!==i)return re(i,t)},oe.findAllInHeaders=he,oe.findAllInSetCookieStrings=pe;var le=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),ge=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fe=M&&M.__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(Q,"__esModule",{value:!0}),Q.setCookie=Q.cookie=void 0,Q.cookie=fe(Z),Q.setCookie=fe(oe);var ye={},me={},Se={};Object.defineProperty(Se,"__esModule",{value:!0}),Se.KINESIS_URL=Se.API_VERSION=Se.REGION=Se.PAYLOAD_TYPE=Se.STATE=void 0,Se.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Se.PAYLOAD_TYPE="string",Se.REGION="eu-west-1",Se.API_VERSION="2013-12-02",Se.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com";var Ce={};Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.headersToRecord=Ce.increaseBatchSize=Ce.handleFailedLogs=Ce.batchArrayForKinesis=Ce.sleep=void 0,Ce.sleep=async function(e){await new Promise((t=>{setTimeout(t,e)}))},Ce.batchArrayForKinesis=function(e,t,i){const a=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);a.push({Data:i.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return a},Ce.handleFailedLogs=function(e,t,i){const a=2*i,o=[...e,...t],s=o.length-a;return s>0&&(console.error(`Netacea Error :: failed to send ${s} log(s) to Kinesis ingest.`),o.splice(0,s)),o},Ce.increaseBatchSize=function(e,t){return e!==t?Math.min(t,2*e):e},Ce.headersToRecord=function(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t},Object.defineProperty(me,"__esModule",{value:!0}),me.WebStandardKinesis=void 0;const ke=Se,Ie=Ce;me.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,Ie.headersToRecord)(i.headers),host:ke.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize=(0,Ie.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ie.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,Ie.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ie.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}async signRequest(e,t,i,a){const o={Records:(0,Ie.batchArrayForKinesis)(i,a,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(ke.KINESIS_URL,{body:JSON.stringify(o),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}};var ve={};Object.defineProperty(ve,"__esModule",{value:!0}),ve.Kinesis=void 0;const we=Se,Ne=Ce;ve.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,Ne.increaseBatchSize)(this.logBatchSize,this.maxLogBatchSize)}catch(t){this.logCache=(0,Ne.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,Ne.sleep)(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=(0,Ne.sleep)(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:o}=e,s={Records:(0,Ne.batchArrayForKinesis)(t,i,this.deps.Buffer),PartitionKey:Date.now().toString(),StreamName:e.streamName};return this.deps.aws4.sign({service:"kinesis",body:JSON.stringify(s),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:we.REGION},{accessKeyId:a,secretAccessKey:o})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Kinesis=e.WebStandardKinesis=void 0;var t=me;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}});var i=ve;Object.defineProperty(e,"Kinesis",{enumerable:!0,get:function(){return i.Kinesis}})}(ye);var Ee={};function Ae(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(Ee,"__esModule",{value:!0}),Ee.parseHttpHeaderName=Ee.stringOrDefault=Ee.parseIntOrDefault=Ee.parseNumberOrDefault=void 0,Ee.parseNumberOrDefault=Ae,Ee.parseIntOrDefault=function(e,t){const i=Ae(e,t);return"number"==typeof i?Math.floor(i):i},Ee.stringOrDefault=function(e,t){return"string"==typeof e&&""!==e?e:"number"==typeof e?e.toString():t},Ee.parseHttpHeaderName=function(e){if("string"!=typeof e)return;return/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(e)?e:void 0};var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.searchParamsFromRecord=void 0,be.searchParamsFromRecord=function(e){const t=new URLSearchParams;for(const[i,a]of Object.entries(e))t.append(i,a);return t};var _e={},Te={};Object.defineProperty(Te,"__esModule",{value:!0}),Te.JweFactory=void 0;Te.JweFactory=class{constructor(e){this.jose=e}async encrypt(e,t,i="A128CBC-HS256"){const a=this.jose.base64url.decode(t),o=(new TextEncoder).encode(e);return await new this.jose.CompactEncrypt(o).setProtectedHeader({alg:"dir",enc:i}).encrypt(a)}async decrypt(e,t){const i=this.jose.base64url.decode(t),{plaintext:a}=await this.jose.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)}static isJweEncrypted(e){return 5===e.split(".").length&&e.includes("..")}};var Oe=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Pe=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Re=M&&M.__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 Pe(t,e),t};Object.defineProperty(_e,"__esModule",{value:!0}),_e.jwe=void 0,_e.jwe=Re(Te);var xe,Ke={};var Me={};Object.defineProperty(Me,"__esModule",{value:!0}),Me.RequestView=Me.AbstractRequestView=void 0;const Ve=Ee;class He{get contentLength(){return(0,Ve.parseIntOrDefault)(this.readHeader("content-length")?.[0],{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get userAgent(){return this.readHeader("user-agent")?.[0]??""}get contentType(){return this.readHeader("content-type")?.[0]}get xForwardedFor(){return this.readHeader("x-forwarded-for")?.[0]}get referer(){return this.readHeader("referer")?.[0]}get accept(){return this.readHeader("accept")?.[0]}get host(){return this.readHeader("host")?.[0]}async getHttpMessageSignatureFields(){const e=this.readJoinedHeader("Signature");return{httpMsgSigSha256:void 0===e?void 0:(await this.sha256Hash(e)).toLowerCase().slice(0,12),httpMsgSigInput:this.readJoinedHeader("Signature-Input"),httpMsgSigAgent:this.readJoinedHeader("Signature-Agent")}}readJoinedHeader(e){const t=this.readHeader(e).join(",");return""!==t?t:void 0}}Me.AbstractRequestView=He;Me.RequestView=class extends He{constructor(e,t){super(),this.request=e,this.sha256Digest=t}get method(){return this.request.method}get url(){return new URL(this.request.url)}async getBody(){return void 0===this._body&&(this._body=await this.request.clone().text()??""),this._body}readHeader(e){const t=this.request.headers.get(e)??void 0;return void 0!==t?[t]:[]}async sha256Hash(e){const t=(new TextEncoder).encode(e),i=await this.sha256Digest.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map((e=>e.toString(16).padStart(2,"0"))).join("")}};var De={};Object.defineProperty(De,"__esModule",{value:!0}),De.ProtectorApiResponseView=De.AbstractProtectorApiResponseView=void 0;const je=Ee;class Le{get redirectHost(){return this.readHeader("x-netacea-redirect-host")?.[0]}get redirectLocation(){return this.readHeader("x-netacea-redirect-location")?.[0]}get redirectStatus(){return this.readHeader("x-netacea-redirect-status")?.[0]}get redirectStatusCode(){const e=this.readHeader("x-netacea-redirect-status")?.[0];if(void 0===e)return;const t=(0,je.parseIntOrDefault)(e,{defaultValue:0,minValue:0,maxValue:Number.MAX_SAFE_INTEGER});return t>=300&&t<400?t:void 0}get eventId(){return this.readHeader("x-netacea-event-id")?.[0]}get sessionCookieMaxAge(){return(0,je.parseIntOrDefault)(this.readHeader("x-netacea-mitata-expiry")?.[0],{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}get captchaCookieMaxAge(){const e=this.readHeader("x-netacea-mitatacaptcha-expiry")?.[0];return(0,je.parseIntOrDefault)(e,{defaultValue:86400,minValue:0,maxValue:Number.MAX_SAFE_INTEGER})}getProtectorCodes(e){return{match:this.readHeader("x-netacea-match")?.[0]??e?.match??"0",mitigate:this.readHeader("x-netacea-mitigate")?.[0]??e?.mitigate??"0",captcha:this.readHeader("x-netacea-captcha")?.[0]??e?.captcha??"0"}}getMonetisationRedirectLocation(e,t){const i=this.redirectLocation;if(void 0!==i)return i;const a=this.redirectHost;if(void 0!==a){const i=new URL(`https://${a}`);return i.pathname=e,i.search=t,i.toString()}}getMonetisationRedirect(e,t){const i=this.getMonetisationRedirectLocation(e,t);if(void 0!==i)return{location:i,statusCode:this.redirectStatusCode??303}}async getCaptchaJson(e,t){const i=await this.getBody();let a=this.eventId;if(void 0===a&&"string"==typeof i){a=function(e){if(null==e||"object"!=typeof e)throw new Error("Response body is not a valid object!");const{trackingId:t}=e;if("string"!=typeof t||0===t.length)throw new Error("Response body does not contain a valid trackingId!");return t}(JSON.parse(i))}if(void 0===a)throw new Error("Could not resolve Tracking ID for captcha event.");return function(e,t,i){const a=`${e}?trackingId=${i}`,o=void 0!==t?`https://${t}${a}`:void 0;return JSON.stringify({captchaRelativeURL:a,captchaAbsoluteURL:o})}(e,t,a)}}De.AbstractProtectorApiResponseView=Le;var Fe;function qe(){return Fe||(Fe=1,function(e){var t=M&&M.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,o)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),i=M&&M.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=M&&M.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&t(a,e,o);return i(a,e),a},o=M&&M.__exportStar||function(e,i){for(var a in e)"default"===a||Object.prototype.hasOwnProperty.call(i,a)||t(i,e,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.graphql=e.webcrypto=e.url=e.parsing=e.ingest=e.headers=e.configValidation=e.cookie=e.NetaceaCookieV3IssueReason=void 0;var s=H;Object.defineProperty(e,"NetaceaCookieV3IssueReason",{enumerable:!0,get:function(){return s.NetaceaCookieV3IssueReason}}),e.cookie=a(D),e.configValidation=a(Y),e.headers=a(Q),e.ingest=a(ye),e.parsing=a(Ee),e.url=a(be),e.webcrypto=a(_e),e.graphql=a(function(){if(xe)return Ke;xe=1,Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.truncateLongFields=Ke.parseGraphQl=Ke.parseGraphQlRequestBody=Ke.getGraphQLParserConfig=void 0;const e=qe();function t(e,t){const i=e.parserRegex;return t.match(i)?.groups??{}}function i(e,t){const i=e.maxValueLength;for(const e of Object.keys(t)){const s=t[e];t[e]=(o=i,(a=s).length<=o?a:a.slice(0,o)+"…")}var a,o;return t}return Ke.getGraphQLParserConfig=function(t){const i={includePaths:[],maxParsableBytes:e.parsing.parseIntOrDefault(t?.maxParsableBytes,{defaultValue:1e6,minValue:1e3}),maxValueLength:e.parsing.parseIntOrDefault(t?.maxValueLength,{defaultValue:256,minValue:8}),parserRegex:/^\s*(?<OpType>query|mutation|subscription)\s+(?<OpName>[_A-Za-z][_0-9A-Za-z]+)?/};if(Array.isArray(t?.includePaths))for(const e of t.includePaths)"string"==typeof e&&i.includePaths.push(e);try{if(t?.parserRegex instanceof RegExp)i.parserRegex=t?.parserRegex;else if("object"==typeof t?.parserRegex){const{regex:e,flags:a}=t?.parserRegex;"string"==typeof e&&(i.parserRegex=new RegExp(e,a))}}catch{}return i},Ke.parseGraphQlRequestBody=function(e,a){if(""===a)throw new Error("Netacea Error: Empty GraphQL body received");const o=JSON.parse(a);if("object"!=typeof o)throw new Error("Netacea Error: Invalid GraphQL JSON");const s={...t(e,o?.query??"")},n=(o?.operationName??"").trim();return""!==n&&(s.OpName=n),i(e,s)},Ke.parseGraphQl=t,Ke.truncateLongFields=i,Ke}()),o(Me,e),o(De,e)}(V)),V}De.ProtectorApiResponseView=class extends Le{constructor(e){super(),this.response=e}get status(){return this.response.status}async getBody(){return void 0===this._body&&(this._body=await this.response.clone().text()??""),this._body}readHeader(e){if("set-cookie"===(e=e.toLowerCase()))return this.response.headers.getSetCookie();const t=this.response.headers.get(e)??void 0;return void 0!==t?[t]:[]}};var Ue=qe();const $e=new Ue.webcrypto.jwe.JweFactory(c);class Be extends Ue.cookie.AbstractCookieFactory{async encrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.encrypt called without a configured encryption key");return await $e.encrypt(e,this.config.cookieEncryptionKey,"A256GCM")}async decrypt(e){if(void 0===this.config.cookieEncryptionKey)throw new Error("VercelCookieFactory.decrypt called without a configured encryption key");return await $e.decrypt(e,this.config.cookieEncryptionKey)}async hash(e,i){const a=await x(t.Buffer.from(e),i),o=t.Buffer.from(a).toString("hex");return t.Buffer.from(o).toString("base64")}getRandomValues(e){return crypto.getRandomValues(e)}}var Ge;function ze(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 We(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:o}=e;return a.includes(i)&&o.includes("trackingId")&&"get"===t.toLowerCase()}function Je(e,t){return"/AtaVerifyCaptcha"===e.pathname&&"post"===t.toLowerCase()}function Xe(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 Ye(e,t,i=""){return e.get(t)??i}function Qe(e){let t="",i="";for(const a in e){const o=e[a];void 0!==o&&(t=`${t}${i}${a}=${o}`,i="; ")}return t}function Ze(e){const t=e.status??403;return new Response("Forbidden",{status:t,statusText:{402:"Payment Required",403:"Forbidden"}[t]??"",headers:e.responseHeaders})}function et(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 tt(e,t,i=303){const a=new Headers(e.responseHeaders);return a.append("Location",t),new Response("Forbidden",{status:i,statusText:"",headers:a})}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(Ge||(Ge={}));class it 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 at(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:o,integrationVersion:s,ip:n,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:d,netaceaCookieStatus:h,path:p,referer:l,requestHost:g,requestId:f,requestTime:y,sessionStatus:m,status:S,timeUnixMsUTC:C,userAgent:k,workerInstanceId:I,xForwardedFor:v,ipHeader:w}){return{Request:`${r} ${p}`,TimeLocal:new Date(C??Date.now()).toUTCString(),TimeUnixMsUTC:C,RealIp:n,UserAgent:k,Status:S,RequestTime:y?.toString(),BytesSent:e?.toString(),Referer:""===l?"-":l,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:m??"",ProtectorLatencyMs:u,ProtectorStatus:d,IntegrationType:o??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:g,RequestId:f??"",XForwardedFor:v,IpFromHeader:w,WorkerInstanceId:I,NetaceaUserIdCookieStatus:h,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const ot="unknown";function st(e,t,i){let{match:a,mitigate:o,captcha:s}=t;i||("2"===s?s="4":"3"===s?s="5":"b"===s?s="d":"c"===s&&(s="e"));let n=E[a]??ot+"_";n+=A[o]??ot;let r=_[o];if("0"!==s){n+=","+(b[s]??ot);const e=T[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=v.none),{sessionStatus:n,mitigation:r,parts:{match:a,mitigate:o,captcha:s}}}function nt(e,t){const i={"x-netacea-match":e.match,"x-netacea-mitigate":e.mitigate,"x-netacea-captcha":e.captcha};return void 0!==t&&(i["x-netacea-event-id"]=t),i}async function rt(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 ct{config;constructor(e){this.config=e}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),o=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("x-forwarded-for")??void 0;let n,r=s?.split(/, ?/)[0]??"";void 0!==this.config.ipHeaderName&&(n=e.headers.get(this.config.ipHeaderName)??void 0,r=n??r);const{sessionCookieDetails:c,sessionCookieStatus:u,sessionStatus:d,userId:h}=await async function(e,t,i,a,o){const s=await e.cookieFactory.retrieveCookieInfo(a,o),n={userId:void 0!==s.mitata?s.mitata.userId:void 0,requiresReissue:s.requiresReissue,isExpired:s.isExpired,shouldExpire:s.shouldExpire,isSameIP:s.isSameIP,isPrimaryHashValid:s.isPrimaryHashValid,protectorCheckCodes:{match:s.match,mitigate:s.mitigate,captcha:s.captcha},issueReason:s.issueReason};if(void 0!==n.userId&&n.isPrimaryHashValid){const a=n.userId,{isExpired:o,shouldExpire:s,isSameIP:r}=n,c=o||s||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?Ge.RENEW_SESSION:Ge.EXISTING_SESSION,{sessionStatus:u}=st(e.mitigationType,n.protectorCheckCodes,Je(t,i));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:n}}return{sessionStatus:"",userId:R(),sessionCookieStatus:Ge.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,r),p={sessionStatus:d,captchaToken:o,sessionCookieDetails:c,sessionCookieStatus:u,userId:h};return{clientIp:r,fingerprints:await ut(e),ipHeader:void 0!==n?`${this.config.ipHeaderName}: ${n}`: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:s}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),o=`${t}=`;for(const e of a)if(e.startsWith(o)){const i=e.slice(o.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await $e.decrypt(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ut(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 rt(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),o=await async function(e){const t=e.join(",");return await rt(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===o?o:`c_${o.substring(1,15)}`}}const{configureCookiesDomain:dt}=S.cookie.attributes;class ht{apiKey;captchaHeader;captchaSecretKey;captchaSiteKey;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;encryptedCookies=[];ingestServiceUrl;ingestType;ipHeaderName;kinesisConfigArgs;mitataCookieExpirySeconds;mitigationServiceTimeoutMs;mitigationServiceUrl;mitigationType;netaceaCaptchaCookieAttributes;netaceaCaptchaCookieName;netaceaCaptchaPath;netaceaCheckpointSignalPath;netaceaCookieAttributes;netaceaCookieName;secretKey;timeout;constructor(e){if(null===e.apiKey||void 0===e.apiKey)throw new Error("apiKey is a required parameter");if(this.apiKey=e.apiKey,null===e.secretKey||void 0===e.secretKey)throw new Error("secretKey is a required parameter");this.secretKey=e.secretKey;const{mitigationServiceUrl:t="https://mitigations.netacea.net"}=e;var i;this.mitigationServiceUrl=t.endsWith("/")?t.slice(0,-1):t,this.ingestServiceUrl=e.ingestServiceUrl??"https://ingest.netacea.net",this.mitigationType=e.mitigationType??exports.NetaceaMitigationType.INGEST,this.ingestType=e.ingestType??exports.NetaceaIngestType.KINESIS,this.kinesisConfigArgs=e.kinesis,void 0===e.captchaSiteKey&&void 0===e.captchaSecretKey||(this.captchaSiteKey=e.captchaSiteKey,this.captchaSecretKey=e.captchaSecretKey),this.timeout=(i=e.timeout??3e3)<=0?d:i,this.mitigationServiceTimeoutMs=Ue.parsing.parseIntOrDefault(e.mitigationServiceTimeoutMs,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=Ue.parsing.stringOrDefault(e.netaceaCookieName,"_mitata"),this.netaceaCaptchaCookieName=Ue.parsing.stringOrDefault(e.netaceaCaptchaCookieName,"_mitatacaptcha");const{cookieAttributes:a,captchaCookieAttributes:o}=dt(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);var s,n;this.netaceaCookieAttributes=a??"",this.netaceaCaptchaCookieAttributes=o??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=(s=this.mitigationType,void 0===(n=e.netaceaCookieExpirySeconds??e.mitataCookieExpirySeconds)?s===exports.NetaceaMitigationType.INGEST?3600:60:n),this.cookieEncryptionKey=e.cookieEncryptionKey,this.netaceaCaptchaPath=function(e){if(Boolean(e)&&"string"==typeof e)return e.startsWith("/")?e:`/${e}`}(e.netaceaCaptchaPath),this.netaceaCheckpointSignalPath=e.netaceaCheckpointSignalPath,void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof e.enableDynamicCaptchaContentType?e.enableDynamicCaptchaContentType:"true"===e.enableDynamicCaptchaContentType),this.captchaHeader=e.captchaHeader,this.ipHeaderName=e.ipHeaderName}}class pt{config;kinesis;requestAnalyser;cookieFactory;workerInstanceId;constructor(i){this.config=new ht(i),this.cookieFactory=new Be({cookieEncryptionKey:this.config.cookieEncryptionKey,secretKey:this.config.secretKey,expirySeconds:this.config.mitataCookieExpirySeconds}),this.config.ingestType===exports.NetaceaIngestType.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ue.ingest.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ct({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,cookieFactory:this.cookieFactory}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request);if(function(e,t,i){let a=e;try{a=new URL(e).pathname}catch(e){}return void 0!==i&&i.length>0&&a.endsWith(i)&&"get"===t.toLowerCase()}(i.url,i.method,this.config.netaceaCheckpointSignalPath)){const e={sessionStatus:",checkpoint_signal"};return await this.handleResponse(i,e,t)}const a=await this.requestAnalyser.getNetaceaRequestDetails(i);let o=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof o&&(o={sessionStatus:"error_open",apiCallLatency:o}),await this.handleResponse(i,o,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t),a=Je(t.url,e.method),o=a&&i.sessionStatus.includes("checkpoint_post"),s=!a&&We(t.url,e.method,this.config.netaceaCaptchaPath),n=()=>{const e=new Headers;if(!s&&!o)for(const t of i.setCookie)e.append("set-cookie",t);return e};return i.mitigated&&!o?"captcha"===i.mitigation?{...i,response:et({config:this.config,responseHeaders:n(),body:i.body})}:{...i,response:Ze({responseHeaders:n()})}:"5"===i.protectorCheckCodes.mitigate?void 0===i.redirect?{...i,response:Ze({status:402,responseHeaders:n()})}:{...i,response:tt({config:this.config,responseHeaders:n()},i.redirect.location,i.redirect.statusCode)}:a?{...i,response:new Response(i.body,{status:200,statusText:"OK",headers:n()})}:i}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:o}=function(e){if(void 0===e)return;const t=e.match(P);if(null!=t){const[,e,i,a,o,s,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:o,mitigationType:s,protectorCheckCodes:{match:n,mitigate:r,captcha:c}}}}(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=st(this.config.mitigationType,a,Je(new URL(e.url),e.method));return{userId:o,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),o=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:Ye(i.rawResponse.headers,"content-length","0"),cookieFingerprint:o.fingerprints.cookieFingerprint,headerFingerprint:o.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:o.clientIp,method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:o.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:null,referer:Ye(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestId:o.requestId,requestTime:"0",sessionStatus:i.sessionStatus??o.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:Ye(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:o.xForwardedForHeaderValue,ipHeader:o.ipHeader})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i),{match:o,mitigate:s,captcha:n}=a.responseView.getProtectorCodes();return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:",captcha_serve",mitigation:"captcha",mitigated:!0,protectorCheckCodes:{match:o,mitigate:s,captcha:n}}}async makeRequest({host:e,method:t,path:i,headers:a,body:o}){const s=`${e}${i}`,n=new Request(s,{...{method:t,body:o,headers:a},duplex:"half"}),r=await I(s,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.clone().text(),headers:c,fetchResponse:r}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(void 0!==t&&"injectHeaders"in t){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)}if(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:Xe(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?ze(e.headers.get("Accept")??void 0):ze();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,o;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof it&&(o=i.latencyMs,a=i.protectorApiResponse?.status);return{response:Je(t.url,e.method)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:nt({match:"0",mitigate:"0",captcha:"0"}),sessionStatus:"error_open",apiCallLatency:o,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await $e.decrypt(a,this.config.cookieEncryptionKey)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.config.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.config.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){const t=Ye(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=at(e);if(this.config.ingestType===exports.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([Ge.NEW_SESSION,Ge.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const i=e.sessionDetails.userId,a=await this.makeMitigateAPICall(e,t,!1,null),o=a.responseView.getProtectorCodes(),{match:s,mitigate:n,captcha:r}=o,c=[await this.createMitata(e.clientIp,i,s,n,r,a.mitataMaxAge,void 0,lt(e))],u={match:s,mitigate:n,captcha:r},d=st(this.config.mitigationType,u,!1),h={body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:c,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),redirect:"5"===n?a.responseView.getMonetisationRedirect(e.url.pathname,e.url.search):void 0,protectorCheckCodes:d.parts};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&d.mitigation!==v.flag||(h.injectHeaders=nt(d.parts,a.eventId)),h}{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes,i={match:t?.match??"0",mitigate:t?.mitigate??"0",captcha:t?.captcha??"0"},a=st(this.config.mitigationType,i,!1),o={body:void 0,apiCallStatus:void 0,apiCallLatency:void 0,setCookie:[],sessionStatus:a.sessionStatus,mitigation:a.mitigation,mitigated:[v.block,v.captcha].includes(a.mitigation),redirect:void 0,protectorCheckCodes:a.parts};return this.config.mitigationType!==exports.NetaceaMitigationType.INJECT&&a.mitigation!==v.flag||(o.injectHeaders=nt(a.parts)),o}}async createMitata(e,t,i,a,o,s=86400,n=void 0,c=r.NO_SESSION){const u=["1","3","5","a","c","e"].includes(o)||"3"===a||"5"===a?-60:this.config.mitataCookieExpirySeconds,d=void 0!==n?n-Math.floor(Date.now()/1e3):u,h=await this.cookieFactory.createCookieValue({clientIP:e,userId:t,match:i,mitigate:a,captcha:o,gracePeriod:d,cookieId:"",issueReason:c});return S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:o,captcha:s,body:n,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:o,captcha:s},d=st(this.config.mitigationType,u,!0);return{body:n,apiCallStatus:i,apiCallLatency:c,setCookie:r,sessionStatus:d.sessionStatus,mitigation:d.mitigation,mitigated:[v.block,v.captcha].includes(d.mitigation),protectorCheckCodes:{match:d.parts.match.toString(),mitigate:d.parts.mitigate.toString(),captcha:d.parts.captcha.toString()}}}async getMitataCaptchaFromHeaders(e){let t=e[w];const i=parseInt(e[N]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await $e.encrypt(t,this.config.cookieEncryptionKey,"A256GCM")),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}parseCaptchaAPICallBody(e,t){let i;if(null!=e)if("string"==typeof e){const a=e.trim();if(a.length>0)if(t.includes("application/json"))try{JSON.parse(a),i=a}catch(e){console.warn("Invalid JSON in captcha data, attempting to serialize:",e),i=JSON.stringify({data:a})}else i=e}else if(e instanceof ReadableStream)i=e;else if(t.includes("application/json"))try{i=JSON.stringify(e)}catch(t){console.warn("Failed to stringify captcha object, wrapping generic container"),i=JSON.stringify({data:e})}else try{i=JSON.stringify(e)}catch{i=String(e)}return i}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":e.contentType??"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==Ge.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),i["X-Netacea-Request-Id"]=e.requestId;const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),o.append("netaceaHeaders","request-id");const s=Date.now(),n=e.contentType??"application/x-www-form-urlencoded; charset=UTF-8",r=this.parseCaptchaAPICallBody(t,n),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${o.toString()}`,headers:i,method:"POST",body:r,timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-s;if(200!==c.status)throw new it(c,u);const d=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=d.sessionCookieMaxAge,f=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,g,void 0,lt(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e)),y=d.eventId;return{status:c.status,match:h,mitigate:p,captcha:l,setCookie:f,body:c.body,eventId:y,mitataMaxAge:g,latency:u}}async makeMitigateAPICall(e,t,i,a){const o={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Qe({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==Ge.NEW_SESSION&&(o["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(o["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,o["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),o["X-Netacea-Captcha-Content-Type"]=t,o["X-Netacea-Request-Id"]=e.requestId;let s="/";const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint),n.append("netaceaHeaders","request-id"),i&&(s="/captcha",null!==a&&n.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${n.toString()}`,headers:o,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;if(200!==c.status)throw new it(c,u);const d=new Ue.ProtectorApiResponseView(c.fetchResponse),{match:h,mitigate:p,captcha:l}=d.getProtectorCodes(),g=[await this.createMitata(e.clientIp,e.sessionDetails.userId,h,p,l,d.sessionCookieMaxAge,void 0,lt(e)),await this.getMitataCaptchaFromHeaders(c.headers)].filter((e=>void 0!==e));if("application/json"===c.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");c.body=await d.getCaptchaJson(this.config.netaceaCaptchaPath,e.url.host)}return{responseView:d,status:c.status,setCookie:g,body:c.body,eventId:d.eventId,mitataMaxAge:d.sessionCookieMaxAge,latency:u}}async processMitigateRequest(e){if(We(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(Je(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.sessionDetails.userId,"0","0","0",86400,void 0,lt(e))]}}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===Ge.NEW_SESSION,a=t===Ge.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e):{sessionStatus:"",setCookie:[]}}}function lt(e){if(void 0===e.sessionDetails.sessionCookieDetails)return r.NO_SESSION;const{isSameIP:t,isExpired:i}=e.sessionDetails.sessionCookieDetails;return t?i?r.EXPIRED_SESSION:r.NO_SESSION:r.IP_CHANGE}const gt=e=>Ue.parsing.parseIntOrDefault(e,{defaultValue:void 0});function ft(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)))}function yt(e,t,i){if("string"==typeof i)return e[`${t}_${i}`]?.trimEnd();for(const a of i){const i=yt(e,t,a);if(void 0!==i)return i}}function mt(e,t){const i=yt(e,t,"CAPTCHA_HEADER_NAME"),a=yt(e,t,"CAPTCHA_HEADER_VALUE");if(void 0!==i&&void 0!==a)return{name:i,value:a}}function St(e,t){const i=yt(e,t,"KINESIS_STREAM_NAME"),a=yt(e,t,"KINESIS_ACCESS_KEY"),o=yt(e,t,"KINESIS_SECRET_KEY"),s=ft({logBatchSize:gt(yt(e,t,"KINESIS_LOG_BATCH_SIZE")),maxLogAgeSeconds:gt(yt(e,t,"KINESIS_MAX_LOG_AGE_SECONDS"))});if(void 0!==i&&void 0!==a&&void 0!==o)return{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:o,...s}}exports.NetaceaVercelIntegration=pt,exports.default=pt,exports.getNetaceaArgsFromEnv=function(e,t="NETACEA"){return ft({apiKey:yt(e,t,"API_KEY"),captchaHeader:mt(e,t),captchaSecretKey:yt(e,t,"CAPTCHA_SECRET_KEY"),captchaSiteKey:yt(e,t,"CAPTCHA_SITE_KEY"),cookieEncryptionKey:yt(e,t,"COOKIE_ENCRYPTION_KEY"),enableDynamicCaptchaContentType:yt(e,t,"ENABLE_DYNAMIC_CAPTCHA_CONTENT_TYPE"),ingestServiceUrl:yt(e,t,"INGEST_SERVICE_URL"),ingestType:yt(e,t,"INGEST_TYPE"),ipHeaderName:yt(e,t,"IP_HEADER_NAME"),kinesis:St(e,t),mitataCookieExpirySeconds:gt(yt(e,t,"MITATA_COOKIE_EXPIRY_SECONDS")),mitigationServiceTimeoutMs:yt(e,t,"MITIGATION_SERVICE_TIMEOUT_MS"),mitigationServiceUrl:yt(e,t,["PROTECTOR_API_URL","MITIGATION_SERVICE_URL"]),mitigationType:yt(e,t,["PROTECTION_MODE","MITIGATION_TYPE"]),netaceaCaptchaCookieAttributes:yt(e,t,"CAPTCHA_COOKIE_ATTRIBUTES"),netaceaCaptchaCookieName:yt(e,t,"CAPTCHA_COOKIE_NAME"),netaceaCaptchaPath:yt(e,t,"CAPTCHA_PATH"),netaceaCheckpointSignalPath:yt(e,t,"CHECKPOINT_SIGNAL_PATH"),netaceaCookieAttributes:yt(e,t,"COOKIE_ATTRIBUTES"),netaceaCookieExpirySeconds:gt(yt(e,t,"COOKIE_EXPIRY_SECONDS")),netaceaCookieName:yt(e,t,"COOKIE_NAME"),secretKey:yt(e,t,"SECRET_KEY"),timeout:gt(yt(e,t,"TIMEOUT"))})};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/vercel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Netacea Vercel CDN Integration",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
"jose": "^4.15.9",
|
|
23
23
|
"uuid": "^10.0.0"
|
|
24
24
|
},
|
|
25
|
-
"gitHead": "
|
|
25
|
+
"gitHead": "d12a7c894c9fe1b9595ce9c0b3cdb6356682032b"
|
|
26
26
|
}
|