perimeterx-js-core 0.7.1 → 0.8.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 (189) hide show
  1. package/lib/action/utils.js +1 -1
  2. package/lib/activities/HttpActivityClient.d.ts +5 -5
  3. package/lib/activities/HttpActivityClient.js +28 -39
  4. package/lib/activities/HttpBatchedActivityClient.d.ts +2 -2
  5. package/lib/activities/HttpBatchedActivityClient.js +19 -32
  6. package/lib/activities/model/AsyncActivity.d.ts +14 -0
  7. package/lib/activities/model/{ActivityDetails.d.ts → AsyncActivityDetails.d.ts} +6 -23
  8. package/lib/activities/model/CommonActivityDetails.d.ts +40 -0
  9. package/lib/activities/model/CommonActivityDetails.js +1 -0
  10. package/lib/activities/model/HeaderEntry.d.ts +4 -0
  11. package/lib/activities/model/HeaderEntry.js +1 -0
  12. package/lib/activities/model/index.d.ts +4 -2
  13. package/lib/activities/model/index.js +4 -2
  14. package/lib/activities/utils.d.ts +6071 -9
  15. package/lib/activities/utils.js +111 -35
  16. package/lib/additional_activity_handler/AdditionalActivityHandler.d.ts +1 -1
  17. package/lib/additional_activity_handler/AdditionalActivityHandlerUtils.js +4 -12
  18. package/lib/config/ConfigurationParams.d.ts +1 -1
  19. package/lib/config/IConfiguration.d.ts +1 -1
  20. package/lib/config/StaticConfigurationBase.d.ts +1 -1
  21. package/lib/config/StaticConfigurationBase.js +3 -1
  22. package/lib/context/DefaultContext.d.ts +1 -1
  23. package/lib/context/DefaultContext.js +40 -8
  24. package/lib/context/interfaces/RiskApiData.d.ts +4 -0
  25. package/lib/cors/DefaultCors.js +21 -31
  26. package/lib/custom_parameters/CustomParametersUtils.js +3 -12
  27. package/lib/enforcer/EnforcerBase.js +51 -62
  28. package/lib/graphql/DefaultGraphQLParser.js +30 -39
  29. package/lib/http/index.d.ts +0 -1
  30. package/lib/http/index.js +0 -1
  31. package/lib/http/interfaces/IBody.d.ts +3 -2
  32. package/lib/http/interfaces/IIncomingRequest.d.ts +4 -0
  33. package/lib/http/interfaces/IURL.d.ts +3 -0
  34. package/lib/http/interfaces/IURLSearchParams.d.ts +9 -0
  35. package/lib/http/interfaces/IURLSearchParams.js +1 -0
  36. package/lib/http/interfaces/index.d.ts +1 -0
  37. package/lib/http/interfaces/index.js +1 -0
  38. package/lib/http/{impl → utils}/FormDataImpl.js +4 -4
  39. package/lib/http/{impl → utils}/MinimalResponseImpl.js +3 -0
  40. package/lib/http/utils/MinimalResponseUtils.js +5 -7
  41. package/lib/http/utils/MultipartFormDataUtils.js +4 -5
  42. package/lib/http/{impl → utils}/OutgoingRequestImpl.d.ts +1 -1
  43. package/lib/http/{impl → utils}/OutgoingRequestImpl.js +5 -1
  44. package/lib/http/utils/URLUtils.d.ts +7 -0
  45. package/lib/http/utils/URLUtils.js +62 -0
  46. package/lib/http/utils/UrlImpl.d.ts +18 -0
  47. package/lib/http/utils/UrlImpl.js +54 -0
  48. package/lib/http/utils/UrlSearchParamsImpl.d.ts +19 -0
  49. package/lib/http/utils/UrlSearchParamsImpl.js +116 -0
  50. package/lib/http/utils/index.d.ts +6 -0
  51. package/lib/http/utils/index.js +6 -0
  52. package/lib/{utils → impl}/base64/AtobBase64Utils.d.ts +1 -1
  53. package/lib/{utils → impl}/base64/BufferBase64Utils.d.ts +1 -1
  54. package/lib/{utils → impl}/base64/BufferBase64Utils.js +1 -1
  55. package/lib/{utils → impl}/base64/JSBase64Base64Utils.d.ts +1 -1
  56. package/lib/{utils → impl}/cipher/CryptoCipherUtils.d.ts +1 -1
  57. package/lib/impl/cipher/CryptoCipherUtils.js +18 -0
  58. package/lib/{utils → impl}/cipher/SubtleCryptoCipherUtils.d.ts +1 -2
  59. package/lib/impl/cipher/SubtleCryptoCipherUtils.js +38 -0
  60. package/lib/{utils → impl}/hash/CryptoHashUtils.d.ts +1 -2
  61. package/lib/impl/hash/CryptoHashUtils.js +10 -0
  62. package/lib/{utils → impl}/hash/CryptoJSHashUtils.d.ts +1 -2
  63. package/lib/{utils → impl}/hash/CryptoJSHashUtils.js +1 -1
  64. package/lib/{utils → impl}/hash/SubtleCryptoHashUtils.d.ts +1 -2
  65. package/lib/impl/hash/SubtleCryptoHashUtils.js +21 -0
  66. package/lib/{utils → impl}/hmac/CryptoHmacUtils.d.ts +1 -2
  67. package/lib/{utils → impl}/hmac/CryptoHmacUtils.js +2 -1
  68. package/lib/{utils → impl}/hmac/CryptoJSHmacUtils.d.ts +1 -2
  69. package/lib/{utils → impl}/hmac/CryptoJSHmacUtils.js +1 -1
  70. package/lib/{http/impl → impl/http}/phin/PhinHttpClient.d.ts +1 -1
  71. package/lib/impl/http/phin/PhinHttpClient.js +31 -0
  72. package/lib/{http/impl → impl/http}/phin/PhinIncomingResponse.d.ts +2 -2
  73. package/lib/impl/http/phin/PhinIncomingResponse.js +23 -0
  74. package/lib/{utils → impl}/ip_range_checker/DefaultIpRangeChecker.d.ts +1 -1
  75. package/lib/{utils → impl}/request_id_generator/UuidRequestIdGenerator.d.ts +1 -1
  76. package/lib/{utils → impl}/url_parser/DefaultUrlParser.d.ts +4 -4
  77. package/lib/{utils → impl}/url_parser/DefaultUrlParser.js +9 -2
  78. package/lib/logger/HttpLogServiceClient.js +27 -35
  79. package/lib/logger/LoggerBase.js +2 -0
  80. package/lib/phase/impl/AdditionalActivityHandlerPhase.js +4 -15
  81. package/lib/phase/impl/CompositePhase.js +9 -19
  82. package/lib/phase/impl/CreateBlockResponsePhase.js +24 -35
  83. package/lib/phase/impl/DecideActionPhase.js +11 -21
  84. package/lib/phase/impl/EnrichContextFromRequestPhase.js +28 -45
  85. package/lib/phase/impl/EnrichContextFromResponsePhase.js +12 -23
  86. package/lib/phase/impl/FilterPhase.js +3 -13
  87. package/lib/phase/impl/FirstPartyPhase.js +21 -32
  88. package/lib/phase/impl/ModifyIncomingRequestPhase.js +4 -14
  89. package/lib/phase/impl/ModifyOutgoingResponsePhase.js +7 -18
  90. package/lib/phase/impl/ParseTokenPhase.js +5 -15
  91. package/lib/phase/impl/PreflightPhase.js +12 -20
  92. package/lib/phase/impl/RiskApiPhase.js +24 -36
  93. package/lib/phase/impl/SendAsyncActivitiesOnRequestPhase.js +8 -20
  94. package/lib/phase/impl/SendAsyncActivitiesOnResponsePhase.js +4 -14
  95. package/lib/phase/impl/SendLogsPhase.js +8 -18
  96. package/lib/phase/impl/TelemetryPhase.js +9 -21
  97. package/lib/products/account_defender/AccountDefender.js +16 -35
  98. package/lib/products/bot_defender/BotDefender.js +51 -72
  99. package/lib/products/bot_defender/BotDefenderActionData.js +2 -0
  100. package/lib/products/bot_defender/block/DefaultBotDefenderBlocker.d.ts +4 -4
  101. package/lib/products/bot_defender/block/DefaultBotDefenderBlocker.js +5 -3
  102. package/lib/products/bot_defender/block/captcha/CaptchaBlocker.d.ts +7 -4
  103. package/lib/products/bot_defender/block/captcha/CaptchaBlocker.js +12 -8
  104. package/lib/products/bot_defender/block/captcha/HtmlCaptchaBlocker.d.ts +1 -1
  105. package/lib/products/bot_defender/block/captcha/HtmlCaptchaBlocker.js +1 -0
  106. package/lib/products/bot_defender/block/captcha/JsonCaptchaBlocker.d.ts +1 -1
  107. package/lib/products/bot_defender/block/captcha/JsonCaptchaBlocker.js +5 -4
  108. package/lib/products/bot_defender/block/captcha/MobileCaptchaBlocker.d.ts +2 -2
  109. package/lib/products/bot_defender/block/captcha/MobileCaptchaBlocker.js +2 -0
  110. package/lib/products/bot_defender/block/utils.js +1 -2
  111. package/lib/products/bot_defender/filter/DefaultBotDefenderFilter.js +2 -0
  112. package/lib/products/bot_defender/first_party/DefaultBotDefenderFirstParty.js +51 -68
  113. package/lib/products/bot_defender/first_party/constants.d.ts +0 -4
  114. package/lib/products/bot_defender/first_party/constants.js +0 -7
  115. package/lib/products/credential_intelligence/CredentialIntelligence.js +42 -63
  116. package/lib/products/credential_intelligence/endpoint/CredentialEndpoint.js +15 -23
  117. package/lib/products/credential_intelligence/endpoint/CredentialEndpointManager.js +9 -22
  118. package/lib/products/credential_intelligence/endpoint/extractor/BodyCredentialExtractor.d.ts +5 -5
  119. package/lib/products/credential_intelligence/endpoint/extractor/BodyCredentialExtractor.js +22 -33
  120. package/lib/products/credential_intelligence/endpoint/extractor/CustomCredentialExtractor.js +8 -18
  121. package/lib/products/credential_intelligence/endpoint/extractor/HeaderCredentialExtractor.js +2 -0
  122. package/lib/products/credential_intelligence/endpoint/extractor/QueryParamCredentialExtractor.d.ts +1 -1
  123. package/lib/products/credential_intelligence/endpoint/extractor/QueryParamCredentialExtractor.js +11 -16
  124. package/lib/products/credential_intelligence/endpoint/hash_protocol/MultistepHashProtocol.js +11 -21
  125. package/lib/products/credential_intelligence/endpoint/hash_protocol/SingleStepAndMultistepHashProtocol.js +9 -18
  126. package/lib/products/credential_intelligence/endpoint/hash_protocol/SingleStepHashProtocol.js +13 -25
  127. package/lib/products/credential_intelligence/endpoint/login_successful/BodyLoginSuccessfulParser.js +4 -14
  128. package/lib/products/credential_intelligence/endpoint/login_successful/CustomLoginSuccessfulParser.js +10 -20
  129. package/lib/products/credential_intelligence/endpoint/login_successful/HeaderLoginSuccessfulParser.js +7 -16
  130. package/lib/products/credential_intelligence/endpoint/login_successful/LoginSuccessfulParserFactory.js +7 -6
  131. package/lib/products/credential_intelligence/endpoint/login_successful/StatusLoginSuccessfulParser.js +3 -13
  132. package/lib/products/credential_intelligence/endpoint/matcher/ExactPathEndpointMatcher.js +2 -0
  133. package/lib/products/credential_intelligence/endpoint/matcher/RegexPathEndpointMatcher.js +2 -0
  134. package/lib/pxde/DefaultDataEnrichment.js +47 -61
  135. package/lib/pxhd/PXHDUtils.js +2 -2
  136. package/lib/risk_api/client/PostRiskApiClientBase.d.ts +7 -12
  137. package/lib/risk_api/client/PostRiskApiClientBase.js +70 -171
  138. package/lib/risk_api/model/RiskActivity.d.ts +5 -45
  139. package/lib/risk_api/risk_response/IRiskResponse.d.ts +1 -0
  140. package/lib/risk_api/risk_response/RiskResponseBase.d.ts +1 -0
  141. package/lib/risk_api/risk_response/RiskResponseBase.js +20 -33
  142. package/lib/risk_api/risk_response/v2/DefaultRiskResponseV2.d.ts +1 -1
  143. package/lib/risk_api/risk_response/v2/DefaultRiskResponseV2.js +3 -5
  144. package/lib/risk_api/risk_response/v2/RiskResponseV2Payload.d.ts +1 -0
  145. package/lib/risk_api/risk_response/v3/DefaultRiskResponseV3.js +2 -4
  146. package/lib/risk_api/risk_response/v3/RiskResponseV3Payload.d.ts +1 -0
  147. package/lib/risk_token/parser/TokenParserBase.js +25 -36
  148. package/lib/risk_token/token/TokenBase.js +24 -29
  149. package/lib/risk_token/token/v2/DefaultTokenV2.js +34 -49
  150. package/lib/risk_token/token/v3/DefaultTokenV3.js +63 -77
  151. package/lib/telemetry/DefaultTelemetry.js +46 -58
  152. package/lib/utils/base64/index.d.ts +0 -3
  153. package/lib/utils/base64/index.js +0 -3
  154. package/lib/utils/cipher/index.d.ts +1 -3
  155. package/lib/utils/cipher/index.js +1 -2
  156. package/lib/utils/constants.d.ts +2 -1
  157. package/lib/utils/constants.js +2 -1
  158. package/lib/utils/hash/index.d.ts +0 -3
  159. package/lib/utils/hash/index.js +0 -3
  160. package/lib/utils/hmac/index.d.ts +0 -2
  161. package/lib/utils/hmac/index.js +0 -2
  162. package/lib/utils/ip_range_checker/index.d.ts +1 -2
  163. package/lib/utils/ip_range_checker/index.js +1 -1
  164. package/lib/utils/request_id_generator/index.d.ts +1 -2
  165. package/lib/utils/request_id_generator/index.js +1 -1
  166. package/lib/utils/url_parser/index.d.ts +0 -1
  167. package/lib/utils/url_parser/index.js +0 -1
  168. package/lib/utils/utils.d.ts +1 -7
  169. package/lib/utils/utils.js +3 -25
  170. package/package.json +12 -6
  171. package/lib/activities/model/Activity.d.ts +0 -13
  172. package/lib/http/impl/index.d.ts +0 -4
  173. package/lib/http/impl/index.js +0 -4
  174. package/lib/http/impl/phin/PhinHttpClient.js +0 -41
  175. package/lib/http/impl/phin/PhinIncomingResponse.js +0 -38
  176. package/lib/utils/cipher/CryptoCipherUtils.js +0 -28
  177. package/lib/utils/cipher/SubtleCryptoCipherUtils.js +0 -47
  178. package/lib/utils/hash/CryptoHashUtils.js +0 -20
  179. package/lib/utils/hash/SubtleCryptoHashUtils.js +0 -31
  180. /package/lib/activities/model/{Activity.js → AsyncActivity.js} +0 -0
  181. /package/lib/activities/model/{ActivityDetails.js → AsyncActivityDetails.js} +0 -0
  182. /package/lib/http/{impl → utils}/FormDataImpl.d.ts +0 -0
  183. /package/lib/http/{impl → utils}/MinimalResponseImpl.d.ts +0 -0
  184. /package/lib/{utils → impl}/base64/AtobBase64Utils.js +0 -0
  185. /package/lib/{utils → impl}/base64/JSBase64Base64Utils.js +0 -0
  186. /package/lib/{http/impl → impl/http}/phin/index.d.ts +0 -0
  187. /package/lib/{http/impl → impl/http}/phin/index.js +0 -0
  188. /package/lib/{utils → impl}/ip_range_checker/DefaultIpRangeChecker.js +0 -0
  189. /package/lib/{utils → impl}/request_id_generator/UuidRequestIdGenerator.js +0 -0
@@ -1,18 +1,18 @@
1
- import { removeSensitiveHeaders, transferExistingProperties } from '../utils';
2
- import { joinHeaderValues } from '../http';
1
+ import { ModuleMode, removeSensitiveHeaders, transferExistingProperties } from '../utils';
2
+ import { ProductName } from '../products';
3
3
  import { BLOCK_ACTION_TO_PRODUCT_MAP } from '../blocker';
4
4
  import { Action } from '../action';
5
5
  import { ActivityType } from './ActivityType';
6
- export const createActivity = (activityType, config, context) => {
7
- var _a;
6
+ import { TokenParseResult } from '../risk_token';
7
+ export const createAsyncActivity = (activityType, config, context) => {
8
8
  return {
9
9
  type: activityType,
10
10
  px_app_id: config.appId,
11
11
  url: context.requestData.rawUrl,
12
12
  headers: activityType !== ActivityType.ADDITIONAL_S2S
13
- ? joinHeaderValues(removeSensitiveHeaders(context.requestData.headers, config.sensitiveHeaders))
13
+ ? toHeaderEntryArray(removeSensitiveHeaders(context.requestData.headers, config.sensitiveHeaders))
14
14
  : undefined,
15
- pxhd: (_a = context.pxhd) === null || _a === void 0 ? void 0 : _a.value,
15
+ pxhd: context.pxhd?.value,
16
16
  socket_ip: context.requestData.ip,
17
17
  timestamp: Date.now(),
18
18
  vid: context.vid,
@@ -20,7 +20,8 @@ export const createActivity = (activityType, config, context) => {
20
20
  };
21
21
  };
22
22
  export const createActivityDetails = (activityType, config, context) => {
23
- const genericActivityDetails = createGenericActivityDetails(config, context);
23
+ const commonActivityDetails = createCommonActivityDetails(config, context);
24
+ const commonAsyncActivityDetails = createAsyncActivityCommonDetails(context);
24
25
  let specificActivityDetails = {};
25
26
  switch (activityType) {
26
27
  case ActivityType.PAGE_REQUESTED:
@@ -33,38 +34,43 @@ export const createActivityDetails = (activityType, config, context) => {
33
34
  specificActivityDetails = createAdditionalS2SActivityDetails(config, context);
34
35
  break;
35
36
  }
36
- return Object.assign(genericActivityDetails, specificActivityDetails);
37
+ return Object.assign(commonActivityDetails, commonAsyncActivityDetails, specificActivityDetails);
37
38
  };
38
- export const createGenericActivityDetails = (config, context) => {
39
- const genericActivityDetails = {
39
+ export const createAsyncActivityCommonDetails = (context) => {
40
+ const details = {
41
+ client_uuid: context.uuid,
42
+ };
43
+ addRiskApiDataToAsyncActivityCommonDetails(details, context);
44
+ addResponseDataToAsyncActivityCommonDetails(details, context);
45
+ return details;
46
+ };
47
+ export const createCommonActivityDetails = (config, context) => {
48
+ const details = {
40
49
  module_version: config.moduleVersion,
50
+ // Note: risk_mode currently reflects only Bot Defender mode
51
+ risk_mode: context.productData.bd?.isMonitoredRequest ? ModuleMode.MONITOR : ModuleMode.ACTIVE_BLOCKING,
41
52
  };
42
- if (context.customParameters) {
43
- Object.assign(genericActivityDetails, context.customParameters);
44
- }
45
- transferExistingProperties(context, genericActivityDetails, {
53
+ addRootContextDataToDetails(details, context);
54
+ addRequestDataToDetails(details, context.requestData);
55
+ addTokenDataToDetails(details, context.tokenData);
56
+ addProductDataToDetails(details, context.productData);
57
+ addServerDataToDetails(details, context.serverData);
58
+ addTlsDataToDetails(details, context.tlsData);
59
+ addCustomParametersToDetails(details, context.customParameters);
60
+ return details;
61
+ };
62
+ export const addRootContextDataToDetails = (details, context) => {
63
+ transferExistingProperties(context, details, {
46
64
  requestId: 'request_id',
47
- uuid: 'client_uuid',
48
65
  tokenOrigin: 'cookie_origin',
66
+ vidSource: 'enforcer_vid_source',
49
67
  graphqlData: 'graphql_operations',
50
68
  });
51
- transferExistingProperties(context.requestData, genericActivityDetails, {
52
- httpVersion: 'http_version',
53
- method: 'http_method',
54
- requestCookieNames: 'request_cookie_names',
55
- });
56
- transferExistingProperties(context.riskApiData, genericActivityDetails, {
57
- riskRtt: 'risk_rtt',
58
- });
59
- transferExistingProperties(context.serverData, genericActivityDetails, {
60
- region: 'server_info_region',
61
- datacenter: 'server_info_datacenter',
62
- });
63
- transferExistingProperties(context.response, genericActivityDetails, {
64
- status: 'http_status_code',
65
- });
66
- addProductDataToDetails(genericActivityDetails, context.productData);
67
- return genericActivityDetails;
69
+ };
70
+ export const addCustomParametersToDetails = (details, customParameters) => {
71
+ if (customParameters) {
72
+ Object.assign(details, customParameters);
73
+ }
68
74
  };
69
75
  export const addProductDataToDetails = (details, productData) => {
70
76
  transferExistingProperties(productData.ad, details, {
@@ -73,9 +79,74 @@ export const addProductDataToDetails = (details, productData) => {
73
79
  crossTabSession: 'cross_tab_session',
74
80
  });
75
81
  transferExistingProperties(productData.ci, details, {
82
+ hashedUsername: 'user',
83
+ hashedPassword: 'pass',
76
84
  ciVersion: 'ci_version',
77
85
  ssoStep: 'sso_step',
78
- isCompromised: 'credentials_compromised',
86
+ });
87
+ };
88
+ export const addTlsDataToDetails = (details, tlsData) => {
89
+ transferExistingProperties(tlsData, details, {
90
+ tlsProtocol: 'tls_protocol',
91
+ tlsServer: 'tls_server',
92
+ tlsCipher: 'tls_cipher',
93
+ tlsCiphersSha: 'tls_ciphers_sha',
94
+ tlsExtensionSha: 'tls_extension_sha',
95
+ tlsPreferredCiphers: 'tls_preferred_ciphers',
96
+ tlsJa3Fingerprint: 'tls_ja3_fingerprint',
97
+ });
98
+ };
99
+ export const addServerDataToDetails = (details, serverData) => {
100
+ transferExistingProperties(serverData, details, {
101
+ region: 'server_info_region',
102
+ datacenter: 'server_info_datacenter',
103
+ });
104
+ };
105
+ export const addRequestDataToDetails = (details, requestData) => {
106
+ transferExistingProperties(requestData, details, {
107
+ httpVersion: 'http_version',
108
+ method: 'http_method',
109
+ requestCookieNames: 'request_cookie_names',
110
+ });
111
+ };
112
+ export const addTokenDataToDetails = (details, { token, mobileData }) => {
113
+ if (token) {
114
+ if (token.isValid()) {
115
+ details.px_cookie = token.getPayloadString();
116
+ details.px_cookie_hmac = token.hmac;
117
+ }
118
+ else {
119
+ details.px_orig_cookie = token.getTokenString();
120
+ }
121
+ }
122
+ if (mobileData) {
123
+ transferExistingProperties(mobileData, details, {
124
+ originalToken: 'original_token',
125
+ decodedOriginalToken: 'px_decoded_original_token',
126
+ });
127
+ if (mobileData.originalTokenParseResult === TokenParseResult.DECRYPTION_FAILED) {
128
+ details.original_token_error = 'cookie_decryption_failed';
129
+ }
130
+ else if (mobileData.originalTokenParseResult === TokenParseResult.VALIDATION_FAILED) {
131
+ details.original_token_error = 'cookie_validation_failed';
132
+ }
133
+ }
134
+ };
135
+ export const addRiskApiDataToAsyncActivityCommonDetails = (details, context) => {
136
+ transferExistingProperties(context.riskApiData, details, {
137
+ riskRtt: 'risk_rtt',
138
+ s2sCallReason: 's2s_call_reason',
139
+ });
140
+ if (context.riskApiData.riskResponse?.additionalRiskInfo) {
141
+ details.additional_risk_info = context.riskApiData.riskResponse.additionalRiskInfo;
142
+ }
143
+ if (context.productData[ProductName.CREDENTIAL_INTELLIGENCE]) {
144
+ details.credentials_compromised = context.productData[ProductName.CREDENTIAL_INTELLIGENCE].isCompromised;
145
+ }
146
+ };
147
+ export const addResponseDataToAsyncActivityCommonDetails = (details, context) => {
148
+ transferExistingProperties(context.response, details, {
149
+ status: 'http_status_code',
79
150
  });
80
151
  };
81
152
  export const createPageRequestedActivityDetails = (context) => {
@@ -91,10 +162,9 @@ export const createPageRequestedActivityDetails = (context) => {
91
162
  return details;
92
163
  };
93
164
  export const createBlockActivityDetails = (context) => {
94
- var _a;
95
165
  const details = {};
96
166
  const blockingProduct = BLOCK_ACTION_TO_PRODUCT_MAP.get(context.blockAction);
97
- details.block_reason = (_a = context.reasons) === null || _a === void 0 ? void 0 : _a[blockingProduct];
167
+ details.block_reason = context.reasons?.[blockingProduct];
98
168
  details.simulated_block = context.action === Action.SIMULATED_BLOCK;
99
169
  transferExistingProperties(context, details, {
100
170
  blockAction: 'block_action',
@@ -112,3 +182,9 @@ export const createAdditionalS2SActivityDetails = ({ ciSendRawUsernameOnAddition
112
182
  }
113
183
  return details;
114
184
  };
185
+ export const toHeaderEntryArray = (headers) => {
186
+ return Object.entries(headers).flatMap(([key, values]) => values.map((value) => ({
187
+ name: key,
188
+ value: value,
189
+ })));
190
+ };
@@ -1,3 +1,3 @@
1
1
  import { ConfigurationParams } from '../config';
2
2
  import { ReadonlyContext } from '../context';
3
- export type AdditionalActivityHandler = <Req, Res>(config: ConfigurationParams<Req, Res>, context: ReadonlyContext<Req, Res>, request: Req) => void | Promise<void>;
3
+ export type AdditionalActivityHandler<Req, Res> = (config: ConfigurationParams<Req, Res>, context: ReadonlyContext<Req, Res>, request: Req) => void | Promise<void>;
@@ -1,22 +1,14 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  export var AdditionalActivityHandlerUtils;
11
2
  (function (AdditionalActivityHandlerUtils) {
12
- AdditionalActivityHandlerUtils.invokeAdditionalActivityHandler = (config, context) => __awaiter(this, void 0, void 0, function* () {
3
+ AdditionalActivityHandlerUtils.invokeAdditionalActivityHandler = async (config, context) => {
13
4
  if (config.additionalActivityHandler && typeof config.additionalActivityHandler === 'function') {
14
5
  try {
15
- yield config.additionalActivityHandler(config.toParams(), context, context.requestData.request.getUnderlyingRequest());
6
+ config.logger.debug('calling additional activity handler');
7
+ await config.additionalActivityHandler(config.toParams(), context, context.requestData.request.getUnderlyingRequest());
16
8
  }
17
9
  catch (e) {
18
10
  config.logger.error(`caught additional activity handler error - ${e}`);
19
11
  }
20
12
  }
21
- });
13
+ };
22
14
  })(AdditionalActivityHandlerUtils || (AdditionalActivityHandlerUtils = {}));
@@ -75,7 +75,7 @@ export type ConfigurationParams<Req, Res> = {
75
75
  px_cors_preflight_request_filter_enabled?: boolean;
76
76
  px_logger_auth_token?: string;
77
77
  px_extract_ip?: () => {};
78
- px_additional_activity_handler?: AdditionalActivityHandler;
78
+ px_additional_activity_handler?: AdditionalActivityHandler<Req, Res>;
79
79
  px_enrich_custom_parameters?: CustomParametersFunction<Req, Res>;
80
80
  px_login_successful_custom_callback?: CustomLoginSuccessfulCallback<Res>;
81
81
  px_cors_custom_preflight_handler?: CustomPreflightHandler<Req>;
@@ -207,7 +207,7 @@ export interface IConfiguration<Req, Res, ParamsType extends ConfigurationParams
207
207
  /**
208
208
  * A function that will be called after the asynchronous activities are sent to the backend.
209
209
  */
210
- readonly additionalActivityHandler: AdditionalActivityHandler;
210
+ readonly additionalActivityHandler: AdditionalActivityHandler<Req, Res>;
211
211
  /**
212
212
  * Whether cors support feature should be enabled.
213
213
  */
@@ -63,7 +63,7 @@ export declare abstract class StaticConfigurationBase<Req, Res, ParamsType exten
63
63
  get sensitiveGraphqlOperationNames(): string[];
64
64
  get sensitiveGraphqlOperationTypes(): string[];
65
65
  get enrichCustomParameters(): CustomParametersFunction<Req, Res>;
66
- get additionalActivityHandler(): AdditionalActivityHandler;
66
+ get additionalActivityHandler(): AdditionalActivityHandler<Req, Res>;
67
67
  get altBackendCaptchaUrl(): string;
68
68
  get corsSupportEnabled(): boolean;
69
69
  get corsCustomPreflightHandler(): CustomPreflightHandler<Req>;
@@ -2,8 +2,10 @@ import { DEFAULT_CONFIGURATIONS } from './DefaultConfigurations';
2
2
  import { LoggerSeverity, DefaultLogger } from '../logger';
3
3
  import { ModuleMode, getScoreApiDomain, getCollectorDomain, isValidEnumValue, EnforcerError, CORE_MODULE_VERSION, } from '../utils';
4
4
  export class StaticConfigurationBase {
5
+ configParams;
6
+ internalLogger;
5
7
  constructor(params, defaultParams) {
6
- this.configParams = this.initialize(params, Object.assign(Object.assign({}, DEFAULT_CONFIGURATIONS), defaultParams));
8
+ this.configParams = this.initialize(params, { ...DEFAULT_CONFIGURATIONS, ...defaultParams });
7
9
  this.internalLogger = new DefaultLogger(this.configParams.px_logger_severity);
8
10
  }
9
11
  initialize(params, defaultParams) {
@@ -9,7 +9,7 @@ import { ICookieParser, IRequestIdGenerator, VidSource } from '../utils';
9
9
  import { IContext, RequestData, RiskApiData, ServerData, TlsData, TokenData } from './interfaces';
10
10
  import { ProductData, ProductName } from '../products';
11
11
  import { Action } from '../action';
12
- import { IURLParser } from '../utils/url_parser';
12
+ import { IURLParser } from '../utils';
13
13
  export type DefaultContextOptions = {
14
14
  cookieParser?: ICookieParser;
15
15
  requestIdGenerator: IRequestIdGenerator;
@@ -4,8 +4,30 @@ import { TokenOrigin, TokenParseResult } from '../risk_token';
4
4
  import { RiskApiCallResult } from '../risk_api';
5
5
  import { COOKIE_HEADER_NAME, toReadonlyHeaders, USER_AGENT_HEADER_NAME, } from '../http';
6
6
  import { StringSplitCookieParser, PXHD_COOKIE_NAME, PXVID_COOKIE_NAME, X_PX_AUTHORIZATION_HEADER_NAME, } from '../utils';
7
- import { DefaultUrlParser } from '../utils/url_parser';
7
+ import { DefaultUrlParser } from '../impl/url_parser/DefaultUrlParser';
8
8
  export class DefaultContext {
9
+ requestId;
10
+ tokenOrigin;
11
+ requestData;
12
+ tokenData;
13
+ riskApiData;
14
+ tlsData;
15
+ serverData;
16
+ productData;
17
+ uuid;
18
+ vid;
19
+ vidSource;
20
+ action;
21
+ reasons;
22
+ score;
23
+ blockAction;
24
+ pxhd;
25
+ pxde;
26
+ pxdeVerified;
27
+ customParameters;
28
+ response;
29
+ config;
30
+ urlParser;
9
31
  constructor(config, request, options) {
10
32
  this.config = config;
11
33
  this.urlParser = options.urlParser || new DefaultUrlParser();
@@ -40,7 +62,19 @@ export class DefaultContext {
40
62
  const readOnlyHeaders = toReadonlyHeaders(headers);
41
63
  const userAgent = this.extractUserAgentFromHeader(config, readOnlyHeaders);
42
64
  const ip = this.extractIpFromHeader(config, readOnlyHeaders) || request.clientIP;
43
- return { url, rawUrl, method, headers: readOnlyHeaders, cookies, ip, userAgent, requestCookieNames, request };
65
+ const httpVersion = request.httpVersion;
66
+ return {
67
+ url,
68
+ rawUrl,
69
+ method,
70
+ headers: readOnlyHeaders,
71
+ cookies,
72
+ ip,
73
+ userAgent,
74
+ requestCookieNames,
75
+ request,
76
+ httpVersion,
77
+ };
44
78
  }
45
79
  static getCookies(cookieParser, ...cookieHeaderValues) {
46
80
  const cookies = {};
@@ -50,8 +84,7 @@ export class DefaultContext {
50
84
  return cookies;
51
85
  }
52
86
  extractUserAgentFromHeader(config, headers) {
53
- var _a;
54
- let userAgent = ((_a = headers[USER_AGENT_HEADER_NAME]) === null || _a === void 0 ? void 0 : _a[0]) || '';
87
+ let userAgent = headers[USER_AGENT_HEADER_NAME]?.[0] || '';
55
88
  if (userAgent.length > config.userAgentMaxLength) {
56
89
  userAgent = userAgent.substring(0, config.userAgentMaxLength);
57
90
  }
@@ -60,8 +93,7 @@ export class DefaultContext {
60
93
  extractIpFromHeader(config, headers) {
61
94
  let ip;
62
95
  config.ipHeaders.some((ipHeader) => {
63
- var _a;
64
- const headerValue = (_a = headers[ipHeader]) === null || _a === void 0 ? void 0 : _a[0];
96
+ const headerValue = headers[ipHeader]?.[0];
65
97
  if (headerValue) {
66
98
  ip = headerValue;
67
99
  return true;
@@ -73,8 +105,8 @@ export class DefaultContext {
73
105
  return request.headers.get(X_PX_AUTHORIZATION_HEADER_NAME) ? TokenOrigin.HEADER : TokenOrigin.COOKIE;
74
106
  }
75
107
  setCookiesOnContext() {
76
- this.vid = this.requestData.cookies[PXVID_COOKIE_NAME] || '';
77
- const pxhdCookie = this.requestData.cookies[PXHD_COOKIE_NAME] || '';
108
+ this.vid = this.requestData.cookies[PXVID_COOKIE_NAME];
109
+ const pxhdCookie = this.requestData.cookies[PXHD_COOKIE_NAME];
78
110
  if (pxhdCookie) {
79
111
  this.pxhd = {
80
112
  value: pxhdCookie,
@@ -4,6 +4,10 @@ export type RiskApiData = {
4
4
  * The result of the risk API call.
5
5
  */
6
6
  riskApiCallResult: RiskApiCallResult;
7
+ /**
8
+ * The reason for the Risk API call.
9
+ */
10
+ s2sCallReason?: string;
7
11
  /**
8
12
  * An interface representing the risk API response.
9
13
  */
@@ -1,15 +1,9 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { ACCESS_CONTROL_REQUEST_METHOD_HEADER, ORIGIN_HEADER } from './constants';
11
2
  import { HttpMethod } from '../http';
12
3
  export class DefaultCors {
4
+ customBlockResponseHeaders;
5
+ customPreflightHandler;
6
+ logger;
13
7
  constructor(config) {
14
8
  this.customBlockResponseHeaders = config.corsCreateCustomBlockResponseHeaders;
15
9
  this.customPreflightHandler = config.corsCustomPreflightHandler;
@@ -21,34 +15,30 @@ export class DefaultCors {
21
15
  requestData.headers[ORIGIN_HEADER] &&
22
16
  requestData.headers[ACCESS_CONTROL_REQUEST_METHOD_HEADER]);
23
17
  }
24
- runPreflightCustomHandler(context) {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- if (this.customPreflightHandler && typeof this.customPreflightHandler === 'function') {
27
- try {
28
- return yield this.customPreflightHandler(context.requestData.request.getUnderlyingRequest());
29
- }
30
- catch (e) {
31
- this.logger.debug(`Exception occurred while executing custom preflight handler: ${e}`);
32
- }
18
+ async runPreflightCustomHandler(context) {
19
+ if (this.customPreflightHandler && typeof this.customPreflightHandler === 'function') {
20
+ try {
21
+ return await this.customPreflightHandler(context.requestData.request.getUnderlyingRequest());
33
22
  }
34
- return null;
35
- });
23
+ catch (e) {
24
+ this.logger.debug(`Exception occurred while executing custom preflight handler: ${e}`);
25
+ }
26
+ }
27
+ return null;
36
28
  }
37
29
  isCorsRequest(context) {
38
30
  return !!context.requestData.headers[ORIGIN_HEADER];
39
31
  }
40
- getCorsBlockHeaders(context) {
41
- return __awaiter(this, void 0, void 0, function* () {
42
- if (this.customBlockResponseHeaders && typeof this.customBlockResponseHeaders === 'function') {
43
- try {
44
- return yield this.customBlockResponseHeaders(context.requestData.request.getUnderlyingRequest());
45
- }
46
- catch (e) {
47
- this.logger.debug(`Exception occurred in px_cors_create_custom_block_response_headers custom function: ${e}`);
48
- }
32
+ async getCorsBlockHeaders(context) {
33
+ if (this.customBlockResponseHeaders && typeof this.customBlockResponseHeaders === 'function') {
34
+ try {
35
+ return await this.customBlockResponseHeaders(context.requestData.request.getUnderlyingRequest());
36
+ }
37
+ catch (e) {
38
+ this.logger.debug(`Exception occurred in px_cors_create_custom_block_response_headers custom function: ${e}`);
49
39
  }
50
- return this.getDefaultCorsHeaders(context);
51
- });
40
+ }
41
+ return this.getDefaultCorsHeaders(context);
52
42
  }
53
43
  getDefaultCorsHeaders(context) {
54
44
  return {
@@ -1,18 +1,9 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  export var CustomParametersUtils;
11
2
  (function (CustomParametersUtils) {
12
- CustomParametersUtils.createCustomParameters = (config, context) => __awaiter(this, void 0, void 0, function* () {
3
+ CustomParametersUtils.createCustomParameters = async (config, context) => {
13
4
  if (config.enrichCustomParameters && typeof config.enrichCustomParameters === 'function') {
14
5
  try {
15
- const parameters = yield config.enrichCustomParameters(config.toParams(), context.requestData.request.getUnderlyingRequest());
6
+ const parameters = await config.enrichCustomParameters(config.toParams(), context.requestData.request.getUnderlyingRequest());
16
7
  return CustomParametersUtils.normalizeCustomParams(parameters);
17
8
  }
18
9
  catch (e) {
@@ -20,7 +11,7 @@ export var CustomParametersUtils;
20
11
  }
21
12
  }
22
13
  return null;
23
- });
14
+ };
24
15
  CustomParametersUtils.normalizeCustomParams = (customParameters) => {
25
16
  const normalizedParams = {};
26
17
  if (customParameters && typeof customParameters === 'object') {
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { DefaultDataEnrichment } from '../pxde';
11
2
  import { DefaultTelemetry } from '../telemetry';
12
3
  import { DefaultTokenV2Parser, DefaultTokenV3Parser, TokenVersion } from '../risk_token';
@@ -18,6 +9,12 @@ import { HttpActivityClient, HttpBatchedActivityClient } from '../activities';
18
9
  import { DefaultGraphQLParser } from '../graphql';
19
10
  import { HttpLogServiceClient } from '../logger';
20
11
  export class EnforcerBase {
12
+ config;
13
+ filterFlow;
14
+ enforceFlow;
15
+ postEnforceFlow;
16
+ endEnforcerFlow;
17
+ activityClient;
21
18
  /**
22
19
  * The EnforcerBase constructor.
23
20
  * @param config - The enforcer configuration.
@@ -38,20 +35,18 @@ export class EnforcerBase {
38
35
  * @param args - The EnforceArgs required to enforce the incoming request.
39
36
  * @returns Promise<Res|null> - A Promise resolving to a Res or null depending on the action that should be taken.
40
37
  */
41
- enforce(...args) {
42
- return __awaiter(this, void 0, void 0, function* () {
43
- try {
44
- if (!this.config.moduleEnabled) {
45
- this.config.logger.debug('module is disabled, will not enforce');
46
- return null;
47
- }
48
- return yield this.doEnforce(...args);
49
- }
50
- catch (e) {
51
- this.config.logger.error(`caught error in enforce - ${e}`);
38
+ async enforce(...args) {
39
+ try {
40
+ if (!this.config.moduleEnabled) {
41
+ this.config.logger.debug('module is disabled, will not enforce');
52
42
  return null;
53
43
  }
54
- });
44
+ return await this.doEnforce(...args);
45
+ }
46
+ catch (e) {
47
+ this.config.logger.error(`caught error in enforce - ${e}`);
48
+ return null;
49
+ }
55
50
  }
56
51
  /**
57
52
  * Performs all enforcer functionality on the incoming request context.
@@ -59,22 +54,20 @@ export class EnforcerBase {
59
54
  * @returns Promise<Res|null> - A Promise resolving to a Res or null depending on the action that should be taken.
60
55
  * @protected
61
56
  */
62
- doEnforce(...args) {
63
- return __awaiter(this, void 0, void 0, function* () {
64
- const context = yield this.constructContext(...args);
65
- let result = yield this.filterFlow.execute(context);
66
- if (result.done) {
67
- yield this.endEnforcerFlow.execute(context);
68
- return result.response ? this.convertToRes(result.response, ...args) : null;
69
- }
70
- this.preserveContext(context, ...args);
71
- result = yield this.enforceFlow.execute(context);
72
- if (result.response) {
73
- yield this.endEnforcerFlow.execute(context);
74
- return this.convertToRes(result.response, ...args);
75
- }
76
- return null;
77
- });
57
+ async doEnforce(...args) {
58
+ const context = await this.constructContext(...args);
59
+ let result = await this.filterFlow.execute(context);
60
+ if (result.done) {
61
+ await this.endEnforcerFlow.execute(context);
62
+ return result.response ? this.convertToRes(result.response, ...args) : null;
63
+ }
64
+ this.preserveContext(context, ...args);
65
+ result = await this.enforceFlow.execute(context);
66
+ if (result.done) {
67
+ await this.endEnforcerFlow.execute(context);
68
+ return result.response ? this.convertToRes(result.response, ...args) : null;
69
+ }
70
+ return null;
78
71
  }
79
72
  /**
80
73
  * Performs all required functionality after an origin response has been received.
@@ -82,28 +75,24 @@ export class EnforcerBase {
82
75
  * @returns Promise<void> - The response parameter will be modified as needed
83
76
  * @protected
84
77
  */
85
- postEnforce(...args) {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- try {
88
- const context = this.retrieveContext(...args);
89
- if (context) {
90
- context.response = yield this.convertToOutgoingResponse(...args);
91
- yield this.postEnforceFlow.execute(context);
92
- }
93
- yield this.endEnforcerFlow.execute(context);
94
- }
95
- catch (e) {
96
- this.config.logger.error(`caught error in post enforce - ${e}`);
97
- }
98
- });
99
- }
100
- sendAdditionalS2SActivity(...args) {
101
- return __awaiter(this, void 0, void 0, function* () {
78
+ async postEnforce(...args) {
79
+ try {
102
80
  const context = this.retrieveContext(...args);
103
81
  if (context) {
104
- yield this.activityClient.sendActivities(context);
82
+ context.response = await this.convertToOutgoingResponse(...args);
83
+ await this.postEnforceFlow.execute(context);
84
+ await this.endEnforcerFlow.execute(context);
105
85
  }
106
- });
86
+ }
87
+ catch (e) {
88
+ this.config.logger.error(`caught error in post enforce - ${e}`);
89
+ }
90
+ }
91
+ async sendAdditionalS2SActivity(...args) {
92
+ const context = this.retrieveContext(...args);
93
+ if (context) {
94
+ await this.activityClient.sendActivities(context);
95
+ }
107
96
  }
108
97
  /**
109
98
  * Returns the components needed to initialize the enforcer according to the provided options. If no
@@ -149,20 +138,20 @@ export class EnforcerBase {
149
138
  logServiceClient,
150
139
  };
151
140
  const products = this.initializeProducts(config, options.products, base64Utils, hashUtils, ipRangeChecker);
152
- return Object.assign({ products }, allOptions);
141
+ return { products, ...allOptions };
153
142
  }
154
143
  initializeProducts(config, products, base64Utils, hashUtils, ipRangeChecker) {
155
- const botDefender = (products === null || products === void 0 ? void 0 : products.bd) || new BotDefender(config, { base64Utils, ipRangeChecker });
156
- const accountDefender = (products === null || products === void 0 ? void 0 : products.ad) || new AccountDefender(config, { base64Utils });
144
+ const botDefender = products?.bd || new BotDefender(config, { base64Utils, ipRangeChecker });
145
+ const accountDefender = products?.ad || new AccountDefender(config, { base64Utils });
157
146
  const credentialIntelligence = config.ciEnabled
158
- ? (products === null || products === void 0 ? void 0 : products.ci) || new CredentialIntelligence(config, hashUtils)
147
+ ? products?.ci || new CredentialIntelligence(config, hashUtils)
159
148
  : null;
160
149
  return {
161
150
  [ProductName.BOT_DEFENDER]: botDefender,
162
151
  [ProductName.ACCOUNT_DEFENDER]: accountDefender,
163
- [ProductName.CODE_DEFENDER]: products === null || products === void 0 ? void 0 : products.cd,
152
+ [ProductName.CODE_DEFENDER]: products?.cd,
164
153
  [ProductName.CREDENTIAL_INTELLIGENCE]: credentialIntelligence,
165
- [ProductName.HYPE_SALE_CHALLENGE]: products === null || products === void 0 ? void 0 : products.hsc,
154
+ [ProductName.HYPE_SALE_CHALLENGE]: products?.hsc,
166
155
  };
167
156
  }
168
157
  }