/
index.js
315 lines (259 loc) · 10.1 KB
/
index.js
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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Platform} from 'react-native';
import * as Sentry from '@sentry/react-native';
import Config from 'assets/config';
import {Client4} from 'mattermost-redux/client';
import {getConfig} from 'mattermost-redux/selectors/entities/general';
import {getCurrentUser} from 'mattermost-redux/selectors/entities/users';
import {getCurrentTeam, getCurrentTeamMembership} from 'mattermost-redux/selectors/entities/teams';
import {getCurrentChannel, getMyCurrentChannelMembership} from 'mattermost-redux/selectors/entities/channels';
export const LOGGER_EXTENSION = 'extension';
export const LOGGER_JAVASCRIPT = 'javascript';
export const LOGGER_JAVASCRIPT_WARNING = 'javascript_warning';
export const LOGGER_NATIVE = 'native';
export const LOGGER_REDUX = 'redux';
export const BREADCRUMB_UNCAUGHT_APP_ERROR = 'uncaught-app-error';
export const BREADCRUMB_UNCAUGHT_NON_ERROR = 'uncaught-non-error';
export function initializeSentry() {
if (!Config.SentryEnabled) {
return;
}
const dsn = getDsn();
if (!dsn) {
console.warn('Sentry is enabled, but not configured on this platform'); // eslint-disable-line no-console
return;
}
Sentry.init({dsn, ...Config.SentryOptions});
}
function getDsn() {
if (Platform.OS === 'android') {
return Config.SentryDsnAndroid;
} else if (Platform.OS === 'ios') {
return Config.SentryDsnIos;
}
return '';
}
export function captureJSException(error, isFatal, store) {
if (!error || !store) {
console.warn('captureJSException called with missing arguments', error, store); // eslint-disable-line no-console
return;
}
if (error instanceof Error) {
captureException(error, LOGGER_JAVASCRIPT, store);
} else {
captureNonErrorAsBreadcrumb(error, isFatal);
}
}
export function captureException(error, logger, store) {
if (!error || !logger || !store) {
console.warn('captureException called with missing arguments', error, logger, store); // eslint-disable-line no-console
return;
}
capture(() => {
Sentry.captureException(error, {logger});
}, store);
}
export function captureExceptionWithoutState(err, logger) {
if (!Config.SentryEnabled) {
return;
}
if (err && logger) {
try {
Sentry.captureException(err, {logger});
} catch (error) {
// do nothing...
}
}
}
export function captureMessage(message, logger, store) {
if (message && logger && store) {
capture(() => {
Sentry.captureMessage(message, {logger});
}, store);
}
}
export function captureNonErrorAsBreadcrumb(obj, isFatal) {
if (!obj || typeof obj !== 'object') {
console.warning('Invalid object passed to captureNonErrorAsBreadcrumb', obj); // eslint-disable-line no-console
return;
}
const isAppError = Boolean(obj.server_error_id);
const breadcrumb = {
category: isAppError ? BREADCRUMB_UNCAUGHT_APP_ERROR : BREADCRUMB_UNCAUGHT_NON_ERROR,
data: {
isFatal: String(isFatal),
},
level: 'warn',
};
if (obj.message) {
breadcrumb.message = obj.message;
} else if (obj.intl && obj.intl.defaultMessage) {
breadcrumb.message = obj.intl.defaultMessage;
} else {
breadcrumb.message = 'no message provided';
}
if (obj.server_error_id) {
breadcrumb.data.server_error_id = obj.server_error_id;
}
if (obj.status_code) {
breadcrumb.data.status_code = obj.status_code;
}
if (obj.url) {
const match = (/^(?:https?:\/\/)[^/]+(\/.*)$/);
if (match && match.length >= 2) {
breadcrumb.data.url = match[1];
}
}
try {
Sentry.addBreadcrumb(breadcrumb);
} catch (e) {
// Do nothing since this is only here to make sure we don't crash when handling an exception
console.warn('Failed to capture breadcrumb of non-error', e); // eslint-disable-line no-console
}
}
// Wrapper function to any calls to Sentry so that we can gather any necessary extra data
// before sending.
function capture(captureFunc, store) {
if (!Config.SentryEnabled) {
return;
}
try {
const state = store.getState();
const config = getConfig(state);
// Don't contact Sentry if we're connected to a server with diagnostics disabled. Note that this will
// still log if we're not connected to any server.
if (config && config.EnableDiagnostics != null && config.EnableDiagnostics !== 'true') {
return;
}
let hasUserContext = false;
const userContext = getUserContext(state);
if (Object.keys(userContext).length) {
hasUserContext = true;
Sentry.setUserContext(userContext);
}
const extraContext = getExtraContext(state);
if (Object.keys(extraContext).length) {
Sentry.setExtraContext(extraContext);
}
const buildTags = getBuildTags(state);
if (Object.keys(buildTags).length) {
Sentry.setTagsContext(buildTags);
}
if (hasUserContext) {
console.warn('Capturing with Sentry at ' + getDsn() + '...'); // eslint-disable-line no-console
captureFunc();
} else {
console.warn('No user context, skipping capture'); // eslint-disable-line no-console
}
} catch (e) {
// Don't want this to get into an infinite loop again...
console.warn('Exception occured while sending to Sentry'); // eslint-disable-line no-console
console.warn(e); // eslint-disable-line no-console
}
}
function getUserContext(state) {
const currentUser = getCurrentUser(state);
if (!currentUser) {
return {};
}
return {
userID: currentUser.id, // This can be changed to id after we upgrade to Sentry >= 0.14.10,
email: '',
username: '',
extra: {
locale: currentUser.locale,
roles: currentUser.roles,
},
};
}
function getExtraContext(state) {
const context = {};
const currentTeam = getCurrentTeam(state);
if (currentTeam) {
context.currentTeam = {
id: currentTeam.id,
};
}
const currentTeamMember = getCurrentTeamMembership(state);
if (currentTeamMember) {
context.currentTeamMember = {
roles: currentTeamMember.roles,
};
}
const currentChannel = getCurrentChannel(state);
if (currentChannel) {
context.currentChannel = {
id: currentChannel.id,
type: currentChannel.type,
};
}
const currentChannelMember = getMyCurrentChannelMembership(state);
if (currentChannelMember) {
context.currentChannelMember = {
roles: currentChannelMember.roles,
};
}
const config = getConfig(state);
if (config) {
context.config = {
BuildDate: config.BuildDate,
BuildEnterpriseReady: config.BuildEnterpriseReady,
BuildHash: config.BuildHash,
BuildHashEnterprise: config.BuildHashEnterprise,
BuildNumber: config.BuildNumber,
};
}
return context;
}
function getBuildTags(state) {
const tags = {};
const config = getConfig(state);
if (config) {
tags.serverBuildHash = config.BuildHash;
tags.serverBuildNumber = config.BuildNumber;
}
return tags;
}
// Given a URL from an API request, return a URL that has any parts removed that are either sensitive or that would
// prevent properly grouping the messages in Sentry.
export function cleanUrlForLogging(original) {
let url = original;
// Trim the host name
url = url.substring(Client4.getUrl().length);
// Filter the query string
const index = url.indexOf('?');
if (index !== -1) {
url = url.substring(0, index);
}
// A non-exhaustive whitelist to exclude parts of the URL that are unimportant (eg IDs) or may be sentsitive
// (eg email addresses). We prefer filtering out fields that aren't recognized because there should generally
// be enough left over for debugging.
//
// Note that new API routes don't need to be added here since this shouldn't be happening for newly added routes.
const whitelist = [
'api', 'v4', 'users', 'teams', 'scheme', 'name', 'members', 'channels', 'posts', 'reactions', 'commands',
'files', 'preferences', 'hooks', 'incoming', 'outgoing', 'oauth', 'apps', 'emoji', 'brand', 'image',
'data_retention', 'jobs', 'plugins', 'roles', 'system', 'timezones', 'schemes', 'redirect_location', 'patch',
'mfa', 'password', 'reset', 'send', 'active', 'verify', 'terms_of_service', 'login', 'logout', 'ids',
'usernames', 'me', 'username', 'email', 'default', 'sessions', 'revoke', 'all', 'audits', 'device', 'status',
'search', 'switch', 'authorized', 'authorize', 'deauthorize', 'tokens', 'disable', 'enable', 'exists', 'unread',
'invite', 'batch', 'stats', 'import', 'schemeRoles', 'direct', 'group', 'convert', 'view', 'search_autocomplete',
'thread', 'info', 'flagged', 'pinned', 'pin', 'unpin', 'opengraph', 'actions', 'thumbnail', 'preview', 'link',
'delete', 'logs', 'ping', 'config', 'client', 'license', 'websocket', 'webrtc', 'token', 'regen_token',
'autocomplete', 'execute', 'regen_secret', 'policy', 'type', 'cancel', 'reload', 'environment', 's3_test', 'file',
'caches', 'invalidate', 'database', 'recycle', 'compliance', 'reports', 'cluster', 'ldap', 'test', 'sync', 'saml',
'certificate', 'public', 'private', 'idp', 'elasticsearch', 'purge_indexes', 'analytics', 'old', 'webapp', 'fake',
];
url = url.split('/').map((part) => {
if (part !== '' && whitelist.indexOf(part) === -1) {
return '<filtered>';
}
return part;
}).join('/');
if (index !== -1) {
// Add this on afterwards since it wouldn't pass the whitelist
url += '?<filtered>';
}
return url;
}