perimeterx-js-core 0.1.0 → 0.2.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.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/lib/activities/HttpActivityClient.d.ts +10 -2
  3. package/lib/activities/HttpActivityClient.js +10 -1
  4. package/lib/activities/HttpBatchedActivityClient.d.ts +21 -0
  5. package/lib/activities/HttpBatchedActivityClient.js +137 -0
  6. package/lib/activities/index.d.ts +1 -0
  7. package/lib/activities/index.js +3 -1
  8. package/lib/activities/model/ActivityDetails.d.ts +1 -0
  9. package/lib/activities/utils.js +1 -0
  10. package/lib/config/DefaultConfigurations.js +1 -1
  11. package/lib/config/IConfiguration.d.ts +8 -0
  12. package/lib/config/StaticConfigurationBase.d.ts +2 -0
  13. package/lib/config/StaticConfigurationBase.js +15 -1
  14. package/lib/context/IContext.d.ts +6 -2
  15. package/lib/enforcer/EnforcerBase.js +5 -1
  16. package/lib/http/IHttpClient.d.ts +5 -1
  17. package/lib/http/index.d.ts +1 -1
  18. package/lib/risk_api/PostRiskApiClient.d.ts +18 -3
  19. package/lib/risk_api/PostRiskApiClient.js +26 -3
  20. package/lib/risk_api/S2SErrorHandler.d.ts +2 -2
  21. package/lib/risk_api/S2SErrorHandler.js +5 -5
  22. package/lib/risk_api/model/RiskActivity.d.ts +4 -4
  23. package/lib/risk_api/risk_response_handler/RiskResponseHandlerBase.js +1 -1
  24. package/lib/risk_token/MobileErrorHandler.js +1 -1
  25. package/lib/risk_token/RiskTokenScoreRetriever.js +2 -2
  26. package/lib/risk_token/token/BotDefenderTokenBase.d.ts +2 -0
  27. package/lib/risk_token/token/BotDefenderTokenBase.js +2 -1
  28. package/lib/risk_token/token/v2/DefaultBotDefenderTokenV2.d.ts +0 -2
  29. package/lib/risk_token/token/v2/DefaultBotDefenderTokenV2.js +0 -1
  30. package/lib/risk_token/token/v3/DefaultBotDefenderTokenV3.d.ts +0 -2
  31. package/lib/risk_token/token/v3/DefaultBotDefenderTokenV3.js +3 -3
  32. package/lib/utils/constants.d.ts +1 -1
  33. package/lib/utils/constants.js +1 -1
  34. package/lib/utils/error/EnforcerError.d.ts +3 -0
  35. package/lib/utils/{EnforcerException.js → error/EnforcerError.js} +10 -7
  36. package/lib/utils/error/EnforcerErrorName.d.ts +4 -0
  37. package/lib/utils/error/EnforcerErrorName.js +8 -0
  38. package/lib/utils/error/EnforcerTimeoutError.d.ts +4 -0
  39. package/lib/utils/error/EnforcerTimeoutError.js +30 -0
  40. package/lib/utils/error/index.d.ts +3 -0
  41. package/lib/utils/error/index.js +9 -0
  42. package/lib/utils/index.d.ts +1 -1
  43. package/lib/utils/index.js +2 -3
  44. package/lib/utils/utils.d.ts +1 -0
  45. package/lib/utils/utils.js +58 -1
  46. package/package.json +9 -2
  47. package/lib/utils/EnforcerException.d.ts +0 -3
package/README.md CHANGED
@@ -101,7 +101,7 @@ or use an external library (e.g., `phin`, `axios`) if needed.
101
101
  ### Crypto
102
102
 
103
103
  Since cryptographic functionality varies from platform to platform, this library's crypto utils takes the form of an interface
104
- as well. It comes with a specific default implementation.
104
+ as well.
105
105
 
106
106
  `IBase64Utils` - Represents a Base64 encoding and decoding utility that other components may require. A `DefaultBase64Utils`
107
107
  implementation using the `js-base64` dependency is provided.
@@ -2,11 +2,19 @@ import { IConfiguration } from '../config';
2
2
  import { IContext } from '../context';
3
3
  import { IHttpClient } from '../http';
4
4
  import { IActivityClient } from './IActivityClient';
5
+ import { Activity } from './model/Activity';
5
6
  export declare class HttpActivityClient implements IActivityClient {
6
7
  private readonly config;
7
8
  private readonly httpClient;
8
9
  constructor(config: IConfiguration, httpClient: IHttpClient);
9
10
  sendActivities(context: IContext): Promise<boolean>;
10
- private createActivities;
11
- private postActivities;
11
+ protected createActivities(context: IContext): Activity[];
12
+ /**
13
+ * Allows for expansions or alterations to the async activity if needed.
14
+ * @param activity
15
+ * @returns Activity
16
+ * @protected
17
+ */
18
+ protected finalizeActivity(activity: Activity): Activity;
19
+ protected postActivities(activities: Activity[]): Promise<boolean>;
12
20
  }
@@ -74,7 +74,16 @@ var HttpActivityClient = /** @class */ (function () {
74
74
  else if (context.passReason) {
75
75
  activities.push((0, utils_2.createActivity)(ActivityType_1.ActivityType.PAGE_REQUESTED, this.config, context));
76
76
  }
77
- return activities;
77
+ return activities.map(this.finalizeActivity);
78
+ };
79
+ /**
80
+ * Allows for expansions or alterations to the async activity if needed.
81
+ * @param activity
82
+ * @returns Activity
83
+ * @protected
84
+ */
85
+ HttpActivityClient.prototype.finalizeActivity = function (activity) {
86
+ return activity;
78
87
  };
79
88
  HttpActivityClient.prototype.postActivities = function (activities) {
80
89
  return __awaiter(this, void 0, void 0, function () {
@@ -0,0 +1,21 @@
1
+ import { HttpActivityClient } from './HttpActivityClient';
2
+ import { IConfiguration } from '../config';
3
+ import { IHttpClient } from '../http';
4
+ import { Activity } from './model/Activity';
5
+ export declare class HttpBatchedActivityClient extends HttpActivityClient {
6
+ private readonly batchSize;
7
+ private readonly timeoutMs;
8
+ private readonly maxBufferSize;
9
+ private buffer;
10
+ private timeoutId;
11
+ constructor(config: IConfiguration, httpClient: IHttpClient);
12
+ stop(): void;
13
+ protected postActivities(activities: Activity[]): Promise<boolean>;
14
+ private addToBuffer;
15
+ private shouldFlush;
16
+ protected triggerFlush(): Promise<boolean>;
17
+ private flush;
18
+ protected clear(): void;
19
+ private startTimer;
20
+ private stopTimer;
21
+ }
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (_) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.HttpBatchedActivityClient = void 0;
55
+ var HttpActivityClient_1 = require("./HttpActivityClient");
56
+ var HttpBatchedActivityClient = /** @class */ (function (_super) {
57
+ __extends(HttpBatchedActivityClient, _super);
58
+ function HttpBatchedActivityClient(config, httpClient) {
59
+ var _this = _super.call(this, config, httpClient) || this;
60
+ _this.buffer = [];
61
+ _this.batchSize = config.maxActivityBatchSize;
62
+ _this.timeoutMs = config.activityBatchTimeoutMs;
63
+ _this.maxBufferSize = _this.batchSize * 2;
64
+ _this.startTimer();
65
+ return _this;
66
+ }
67
+ HttpBatchedActivityClient.prototype.stop = function () {
68
+ this.stopTimer();
69
+ };
70
+ HttpBatchedActivityClient.prototype.postActivities = function (activities) {
71
+ return __awaiter(this, void 0, void 0, function () {
72
+ return __generator(this, function (_a) {
73
+ this.addToBuffer(activities);
74
+ return [2 /*return*/, this.shouldFlush() ? this.triggerFlush() : true];
75
+ });
76
+ });
77
+ };
78
+ HttpBatchedActivityClient.prototype.addToBuffer = function (activities) {
79
+ this.buffer = activities.concat(this.buffer);
80
+ if (this.buffer.length > this.maxBufferSize) {
81
+ this.buffer = this.buffer.slice(0, this.maxBufferSize);
82
+ }
83
+ };
84
+ HttpBatchedActivityClient.prototype.shouldFlush = function () {
85
+ return this.buffer.length >= this.batchSize;
86
+ };
87
+ HttpBatchedActivityClient.prototype.triggerFlush = function () {
88
+ return __awaiter(this, void 0, void 0, function () {
89
+ var sentSuccessfully, _a;
90
+ return __generator(this, function (_b) {
91
+ switch (_b.label) {
92
+ case 0:
93
+ this.stopTimer();
94
+ _a = this.buffer.length > 0;
95
+ if (!_a) return [3 /*break*/, 2];
96
+ return [4 /*yield*/, this.flush()];
97
+ case 1:
98
+ _a = (_b.sent());
99
+ _b.label = 2;
100
+ case 2:
101
+ sentSuccessfully = _a;
102
+ this.startTimer();
103
+ return [2 /*return*/, sentSuccessfully];
104
+ }
105
+ });
106
+ });
107
+ };
108
+ HttpBatchedActivityClient.prototype.flush = function () {
109
+ return __awaiter(this, void 0, void 0, function () {
110
+ var sentSuccessfully;
111
+ return __generator(this, function (_a) {
112
+ switch (_a.label) {
113
+ case 0: return [4 /*yield*/, _super.prototype.postActivities.call(this, this.buffer)];
114
+ case 1:
115
+ sentSuccessfully = _a.sent();
116
+ if (sentSuccessfully) {
117
+ this.clear();
118
+ }
119
+ return [2 /*return*/, sentSuccessfully];
120
+ }
121
+ });
122
+ });
123
+ };
124
+ HttpBatchedActivityClient.prototype.clear = function () {
125
+ this.buffer = [];
126
+ };
127
+ HttpBatchedActivityClient.prototype.startTimer = function () {
128
+ var _this = this;
129
+ this.timeoutId = setTimeout(function () { return _this.triggerFlush(); }, this.timeoutMs);
130
+ };
131
+ HttpBatchedActivityClient.prototype.stopTimer = function () {
132
+ clearTimeout(this.timeoutId);
133
+ this.timeoutId = null;
134
+ };
135
+ return HttpBatchedActivityClient;
136
+ }(HttpActivityClient_1.HttpActivityClient));
137
+ exports.HttpBatchedActivityClient = HttpBatchedActivityClient;
@@ -3,3 +3,4 @@ export { Activity } from './model/Activity';
3
3
  export { ActivityTypeDetails, ActivityDetails, BlockActivityDetails, PageRequestedActivityDetails, } from './model/ActivityDetails';
4
4
  export { ActivityType } from './ActivityType';
5
5
  export { HttpActivityClient } from './HttpActivityClient';
6
+ export { HttpBatchedActivityClient } from './HttpBatchedActivityClient';
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpActivityClient = exports.ActivityType = void 0;
3
+ exports.HttpBatchedActivityClient = exports.HttpActivityClient = exports.ActivityType = void 0;
4
4
  var ActivityType_1 = require("./ActivityType");
5
5
  Object.defineProperty(exports, "ActivityType", { enumerable: true, get: function () { return ActivityType_1.ActivityType; } });
6
6
  var HttpActivityClient_1 = require("./HttpActivityClient");
7
7
  Object.defineProperty(exports, "HttpActivityClient", { enumerable: true, get: function () { return HttpActivityClient_1.HttpActivityClient; } });
8
+ var HttpBatchedActivityClient_1 = require("./HttpBatchedActivityClient");
9
+ Object.defineProperty(exports, "HttpBatchedActivityClient", { enumerable: true, get: function () { return HttpBatchedActivityClient_1.HttpBatchedActivityClient; } });
@@ -11,6 +11,7 @@ export declare type ActivityDetails = ActivityTypeDetails & {
11
11
  risk_rtt?: number;
12
12
  request_cookie_names?: string[];
13
13
  server_info_region?: string;
14
+ server_info_datacenter?: string;
14
15
  tls_protocol?: string;
15
16
  tls_cipher?: string;
16
17
  tls_preferred_ciphers?: string;
@@ -55,6 +55,7 @@ var createGenericActivityDetails = function (config, context) {
55
55
  });
56
56
  (0, utils_1.transferExistingProperties)(context.serverData, genericActivityDetails, {
57
57
  region: 'server_info_region',
58
+ datacenter: 'server_info_datacenter',
58
59
  });
59
60
  return genericActivityDetails;
60
61
  };
@@ -20,7 +20,7 @@ exports.DEFAULT_CONFIGURATIONS = {
20
20
  px_module_mode: ModuleMode_1.ModuleMode.MONITOR,
21
21
  px_additional_activity_handler: null,
22
22
  px_advanced_blocking_response_enabled: true,
23
- px_max_activity_batch_size: 20,
23
+ px_max_activity_batch_size: 0,
24
24
  px_batch_activities_timeout_ms: 1000,
25
25
  px_bypass_monitor_header: '',
26
26
  px_csp_enabled: false,
@@ -157,6 +157,14 @@ export interface IConfiguration<ParamsType extends ConfigurationParams = Configu
157
157
  * The maximum expected length of the user-agent beyond which it will be truncated.
158
158
  */
159
159
  readonly userAgentMaxLength: number;
160
+ /**
161
+ * The batch size at which asynchronous activities are sent to the collector.
162
+ */
163
+ readonly maxActivityBatchSize: number;
164
+ /**
165
+ * The maximum amount of time to wait before sending asynchronous activities to the collector.
166
+ */
167
+ readonly activityBatchTimeoutMs: number;
160
168
  /**
161
169
  * A function returning CustomParameters that will be added to the enforcer activities.
162
170
  */
@@ -51,6 +51,8 @@ export declare abstract class StaticConfigurationBase<ParamsType extends Configu
51
51
  get riskCookieMinIterations(): number;
52
52
  get riskCookieMaxLength(): number;
53
53
  get userAgentMaxLength(): number;
54
+ get maxActivityBatchSize(): number;
55
+ get activityBatchTimeoutMs(): number;
54
56
  get enrichCustomParameters(): CustomParametersFunction;
55
57
  get additionalActivityHandler(): AdditionalActivityHandler;
56
58
  get altBackendCaptchaUrl(): string;
@@ -34,7 +34,7 @@ var StaticConfigurationBase = /** @class */ (function () {
34
34
  var REQUIRED_FIELDS = ['px_app_id', 'px_cookie_secret', 'px_auth_token'];
35
35
  REQUIRED_FIELDS.forEach(function (key) {
36
36
  if (!params[key]) {
37
- throw new utils_1.EnforcerException("".concat(key, " cannot be empty!"));
37
+ throw new utils_1.EnforcerError("".concat(key, " cannot be empty!"));
38
38
  }
39
39
  });
40
40
  };
@@ -329,6 +329,20 @@ var StaticConfigurationBase = /** @class */ (function () {
329
329
  enumerable: false,
330
330
  configurable: true
331
331
  });
332
+ Object.defineProperty(StaticConfigurationBase.prototype, "maxActivityBatchSize", {
333
+ get: function () {
334
+ return this.configParams.px_max_activity_batch_size;
335
+ },
336
+ enumerable: false,
337
+ configurable: true
338
+ });
339
+ Object.defineProperty(StaticConfigurationBase.prototype, "activityBatchTimeoutMs", {
340
+ get: function () {
341
+ return this.configParams.px_batch_activities_timeout_ms;
342
+ },
343
+ enumerable: false,
344
+ configurable: true
345
+ });
332
346
  Object.defineProperty(StaticConfigurationBase.prototype, "enrichCustomParameters", {
333
347
  get: function () {
334
348
  return this.configParams.px_enrich_custom_parameters || null;
@@ -136,17 +136,21 @@ export interface ServerData {
136
136
  */
137
137
  osName?: string;
138
138
  /**
139
- * The CDN PoP/data center region the request hit.
139
+ * The server region the request hit.
140
140
  */
141
141
  region?: string;
142
142
  /**
143
143
  * The host name of the operating system.
144
144
  */
145
145
  nodeName?: string;
146
+ /**
147
+ * The name or code associated with the server PoP/datacenter.
148
+ */
149
+ datacenter?: string;
146
150
  }
147
151
  export interface IContext {
148
152
  /**
149
- * A UUID v4 generated in the enforcer unique to each HTTP request.
153
+ * A UUID generated in the enforcer unique to each HTTP request.
150
154
  */
151
155
  readonly requestId: string;
152
156
  /**
@@ -75,7 +75,11 @@ var EnforcerBase = /** @class */ (function () {
75
75
  var httpClient = options.httpClient;
76
76
  this.firstParty = options.firstParty || new first_party_1.DefaultFirstParty(this.config, httpClient);
77
77
  this.telemetry = options.telemetry || new telemetry_1.DefaultTelemetry(this.config, httpClient, base64Utils, hashUtils);
78
- this.activityClient = options.activityClient || new activities_1.HttpActivityClient(this.config, httpClient);
78
+ this.activityClient =
79
+ options.activityClient ||
80
+ (this.config.maxActivityBatchSize > 1
81
+ ? new activities_1.HttpBatchedActivityClient(this.config, httpClient)
82
+ : new activities_1.HttpActivityClient(this.config, httpClient));
79
83
  var riskResponseHandler = options.tokenVersion === risk_token_1.TokenVersion.V2
80
84
  ? new risk_api_1.RiskResponseV2Handler(this.config)
81
85
  : new risk_api_1.RiskResponseV3Handler(this.config);
@@ -1,10 +1,14 @@
1
1
  import { IHttpRequest } from './request/IHttpRequest';
2
2
  import { IHttpResponse } from './response/IHttpResponse';
3
+ export declare type HttpSendOptions = {
4
+ timeoutMs?: number;
5
+ };
3
6
  export interface IHttpClient<UnreadBodyType = unknown> {
4
7
  /**
5
8
  * A function that sends the provided IHttpRequest and returns a Promise resolving to an IHttpResponse.
6
9
  * @param request - The request to be sent by the client.
10
+ * @param options - Options that the HttpClient should consider
7
11
  * @returns Promise<IHttpResponse> - A Promise resolving to the response the client received.
8
12
  */
9
- send(request: IHttpRequest<UnreadBodyType>): Promise<IHttpResponse<UnreadBodyType>>;
13
+ send(request: IHttpRequest<UnreadBodyType>, options?: HttpSendOptions): Promise<IHttpResponse<UnreadBodyType>>;
10
14
  }
@@ -1,4 +1,4 @@
1
- export { IHttpClient } from './IHttpClient';
1
+ export { IHttpClient, HttpSendOptions } from './IHttpClient';
2
2
  export { IHttpRequest } from './request/IHttpRequest';
3
3
  export { HttpRequestBase, HttpRequestOptions, HttpRequestBaseOptions } from './request/HttpRequestBase';
4
4
  export { DefaultHttpRequest } from './request/DefaultHttpRequest';
@@ -1,6 +1,7 @@
1
1
  import { IContext } from '../context';
2
2
  import { IConfiguration } from '../config';
3
- import { IHttpClient } from '../http';
3
+ import { RiskActivity } from './model/RiskActivity';
4
+ import { IHttpClient, IHttpResponse } from '../http';
4
5
  import { IScoreRetriever } from '../utils';
5
6
  import { IRiskResponseHandler } from './risk_response_handler/IRiskResponseHandler';
6
7
  import { RiskResponseV2 } from './model/RiskResponseV2';
@@ -14,14 +15,28 @@ export declare class PostRiskApiClient<RiskResponseType extends RiskResponseV2 |
14
15
  shouldRetrieveScore(context: IContext): boolean;
15
16
  private unsetScoreFields;
16
17
  retrieveScore(context: IContext): Promise<boolean>;
17
- private createRiskActivity;
18
+ /**
19
+ * Creates the RiskActivity payload
20
+ * @param context
21
+ * @returns RiskActivity
22
+ * @protected
23
+ */
24
+ protected createRiskActivity(context: IContext): RiskActivity;
25
+ /**
26
+ * Protected function in case expansions or alterations to the risk activity are needed for certain platforms.
27
+ * @param riskActivity
28
+ * @returns RiskActivity
29
+ * @protected
30
+ */
31
+ protected finalizeRiskActivity(riskActivity: RiskActivity): RiskActivity;
18
32
  private addOptionalRiskFields;
19
33
  private addOptionalRiskFieldsToRoot;
20
34
  private addOptionalRiskFieldsToAdditional;
21
35
  private addCustomParamsToAdditional;
22
36
  private addCookieRiskFieldsToAdditional;
23
37
  private formatRiskHeadersField;
24
- private sendRiskActivity;
38
+ protected sendRiskActivity(context: IContext, riskActivity: RiskActivity): Promise<IHttpResponse>;
25
39
  private getRiskUrl;
26
40
  private getRiskHeaders;
41
+ private handleS2STimeout;
27
42
  }
@@ -37,7 +37,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.PostRiskApiClient = void 0;
40
- var risk_token_1 = require("../risk_token");
40
+ var TokenOrigin_1 = require("../risk_token/TokenOrigin");
41
41
  var http_1 = require("../http");
42
42
  var utils_1 = require("../utils");
43
43
  var S2SCallReason_1 = require("./S2SCallReason");
@@ -103,6 +103,10 @@ var PostRiskApiClient = /** @class */ (function () {
103
103
  return [2 /*return*/, true];
104
104
  case 6:
105
105
  err_1 = _a.sent();
106
+ if (err_1.name === utils_1.EnforcerErrorName.ENFORCER_TIMEOUT_ERROR) {
107
+ this.handleS2STimeout(context);
108
+ return [2 /*return*/, false];
109
+ }
106
110
  this.config.logger.error("Caught error on Risk API: ".concat(err_1));
107
111
  return [4 /*yield*/, this.s2sErrorHandler.handleS2SError(context, response, riskResponse, err_1)];
108
112
  case 7:
@@ -113,6 +117,12 @@ var PostRiskApiClient = /** @class */ (function () {
113
117
  });
114
118
  });
115
119
  };
120
+ /**
121
+ * Creates the RiskActivity payload
122
+ * @param context
123
+ * @returns RiskActivity
124
+ * @protected
125
+ */
116
126
  PostRiskApiClient.prototype.createRiskActivity = function (context) {
117
127
  var riskActivity = {
118
128
  request: {
@@ -126,12 +136,21 @@ var PostRiskApiClient = /** @class */ (function () {
126
136
  http_method: context.requestData.method,
127
137
  http_version: context.requestData.httpVersion,
128
138
  risk_mode: context.isMonitoredRequest ? utils_1.ModuleMode.MONITOR : utils_1.ModuleMode.ACTIVE_BLOCKING,
129
- cookie_origin: context.tokenOrigin || risk_token_1.TokenOrigin.COOKIE,
139
+ cookie_origin: context.tokenOrigin || TokenOrigin_1.TokenOrigin.COOKIE,
130
140
  request_cookie_names: context.requestData.requestCookieNames,
131
141
  request_id: context.requestId,
132
142
  },
133
143
  };
134
144
  this.addOptionalRiskFields(riskActivity, context);
145
+ return this.finalizeRiskActivity(riskActivity);
146
+ };
147
+ /**
148
+ * Protected function in case expansions or alterations to the risk activity are needed for certain platforms.
149
+ * @param riskActivity
150
+ * @returns RiskActivity
151
+ * @protected
152
+ */
153
+ PostRiskApiClient.prototype.finalizeRiskActivity = function (riskActivity) {
135
154
  return riskActivity;
136
155
  };
137
156
  PostRiskApiClient.prototype.addOptionalRiskFields = function (riskActivity, context) {
@@ -153,6 +172,7 @@ var PostRiskApiClient = /** @class */ (function () {
153
172
  });
154
173
  (0, utils_1.transferExistingProperties)(context.serverData, riskActivity.additional, {
155
174
  region: 'server_info_region',
175
+ datacenter: 'server_info_datacenter',
156
176
  });
157
177
  (0, utils_1.transferExistingProperties)(context.mobileData, riskActivity.additional, {
158
178
  originalToken: 'original_token',
@@ -206,7 +226,7 @@ var PostRiskApiClient = /** @class */ (function () {
206
226
  riskRequest = new http_1.DefaultHttpRequest(url, { headers: headers, method: method, body: body });
207
227
  this.config.logger.debug("sending risk api to ".concat(url));
208
228
  startTime = Date.now();
209
- return [4 /*yield*/, this.httpClient.send(riskRequest)];
229
+ return [4 /*yield*/, this.httpClient.send(riskRequest, { timeoutMs: this.config.s2sTimeout })];
210
230
  case 1:
211
231
  response = _a.sent();
212
232
  endTime = Date.now();
@@ -227,6 +247,9 @@ var PostRiskApiClient = /** @class */ (function () {
227
247
  _a[http_1.AUTHORIZATION_HEADER_NAME] = [(0, utils_1.getAuthorizationHeader)(this.config.authToken)],
228
248
  _a));
229
249
  };
250
+ PostRiskApiClient.prototype.handleS2STimeout = function (context) {
251
+ context.passReason = utils_1.PassReason.S2S_TIMEOUT;
252
+ };
230
253
  return PostRiskApiClient;
231
254
  }());
232
255
  exports.PostRiskApiClient = PostRiskApiClient;
@@ -3,7 +3,7 @@ import { IHttpResponse } from '../http';
3
3
  import { RiskResponseV2 } from './model/RiskResponseV2';
4
4
  import { RiskResponseV3 } from './model/RiskResponseV3';
5
5
  export declare class S2SErrorHandler {
6
- handleS2SError(context: IContext, response?: IHttpResponse, responseBody?: RiskResponseV2 | RiskResponseV3, exception?: Error): Promise<void>;
6
+ handleS2SError(context: IContext, response?: IHttpResponse, responseBody?: RiskResponseV2 | RiskResponseV3, error?: Error): Promise<void>;
7
7
  private enrichS2SErrorWithResponse;
8
- private enrichS2SErrorWithException;
8
+ private enrichS2SErrorWithError;
9
9
  }
@@ -43,7 +43,7 @@ var RiskStatus_1 = require("./model/RiskStatus");
43
43
  var S2SErrorHandler = /** @class */ (function () {
44
44
  function S2SErrorHandler() {
45
45
  }
46
- S2SErrorHandler.prototype.handleS2SError = function (context, response, responseBody, exception) {
46
+ S2SErrorHandler.prototype.handleS2SError = function (context, response, responseBody, error) {
47
47
  return __awaiter(this, void 0, void 0, function () {
48
48
  return __generator(this, function (_a) {
49
49
  switch (_a.label) {
@@ -56,8 +56,8 @@ var S2SErrorHandler = /** @class */ (function () {
56
56
  _a.sent();
57
57
  _a.label = 2;
58
58
  case 2:
59
- if (exception) {
60
- this.enrichS2SErrorWithException(context, exception);
59
+ if (error) {
60
+ this.enrichS2SErrorWithError(context, error);
61
61
  }
62
62
  return [2 /*return*/];
63
63
  }
@@ -111,8 +111,8 @@ var S2SErrorHandler = /** @class */ (function () {
111
111
  });
112
112
  });
113
113
  };
114
- S2SErrorHandler.prototype.enrichS2SErrorWithException = function (context, exception) {
115
- var errorMessage = "encountered error ".concat(exception);
114
+ S2SErrorHandler.prototype.enrichS2SErrorWithError = function (context, error) {
115
+ var errorMessage = "".concat(error);
116
116
  var existingMessage = context.riskApiData.errorMessage;
117
117
  context.riskApiData.errorMessage = existingMessage ? "".concat(existingMessage, ", ").concat(errorMessage) : errorMessage;
118
118
  };
@@ -1,8 +1,7 @@
1
+ import { ModuleMode, VidSource } from '../../utils';
2
+ import { TokenOrigin } from '../../risk_token';
3
+ import { CustomParameters } from '../../custom_parameters';
1
4
  import { S2SCallReason } from '../S2SCallReason';
2
- import { ModuleMode } from '../../utils/ModuleMode';
3
- import { VidSource } from '../../utils/VidSource';
4
- import { TokenOrigin } from '../../risk_token/TokenOrigin';
5
- import { CustomParameters } from '../../custom_parameters/CustomParameters';
6
5
  export declare type HeaderEntry = {
7
6
  name: string;
8
7
  value: string;
@@ -37,6 +36,7 @@ export declare type RiskAdditionalData = {
37
36
  cookie_origin?: TokenOrigin;
38
37
  request_cookie_names?: string[];
39
38
  server_info_region?: string;
39
+ server_info_datacenter?: string;
40
40
  cross_tab_session?: string;
41
41
  app_user_id?: string;
42
42
  jwt_additional_fields?: string[];
@@ -47,7 +47,7 @@ var RiskResponseHandlerBase = /** @class */ (function () {
47
47
  return __awaiter(this, void 0, void 0, function () {
48
48
  return __generator(this, function (_a) {
49
49
  if (!this.isRiskResponseValid(riskResponse)) {
50
- throw new utils_1.EnforcerException('invalid risk response');
50
+ throw new utils_1.EnforcerError('invalid risk response');
51
51
  }
52
52
  this.config.logger.debug("received risk response, rtt: ".concat(context.riskApiData.riskRtt));
53
53
  this.handleValidRiskResponse(context, riskResponse);
@@ -70,7 +70,7 @@ var MobileErrorHandler = /** @class */ (function () {
70
70
  case 2: return [3 /*break*/, 4];
71
71
  case 3:
72
72
  e_1 = _b.sent();
73
- this.config.logger.debug("caught exception in mobile error handler - ".concat(e_1));
73
+ this.config.logger.debug("caught error in mobile error handler - ".concat(e_1));
74
74
  return [3 /*break*/, 4];
75
75
  case 4: return [2 /*return*/];
76
76
  }
@@ -81,7 +81,7 @@ var RiskTokenScoreRetriever = /** @class */ (function () {
81
81
  return [2 /*return*/, true];
82
82
  case 5:
83
83
  e_1 = _a.sent();
84
- this.config.logger.debug("caught exception in cookie score service - ".concat(e_1));
84
+ this.config.logger.debug("caught error in cookie score service - ".concat(e_1));
85
85
  s2sCallReason = token ? risk_api_1.S2SCallReason.COOKIE_DECRYPTION_FAILED : risk_api_1.S2SCallReason.NO_COOKIE;
86
86
  return [2 /*return*/, this.handleFailure(context, s2sCallReason)];
87
87
  case 6: return [2 /*return*/];
@@ -97,7 +97,7 @@ var RiskTokenScoreRetriever = /** @class */ (function () {
97
97
  case 0: return [4 /*yield*/, token.verify(context)];
98
98
  case 1:
99
99
  result = _a.sent();
100
- if (result === TokenVerificationResult_1.TokenVerificationResult.DECRYPTION_FAILED) {
100
+ if (result === TokenVerificationResult_1.TokenVerificationResult.DECRYPTION_FAILED || result === TokenVerificationResult_1.TokenVerificationResult.CANNOT_VERIFY) {
101
101
  return [2 /*return*/, this.handleFailure(context, risk_api_1.S2SCallReason.COOKIE_DECRYPTION_FAILED)];
102
102
  }
103
103
  if (result === TokenVerificationResult_1.TokenVerificationResult.VALIDATION_FAILED) {
@@ -3,6 +3,7 @@ import { TokenVerificationResult } from '../TokenVerificationResult';
3
3
  import { IContext } from '../../context';
4
4
  import { BlockAction } from '../../block_handler';
5
5
  import { IConfiguration } from '../../config';
6
+ import { ILogger } from '../../logger';
6
7
  export declare abstract class BotDefenderTokenBase<PayloadType> implements IBotDefenderToken {
7
8
  abstract readonly action: BlockAction;
8
9
  abstract readonly hmac: string;
@@ -14,6 +15,7 @@ export declare abstract class BotDefenderTokenBase<PayloadType> implements IBotD
14
15
  abstract isHighScore(): boolean;
15
16
  protected abstract decrypt(context: IContext): Promise<PayloadType>;
16
17
  protected abstract validate(context: IContext): Promise<boolean>;
18
+ protected readonly logger: ILogger;
17
19
  protected payload: PayloadType;
18
20
  protected cookieString: string;
19
21
  protected cookieSecret: string;
@@ -40,9 +40,10 @@ exports.BotDefenderTokenBase = void 0;
40
40
  var TokenVerificationResult_1 = require("../TokenVerificationResult");
41
41
  var BotDefenderTokenBase = /** @class */ (function () {
42
42
  function BotDefenderTokenBase(config, cookieString) {
43
- this.cookieString = cookieString;
43
+ this.logger = config.logger;
44
44
  this.cookieSecret = config.cookieSecret;
45
45
  this.cookieMaxLength = config.riskCookieMaxLength;
46
+ this.cookieString = cookieString;
46
47
  this.isValidated = false;
47
48
  }
48
49
  BotDefenderTokenBase.prototype.verify = function (context) {
@@ -1,12 +1,10 @@
1
1
  import { IConfiguration } from '../../../config';
2
2
  import { IContext } from '../../../context';
3
- import { ILogger } from '../../../logger';
4
3
  import { BlockAction } from '../../../block_handler';
5
4
  import { IBase64Utils, IHashUtils } from '../../../utils';
6
5
  import { BotDefenderTokenV2Payload } from './BotDefenderTokenV2Payload';
7
6
  import { BotDefenderTokenBase } from '../BotDefenderTokenBase';
8
7
  export declare class DefaultBotDefenderTokenV2 extends BotDefenderTokenBase<BotDefenderTokenV2Payload> {
9
- protected readonly logger: ILogger;
10
8
  protected readonly base64Utils: IBase64Utils;
11
9
  protected readonly hashUtils: IHashUtils;
12
10
  protected isHighRisk: boolean;
@@ -59,7 +59,6 @@ var DefaultBotDefenderTokenV2 = /** @class */ (function (_super) {
59
59
  __extends(DefaultBotDefenderTokenV2, _super);
60
60
  function DefaultBotDefenderTokenV2(config, cookieString, base64Utils, hashUtils) {
61
61
  var _this = _super.call(this, config, cookieString) || this;
62
- _this.logger = config.logger;
63
62
  _this.base64Utils = base64Utils;
64
63
  _this.hashUtils = hashUtils;
65
64
  _this.isHighRisk = undefined;
@@ -1,13 +1,11 @@
1
1
  import { IConfiguration } from '../../../config';
2
2
  import { IContext } from '../../../context';
3
- import { ILogger } from '../../../logger';
4
3
  import { ICipherUtils, IHashUtils } from '../../../utils';
5
4
  import { BlockAction } from '../../../block_handler';
6
5
  import { BotDefenderTokenV3Payload } from './BotDefenderTokenV3Payload';
7
6
  import { TokenSignField } from './TokenSignField';
8
7
  import { BotDefenderTokenBase } from '../BotDefenderTokenBase';
9
8
  export declare class DefaultBotDefenderTokenV3 extends BotDefenderTokenBase<BotDefenderTokenV3Payload> {
10
- protected readonly logger: ILogger;
11
9
  protected readonly maxIterations: number;
12
10
  protected readonly minIterations: number;
13
11
  protected readonly blockingScore: number;
@@ -60,7 +60,6 @@ var DefaultBotDefenderTokenV3 = /** @class */ (function (_super) {
60
60
  __extends(DefaultBotDefenderTokenV3, _super);
61
61
  function DefaultBotDefenderTokenV3(config, cookieString, cipherUtils, hashUtils) {
62
62
  var _this = _super.call(this, config, cookieString) || this;
63
- _this.logger = config.logger;
64
63
  _this.maxIterations = config.riskCookieMaxIterations;
65
64
  _this.minIterations = config.riskCookieMinIterations;
66
65
  _this.blockingScore = config.blockingScore;
@@ -131,11 +130,12 @@ var DefaultBotDefenderTokenV3 = /** @class */ (function (_super) {
131
130
  };
132
131
  DefaultBotDefenderTokenV3.prototype.validate = function (context) {
133
132
  return __awaiter(this, void 0, void 0, function () {
134
- var signedFields, payload, hash;
133
+ var signedFields, hmacStrBase, payload, hash;
135
134
  return __generator(this, function (_a) {
136
135
  try {
137
136
  signedFields = this.getSignedWithFields(context);
138
- payload = "".concat(this.cookieString).concat(signedFields.join(''));
137
+ hmacStrBase = this.cookieString.substring(this.cookieString.indexOf(constants_1.COOKIE_SPLIT_DELIMITER) + 1);
138
+ payload = "".concat(hmacStrBase).concat(signedFields.join(''));
139
139
  hash = this.hashUtils.createHmac(utils_1.Algorithm.SHA256, payload, this.cookieSecret);
140
140
  return [2 /*return*/, hash === this.hmac];
141
141
  }
@@ -7,4 +7,4 @@ export declare const BYPASS_MONITOR_HEADER_VALUE = "1";
7
7
  export declare const X_PX_AUTHORIZATION_HEADER_NAME = "x-px-authorization";
8
8
  export declare const X_PX_ORIGINAL_TOKEN_HEADER_NAME = "x-px-original-token";
9
9
  export declare const X_PX_BYPASS_REASON_HEADER_NAME = "x-px-bypass-reason";
10
- export declare const CORE_MODULE_VERSION = "JS Core 0.1.0";
10
+ export declare const CORE_MODULE_VERSION = "JS Core 0.2.0";
@@ -10,4 +10,4 @@ exports.BYPASS_MONITOR_HEADER_VALUE = '1';
10
10
  exports.X_PX_AUTHORIZATION_HEADER_NAME = 'x-px-authorization';
11
11
  exports.X_PX_ORIGINAL_TOKEN_HEADER_NAME = 'x-px-original-token';
12
12
  exports.X_PX_BYPASS_REASON_HEADER_NAME = 'x-px-bypass-reason';
13
- exports.CORE_MODULE_VERSION = 'JS Core 0.1.0';
13
+ exports.CORE_MODULE_VERSION = 'JS Core 0.2.0';
@@ -0,0 +1,3 @@
1
+ export declare class EnforcerError extends Error {
2
+ constructor(message?: string);
3
+ }
@@ -15,12 +15,15 @@ var __extends = (this && this.__extends) || (function () {
15
15
  };
16
16
  })();
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.EnforcerException = void 0;
19
- var EnforcerException = /** @class */ (function (_super) {
20
- __extends(EnforcerException, _super);
21
- function EnforcerException(message) {
22
- return _super.call(this, "enforcer exception - ".concat(message)) || this;
18
+ exports.EnforcerError = void 0;
19
+ var EnforcerErrorName_1 = require("./EnforcerErrorName");
20
+ var EnforcerError = /** @class */ (function (_super) {
21
+ __extends(EnforcerError, _super);
22
+ function EnforcerError(message) {
23
+ var _this = _super.call(this, message) || this;
24
+ _this.name = EnforcerErrorName_1.EnforcerErrorName.ENFORCER_ERROR;
25
+ return _this;
23
26
  }
24
- return EnforcerException;
27
+ return EnforcerError;
25
28
  }(Error));
26
- exports.EnforcerException = EnforcerException;
29
+ exports.EnforcerError = EnforcerError;
@@ -0,0 +1,4 @@
1
+ export declare enum EnforcerErrorName {
2
+ ENFORCER_ERROR = "EnforcerError",
3
+ ENFORCER_TIMEOUT_ERROR = "EnforcerTimeoutError"
4
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EnforcerErrorName = void 0;
4
+ var EnforcerErrorName;
5
+ (function (EnforcerErrorName) {
6
+ EnforcerErrorName["ENFORCER_ERROR"] = "EnforcerError";
7
+ EnforcerErrorName["ENFORCER_TIMEOUT_ERROR"] = "EnforcerTimeoutError";
8
+ })(EnforcerErrorName = exports.EnforcerErrorName || (exports.EnforcerErrorName = {}));
@@ -0,0 +1,4 @@
1
+ import { EnforcerError } from './EnforcerError';
2
+ export declare class EnforcerTimeoutError extends EnforcerError {
3
+ constructor(ms?: number);
4
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.EnforcerTimeoutError = void 0;
19
+ var EnforcerError_1 = require("./EnforcerError");
20
+ var EnforcerErrorName_1 = require("./EnforcerErrorName");
21
+ var EnforcerTimeoutError = /** @class */ (function (_super) {
22
+ __extends(EnforcerTimeoutError, _super);
23
+ function EnforcerTimeoutError(ms) {
24
+ var _this = _super.call(this, "".concat(typeof ms === 'number' ? "".concat(ms, "ms ") : '', "timeout reached")) || this;
25
+ _this.name = EnforcerErrorName_1.EnforcerErrorName.ENFORCER_TIMEOUT_ERROR;
26
+ return _this;
27
+ }
28
+ return EnforcerTimeoutError;
29
+ }(EnforcerError_1.EnforcerError));
30
+ exports.EnforcerTimeoutError = EnforcerTimeoutError;
@@ -0,0 +1,3 @@
1
+ export { EnforcerErrorName } from './EnforcerErrorName';
2
+ export { EnforcerError } from './EnforcerError';
3
+ export { EnforcerTimeoutError } from './EnforcerTimeoutError';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EnforcerTimeoutError = exports.EnforcerError = exports.EnforcerErrorName = void 0;
4
+ var EnforcerErrorName_1 = require("./EnforcerErrorName");
5
+ Object.defineProperty(exports, "EnforcerErrorName", { enumerable: true, get: function () { return EnforcerErrorName_1.EnforcerErrorName; } });
6
+ var EnforcerError_1 = require("./EnforcerError");
7
+ Object.defineProperty(exports, "EnforcerError", { enumerable: true, get: function () { return EnforcerError_1.EnforcerError; } });
8
+ var EnforcerTimeoutError_1 = require("./EnforcerTimeoutError");
9
+ Object.defineProperty(exports, "EnforcerTimeoutError", { enumerable: true, get: function () { return EnforcerTimeoutError_1.EnforcerTimeoutError; } });
@@ -4,11 +4,11 @@ export * from './hash';
4
4
  export * from './ip_range_checker';
5
5
  export * from './uuid_generator';
6
6
  export * from './cipher';
7
+ export * from './error';
7
8
  export * from './utils';
8
9
  export * from './constants';
9
10
  export { ModuleMode } from './ModuleMode';
10
11
  export { VidSource } from './VidSource';
11
12
  export { PassReason } from './PassReason';
12
13
  export { Algorithm } from './Algorithm';
13
- export { EnforcerException } from './EnforcerException';
14
14
  export { IScoreRetriever } from './IScoreRetriever';
@@ -14,13 +14,14 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.EnforcerException = exports.Algorithm = exports.PassReason = exports.VidSource = exports.ModuleMode = void 0;
17
+ exports.Algorithm = exports.PassReason = exports.VidSource = exports.ModuleMode = void 0;
18
18
  __exportStar(require("./base64"), exports);
19
19
  __exportStar(require("./cookie_parser"), exports);
20
20
  __exportStar(require("./hash"), exports);
21
21
  __exportStar(require("./ip_range_checker"), exports);
22
22
  __exportStar(require("./uuid_generator"), exports);
23
23
  __exportStar(require("./cipher"), exports);
24
+ __exportStar(require("./error"), exports);
24
25
  __exportStar(require("./utils"), exports);
25
26
  __exportStar(require("./constants"), exports);
26
27
  var ModuleMode_1 = require("./ModuleMode");
@@ -31,5 +32,3 @@ var PassReason_1 = require("./PassReason");
31
32
  Object.defineProperty(exports, "PassReason", { enumerable: true, get: function () { return PassReason_1.PassReason; } });
32
33
  var Algorithm_1 = require("./Algorithm");
33
34
  Object.defineProperty(exports, "Algorithm", { enumerable: true, get: function () { return Algorithm_1.Algorithm; } });
34
- var EnforcerException_1 = require("./EnforcerException");
35
- Object.defineProperty(exports, "EnforcerException", { enumerable: true, get: function () { return EnforcerException_1.EnforcerException; } });
@@ -11,3 +11,4 @@ export declare const removeSensitiveHeaders: (headers: HttpHeaders, sensitiveHea
11
11
  export declare const isRouteInPatterns: (route: string, patterns: Array<string | RegExp>) => boolean;
12
12
  export declare const isRouteMatch: (route: string, pattern: string | RegExp) => boolean;
13
13
  export declare const transferExistingProperties: <FromObj extends Record<string, any>, ToObj extends Record<string, any>>(fromObj: FromObj, toObj: ToObj, propertyMappings: Partial<Record<keyof FromObj, keyof ToObj>>) => void;
14
+ export declare const rejectOnTimeout: <T>(promise: Promise<T>, ms: number) => Promise<T>;
@@ -1,6 +1,43 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transferExistingProperties = exports.isRouteMatch = exports.isRouteInPatterns = exports.removeSensitiveHeaders = exports.removeSensitiveFields = exports.getDecodedUrl = exports.getExtension = exports.getAuthorizationHeader = exports.getCollectorDomain = exports.getScoreApiDomain = exports.isValidUuid = exports.isValidEnumValue = void 0;
39
+ exports.rejectOnTimeout = exports.transferExistingProperties = exports.isRouteMatch = exports.isRouteInPatterns = exports.removeSensitiveHeaders = exports.removeSensitiveFields = exports.getDecodedUrl = exports.getExtension = exports.getAuthorizationHeader = exports.getCollectorDomain = exports.getScoreApiDomain = exports.isValidUuid = exports.isValidEnumValue = void 0;
40
+ var error_1 = require("./error");
4
41
  var isValidEnumValue = function (options, selection) {
5
42
  return Object.values(options).includes(selection);
6
43
  };
@@ -89,3 +126,23 @@ var transferExistingProperties = function (fromObj, toObj, propertyMappings) {
89
126
  });
90
127
  };
91
128
  exports.transferExistingProperties = transferExistingProperties;
129
+ var rejectOnTimeout = function (promise, ms) { return __awaiter(void 0, void 0, void 0, function () {
130
+ var id, timeout, resolvedPromise;
131
+ return __generator(this, function (_a) {
132
+ switch (_a.label) {
133
+ case 0:
134
+ timeout = new Promise(function (resolve, reject) {
135
+ id = setTimeout(function () {
136
+ clearTimeout(id);
137
+ reject(new error_1.EnforcerTimeoutError(ms));
138
+ }, ms);
139
+ });
140
+ return [4 /*yield*/, Promise.race([promise, timeout])];
141
+ case 1:
142
+ resolvedPromise = _a.sent();
143
+ clearTimeout(id);
144
+ return [2 /*return*/, resolvedPromise];
145
+ }
146
+ });
147
+ }); };
148
+ exports.rejectOnTimeout = rejectOnTimeout;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "perimeterx-js-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -13,7 +13,9 @@
13
13
  "lint": "./node_modules/eslint/bin/eslint.js . --ext .ts",
14
14
  "lint:fix": "./node_modules/eslint/bin/eslint.js . --ext .ts --fix",
15
15
  "test": "mocha",
16
- "coverage": "nyc npm run test"
16
+ "coverage": "nyc npm run test",
17
+ "pre-commit": "./node_modules/.bin/lint-staged",
18
+ "prepare": "husky install"
17
19
  },
18
20
  "dependencies": {
19
21
  "cookie": "^0.5.0",
@@ -39,6 +41,8 @@
39
41
  "eslint-config-prettier": "^8.5.0",
40
42
  "eslint-plugin-no-loops": "^0.3.0",
41
43
  "eslint-plugin-prettier": "^4.2.1",
44
+ "husky": "^8.0.3",
45
+ "lint-staged": "^13.1.0",
42
46
  "mocha": "^10.0.0",
43
47
  "nyc": "^15.1.0",
44
48
  "prettier": "^2.7.1",
@@ -47,6 +51,9 @@
47
51
  "ts-node": "^10.9.1",
48
52
  "typescript": "^4.4.4"
49
53
  },
54
+ "lint-staged": {
55
+ "*.ts": "npm run lint:fix"
56
+ },
50
57
  "author": "",
51
58
  "license": "ISC"
52
59
  }
@@ -1,3 +0,0 @@
1
- export declare class EnforcerException extends Error {
2
- constructor(message: string);
3
- }