-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
handlers.ts
294 lines (269 loc) · 7.47 KB
/
handlers.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
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
import { captureException, getCurrentHub } from '@sentry/core';
import { SentryEvent } from '@sentry/types';
import { forget } from '@sentry/utils/async';
import { logger } from '@sentry/utils/logger';
import { serialize } from '@sentry/utils/object';
import * as cookie from 'cookie';
import * as domain from 'domain';
import * as http from 'http';
import * as os from 'os';
import * as url from 'url';
import { NodeClient } from './client';
const DEFAULT_SHUTDOWN_TIMEOUT = 2000;
type TransactionTypes = 'path' | 'methodPath' | 'handler';
/** JSDoc */
function extractTransaction(req: { [key: string]: any }, type: boolean | TransactionTypes): string | undefined {
try {
// Express.js shape
const request = req as {
method: string;
route: {
path: string;
stack: [
{
name: string;
}
];
};
};
switch (type) {
case 'path': {
return request.route.path;
}
case 'handler': {
return request.route.stack[0].name;
}
case 'methodPath':
default: {
const method = request.method.toUpperCase();
const path = request.route.path;
return `${method}|${path}`;
}
}
} catch (_oO) {
return undefined;
}
}
/** JSDoc */
function extractRequestData(req: { [key: string]: any }): { [key: string]: string } {
// headers:
// node, express: req.headers
// koa: req.header
const headers = (req.headers || req.header || {}) as {
host?: string;
cookie?: string;
};
// method:
// node, express, koa: req.method
const method = req.method;
// host:
// express: req.hostname in > 4 and req.host in < 4
// koa: req.host
// node: req.headers.host
const host = req.hostname || req.host || headers.host || '<no host>';
// protocol:
// node: <n/a>
// express, koa: req.protocol
const protocol =
req.protocol === 'https' || req.secure || ((req.socket || {}) as { encrypted?: boolean }).encrypted
? 'https'
: 'http';
// url (including path and query string):
// node, express: req.originalUrl
// koa: req.url
const originalUrl = (req.originalUrl || req.url) as string;
// absolute url
const absoluteUrl = `${protocol}://${host}${originalUrl}`;
// query string:
// node: req.url (raw)
// express, koa: req.query
const query = url.parse(originalUrl || '', false).query;
// cookies:
// node, express, koa: req.headers.cookie
const cookies = cookie.parse(headers.cookie || '');
// body data:
// node, express, koa: req.body
let data = req.body;
if (method === 'GET' || method === 'HEAD') {
if (typeof data === 'undefined') {
data = '<unavailable>';
}
}
if (data && typeof data !== 'string' && {}.toString.call(data) !== '[object String]') {
// Make sure the request body is a string
data = serialize(data);
}
// request interface
const request: {
[key: string]: any;
} = {
cookies,
data,
headers,
method,
query_string: query,
url: absoluteUrl,
};
return request;
}
/** Default user keys that'll be used to extract data from the request */
const DEFAULT_USER_KEYS = ['id', 'username', 'email'];
/** JSDoc */
function extractUserData(req: { [key: string]: any }, keys: boolean | string[]): { [key: string]: string } {
const user: { [key: string]: string } = {};
const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;
attributes.forEach(key => {
if ({}.hasOwnProperty.call(req.user, key)) {
user[key] = (req.user as { [key: string]: string })[key];
}
});
// client ip:
// node: req.connection.remoteAddress
// express, koa: req.ip
const ip =
req.ip ||
(req.connection &&
(req.connection as {
remoteAddress?: string;
}).remoteAddress);
if (ip) {
user.ip_address = ip as string;
}
return user;
}
/**
* Enriches passed event with request data.
*
*
* @param event Will be mutated and enriched with req data
* @param req Request object
* @param options object containing flags to enable functionality
*/
export function parseRequest(
event: SentryEvent,
req: {
[key: string]: any;
},
options?: {
request?: boolean;
serverName?: boolean;
transaction?: boolean | TransactionTypes;
user?: boolean | string[];
version?: boolean;
},
): SentryEvent {
// tslint:disable-next-line:no-parameter-reassignment
options = {
request: true,
serverName: true,
transaction: true,
user: true,
version: true,
...options,
};
if (options.version) {
event.extra = {
...event.extra,
node: global.process.version,
};
}
if (options.request) {
event.request = {
...event.request,
...extractRequestData(req),
};
}
if (options.serverName) {
event.server_name = global.process.env.SENTRY_NAME || os.hostname();
}
if (options.user && req.user) {
event.user = {
...event.user,
...extractUserData(req, options.user),
};
}
if (options.transaction) {
const transaction = extractTransaction(req, options.transaction);
if (transaction) {
event.transaction = transaction;
}
}
return event;
}
/** JSDoc */
export function requestHandler(options?: {
request?: boolean;
serverName?: boolean;
transaction?: boolean | TransactionTypes;
user?: boolean | string[];
version?: boolean;
}): (req: http.IncomingMessage, res: http.ServerResponse, next: (error?: any) => void) => void {
return function sentryRequestMiddleware(
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error?: any) => void,
): void {
const local = domain.create();
local.add(req);
local.add(res);
local.on('error', next);
local.run(() => {
getCurrentHub().configureScope(scope =>
scope.addEventProcessor(async (event: SentryEvent) => parseRequest(event, req, options)),
);
next();
});
};
}
/** JSDoc */
interface MiddlewareError extends Error {
status?: number | string;
statusCode?: number | string;
status_code?: number | string;
output?: {
statusCode?: number | string;
};
}
/** JSDoc */
function getStatusCodeFromResponse(error: MiddlewareError): number {
const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);
return statusCode ? parseInt(statusCode as string, 10) : 500;
}
/** JSDoc */
export function errorHandler(): (
error: MiddlewareError,
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error: MiddlewareError) => void,
) => void {
return function sentryErrorMiddleware(
error: MiddlewareError,
_req: http.IncomingMessage,
_res: http.ServerResponse,
next: (error: MiddlewareError) => void,
): void {
const status = getStatusCodeFromResponse(error);
if (status < 500) {
next(error);
return;
}
captureException(error);
next(error);
};
}
/** JSDoc */
export function defaultOnFatalError(error: Error): void {
console.error(error && error.stack ? error.stack : error);
const options = (getCurrentHub().getClient() as NodeClient).getOptions();
const timeout =
(options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||
DEFAULT_SHUTDOWN_TIMEOUT;
forget(
(getCurrentHub().getClient() as NodeClient).close(timeout).then((result: boolean) => {
if (!result) {
logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');
}
global.process.exit(1);
}),
);
}