@netacea/cloudflare 6.0.43 → 6.0.45
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 +321 -7
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,274 @@
|
|
|
1
|
-
import { NetaceaCookieV3IssueReason, NetaceaIngestType, NetaceaMitigationType, NetaceaBaseArgs, InjectResponse, NetaceaMitigationResponse, MakeRequestResponse, IngestArgs, NetaceaResponseBase, InjectHeaders } from '@netacea/netaceaintegrationbase';
|
|
2
|
-
export { NetaceaMitigationType } from '@netacea/netaceaintegrationbase';
|
|
3
1
|
import { Request as Request$1 } from '@cloudflare/workers-types/experimental';
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
2
|
+
import { AwsClient } from 'aws4fetch';
|
|
3
|
+
import { Buffer } from 'buffer/';
|
|
4
|
+
|
|
5
|
+
interface KinesisIngestConfigArgs$1 {
|
|
6
|
+
kinesisStreamName: string;
|
|
7
|
+
kinesisAccessKey?: string;
|
|
8
|
+
kinesisSecretKey?: string;
|
|
9
|
+
logBatchSize?: number;
|
|
10
|
+
maxLogAgeSeconds?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
declare enum NetaceaIngestType {
|
|
14
|
+
/**
|
|
15
|
+
* ORIGIN Ingest mode; data to be ingested is set by headers, so it can be forwarded via a seperate mechanism
|
|
16
|
+
*/
|
|
17
|
+
ORIGIN = "ORIGIN",
|
|
18
|
+
/**
|
|
19
|
+
* HTTP Ingest mode, this is the standard implementation
|
|
20
|
+
*/
|
|
21
|
+
HTTP = "HTTP",
|
|
22
|
+
/**
|
|
23
|
+
* Ingest over Kinesis, Netacea will inform you if this is required
|
|
24
|
+
* and will provide you with kinesis credentials.
|
|
25
|
+
*/
|
|
26
|
+
KINESIS = "KINESIS",
|
|
27
|
+
/**
|
|
28
|
+
* Data to be Ingest via some mechanism native to the host/CDN, e.g. log shipping.
|
|
29
|
+
*/
|
|
30
|
+
NATIVE = "NATIVE"
|
|
31
|
+
}
|
|
32
|
+
declare enum NetaceaMitigationType {
|
|
33
|
+
/**
|
|
34
|
+
* Run Netacea with mitigation mode enabled.
|
|
35
|
+
* This will serve Captcha pages and Forbidden pages when instructed to do so
|
|
36
|
+
*/
|
|
37
|
+
MITIGATE = "MITIGATE",
|
|
38
|
+
/**
|
|
39
|
+
* Run Netacea with Inject mode enabled.
|
|
40
|
+
* The end-user will only receive a cookie.
|
|
41
|
+
* The origin server will receive 3-4 headers,
|
|
42
|
+
*
|
|
43
|
+
* 'x-netacea-match' indicating what was matched (nothing(0), ua(1), ip(2), etc...)
|
|
44
|
+
*
|
|
45
|
+
* 'x-netacea-mitigate' indicating what action would've be taken (nothing (0), block(1), allow(2), etc...)
|
|
46
|
+
*
|
|
47
|
+
* 'x-netacea-captcha' indicating what captcha action would've been taken
|
|
48
|
+
*
|
|
49
|
+
* 'x-netacea-event-id' event id value that should be injected to the captcha
|
|
50
|
+
* page if using `@netacea/captchafeedback` module on the origin server
|
|
51
|
+
*/
|
|
52
|
+
INJECT = "INJECT",
|
|
53
|
+
/**
|
|
54
|
+
* Run Netacea with Ingest only mode
|
|
55
|
+
* No cookies will be set for the end user.
|
|
56
|
+
* No mitigations will be applied.
|
|
57
|
+
*
|
|
58
|
+
* **It's recommended to start in this mode!**
|
|
59
|
+
*/
|
|
60
|
+
INGEST = "INGEST"
|
|
61
|
+
}
|
|
62
|
+
declare enum NetaceaCookieV3IssueReason {
|
|
63
|
+
CAPTCHA_GET = "captcha_get",
|
|
64
|
+
CAPTCHA_POST = "captcha_post",
|
|
65
|
+
EXPIRED_SESSION = "expired_session",
|
|
66
|
+
FORCED_REVALIDATION = "forced_revalidation",
|
|
67
|
+
INVALID_SESSION = "invalid_session",
|
|
68
|
+
IP_CHANGE = "ip_change",
|
|
69
|
+
NO_SESSION = "no_session"
|
|
70
|
+
}
|
|
71
|
+
interface MakeRequestResponse {
|
|
72
|
+
/**
|
|
73
|
+
* Numerical status code of the response
|
|
74
|
+
*/
|
|
75
|
+
status: number;
|
|
76
|
+
/**
|
|
77
|
+
* Key value collection of the response headers
|
|
78
|
+
*/
|
|
79
|
+
headers: Record<string, string>;
|
|
80
|
+
/**
|
|
81
|
+
* Response body value
|
|
82
|
+
*/
|
|
83
|
+
body?: string;
|
|
84
|
+
}
|
|
85
|
+
interface NetaceaBaseArgs {
|
|
86
|
+
/**
|
|
87
|
+
* Netacea APIKey
|
|
88
|
+
*/
|
|
89
|
+
apiKey: string;
|
|
90
|
+
/**
|
|
91
|
+
* Netacea Secret Key
|
|
92
|
+
*/
|
|
93
|
+
secretKey: string;
|
|
94
|
+
/**
|
|
95
|
+
* Google RECaptcha Site Key.
|
|
96
|
+
* This is used for providing your own captcha values without updating these in the Netacea console.
|
|
97
|
+
*/
|
|
98
|
+
captchaSiteKey?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Google RECaptcha Secret Key.
|
|
101
|
+
* This is used for providing your own captcha values without updating these in the Netacea console.
|
|
102
|
+
*/
|
|
103
|
+
captchaSecretKey?: string;
|
|
104
|
+
/**
|
|
105
|
+
* Request timeout in ms
|
|
106
|
+
*/
|
|
107
|
+
timeout?: number;
|
|
108
|
+
/**
|
|
109
|
+
* URL of the Netacea ingest service.
|
|
110
|
+
* DEFAULT: https://ingest.netacea.net
|
|
111
|
+
*/
|
|
112
|
+
ingestServiceUrl?: string;
|
|
113
|
+
/**
|
|
114
|
+
* URL of the Netacea mitigation service.
|
|
115
|
+
* DEFAULT: https://mitigations.netacea.net
|
|
116
|
+
*/
|
|
117
|
+
mitigationServiceUrl?: string;
|
|
118
|
+
/**
|
|
119
|
+
* Type of mitigation applied, see the `NetaceaMitigationType` ENUM
|
|
120
|
+
* - INGEST - Ingest only mode, no mitigations applied
|
|
121
|
+
* - MITIGATION - Mitigation mode, active blocking/captcha rules will be applied.
|
|
122
|
+
* - INJECT - Inject mode, headers will be sent to your origin server
|
|
123
|
+
* indicating what actions Netacea would have taken.
|
|
124
|
+
* DEFAULT: NetaceaMitigationType.INGEST
|
|
125
|
+
*/
|
|
126
|
+
mitigationType?: NetaceaMitigationType;
|
|
127
|
+
/**
|
|
128
|
+
* Type of ingest, see the `NetaceaIngestType` ENUM
|
|
129
|
+
* - HTTP - Ingest via HTTP.
|
|
130
|
+
* - KINESIS - Ingest via KINESIS
|
|
131
|
+
* DEFAULT: NetaceaIngestType.HTTP
|
|
132
|
+
*/
|
|
133
|
+
ingestType?: NetaceaIngestType;
|
|
134
|
+
/**
|
|
135
|
+
* Kinesis ingest definition, see the `KinesisIngestConfigArgs` type.
|
|
136
|
+
* Only to be provided if ingestType is set to KINESIS.
|
|
137
|
+
* Netacea will provide you with the details for this stream.
|
|
138
|
+
*/
|
|
139
|
+
kinesis?: KinesisIngestConfigArgs$1;
|
|
140
|
+
/**
|
|
141
|
+
* Deprecated: alias for netaceaCookieExpirySeconds.
|
|
142
|
+
* If both are set, netaceaCookieExpirySeconds is prefered.
|
|
143
|
+
* Seconds for the netacea cookie to be revalidated after.
|
|
144
|
+
*/
|
|
145
|
+
mitataCookieExpirySeconds?: number;
|
|
146
|
+
/**
|
|
147
|
+
* Seconds for the netacea cookie to be revalidated after.
|
|
148
|
+
*/
|
|
149
|
+
netaceaCookieExpirySeconds?: number;
|
|
150
|
+
/**
|
|
151
|
+
* The name of the netacea cookie. Defaults to _mitata.
|
|
152
|
+
*/
|
|
153
|
+
netaceaCookieName?: string;
|
|
154
|
+
/**
|
|
155
|
+
* The name of the netacea captcha cookie. Defaults to _mitatacaptcha.
|
|
156
|
+
*/
|
|
157
|
+
netaceaCaptchaCookieName?: string;
|
|
158
|
+
}
|
|
159
|
+
interface InjectHeaders {
|
|
160
|
+
'x-netacea-match': string;
|
|
161
|
+
'x-netacea-mitigate': string;
|
|
162
|
+
'x-netacea-captcha': string;
|
|
163
|
+
'x-netacea-event-id'?: string;
|
|
164
|
+
}
|
|
165
|
+
interface IngestArgs {
|
|
166
|
+
/**
|
|
167
|
+
* Client IP Address
|
|
168
|
+
*/
|
|
169
|
+
ip: string;
|
|
170
|
+
/**
|
|
171
|
+
* Client User-Agent header value
|
|
172
|
+
*/
|
|
173
|
+
userAgent: string;
|
|
174
|
+
/**
|
|
175
|
+
* Response status code
|
|
176
|
+
* Should be 403 if Netacea mitigated
|
|
177
|
+
*/
|
|
178
|
+
status: string;
|
|
179
|
+
/**
|
|
180
|
+
* Request method
|
|
181
|
+
*/
|
|
182
|
+
method: string;
|
|
183
|
+
/**
|
|
184
|
+
* Request path
|
|
185
|
+
*/
|
|
186
|
+
path: string;
|
|
187
|
+
/**
|
|
188
|
+
* Request protocol
|
|
189
|
+
*/
|
|
190
|
+
protocol: string | null;
|
|
191
|
+
/**
|
|
192
|
+
* Request referer header value
|
|
193
|
+
*/
|
|
194
|
+
referer: string;
|
|
195
|
+
/**
|
|
196
|
+
* Request content-length header, or body size
|
|
197
|
+
*/
|
|
198
|
+
bytesSent: string | number;
|
|
199
|
+
/**
|
|
200
|
+
* The time the request was started, in unix milliseconds format.
|
|
201
|
+
*/
|
|
202
|
+
timeUnixMsUTC?: number;
|
|
203
|
+
/**
|
|
204
|
+
* Time taken to serve request
|
|
205
|
+
*/
|
|
206
|
+
requestTime: string | number;
|
|
207
|
+
/**
|
|
208
|
+
* Netacea mitata cookie value.
|
|
209
|
+
* Should be request's cookie value if Netacea was not called.
|
|
210
|
+
*/
|
|
211
|
+
mitataCookie?: string;
|
|
212
|
+
/**
|
|
213
|
+
* Session status from `ComposeResultResponse`
|
|
214
|
+
*/
|
|
215
|
+
sessionStatus?: string;
|
|
216
|
+
/**
|
|
217
|
+
* Type of the integration, for example "Cloudflare" or "Cloudfront"
|
|
218
|
+
*/
|
|
219
|
+
integrationType?: string;
|
|
220
|
+
/**
|
|
221
|
+
* SEMVER string indicating the version of the integration
|
|
222
|
+
* Example: 1.2.3
|
|
223
|
+
*/
|
|
224
|
+
integrationVersion?: string;
|
|
225
|
+
/**
|
|
226
|
+
* IP values set by a CDN under "x-fowarded-for" header
|
|
227
|
+
*/
|
|
228
|
+
xForwardedFor?: string;
|
|
229
|
+
headerFingerprint?: string;
|
|
230
|
+
cookieFingerprint?: string;
|
|
231
|
+
integrationMode?: string;
|
|
232
|
+
requestHost?: string;
|
|
233
|
+
mitigationLatency?: number;
|
|
234
|
+
mitigationStatus?: number;
|
|
235
|
+
netaceaCookieStatus?: number;
|
|
236
|
+
workerInstanceId?: string;
|
|
237
|
+
}
|
|
238
|
+
interface NetaceaResponseBase {
|
|
239
|
+
/**
|
|
240
|
+
* Cookies that should be set back to the user.
|
|
241
|
+
*/
|
|
242
|
+
setCookie?: string[];
|
|
243
|
+
/**
|
|
244
|
+
* Netacea session status string
|
|
245
|
+
*/
|
|
246
|
+
sessionStatus: string;
|
|
247
|
+
apiCallLatency?: number;
|
|
248
|
+
apiCallStatus?: number;
|
|
249
|
+
cookieSessionStatus?: string | undefined;
|
|
250
|
+
}
|
|
251
|
+
interface MitigateResponse<T = any> extends NetaceaResponseBase {
|
|
252
|
+
/**
|
|
253
|
+
* Response value, using Response generic
|
|
254
|
+
*/
|
|
255
|
+
response?: T;
|
|
256
|
+
}
|
|
257
|
+
interface InjectResponse<T = any> extends MitigateResponse<T> {
|
|
258
|
+
/**
|
|
259
|
+
* Headers to be sent to the origin server
|
|
260
|
+
* X-Netacea-Match
|
|
261
|
+
* X-Netacea-Mitigate
|
|
262
|
+
* X-Netacea-Captcha
|
|
263
|
+
* X-Netacea-Event-ID (Only sent when CAPTCHA is served)
|
|
264
|
+
*/
|
|
265
|
+
injectHeaders: InjectHeaders | undefined;
|
|
266
|
+
/**
|
|
267
|
+
* Response value, using Response generic
|
|
268
|
+
*/
|
|
269
|
+
response?: T | undefined;
|
|
270
|
+
}
|
|
271
|
+
type NetaceaMitigationResponse<T> = MitigateResponse<T> | InjectResponse<T> | undefined;
|
|
6
272
|
|
|
7
273
|
interface NetaceaCloudflareResult {
|
|
8
274
|
response: Response;
|
|
@@ -70,7 +336,7 @@ declare class CloudflareConfig {
|
|
|
70
336
|
readonly secretKey: string;
|
|
71
337
|
readonly mitigationServiceUrl: string;
|
|
72
338
|
readonly ingestServiceUrl: string;
|
|
73
|
-
readonly kinesisConfigArgs?: KinesisIngestConfigArgs;
|
|
339
|
+
readonly kinesisConfigArgs?: KinesisIngestConfigArgs$1;
|
|
74
340
|
readonly timeout: number;
|
|
75
341
|
readonly mitigationServiceTimeoutMs: number;
|
|
76
342
|
readonly captchaSiteKey?: string;
|
|
@@ -90,6 +356,54 @@ declare class CloudflareConfig {
|
|
|
90
356
|
constructor(args: CloudflareConstructorArgs$1);
|
|
91
357
|
}
|
|
92
358
|
|
|
359
|
+
type KinesisMakeRequest = (args: {
|
|
360
|
+
headers: Record<string, string>;
|
|
361
|
+
method: 'POST' | 'GET';
|
|
362
|
+
host: string;
|
|
363
|
+
path: string;
|
|
364
|
+
body?: any;
|
|
365
|
+
}) => Promise<any>;
|
|
366
|
+
interface KinesisIngestWebLog {
|
|
367
|
+
apiKey: string;
|
|
368
|
+
}
|
|
369
|
+
interface KinesisIngestConfigArgs {
|
|
370
|
+
kinesisStreamName: string;
|
|
371
|
+
kinesisAccessKey?: string;
|
|
372
|
+
kinesisSecretKey?: string;
|
|
373
|
+
logBatchSize?: number;
|
|
374
|
+
maxLogAgeSeconds?: number;
|
|
375
|
+
}
|
|
376
|
+
interface KinesisIngestArgs extends KinesisIngestConfigArgs {
|
|
377
|
+
apiKey: string;
|
|
378
|
+
rampUpBatchSize?: boolean;
|
|
379
|
+
maxAwaitTimePerIngestCallMs?: number;
|
|
380
|
+
}
|
|
381
|
+
interface WebStandardKinesisDependencies {
|
|
382
|
+
AwsClient: typeof AwsClient;
|
|
383
|
+
Buffer: typeof Buffer;
|
|
384
|
+
makeRequest: KinesisMakeRequest;
|
|
385
|
+
}
|
|
386
|
+
declare class WebStandardKinesis {
|
|
387
|
+
private readonly deps;
|
|
388
|
+
protected readonly kinesisStreamName: string;
|
|
389
|
+
protected readonly kinesisAccessKey: string;
|
|
390
|
+
protected readonly kinesisSecretKey: string;
|
|
391
|
+
protected readonly maxLogBatchSize: number;
|
|
392
|
+
protected readonly maxLogAgeSeconds: number;
|
|
393
|
+
protected logBatchSize: number;
|
|
394
|
+
protected maxAwaitTimePerIngestCallMs: undefined | number;
|
|
395
|
+
protected logCache: KinesisIngestWebLog[];
|
|
396
|
+
private intervalSet;
|
|
397
|
+
constructor({ deps, kinesisIngestArgs }: {
|
|
398
|
+
deps: WebStandardKinesisDependencies;
|
|
399
|
+
kinesisIngestArgs: KinesisIngestArgs;
|
|
400
|
+
});
|
|
401
|
+
putToKinesis(): Promise<void>;
|
|
402
|
+
ingest<LogFormat extends KinesisIngestWebLog>(log: LogFormat): Promise<void>;
|
|
403
|
+
private batchArrayForKinesis;
|
|
404
|
+
private signRequest;
|
|
405
|
+
}
|
|
406
|
+
|
|
93
407
|
type CloudflareConstructorArgs = NetaceaBaseArgs & {
|
|
94
408
|
cookieEncryptionKey?: string;
|
|
95
409
|
enableDynamicCaptchaContentType?: boolean | string;
|
|
@@ -122,7 +436,7 @@ interface MakeRequestArgs {
|
|
|
122
436
|
}
|
|
123
437
|
declare class Cloudflare {
|
|
124
438
|
protected readonly config: CloudflareConfig;
|
|
125
|
-
protected readonly kinesis?:
|
|
439
|
+
protected readonly kinesis?: WebStandardKinesis;
|
|
126
440
|
private readonly requestAnalyser;
|
|
127
441
|
private workerInstanceId;
|
|
128
442
|
constructor(args: CloudflareConstructorArgs);
|
|
@@ -179,4 +493,4 @@ declare class Cloudflare {
|
|
|
179
493
|
protected processIngest(requestDetails: NetaceaRequestDetails): Promise<NetaceaResponseBase>;
|
|
180
494
|
}
|
|
181
495
|
|
|
182
|
-
export { type CloudflareConstructorArgs, type NetaceaCloudflareResult, Cloudflare as default };
|
|
496
|
+
export { type CloudflareConstructorArgs, type NetaceaCloudflareResult, NetaceaMitigationType, Cloudflare as default };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function p(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function l(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var f=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=l(e??"",!0),a=t=l(t??"",!0);if(void 0!==e&&void 0!==t){const n=p(e,"Domain"),s=p(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=p(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=p(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=p(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:p,removeDuplicateAttrs:l});function g(e){const t=l([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:g});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:f,netaceaSession:y}};var C="@netacea/cloudflare",k="6.0.43";const w=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",b="x-netacea-mitigate",N="x-netacea-captcha",A="x-netacea-mitata-expiry",E="x-netacea-mitatacaptcha-value",T="x-netacea-mitatacaptcha-expiry",_="x-netacea-event-id",P={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},O={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},x={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},M={0:I.none,1:I.block,2:I.none,3:I.block,4:I.block},R={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha},K="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),j=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function L(e){if(void 0===e)return;const t=e.match(j);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function H(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var V;async function $(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function U(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function G(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}async function W(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:n}=e;return a.includes(i)&&n.includes("trackingId")&&"get"===t.toLowerCase()}function B(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function z(e){return void 0!==e&&e.startsWith("/")&&e.length>=5?e:"/AtaVerifyCaptcha"}function X(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 J(e,t,i=""){return e.get(t)??i}function Y(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(V||(V={}));class Z extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Q(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({ip:e,userAgent:t,status:i,method:a,path:n,protocol:s,referer:o,bytesSent:r,requestTime:c,mitataCookie:u,sessionStatus:h,integrationType:p,integrationVersion:l,integrationMode:d,xForwardedFor:f,headerFingerprint:g,cookieFingerprint:y,requestHost:m,mitigationLatency:S,mitigationStatus:C,netaceaCookieStatus:k,workerInstanceId:w}){return{Request:`${a} ${n} ${s}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,RequestTime:c?.toString(),BytesSent:r?.toString(),Referer:""===o?"-":o,NetaceaUserIdCookie:u??"",NetaceaMitigationApplied:h??"",ProtectorLatencyMs:S,ProtectorStatus:C,IntegrationType:p??"",IntegrationVersion:l??"",ProtectionMode:d??"",RequestHost:m,XForwardedFor:f,WorkerInstanceId:w,NetaceaUserIdCookieStatus:k,optional:{headerFingerprint:g,cookieFingerprint:y}}}(e)}const ee="unknown";function te(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s&&(s="5"));let o=P[a]??ee+"_";o+=O[n]??ee;let r=M[n];if("0"!==s){o+=","+(x[s]??ee);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function ie(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class ae{config;constructor(e){this.config=e,this.config.captchaVerificationPath=z(e.captchaVerificationPath)}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("cf-connecting-ip")??"",{sessionCookieDetails:o,sessionCookieStatus:r,sessionStatus:c,userId:u}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=L(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(K),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await F(t+"|"+n.expiry,i),h=n.ipHash===u,p=n.signature===await F(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:p,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?V.RENEW_SESSION:V.EXISTING_SESSION,{sessionStatus:u}=te(e.mitigationType,s.protectorCheckCodes,B(t,i,e.captchaVerificationPath));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:H(),sessionCookieStatus:V.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await ne(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",sessionDetails:{sessionStatus:c,captchaToken:n,sessionCookieDetails:o,sessionCookieStatus:r,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await U(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ne(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await ie(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await ie(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}var se="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},oe={},re={},ce={},ue=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),he=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pe=se&&se.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ue(t,e,i);return he(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0}),ce.isJweEncrypted=ce.decrypt=ce.encrypt=void 0;const le=pe(i);ce.encrypt=async function(e,t){const i=le.base64url.decode(t),a=(new TextEncoder).encode(e);return await new le.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ce.decrypt=async function(e,t){const i=le.base64url.decode(t),{plaintext:a}=await le.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ce.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var de=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ge=se&&se.__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)&&de(t,e,i);return fe(t,e),t};Object.defineProperty(re,"__esModule",{value:!0}),re.jwe=void 0,re.jwe=ge(ce);var ye={},me={};function Se(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=ke("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function Ce(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...we(s,t))}return i}function ke(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function we(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(me,"__esModule",{value:!0}),me.findAllInCookieString=me.findFirstInCookieString=me.findAllInHeaders=me.findFirstInHeaders=me.findOnlyValueInHeaders=me.findAllValuesInHeaders=me.findFirstValueInHeaders=void 0,me.findFirstValueInHeaders=function(e,t){const i=Se(e,t);if(void 0!==i)return i.slice(t.length+1)},me.findAllValuesInHeaders=function(e,t){return Ce(e,t).map((e=>e.slice(t.length+1)))},me.findOnlyValueInHeaders=function(e,t){const i=Ce(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},me.findFirstInHeaders=Se,me.findAllInHeaders=Ce,me.findFirstInCookieString=ke,me.findAllInCookieString=we;var Ie={};function ve(e){return"set-cookie"===e||"Set-Cookie"===e}function be(e,t){const i=t+"=";return e.startsWith(i)}function Ne(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Ae(e,t){for(const i of Object.keys(e)){if(!ve(i))continue;const a=Ee(Ne(e,i),t);if(void 0!==a)return a}}function Ee(e,t){return e.map((e=>e.trimStart())).find((e=>be(e,t)))}function Te(e,t){const i=[];for(const a of Object.keys(e)){if(!ve(a))continue;const n=Ne(e,a);i.push(..._e(n,t))}return i}function _e(e,t){return e.map((e=>e.trimStart())).filter((e=>be(e,t)))}Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.findAllInSetCookieStrings=Ie.findAllInHeaders=Ie.findFirstInSetCookieStrings=Ie.findFirstInHeaders=Ie.findOnlyValueInHeaders=Ie.findFirstValueInHeaders=void 0,Ie.findFirstValueInHeaders=function(e,t){const i=Ae(e,t);return i?.slice(t.length+1)?.split(";")[0]},Ie.findOnlyValueInHeaders=function(e,t){const i=Te(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},Ie.findFirstInHeaders=Ae,Ie.findFirstInSetCookieStrings=Ee,Ie.findAllInHeaders=Te,Ie.findAllInSetCookieStrings=_e;var Pe=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Oe=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xe=se&&se.__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)&&Pe(t,e,i);return Oe(t,e),t};Object.defineProperty(ye,"__esModule",{value:!0}),ye.setCookie=ye.cookie=void 0,ye.cookie=xe(me),ye.setCookie=xe(Ie);var Me={},Re={},Ke={};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.KINESIS_URL=Ke.API_VERSION=Ke.REGION=Ke.PAYLOAD_TYPE=Ke.STATE=void 0,Ke.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ke.PAYLOAD_TYPE="string",Ke.REGION="eu-west-1",Ke.API_VERSION="2013-12-02",Ke.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com",Object.defineProperty(Re,"__esModule",{value:!0}),Re.WebStandardKinesis=void 0;const De=Ke;async function je(e){await new Promise((t=>{setTimeout(t,e)}))}function Le(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}Re.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e;const{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,maxLogAgeSeconds:s,logBatchSize:o,rampUpBatchSize:r,maxAwaitTimePerIngestCallMs:c}=t;if(void 0===a)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===n)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=i,this.kinesisAccessKey=a,this.kinesisSecretKey=n,this.maxAwaitTimePerIngestCallMs=c,void 0!==s&&s<this.maxLogAgeSeconds&&s>0&&(this.maxLogAgeSeconds=s),void 0!==o&&(this.maxLogBatchSize=o),this.logBatchSize=!0===r?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:Le(i.headers),host:De.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(je(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=je(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const n=e.slice(a,a+t);i.push({Data:this.deps.Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}async signRequest(e,t,i,a){const n={Records:this.batchArrayForKinesis(i,a),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(De.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebStandardKinesis=void 0;var t=Re;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}})}(Me);var He={};function qe(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}return null===i&&(i=t.defaultValue),void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(He,"__esModule",{value:!0}),He.parseIntOrDefault=He.parseNumberOrDefault=void 0,He.parseNumberOrDefault=qe,He.parseIntOrDefault=function(e,t){return Math.floor(qe(e,t))};var Fe=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ve=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$e=se&&se.__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)&&Fe(t,e,i);return Ve(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0});var Ue=oe.parsing=Ge=oe.ingest=oe.headers=oe.webcrypto=void 0;oe.webcrypto=$e(re),oe.headers=$e(ye);var Ge=oe.ingest=$e(Me);Ue=oe.parsing=$e(He);const{configureCookiesDomain:We}=S.cookie.attributes;class Be{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;mitigationServiceTimeoutMs;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;netaceaCaptchaVerificationPath;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:p,ingestType:l=s.HTTP,kinesis:d,mitataCookieExpirySeconds:f,netaceaCookieExpirySeconds:g,netaceaCookieName:y,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:S=!1,captchaHeader:C,netaceaCaptchaPath:k,netaceaCaptchaVerificationPath:w}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=l??s.HTTP,this.kinesisConfigArgs=d,void 0===u&&void 0===p||(this.captchaSiteKey=u,this.captchaSecretKey=p),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Ue.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=y??"_mitata",this.netaceaCaptchaCookieName=m??"_mitatacaptcha";const{cookieAttributes:I,captchaCookieAttributes:v}=We(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=I??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,g??f),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(k)&&"string"==typeof k&&(this.netaceaCaptchaPath=k.startsWith("/")?k:`/${k}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof S?S:"true"===S),this.captchaHeader=C,this.netaceaCaptchaVerificationPath=z(w)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Be(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ge.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ae({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,captchaVerificationPath:this.config.netaceaCaptchaVerificationPath}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t);if(i.mitigated){const a=new Headers;if(!await W(t.url,e.method,this.config.netaceaCaptchaPath))for(const e of i.setCookie)a.append("set-cookie",e);let n="Forbidden";return"captcha"===i.mitigation&&(void 0!==this.config.captchaHeader&&a.append(this.config.captchaHeader.name,this.config.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),n=i.body),{response:new Response(n,{status:403,statusText:"Forbidden",headers:a}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}if(B(t.url,e.method,this.config.netaceaCaptchaVerificationPath)){const e=new Headers;for(const t of i.setCookie)e.append("set-cookie",t);return{response:new Response(i.body,{status:200,statusText:"OK",headers:e}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}return{setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=L(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=te(this.config.mitigationType,a,B(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:J(i.rawResponse.headers,"content-length","0"),ip:J(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:n.protocol??null,referer:J(e.headers,"referer"),requestTime:"0",sessionStatus:i.sessionStatus??n.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),userAgent:J(e.headers,"user-agent","-"),mitataCookie:a,integrationType:C.replace("@netacea/",""),integrationVersion:k,xForwardedFor:J(e.headers,"x-forwarded-for"),headerFingerprint:n.fingerprints.headerFingerprint,cookieFingerprint:n.fingerprints.cookieFingerprint,integrationMode:this.config.mitigationType,requestHost:new URL(e.url).hostname,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,workerInstanceId:this.workerInstanceId})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await w(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===s.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:X(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?G(e.headers.get("Accept")??void 0):G();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Z&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:B(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await U(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=J(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Q(e);if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([V.NEW_SESSION,V.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,p=await this.makeMitigateAPICall(e,t,!1,null);i=p.status,a=p.match,n=p.mitigate,s=p.captcha,o=p.body,u=p.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,p.mitataMaxAge)],c=p.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await F(e+"|"+String(i),a),n].join(K);return`${await F(s,a)}${K}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await $(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[E];const i=parseInt(e[T]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await $(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==V.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint);const s=Date.now(),o=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:t,timeout:this.config.mitigationServiceTimeoutMs}),r=Date.now()-s;return await this.getApiCallResponseFromResponse(o,e,r)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Z(e,i);const a=e.headers[v],n=e.headers[b],s=e.headers[N];let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[_];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Y({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==V.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=te(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[I.block,I.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(await W(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(B(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===V.NEW_SESSION,a=t===V.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("aws4fetch"),t=require("buffer/"),i=require("jose"),a=require("uuid");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var a=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,a.get?a:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var s,o,r,c=n(i),u=n(a);!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(s||(s={})),exports.NetaceaMitigationType=void 0,(o=exports.NetaceaMitigationType||(exports.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(r||(r={}));const h=3e3;function p(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function l(e,t=!1){return"string"!=typeof e&&(e=e.join("; ")),""===e?"":d(e.split(";"),t).join("; ")}function d(e,t=!1){if(t)return d(e.reverse()).reverse();const i=new Set,a=[];for(let t of e){if(t=t.trimStart(),""===t.trim())continue;const e=t.split("=")[0].toUpperCase();i.has(e)||(i.add(e),a.push(t))}return a}var f=Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=l(e??"",!0),a=t=l(t??"",!0);if(void 0!==e&&void 0!==t){const n=p(e,"Domain"),s=p(t,"Domain");void 0!==n&&void 0!==s?a=t.replace(s,n):void 0!==n&&void 0===s?a=t+(""!==t?`; Domain=${n}`:`Domain=${n}`):void 0===n&&void 0!==s&&(i=e+(""!==e?`; Domain=${s}`:`Domain=${s}`))}else if(void 0!==e&&void 0===t){const t=p(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=p(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=p(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:p,removeDuplicateAttrs:l});function g(e){const t=l([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}var y=Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return g({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:g});var m=Object.freeze({__proto__:null,parseSetCookie:function(e){const t=e.indexOf("=");if(t<0)throw new Error("Could not parse the given set-cookie value.");const i=e.slice(0,t),a=e.slice(t+1),n=a.indexOf(";");return{name:i,value:a.slice(0,n),attributes:a.slice(n).trimStart()}}});const S={cookie:{parse:m,attributes:f,netaceaSession:y}};var C="@netacea/cloudflare",k="6.0.45";const w=globalThis.fetch.bind(globalThis),I={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},v="x-netacea-match",b="x-netacea-mitigate",N="x-netacea-captcha",A="x-netacea-mitata-expiry",T="x-netacea-mitatacaptcha-value",E="x-netacea-mitatacaptcha-expiry",_="x-netacea-event-id",P={0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_",b:"headerFP_"},O={0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},x={0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},M={0:I.none,1:I.block,2:I.none,3:I.block,4:I.block},R={1:I.captcha,2:I.captchaPass,3:I.captcha,4:I.allow,5:I.captcha},K="_/@#/",D="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),j=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(([a-zA-Z\d])(\d)(\d))$/;function L(e){if(void 0===e)return;const t=e.match(j);if(null!=t){const[,e,i,a,n,s,o,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:n,mitigationType:s,protectorCheckCodes:{match:o,mitigate:r,captcha:c}}}}function H(e=16,t=D){const i=new Uint16Array(e-1);crypto.getRandomValues(i);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}async function q(e,t){const i=await async function(e){return await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}(function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(t));return new Uint8Array(await crypto.subtle.sign("HMAC",i,e))}async function F(e,i){const a=await q(t.Buffer.from(e),i),n=t.Buffer.from(a).toString("hex");return t.Buffer.from(n).toString("base64")}var V;async function $(e,t){const i=c.base64url.decode(t),a=(new TextEncoder).encode(e);return await new c.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)}async function U(e,t){const i=c.base64url.decode(t),{plaintext:a}=await c.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)}function G(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"}async function W(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:n}=e;return a.includes(i)&&n.includes("trackingId")&&"get"===t.toLowerCase()}function B(e,t,i){return i.startsWith("/")||(i="/"+i),e.pathname===i&&"post"===t.toLowerCase()}function z(e){return void 0!==e&&e.startsWith("/")&&e.length>=5?e:"/AtaVerifyCaptcha"}function X(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 J(e,t,i=""){return e.get(t)??i}function Y(e){let t="",i="";for(const a in e){const n=e[a];void 0!==n&&(t=`${t}${i}${a}=${n}`,i="; ")}return t}!function(e){e[e.NEW_SESSION=1]="NEW_SESSION",e[e.EXISTING_SESSION=2]="EXISTING_SESSION",e[e.RENEW_SESSION=3]="RENEW_SESSION"}(V||(V={}));class Z extends Error{protectorApiResponse;latencyMs;constructor(e,t){super(`Got status ${e.status} when calling protector API with ${t}ms latency.`),this.protectorApiResponse=e,this.latencyMs=t}}function Q(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,function({bytesSent:e,cookieFingerprint:t,headerFingerprint:i,integrationMode:a,integrationType:n,integrationVersion:s,ip:o,method:r,mitataCookie:c,mitigationLatency:u,mitigationStatus:h,netaceaCookieStatus:p,path:l,protocol:d,referer:f,requestHost:g,timeUnixMsUTC:y,requestTime:m,sessionStatus:S,status:C,userAgent:k,workerInstanceId:w,xForwardedFor:I}){return{Request:`${r} ${l} ${d}`,TimeLocal:new Date(y??Date.now()).toUTCString(),TimeUnixMsUTC:y,RealIp:o,UserAgent:k,Status:C,RequestTime:m?.toString(),BytesSent:e?.toString(),Referer:""===f?"-":f,NetaceaUserIdCookie:c??"",NetaceaMitigationApplied:S??"",ProtectorLatencyMs:u,ProtectorStatus:h,IntegrationType:n??"",IntegrationVersion:s??"",ProtectionMode:a??"",RequestHost:g,XForwardedFor:I,WorkerInstanceId:w,NetaceaUserIdCookieStatus:p,optional:{headerFingerprint:i,cookieFingerprint:t}}}(e)}const ee="unknown";function te(e,t,i){let{match:a,mitigate:n,captcha:s}=t;i||("2"===s?s="4":"3"===s&&(s="5"));let o=P[a]??ee+"_";o+=O[n]??ee;let r=M[n];if("0"!==s){o+=","+(x[s]??ee);const e=R[s];void 0!==e&&(r=e)}return e===exports.NetaceaMitigationType.INJECT&&(r=I.none),{sessionStatus:o,mitigation:r,parts:{match:a,mitigate:n,captcha:s}}}async function ie(e){let t="";try{t=await async function(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}("SHA-256",e)}catch(e){t=""}return t}class ae{config;constructor(e){this.config=e,this.config.captchaVerificationPath=z(e.captchaVerificationPath)}async getNetaceaRequestDetails(e){const t=new URL(e.url),i=e.method,a=await this.readCookie(e,this.config.sessionCookieName),n=await this.readCookie(e,this.config.captchaCookieName),s=e.headers.get("cf-connecting-ip")??"",{sessionCookieDetails:o,sessionCookieStatus:r,sessionStatus:c,userId:u}=await async function(e,t,i,a,n){const s=await async function(e,t,i){const a={userId:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,protectorCheckCodes:{captcha:"0",match:"0",mitigate:"0"}};if("string"!=typeof e||""===e)return a;const n=L(e);if(void 0!==n){const e=[n.expiry,n.userId,n.ipHash,n.mitigationType].join(K),a=Math.floor(Date.now()/1e3),s=parseInt(n.expiry)<a,o=["1","3","5"].includes(n.protectorCheckCodes.captcha),r="3"===n.protectorCheckCodes.mitigate,c=o||r,u=await F(t+"|"+n.expiry,i),h=n.ipHash===u,p=n.signature===await F(e,i);return{userId:n.userId,requiresReissue:s||!h,isExpired:s,shouldExpire:c,isSameIP:h,isPrimaryHashValid:p,protectorCheckCodes:n.protectorCheckCodes}}return a}(a,n,e.secretKey);if(void 0!==s.userId&&s.isPrimaryHashValid){const a=s.userId,{isExpired:n,shouldExpire:o,isSameIP:r}=s,c=n||o||!r&&e.mitigationType!==exports.NetaceaMitigationType.INGEST?V.RENEW_SESSION:V.EXISTING_SESSION,{sessionStatus:u}=te(e.mitigationType,s.protectorCheckCodes,B(t,i,e.captchaVerificationPath));return{userId:a,sessionCookieStatus:c,sessionStatus:u,sessionCookieDetails:s}}return{sessionStatus:"",userId:H(),sessionCookieStatus:V.NEW_SESSION,sessionCookieDetails:void 0}}(this.config,t,i,a,s);return{clientIp:s,fingerprints:await ne(e),method:i,protocol:String(e.cf?.httpProtocol),url:t,userAgent:e.headers.get("user-agent")??"",sessionDetails:{sessionStatus:c,captchaToken:n,sessionCookieDetails:o,sessionCookieStatus:r,userId:u}}}async readCookie(e,t){const i=e.headers.get("Cookie");if(null==i)return;const a=i.split(/; ?/g),n=`${t}=`;for(const e of a)if(e.startsWith(n)){const i=e.slice(n.length),a=this.config.encryptedCookies??[];if(void 0!==this.config.cookieEncryptionKey&&a.includes(t))try{return await U(i,this.config.cookieEncryptionKey)}catch(e){return}return i}}}async function ne(e){const{headers:t}=e,i=await async function(e){const t=function(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}(e);return await ie(t)}(t),a=function(e,t){return e.get(t)?.split(/; ?/)??[]}(t,"cookie").map((e=>e.split("=")[0])).flat(),n=await async function(e){const t=e.join(",");return await ie(t)}(a);return{headerFingerprint:""===i?i:`h_${i.substring(1,15)}`,cookieFingerprint:""===n?n:`c_${n.substring(1,15)}`}}var se="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},oe={},re={},ce={},ue=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),he=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pe=se&&se.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&ue(t,e,i);return he(t,e),t};Object.defineProperty(ce,"__esModule",{value:!0}),ce.isJweEncrypted=ce.decrypt=ce.encrypt=void 0;const le=pe(i);ce.encrypt=async function(e,t){const i=le.base64url.decode(t),a=(new TextEncoder).encode(e);return await new le.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A128CBC-HS256"}).encrypt(i)},ce.decrypt=async function(e,t){const i=le.base64url.decode(t),{plaintext:a}=await le.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM","A128CBC-HS256"]});return(new TextDecoder).decode(a)},ce.isJweEncrypted=function(e){return 5===e.split(".").length&&e.includes("..")};var de=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),fe=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ge=se&&se.__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)&&de(t,e,i);return fe(t,e),t};Object.defineProperty(re,"__esModule",{value:!0}),re.jwe=void 0,re.jwe=ge(ce);var ye={},me={};function Se(e,t){for(const i of Object.keys(e)){if("cookie"!==i&&"Cookie"!==i)continue;const a=e[i]??"",n=ke("string"==typeof a?a:a.join("; "),t);if(void 0!==n)return n}}function Ce(e,t){const i=[];for(const a of Object.keys(e)){if("cookie"!==a&&"Cookie"!==a)continue;const n=e[a]??"",s="string"==typeof n?n:n.join("; ");i.push(...we(s,t))}return i}function ke(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).find((e=>e.startsWith(i)))}function we(e,t){const i=t+"=";return e.split(";").map((e=>e.trimStart())).filter((e=>e.startsWith(i)))}Object.defineProperty(me,"__esModule",{value:!0}),me.findAllInCookieString=me.findFirstInCookieString=me.findAllInHeaders=me.findFirstInHeaders=me.findOnlyValueInHeaders=me.findAllValuesInHeaders=me.findFirstValueInHeaders=void 0,me.findFirstValueInHeaders=function(e,t){const i=Se(e,t);if(void 0!==i)return i.slice(t.length+1)},me.findAllValuesInHeaders=function(e,t){return Ce(e,t).map((e=>e.slice(t.length+1)))},me.findOnlyValueInHeaders=function(e,t){const i=Ce(e,t);if(i.length>1)throw new Error(`Found more than one cookie with name ${t}`);return i[0]?.slice(t.length+1)},me.findFirstInHeaders=Se,me.findAllInHeaders=Ce,me.findFirstInCookieString=ke,me.findAllInCookieString=we;var Ie={};function ve(e){return"set-cookie"===e||"Set-Cookie"===e}function be(e,t){const i=t+"=";return e.startsWith(i)}function Ne(e,t){const i=e[t]??[];return"string"==typeof i?[i]:i}function Ae(e,t){for(const i of Object.keys(e)){if(!ve(i))continue;const a=Te(Ne(e,i),t);if(void 0!==a)return a}}function Te(e,t){return e.map((e=>e.trimStart())).find((e=>be(e,t)))}function Ee(e,t){const i=[];for(const a of Object.keys(e)){if(!ve(a))continue;const n=Ne(e,a);i.push(..._e(n,t))}return i}function _e(e,t){return e.map((e=>e.trimStart())).filter((e=>be(e,t)))}Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.findAllInSetCookieStrings=Ie.findAllInHeaders=Ie.findFirstInSetCookieStrings=Ie.findFirstInHeaders=Ie.findOnlyValueInHeaders=Ie.findFirstValueInHeaders=void 0,Ie.findFirstValueInHeaders=function(e,t){const i=Ae(e,t);return i?.slice(t.length+1)?.split(";")[0]},Ie.findOnlyValueInHeaders=function(e,t){const i=Ee(e,t);if(i.length>1)throw new Error(`Found more than one set-cookie with name ${t}`);return i[0]?.slice(t.length+1)?.split(";")[0]},Ie.findFirstInHeaders=Ae,Ie.findFirstInSetCookieStrings=Te,Ie.findAllInHeaders=Ee,Ie.findAllInSetCookieStrings=_e;var Pe=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Oe=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xe=se&&se.__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)&&Pe(t,e,i);return Oe(t,e),t};Object.defineProperty(ye,"__esModule",{value:!0}),ye.setCookie=ye.cookie=void 0,ye.cookie=xe(me),ye.setCookie=xe(Ie);var Me={},Re={},Ke={};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.KINESIS_URL=Ke.API_VERSION=Ke.REGION=Ke.PAYLOAD_TYPE=Ke.STATE=void 0,Ke.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},Ke.PAYLOAD_TYPE="string",Ke.REGION="eu-west-1",Ke.API_VERSION="2013-12-02",Ke.KINESIS_URL="https://kinesis.eu-west-1.amazonaws.com",Object.defineProperty(Re,"__esModule",{value:!0}),Re.WebStandardKinesis=void 0;const De=Ke;async function je(e){await new Promise((t=>{setTimeout(t,e)}))}function Le(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}Re.WebStandardKinesis=class{constructor({deps:e,kinesisIngestArgs:t}){this.maxLogBatchSize=20,this.maxLogAgeSeconds=10,this.logBatchSize=20,this.logCache=[],this.intervalSet=!1,this.deps=e;const{kinesisStreamName:i,kinesisAccessKey:a,kinesisSecretKey:n,maxLogAgeSeconds:s,logBatchSize:o,rampUpBatchSize:r,maxAwaitTimePerIngestCallMs:c}=t;if(void 0===a)throw new Error("kinesisAccessKey is required for kinesis ingest");if(void 0===n)throw new Error("kinesisSecretKey is required for kinesis ingest");this.kinesisStreamName=i,this.kinesisAccessKey=a,this.kinesisSecretKey=n,this.maxAwaitTimePerIngestCallMs=c,void 0!==s&&s<this.maxLogAgeSeconds&&s>0&&(this.maxLogAgeSeconds=s),void 0!==o&&(this.maxLogBatchSize=o),this.logBatchSize=!0===r?1:this.maxLogBatchSize}async putToKinesis(){if(0===this.logCache.length)return;const e=[...this.logCache];this.logCache=[];try{const t=new this.deps.AwsClient({accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey}),i=await this.signRequest(t,{streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},e,this.logBatchSize);await this.deps.makeRequest({headers:Le(i.headers),host:De.KINESIS_URL,method:"POST",path:"/",body:i.body}),this.logBatchSize!==this.maxLogBatchSize&&(this.logBatchSize=Math.min(this.maxLogBatchSize,2*this.logBatchSize))}catch(t){this.logCache.push(...e),console.error(t)}}async ingest(e){if(this.logCache.push(e),this.logCache.length>=this.logBatchSize){const e=[];e.push(this.putToKinesis()),void 0!==this.maxAwaitTimePerIngestCallMs&&e.push(je(this.maxAwaitTimePerIngestCallMs)),await Promise.race(e)}else if(!this.intervalSet){this.intervalSet=!0;const e=je(1e3*this.maxLogAgeSeconds).then((async()=>{await this.putToKinesis(),this.intervalSet=!1})).catch((()=>{}));void 0===this.maxAwaitTimePerIngestCallMs&&await e}}batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const n=e.slice(a,a+t);i.push({Data:this.deps.Buffer.from(JSON.stringify(n)).toString("base64"),PartitionKey:Date.now().toString()})}return i}async signRequest(e,t,i,a){const n={Records:this.batchArrayForKinesis(i,a),PartitionKey:Date.now().toString(),StreamName:t.streamName};return await e.sign(De.KINESIS_URL,{body:JSON.stringify(n),method:"POST",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"}})}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebStandardKinesis=void 0;var t=Re;Object.defineProperty(e,"WebStandardKinesis",{enumerable:!0,get:function(){return t.WebStandardKinesis}})}(Me);var He={};function qe(e,t){let i=null;if("number"==typeof e)i=e;else if("string"==typeof e){const t=parseFloat(e);isNaN(t)||(i=t)}return null===i&&(i=t.defaultValue),void 0!==t.minValue&&(i=Math.max(t.minValue,i)),void 0!==t.maxValue&&(i=Math.min(t.maxValue,i)),i}Object.defineProperty(He,"__esModule",{value:!0}),He.parseIntOrDefault=He.parseNumberOrDefault=void 0,He.parseNumberOrDefault=qe,He.parseIntOrDefault=function(e,t){return Math.floor(qe(e,t))};var Fe=se&&se.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,n)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),Ve=se&&se.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$e=se&&se.__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)&&Fe(t,e,i);return Ve(t,e),t};Object.defineProperty(oe,"__esModule",{value:!0});var Ue=oe.parsing=Ge=oe.ingest=oe.headers=oe.webcrypto=void 0;oe.webcrypto=$e(re),oe.headers=$e(ye);var Ge=oe.ingest=$e(Me);Ue=oe.parsing=$e(He);const{configureCookiesDomain:We}=S.cookie.attributes;class Be{mitataCookieExpirySeconds;apiKey;secretKey;mitigationServiceUrl;ingestServiceUrl;kinesisConfigArgs;timeout;mitigationServiceTimeoutMs;captchaSiteKey;captchaSecretKey;ingestType;mitigationType;encryptedCookies=[];netaceaCookieName;netaceaCaptchaCookieName;cookieEncryptionKey;enableDynamicCaptchaContentType=!1;netaceaCaptchaPath;captchaHeader;netaceaCookieAttributes;netaceaCaptchaCookieAttributes;netaceaCaptchaVerificationPath;constructor(e){const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceTimeoutMs:n=1e3,mitigationServiceUrl:o="https://mitigations.netacea.net",ingestServiceUrl:r="https://ingest.netacea.net",mitigationType:c=exports.NetaceaMitigationType.INGEST,captchaSiteKey:u,captchaSecretKey:p,ingestType:l=s.HTTP,kinesis:d,mitataCookieExpirySeconds:f,netaceaCookieExpirySeconds:g,netaceaCookieName:y,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:S=!1,captchaHeader:C,netaceaCaptchaPath:k,netaceaCaptchaVerificationPath:w}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=o.endsWith("/")?o.slice(0,-1):o,this.ingestServiceUrl=r,this.mitigationType=c,this.ingestType=l??s.HTTP,this.kinesisConfigArgs=d,void 0===u&&void 0===p||(this.captchaSiteKey=u,this.captchaSecretKey=p),this.timeout=function(e){return e<=0?h:e}(a),this.mitigationServiceTimeoutMs=Ue.parseIntOrDefault(n,{defaultValue:1e3,minValue:100,maxValue:1e4}),this.netaceaCookieName=y??"_mitata",this.netaceaCaptchaCookieName=m??"_mitatacaptcha";const{cookieAttributes:I,captchaCookieAttributes:v}=We(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=I??"",this.netaceaCaptchaCookieAttributes=v??"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===exports.NetaceaMitigationType.INGEST?3600:60:t}(c,g??f),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(k)&&"string"==typeof k&&(this.netaceaCaptchaPath=k.startsWith("/")?k:`/${k}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof S?S:"true"===S),this.captchaHeader=C,this.netaceaCaptchaVerificationPath=z(w)}}exports.default=class{config;kinesis;requestAnalyser;workerInstanceId;constructor(i){this.config=new Be(i),this.config.ingestType===s.KINESIS&&(void 0===this.config.kinesisConfigArgs?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.config.ingestType}`):this.kinesis=new Ge.WebStandardKinesis({deps:{AwsClient:e.AwsClient,Buffer:t.Buffer,makeRequest:this.makeRequest.bind(this)},kinesisIngestArgs:{...this.config.kinesisConfigArgs,apiKey:this.config.apiKey}})),this.requestAnalyser=new ae({cookieEncryptionKey:this.config.cookieEncryptionKey,encryptedCookies:this.config.encryptedCookies,mitigationType:this.config.mitigationType,secretKey:this.config.secretKey,sessionCookieName:this.config.netaceaCookieName,captchaCookieName:this.config.netaceaCaptchaCookieName,captchaVerificationPath:this.config.netaceaCaptchaVerificationPath}),this.workerInstanceId=""}async run(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=new Request(e.request),a=await this.requestAnalyser.getNetaceaRequestDetails(i);let n=await async function(e,t){const i=new Promise(((e,i)=>{const a=Date.now();setTimeout((()=>{const t=Date.now()-a;e(t)}),t)}));return await Promise.race([e,i])}(this.runMitigation(i,a),this.config.mitigationServiceTimeoutMs);return"number"==typeof n&&(n={sessionStatus:"error_open",apiCallLatency:n}),await this.handleResponse(i,n,t)}async inject(e,t){const i=await this.getMitigationResponse(e,t);return{injectHeaders:i.injectHeaders,sessionStatus:i.sessionStatus,setCookie:i.setCookie,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async mitigate(e,t){const i=await this.getMitigationResponse(e,t);if(i.mitigated){const a=new Headers;if(!await W(t.url,e.method,this.config.netaceaCaptchaPath))for(const e of i.setCookie)a.append("set-cookie",e);let n="Forbidden";return"captcha"===i.mitigation&&(void 0!==this.config.captchaHeader&&a.append(this.config.captchaHeader.name,this.config.captchaHeader.value),a.append("content-type","text/html; charset=UTF-8"),n=i.body),{response:new Response(n,{status:403,statusText:"Forbidden",headers:a}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}if(B(t.url,e.method,this.config.netaceaCaptchaVerificationPath)){const e=new Headers;for(const t of i.setCookie)e.append("set-cookie",t);return{response:new Response(i.body,{status:200,statusText:"OK",headers:e}),setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}return{setCookie:i.setCookie,sessionStatus:i.sessionStatus,apiCallLatency:i.apiCallLatency,apiCallStatus:i.apiCallStatus}}async getNetaceaSession(e,t){const i=(void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0)??await this.getNetaceaCookieFromRequest(e),{protectorCheckCodes:a,userId:n}=L(i??"")??{userId:"",protectorCheckCodes:{match:"0",mitigate:"0",captcha:"0"}},{sessionStatus:s}=te(this.config.mitigationType,a,B(new URL(e.url),e.method,this.config.netaceaCaptchaVerificationPath));return{userId:n,sessionStatus:s,netaceaCookie:i}}getResponseDetails(e){return e instanceof Response?{rawResponse:e}:{rawResponse:e.response,mitigationLatency:e.protectorLatencyMs,mitigationStatus:e.protectorStatus,sessionStatus:e.sessionStatus}}async ingest(e,t){""===this.workerInstanceId&&(this.workerInstanceId=u.v4());const i=this.getResponseDetails(t),{netaceaCookie:a}=await this.getNetaceaSession(e,i.rawResponse),n=await this.requestAnalyser.getNetaceaRequestDetails(e);await this.callIngest({bytesSent:J(i.rawResponse.headers,"content-length","0"),cookieFingerprint:n.fingerprints.cookieFingerprint,headerFingerprint:n.fingerprints.headerFingerprint,integrationMode:this.config.mitigationType,integrationType:C.replace("@netacea/",""),integrationVersion:k,ip:J(e.headers,"cf-connecting-ip"),method:e.method,mitataCookie:a,mitigationLatency:i.mitigationLatency,mitigationStatus:i.mitigationStatus,netaceaCookieStatus:n.sessionDetails.sessionCookieStatus,path:new URL(e.url).pathname,protocol:n.protocol??null,referer:J(e.headers,"referer"),requestHost:new URL(e.url).hostname,requestTime:"0",sessionStatus:i.sessionStatus??n.sessionDetails.sessionStatus,status:i.rawResponse.status.toString(),timeUnixMsUTC:Date.now(),userAgent:J(e.headers,"user-agent","-"),workerInstanceId:this.workerInstanceId,xForwardedFor:J(e.headers,"x-forwarded-for")})}async handleGetCaptchaRequest(e,t,i){if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");const a=await this.makeMitigateAPICall(e,t,!0,i);return{body:a.body,apiCallStatus:a.status,apiCallLatency:a.latency,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:n}){const s=`${e}${i}`,o=new Request(s,{...{method:t,body:n,headers:a},duplex:"half"}),r=await w(s,o),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}async handleResponse(e,t,i){if(this.config.mitigationType===exports.NetaceaMitigationType.MITIGATE&&void 0!==t?.response)return{sessionStatus:t?.sessionStatus??"",response:t.response,protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT&&(e=function(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}(e,t)),this.config.ingestType===s.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);!function(e,t,i){e.headers.set("x-netacea-integration-type",C.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",k),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)}(e,i,a)}const a=await i(e);return{sessionStatus:t?.sessionStatus??"",response:X(a,t),protectorLatencyMs:t?.apiCallLatency,protectorStatus:t?.apiCallStatus}}async getMitigationResponse(e,t){const i=this.config.enableDynamicCaptchaContentType?G(e.headers.get("Accept")??void 0):G();return await this.processMitigateRequest({getBodyFn:async()=>await Promise.resolve(e.body)??void 0,requestDetails:t,captchaPageContentType:i})}async runMitigation(e,t){try{switch(this.config.mitigationType){case exports.NetaceaMitigationType.MITIGATE:return await this.mitigate(e,t);case exports.NetaceaMitigationType.INJECT:return await this.inject(e,t);case exports.NetaceaMitigationType.INGEST:return await this.processIngest(t);default:throw new Error(`Netacea Error: Mitigation type ${String(this.config.mitigationType)} not recognised`)}}catch(i){let a,n;i instanceof Error&&console.error("Netacea FAILOPEN Error:",i,i.stack),i instanceof Z&&(n=i.latencyMs,a=i.protectorApiResponse?.status);return{response:B(t.url,e.method,this.config.netaceaCaptchaVerificationPath)?new Response("",{status:500,statusText:"Internal Server Error",headers:{}}):void 0,injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:"error_open",apiCallLatency:n,apiCallStatus:a}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(e))try{return await U(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=J(e.headers,"cookie");return await this.readCookie(this.config.netaceaCookieName,t)??""}async callIngest(e){const t=Q(e);if(this.config.ingestType===s.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.config.apiKey})}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.config.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw function(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.config.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.config.timeout})}async check(e,t){let i,a,n,s,o,r,c,u;if(void 0===this.config.secretKey)throw new Error("Secret key is required to mitigate");if([V.NEW_SESSION,V.RENEW_SESSION].includes(e.sessionDetails.sessionCookieStatus)){const h=e.sessionDetails.userId,p=await this.makeMitigateAPICall(e,t,!1,null);i=p.status,a=p.match,n=p.mitigate,s=p.captcha,o=p.body,u=p.latency,r=[await this.createMitata(e.clientIp,h,a,n,s,p.mitataMaxAge)],c=p.eventId}else{const t=e.sessionDetails.sessionCookieDetails?.protectorCheckCodes;a=t?.match??"0",n=t?.mitigate??"0",s=t?.captcha??"0",o=void 0,r=[]}const h={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,h,!1,u,c)}async createMitata(e,t,i,a,n,s=86400,o=void 0){const r=["1","3","5"].includes(n)||"3"===a?-60:this.config.mitataCookieExpirySeconds,c=o??Math.floor(Date.now()/1e3)+r;if(void 0===this.config.secretKey)throw new Error("Cannot build cookie without secret key.");const u=[i,a,n].join("");let h=await async function(e,t,i,a,n="000"){const s=[i,t,await F(e+"|"+String(i),a),n].join(K);return`${await F(s,a)}${K}${s}`}(e,t,c,this.config.secretKey,u);return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCookieName)&&(h=await $(h,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.config.netaceaCookieName,cookieValue:h,otherAttributes:this.config.netaceaCookieAttributes})}async processCaptcha(e,t){const{status:i,match:a,mitigate:n,captcha:s,body:o,setCookie:r,latency:c}=await this.makeCaptchaAPICall(e,t),u={match:a,mitigate:n,captcha:s};return this.composeResult(o,r,i,u,!0,c)}async getMitataCaptchaFromHeaders(e){let t=e[T];const i=parseInt(e[E]);if(void 0!==t)return void 0!==this.config.cookieEncryptionKey&&this.config.encryptedCookies.includes(this.config.netaceaCaptchaCookieName)&&(t=await $(t,this.config.cookieEncryptionKey)),S.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.config.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.config.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t){const i={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},a=e.sessionDetails.userId;e.sessionDetails.sessionCookieStatus!==V.NEW_SESSION&&(i["X-Netacea-UserId"]=a),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(i["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,i["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey);const n=new URLSearchParams;n.append("headerFP",e.fingerprints.headerFingerprint);const s=Date.now(),o=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`/AtaVerifyCaptcha?${n.toString()}`,headers:i,method:"POST",body:t,timeout:this.config.mitigationServiceTimeoutMs}),r=Date.now()-s;return await this.getApiCallResponseFromResponse(o,e,r)}async getApiCallResponseFromResponse(e,t,i){if(200!==e.status)throw new Z(e,i);const a=e.headers[v],n=e.headers[b],s=e.headers[N];let o=parseInt(e.headers[A]);isNaN(o)&&(o=86400);const r=t.sessionDetails.userId,c=[await this.createMitata(t.clientIp,r,a,n,s,o),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[_];if("application/json"===e.headers["content-type"]?.toLowerCase()){if(void 0===this.config.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:n}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${n}${t}?trackingId=${a}`})}(e.body??"",this.config.netaceaCaptchaPath,t.url.toString())}return{status:e.status,match:a,mitigate:n,captcha:s,setCookie:c,body:e.body,eventId:u,mitataMaxAge:o,latency:i}}async makeMitigateAPICall(e,t,i,a){const n={"X-Netacea-API-Key":this.config.apiKey,"X-Netacea-Client-IP":e.clientIp,"user-agent":e.userAgent,cookie:Y({_mitatacaptcha:e.sessionDetails.captchaToken})};e.sessionDetails.sessionCookieStatus!==V.NEW_SESSION&&(n["X-Netacea-UserId"]=e.sessionDetails.userId),void 0!==this.config.captchaSiteKey&&void 0!==this.config.captchaSecretKey&&(n["X-Netacea-Captcha-Site-Key"]=this.config.captchaSiteKey,n["X-Netacea-Captcha-Secret-Key"]=this.config.captchaSecretKey),n["X-Netacea-Captcha-Content-Type"]=t;let s="/";const o=new URLSearchParams;o.append("headerFP",e.fingerprints.headerFingerprint),i&&(s="/captcha",null!==a&&o.append("trackingId",a));const r=Date.now(),c=await this.makeRequest({host:this.config.mitigationServiceUrl,path:`${s}?${o.toString()}`,headers:n,method:"GET",timeout:this.config.mitigationServiceTimeoutMs}),u=Date.now()-r;return await this.getApiCallResponseFromResponse(c,e,u)}composeResult(e,t,i,a,n,s,o){const r=te(this.config.mitigationType,a,n),c={body:e,apiCallStatus:i,apiCallLatency:s,setCookie:t,sessionStatus:r.sessionStatus,mitigation:r.mitigation,mitigated:[I.block,I.captcha].includes(r.mitigation)};if(this.config.mitigationType===exports.NetaceaMitigationType.INJECT){const e={"x-netacea-match":r.parts.match.toString(),"x-netacea-mitigate":r.parts.mitigate.toString(),"x-netacea-captcha":r.parts.captcha.toString()};void 0!==o&&(e["x-netacea-event-id"]=o),c.injectHeaders=e}return c}async processMitigateRequest(e){if(await W(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(B(e.requestDetails.url,e.requestDetails.method,this.config.netaceaCaptchaVerificationPath)){const t=await e.getBodyFn()??"";return await this.processCaptcha(e.requestDetails,t)}return await this.check(e.requestDetails,e.captchaPageContentType)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata("ignored",e,"0","0","0",86400)]}}async processIngest(e){if(void 0===this.config.secretKey)throw new Error("Secret key is required for ingest");const t=e.sessionDetails.sessionCookieStatus,i=t===V.NEW_SESSION,a=t===V.RENEW_SESSION;return i||a?await this.setIngestOnlyMitataCookie(e.sessionDetails.userId):{sessionStatus:"",setCookie:[]}}};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netacea/cloudflare",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.45",
|
|
4
4
|
"description": "Netacea Cloudflare CDN Integration",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
},
|
|
19
19
|
"license": "ISC",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@netacea/netaceaintegrationbase": "^2.0.
|
|
21
|
+
"@netacea/netaceaintegrationbase": "^2.0.88",
|
|
22
22
|
"aws4fetch": "^1.0.20",
|
|
23
23
|
"jose": "^4.11.2",
|
|
24
24
|
"uuid": "^10.0.0"
|
|
25
25
|
},
|
|
26
|
-
"gitHead": "
|
|
26
|
+
"gitHead": "2406302b62a3db0af442fb6cc1ce82345267ef6b"
|
|
27
27
|
}
|