-
Notifications
You must be signed in to change notification settings - Fork 541
/
index.ts
165 lines (148 loc) · 4.58 KB
/
index.ts
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
import * as createDebug from 'debug';
import * as needle from 'needle';
import stripAnsi = require('strip-ansi');
import { getAuthHeader, someTokenExists } from '../api-token';
import config from '../config';
import { makeRequest } from '../request';
import { config as userConfig } from '../user-config';
import { getStandardData } from './getStandardData';
// Add flags whose values should be redacted in analytics here.
// TODO make this less error-prone by baking the concept of sensitivity into the
// flag-parsing code, but this is a start.
const sensitiveFlags = [
'tfc-token',
'azurerm-account-key',
'fetch-tfstate-headers',
];
const debug = createDebug('snyk');
const metadata = {};
// analytics module is required at the beginning of the CLI run cycle
/**
*
* @param data the data to merge into that data which has been staged thus far (with the {@link add} function)
* and then sent to the backend.
*/
export function addDataAndSend(
data,
): Promise<void | { res: needle.NeedleResponse; body: any }> {
if (!data) {
data = {};
}
// merge any new data with data we picked up along the way
if (Array.isArray(data.args)) {
// this is an overhang from the cli/args.js and we don't want it
delete (data.args.slice(-1).pop() || {})._;
data.args.forEach((argObj) => {
if (typeof argObj === 'object') {
Object.keys(argObj).forEach((field) => {
if (sensitiveFlags.includes(field)) {
argObj[field] = 'REDACTED';
}
});
}
});
}
if (Object.keys(metadata).length) {
data.metadata = metadata;
}
return postAnalytics(data);
}
export function allowAnalytics(): boolean {
if (userConfig.get('disable-analytics') || config.DISABLE_ANALYTICS) {
return false;
} else {
return true;
}
}
/**
* Actually send the analytics to the backend. This can be used standalone to send only the data
* given by the data parameter, or called from {@link addDataAndSend}.
* @param customData the analytics data to send to the backend.
*/
async function postAnalytics(
customData,
): Promise<void | { res: needle.NeedleResponse; body: any }> {
// if the user opt'ed out of analytics, then let's bail out early
// ths applies to all sending to protect user's privacy
if (!allowAnalytics()) {
debug('analytics disabled');
return Promise.resolve();
}
try {
const standardData = await getStandardData(customData.args);
const analyticsData = {
...customData,
...standardData,
};
debug('analytics', JSON.stringify(analyticsData, null, ' '));
const headers = {};
if (someTokenExists()) {
headers['authorization'] = getAuthHeader();
}
const queryStringParams = {};
if (analyticsData.org) {
queryStringParams['org'] = analyticsData.org;
}
const queryString =
Object.keys(queryStringParams).length > 0 ? queryStringParams : undefined;
const res = await makeRequest({
body: {
data: analyticsData,
},
qs: queryString,
url: config.API + '/analytics/cli',
json: true,
method: 'post',
headers: headers,
});
return res;
} catch (err) {
debug('analytics', err); // this swallows the analytics error
}
}
/**
* Adds a key-value pair to the analytics data `metadata` field. This doesn't send the analytics, just stages it for
* sending later (via the {@link addDataAndSend} function).
* @param key
* @param value
*/
export function add(key: string, value: unknown): void {
if (typeof value === 'string') {
value = stripAnsi(value);
}
if (metadata[key]) {
switch (key) {
case 'iac-metrics':
break;
case 'iac-type':
if (typeof value === 'object') {
for (const type in value) {
if (metadata[key][type]) {
for (const metric in value[type]) {
metadata[key][type][metric] &&
typeof value[type][metric] === 'number'
? (metadata[key][type][metric] += value[type][metric])
: (metadata[key][type][metric] = value[type][metric]);
}
} else {
metadata[key][type] = value[type];
}
}
}
break;
default:
if (typeof value === 'number' && typeof metadata[key] === 'number') {
metadata[key] += value;
} else {
if (!Array.isArray(metadata[key])) {
metadata[key] = [metadata[key]];
}
Array.isArray(value)
? metadata[key].push(...value)
: metadata[key].push(value);
}
}
} else {
metadata[key] = value;
}
}