-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathEnvUtils.ts
More file actions
582 lines (509 loc) · 18.3 KB
/
EnvUtils.ts
File metadata and controls
582 lines (509 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
"use strict";
import { getGlobal, strShimObject, strShimPrototype, strShimUndefined } from "@microsoft/applicationinsights-shims";
import {
ICachedValue, arrForEach, createCachedValue, getDeferred, getDocument, getInst, getLazy, getNavigator, getPerformance, hasNavigator,
isFunction, isNullOrUndefined, isString, isUndefined, mathMax, strIndexOf, strSubstring
} from "@nevware21/ts-utils";
import { DEFAULT_SENSITIVE_PARAMS, STR_EMPTY, STR_REDACTED } from "../constants/InternalConstants";
import { UrlRedactionOptions } from "../enums/ai/UrlRedactionOptions";
import { IConfiguration } from "../interfaces/ai/IConfiguration";
import { strContains } from "./HelperFuncs";
// TypeScript removed this interface so we need to declare the global so we can check for it's existence.
declare var XDomainRequest: any;
/**
* This file exists to hold environment utilities that are required to check and
* validate the current operating environment. Unless otherwise required, please
* only use defined methods (functions) in this class so that users of these
* functions/properties only need to include those that are used within their own modules.
*/
const strDocumentMode = "documentMode";
const strLocation = "location";
const strConsole = "console";
const strJSON = "JSON";
const strCrypto = "crypto";
const strMsCrypto = "msCrypto";
const strReactNative = "ReactNative";
const strMsie = "msie";
const strTrident = "trident/";
const strXMLHttpRequest = "XMLHttpRequest";
// Local cached properties which are used to avoid multiple checks within the module
let _isTrident: ICachedValue<boolean>;
let _navUserAgentCheck: string;
let _enableMocks = false;
let _useXDomainRequest: ICachedValue<boolean>;
let _beaconsSupported: ICachedValue<boolean>;
let _userAgent: ICachedValue<string>;
function _hasProperty(theClass: any, property: string) {
let supported = false;
if (theClass) {
try {
supported = property in theClass;
if (!supported) {
let proto = theClass[strShimPrototype];
if (proto) {
supported = property in proto;
}
}
} catch (e) {
// Do Nothing
}
if (!supported) {
try {
let tmp = new theClass();
supported = !isUndefined(tmp[property]);
} catch (e) {
// Do Nothing
}
}
}
return supported;
}
/*#__NO_SIDE_EFFECTS__*/
export function getUserAgentString(): string {
if (!_userAgent) {
// Use lazy to allow mocking
_userAgent = getLazy(() => {
let nav = getNavigator() || {} as Navigator;
return nav.userAgent || STR_EMPTY;
});
}
return _userAgent.v;
}
/**
* Enable the lookup of test mock objects if requested
* @param enabled - A flag to enable or disable the mock
*/
export function setEnableEnvMocks(enabled: boolean) {
_enableMocks = enabled;
}
/**
* Returns the global location object if it is present otherwise null.
* This helper is used to access the location object without causing an exception
* "Uncaught ReferenceError: location is not defined"
*/
/*#__NO_SIDE_EFFECTS__*/
export function getLocation(checkForMock?: boolean): Location | null {
if (checkForMock && _enableMocks) {
let mockLocation = getInst("__mockLocation") as Location;
if (mockLocation) {
return mockLocation;
}
}
if (typeof location === strShimObject && location) {
return location;
}
return getInst(strLocation);
}
/**
* Returns the global console object
*/
/*#__NO_SIDE_EFFECTS__*/
export function getConsole(): Console | null {
if (typeof console !== strShimUndefined) {
return console;
}
return getInst(strConsole);
}
/**
* Checks if JSON object is available, this is required as we support the API running without a
* window /document (eg. Node server, electron webworkers) and if we attempt to assign a history
* object to a local variable or pass as an argument an "Uncaught ReferenceError: JSON is not defined"
* exception will be thrown.
* Defined as a function to support lazy / late binding environments.
*/
/*#__NO_SIDE_EFFECTS__*/
export function hasJSON(): boolean {
return Boolean((typeof JSON === strShimObject && JSON) || getInst(strJSON) !== null);
}
/**
* Returns the global JSON object if it is present otherwise null.
* This helper is used to access the JSON object without causing an exception
* "Uncaught ReferenceError: JSON is not defined"
*/
/*#__NO_SIDE_EFFECTS__*/
export function getJSON(): JSON | null {
if (hasJSON()) {
return JSON || getInst(strJSON);
}
return null;
}
/**
* Returns the crypto object if it is present otherwise null.
* This helper is used to access the crypto object from the current
* global instance which could be window or globalThis for a web worker
*/
/*#__NO_SIDE_EFFECTS__*/
export function getCrypto(): Crypto | null {
return getInst(strCrypto);
}
/**
* Returns the crypto object if it is present otherwise null.
* This helper is used to access the crypto object from the current
* global instance which could be window or globalThis for a web worker
*/
/*#__NO_SIDE_EFFECTS__*/
export function getMsCrypto(): Crypto | null {
return getInst(strMsCrypto);
}
/**
* Returns whether the environment is reporting that we are running in a React Native Environment
*/
/*#__NO_SIDE_EFFECTS__*/
export function isReactNative(): boolean {
// If running in React Native, navigator.product will be populated
var nav = getNavigator();
if (nav && nav.product) {
return nav.product === strReactNative;
}
return false;
}
/**
* Identifies whether the current environment appears to be IE
*/
/*#__NO_SIDE_EFFECTS__*/
export function isIE() {
let userAgent = getUserAgentString();
if (!_isTrident || userAgent !== _navUserAgentCheck) {
// Added to support test mocking of the user agent
_navUserAgentCheck = userAgent;
let lwrUserAgent = _navUserAgentCheck.toLowerCase();
_isTrident = createCachedValue( strContains(lwrUserAgent, strMsie) || strContains(lwrUserAgent, strTrident));
}
return _isTrident.v;
}
/**
* Gets IE version returning the document emulation mode if we are running on IE, or null otherwise
*/
/*#__NO_SIDE_EFFECTS__*/
export function getIEVersion(userAgentStr: string = null): number {
if (!userAgentStr) {
userAgentStr = getUserAgentString();
}
var ua = (userAgentStr || STR_EMPTY).toLowerCase();
// Also check for documentMode in case X-UA-Compatible meta tag was included in HTML.
if (strContains(ua, strMsie)) {
let doc = getDocument() || {} as Document;
return mathMax(parseInt(ua.split(strMsie)[1]), (doc[strDocumentMode] || 0));
} else if (strContains(ua, strTrident)) {
let tridentVer = parseInt(ua.split(strTrident)[1]);
if (tridentVer) {
return tridentVer + 4;
}
}
return null;
}
/*#__NO_SIDE_EFFECTS__*/
export function isSafari(userAgentStr ?: string) {
if (!userAgentStr || !isString(userAgentStr)) {
userAgentStr = getUserAgentString().toLowerCase();
}
var ua = (userAgentStr || STR_EMPTY).toLowerCase();
return (strIndexOf(ua, "safari") >= 0);
}
/**
* Checks if HTML5 Beacons are supported in the current environment. There is a side effect (for testing)
* when `useCached` is set to `false`, it will reset the cached value causing all future calls to
* use the new re-evaluated value for all future calls.
* @param useCached - [Optional] used for testing to bypass the cached lookup, when `true` this will
* cause the cached global to be reset.
* @returns True if supported, false otherwise.
*/
export function isBeaconsSupported(useCached?: boolean): boolean {
if (!_beaconsSupported || useCached === false) {
_beaconsSupported = createCachedValue(hasNavigator() && !!(getNavigator().sendBeacon));
}
return _beaconsSupported.v;
}
/**
* Checks if the Fetch API is supported in the current environment.
* @param withKeepAlive - [Optional] If True, check if fetch is available and it supports the keepalive feature, otherwise only check if fetch is supported
* @returns True if supported, otherwise false
*/
/*#__NO_SIDE_EFFECTS__*/
export function isFetchSupported(withKeepAlive?: boolean): boolean {
let isSupported = false;
try {
isSupported = !!getInst("fetch");
const request = getInst("Request");
if (isSupported && withKeepAlive && request) {
isSupported = _hasProperty(request, "keepalive");
}
} catch (e) {
// Just Swallow any failure during availability checks
}
return isSupported;
}
/*#__NO_SIDE_EFFECTS__*/
export function useXDomainRequest(): boolean | undefined {
if (!_useXDomainRequest) {
_useXDomainRequest = getDeferred(() => {
let useXDomainRequest = (typeof XDomainRequest !== strShimUndefined);
if (useXDomainRequest && isXhrSupported()) {
useXDomainRequest = useXDomainRequest && !_hasProperty(getInst(strXMLHttpRequest), "withCredentials");
}
return !!useXDomainRequest;
});
}
return _useXDomainRequest.v;
}
/**
* Checks if XMLHttpRequest is supported
* @returns True if supported, otherwise false
*/
/*#__NO_SIDE_EFFECTS__*/
export function isXhrSupported(): boolean {
let isSupported = false;
try {
const xmlHttpRequest = getInst(strXMLHttpRequest);
isSupported = !!xmlHttpRequest;
} catch (e) {
// Just Swallow any failure during availability checks
}
return isSupported;
}
/*#__NO_SIDE_EFFECTS__*/
function _getNamedValue<T>(values: any, name: string): T[] {
let items: T[] = [];
if (values) {
arrForEach(values, (value) => {
if (value.name) {
if(value.name === name) {
items.push(value);
}
}
});
}
return items;
}
/**
* Helper function to fetch the named meta-tag from the page.
* @param name - The name of the meta-tag to find.
*/
/*#__NO_SIDE_EFFECTS__*/
export function findMetaTag(name: string): any {
let tags = findMetaTags(name);
if (tags.length > 0) {
return tags[0];
}
return null;
}
/**
* Helper function to fetch all named meta-tag from the page.
* @since 3.4.0
* @param name - The name of the meta-tag to find.
* @returns - An array of meta-tag values.
*/
/*#__NO_SIDE_EFFECTS__*/
export function findMetaTags(name: string): string[] {
let tags: string[] = [];
let doc = getDocument();
if (doc && name) {
// Look for a meta-tag
arrForEach(_getNamedValue<any>(doc.querySelectorAll("meta"), name), (item) => {
tags.push(item.content);
});
}
return tags;
}
/**
* Helper function to fetch the named server timing value from the page response (first navigation event).
* @param name - The name of the server timing value to find.
*/
/*#__NO_SIDE_EFFECTS__*/
export function findNamedServerTiming(name: string): any {
let value: any;
let serverTimings = findNamedServerTimings(name);
if (serverTimings.length > 0) {
value = serverTimings[0];
}
return value;
}
/**
* Helper function to fetch the named server timing value from the page response (first navigation event).
* @since 3.4.0
* @param name - The name of the server timing value to find.
* @returns - An array of server timing values.
*/
/*#__NO_SIDE_EFFECTS__*/
export function findNamedServerTimings(name: string): string[] {
let values: string[] = [];
let perf = getPerformance();
if (perf && perf.getEntriesByType) {
// Try looking for a server-timing header
arrForEach(perf.getEntriesByType("navigation") || [], (navPerf: any) => {
arrForEach(_getNamedValue(navPerf.serverTiming, name), (value: any) => {
let desc = value.description;
if (!isNullOrUndefined(desc)) {
values.push(desc);
}
});
});
}
return values;
}
// TODO: should reuse this method for analytics plugin
export function dispatchEvent(target:EventTarget, evnt: Event | CustomEvent): boolean {
if (target && target.dispatchEvent && evnt) {
target.dispatchEvent(evnt);
return true;
}
return false;
}
/*#__NO_SIDE_EFFECTS__*/
export function createCustomDomEvent(eventName: string, details?: any): CustomEvent {
let event: CustomEvent = null;
let detail = {detail: details || null } as CustomEventInit;
if (isFunction(CustomEvent)) { // Use CustomEvent constructor when available
event = new CustomEvent(eventName, detail);
} else { // CustomEvent has no constructor in IE
let doc = getDocument();
if (doc && doc.createEvent) {
event = doc.createEvent("CustomEvent");
event.initCustomEvent(eventName, true, true, detail);
}
}
return event;
}
export function sendCustomEvent(evtName: string, cfg?: any, customDetails?: any): boolean {
let global = getGlobal();
if (global && (global as any).CustomEvent) {
try {
let details = {cfg: cfg || null, customDetails: customDetails || null} as any;
return dispatchEvent(global, createCustomDomEvent(evtName, details));
} catch(e) {
// eslint-disable-next-line no-empty
}
}
return false;
}
/**
* Redacts user information from a URL
* @param url - The URL string to redact
* @returns The URL with user information redacted
*/
/*#__NO_SIDE_EFFECTS__*/
function redactUserInfo(url: string): string {
return url.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@]{1,200}):([^@]{1,200})@(.*)$/, "$1REDACTED:REDACTED@$4");
}
/**
* Redacts sensitive query parameters from a URL
* @param url - The URL string to redact
* @returns The URL with sensitive query parameters redacted
*/
/*#__NO_SIDE_EFFECTS__*/
function redactQueryParameters(url: string, config?: IConfiguration): string {
let sensitiveParams: string[];
const questionMarkIndex = strIndexOf(url, "?");
if (questionMarkIndex === -1) {
return url;
}
if (config && config.redactUrls === UrlRedactionOptions.append) {
sensitiveParams = DEFAULT_SENSITIVE_PARAMS.concat(config.redactQueryParams);
} else if (config && config.redactUrls === UrlRedactionOptions.replace) {
sensitiveParams = config.redactQueryParams;
} else {
sensitiveParams = DEFAULT_SENSITIVE_PARAMS;
}
const baseUrl = strSubstring(url, 0, questionMarkIndex + 1);
let queryString = strSubstring(url, questionMarkIndex + 1);
let fragment = STR_EMPTY;
const hashIndex = strIndexOf(queryString, "#");
if (hashIndex !== -1) {
fragment = strSubstring(queryString, hashIndex);
queryString = strSubstring(queryString, 0, hashIndex);
}
let hasPotentialSensitiveParam = false;
for (let i = 0; i < sensitiveParams.length; i++) {
const paramCheck = sensitiveParams[i] + "=";
if (strIndexOf(queryString, paramCheck) !== -1) {
hasPotentialSensitiveParam = true;
break;
}
}
if (!hasPotentialSensitiveParam) {
return url;
}
const resultParts: string[] = [];
let anyParamRedacted = false;
if (queryString && queryString.length) {
const pairs = queryString.split("&");
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i];
if (!pair) {
continue;
}
const equalsIndex = strIndexOf(pair, "=");
if (equalsIndex === -1) {
// Parameter without value
resultParts.push(pair);
} else {
const paramName = pair.substring(0, equalsIndex);
const paramValue = pair.substring(equalsIndex + 1);
if (paramValue === STR_EMPTY) {
resultParts.push(pair);
} else {
let shouldRedact = false;
for (let j = 0; j < sensitiveParams.length; j++) {
if (paramName === sensitiveParams[j]) {
shouldRedact = true;
anyParamRedacted = true;
break;
}
}
if (shouldRedact) {
resultParts.push(paramName + "=" + STR_REDACTED);
} else {
resultParts.push(pair);
}
}
}
}
}
// If no parameters were redacted, return the original URL
if (!anyParamRedacted) {
return url;
}
return baseUrl + resultParts.join("&") + fragment;
}
/**
* Redacts sensitive information from a URL string, including credentials and specific query parameters.
* @param input - The URL string to be redacted.
* @param config - Configuration object that contain redactUrls setting.
* @returns The redacted URL string or the original string if no redaction was needed or possible.
*/
/*#__NO_SIDE_EFFECTS__*/
export function fieldRedaction(input: string, config: IConfiguration): string {
if (!input || !isString(input) || strIndexOf(input, " ") !== -1) {
return input;
}
const isRedactionDisabled = config && (config.redactUrls === false || config.redactUrls === UrlRedactionOptions.false);
if (isRedactionDisabled) {
return input;
}
let hasCredentials = strIndexOf(input, "@") !== -1;
let hasQueryParams = strIndexOf(input, "?") !== -1;
// If no credentials and no query params, return original
if (!hasCredentials && !hasQueryParams) {
return input;
}
if (config.redactUrls === UrlRedactionOptions.usernamePasswordOnly) {
hasQueryParams = false;
}
if (config.redactUrls === UrlRedactionOptions.queryParamsOnly) {
hasCredentials = false;
}
try {
let result = input;
if (hasCredentials) {
result = redactUserInfo(input);
}
if (hasQueryParams) {
result = redactQueryParameters(result, config);
}
return result;
} catch (e) {
return input;
}
}