1 | import { __assign } from "tslib";
|
2 |
|
3 |
|
4 | import { captureException, getCurrentHub, startTransaction, withScope } from '@sentry/core';
|
5 | import { extractTraceparentData } from '@sentry/tracing';
|
6 | import { RequestSessionStatus } from '@sentry/types';
|
7 | import { isPlainObject, isString, logger, normalize, stripUrlQueryAndFragment } from '@sentry/utils';
|
8 | import * as cookie from 'cookie';
|
9 | import * as domain from 'domain';
|
10 | import * as os from 'os';
|
11 | import * as url from 'url';
|
12 | import { flush, isAutoSessionTrackingEnabled } from './sdk';
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export function tracingHandler() {
|
18 | return function sentryTracingMiddleware(req, res, next) {
|
19 |
|
20 | var traceparentData;
|
21 | if (req.headers && isString(req.headers['sentry-trace'])) {
|
22 | traceparentData = extractTraceparentData(req.headers['sentry-trace']);
|
23 | }
|
24 | var transaction = startTransaction(__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData),
|
25 |
|
26 | { request: extractRequestData(req) });
|
27 |
|
28 | getCurrentHub().configureScope(function (scope) {
|
29 | scope.setSpan(transaction);
|
30 | });
|
31 |
|
32 |
|
33 |
|
34 | res.__sentry_transaction = transaction;
|
35 | res.once('finish', function () {
|
36 |
|
37 |
|
38 | setImmediate(function () {
|
39 | addExpressReqToTransaction(transaction, req);
|
40 | transaction.setHttpStatus(res.statusCode);
|
41 | transaction.finish();
|
42 | });
|
43 | });
|
44 | next();
|
45 | };
|
46 | }
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | function addExpressReqToTransaction(transaction, req) {
|
52 | if (!transaction)
|
53 | return;
|
54 | transaction.name = extractExpressTransactionName(req, { path: true, method: true });
|
55 | transaction.setData('url', req.originalUrl);
|
56 | transaction.setData('baseUrl', req.baseUrl);
|
57 | transaction.setData('query', req.query);
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | function extractExpressTransactionName(req, options) {
|
70 | if (options === void 0) { options = {}; }
|
71 | var _a;
|
72 | var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase();
|
73 | var path = '';
|
74 | if (req.route) {
|
75 | path = "" + (req.baseUrl || '') + req.route.path;
|
76 | }
|
77 | else if (req.originalUrl || req.url) {
|
78 | path = stripUrlQueryAndFragment(req.originalUrl || req.url || '');
|
79 | }
|
80 | var info = '';
|
81 | if (options.method && method) {
|
82 | info += method;
|
83 | }
|
84 | if (options.method && options.path) {
|
85 | info += " ";
|
86 | }
|
87 | if (options.path && path) {
|
88 | info += path;
|
89 | }
|
90 | return info;
|
91 | }
|
92 |
|
93 | function extractTransaction(req, type) {
|
94 | var _a;
|
95 | switch (type) {
|
96 | case 'path': {
|
97 | return extractExpressTransactionName(req, { path: true });
|
98 | }
|
99 | case 'handler': {
|
100 | return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || '<anonymous>';
|
101 | }
|
102 | case 'methodPath':
|
103 | default: {
|
104 | return extractExpressTransactionName(req, { path: true, method: true });
|
105 | }
|
106 | }
|
107 | }
|
108 |
|
109 | var DEFAULT_USER_KEYS = ['id', 'username', 'email'];
|
110 |
|
111 | function extractUserData(user, keys) {
|
112 | var extractedUser = {};
|
113 | var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;
|
114 | attributes.forEach(function (key) {
|
115 | if (user && key in user) {
|
116 | extractedUser[key] = user[key];
|
117 | }
|
118 | });
|
119 | return extractedUser;
|
120 | }
|
121 |
|
122 | var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 | export function extractRequestData(req, keys) {
|
132 | if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; }
|
133 | var requestData = {};
|
134 |
|
135 |
|
136 |
|
137 | var headers = (req.headers || req.header || {});
|
138 |
|
139 |
|
140 | var method = req.method;
|
141 |
|
142 |
|
143 |
|
144 |
|
145 | var host = req.hostname || req.host || headers.host || '<no host>';
|
146 |
|
147 |
|
148 |
|
149 | var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted
|
150 | ? 'https'
|
151 | : 'http';
|
152 |
|
153 |
|
154 |
|
155 | var originalUrl = (req.originalUrl || req.url || '');
|
156 |
|
157 | var absoluteUrl = protocol + "://" + host + originalUrl;
|
158 | keys.forEach(function (key) {
|
159 | switch (key) {
|
160 | case 'headers':
|
161 | requestData.headers = headers;
|
162 | break;
|
163 | case 'method':
|
164 | requestData.method = method;
|
165 | break;
|
166 | case 'url':
|
167 | requestData.url = absoluteUrl;
|
168 | break;
|
169 | case 'cookies':
|
170 |
|
171 |
|
172 |
|
173 |
|
174 | requestData.cookies = req.cookies || cookie.parse(headers.cookie || '');
|
175 | break;
|
176 | case 'query_string':
|
177 |
|
178 |
|
179 |
|
180 |
|
181 | requestData.query_string = req.query || url.parse(originalUrl || '', false).query;
|
182 | break;
|
183 | case 'data':
|
184 | if (method === 'GET' || method === 'HEAD') {
|
185 | break;
|
186 | }
|
187 |
|
188 |
|
189 |
|
190 |
|
191 |
|
192 |
|
193 | if (req.body !== undefined) {
|
194 | requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));
|
195 | }
|
196 | break;
|
197 | default:
|
198 | if ({}.hasOwnProperty.call(req, key)) {
|
199 | requestData[key] = req[key];
|
200 | }
|
201 | }
|
202 | });
|
203 | return requestData;
|
204 | }
|
205 |
|
206 |
|
207 |
|
208 |
|
209 |
|
210 |
|
211 |
|
212 |
|
213 | export function parseRequest(event, req, options) {
|
214 |
|
215 | options = __assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options);
|
216 | if (options.version) {
|
217 | event.contexts = __assign(__assign({}, event.contexts), { runtime: {
|
218 | name: 'node',
|
219 | version: global.process.version,
|
220 | } });
|
221 | }
|
222 | if (options.request) {
|
223 |
|
224 | var extractedRequestData = Array.isArray(options.request)
|
225 | ? extractRequestData(req, options.request)
|
226 | : extractRequestData(req);
|
227 | event.request = __assign(__assign({}, event.request), extractedRequestData);
|
228 | }
|
229 | if (options.serverName && !event.server_name) {
|
230 | event.server_name = global.process.env.SENTRY_NAME || os.hostname();
|
231 | }
|
232 | if (options.user) {
|
233 | var extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, options.user) : {};
|
234 | if (Object.keys(extractedUser)) {
|
235 | event.user = __assign(__assign({}, event.user), extractedUser);
|
236 | }
|
237 | }
|
238 |
|
239 |
|
240 |
|
241 | if (options.ip) {
|
242 | var ip = req.ip || (req.connection && req.connection.remoteAddress);
|
243 | if (ip) {
|
244 | event.user = __assign(__assign({}, event.user), { ip_address: ip });
|
245 | }
|
246 | }
|
247 | if (options.transaction && !event.transaction) {
|
248 |
|
249 |
|
250 | event.transaction = extractTransaction(req, options.transaction);
|
251 | }
|
252 | return event;
|
253 | }
|
254 |
|
255 |
|
256 |
|
257 |
|
258 | export function requestHandler(options) {
|
259 | var currentHub = getCurrentHub();
|
260 | var client = currentHub.getClient();
|
261 |
|
262 |
|
263 | if (client && isAutoSessionTrackingEnabled(client)) {
|
264 | client.initSessionFlusher();
|
265 |
|
266 | var scope = currentHub.getScope();
|
267 | if (scope && scope.getSession()) {
|
268 | scope.setSession();
|
269 | }
|
270 | }
|
271 | return function sentryRequestMiddleware(req, res, next) {
|
272 | if (options && options.flushTimeout && options.flushTimeout > 0) {
|
273 |
|
274 | var _end_1 = res.end;
|
275 | res.end = function (chunk, encoding, cb) {
|
276 | var _this = this;
|
277 | void flush(options.flushTimeout)
|
278 | .then(function () {
|
279 | _end_1.call(_this, chunk, encoding, cb);
|
280 | })
|
281 | .then(null, function (e) {
|
282 | logger.error(e);
|
283 | });
|
284 | };
|
285 | }
|
286 | var local = domain.create();
|
287 | local.add(req);
|
288 | local.add(res);
|
289 | local.on('error', next);
|
290 | local.run(function () {
|
291 | var currentHub = getCurrentHub();
|
292 | currentHub.configureScope(function (scope) {
|
293 | scope.addEventProcessor(function (event) { return parseRequest(event, req, options); });
|
294 | var client = currentHub.getClient();
|
295 | if (isAutoSessionTrackingEnabled(client)) {
|
296 | var scope_1 = currentHub.getScope();
|
297 | if (scope_1) {
|
298 |
|
299 | scope_1.setRequestSession({ status: RequestSessionStatus.Ok });
|
300 | }
|
301 | }
|
302 | });
|
303 | res.once('finish', function () {
|
304 | var client = currentHub.getClient();
|
305 | if (isAutoSessionTrackingEnabled(client)) {
|
306 | setImmediate(function () {
|
307 |
|
308 | if (client && client._captureRequestSession) {
|
309 |
|
310 |
|
311 |
|
312 | client._captureRequestSession();
|
313 | }
|
314 | });
|
315 | }
|
316 | });
|
317 | next();
|
318 | });
|
319 | };
|
320 | }
|
321 |
|
322 | function getStatusCodeFromResponse(error) {
|
323 | var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);
|
324 | return statusCode ? parseInt(statusCode, 10) : 500;
|
325 | }
|
326 |
|
327 | function defaultShouldHandleError(error) {
|
328 | var status = getStatusCodeFromResponse(error);
|
329 | return status >= 500;
|
330 | }
|
331 |
|
332 |
|
333 |
|
334 |
|
335 | export function errorHandler(options) {
|
336 | return function sentryErrorMiddleware(error, _req, res, next) {
|
337 |
|
338 | var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;
|
339 | if (shouldHandleError(error)) {
|
340 | withScope(function (_scope) {
|
341 |
|
342 |
|
343 | var transaction = res.__sentry_transaction;
|
344 | if (transaction && _scope.getSpan() === undefined) {
|
345 | _scope.setSpan(transaction);
|
346 | }
|
347 | var client = getCurrentHub().getClient();
|
348 | if (client && isAutoSessionTrackingEnabled(client)) {
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 | var isSessionAggregatesMode = client._sessionFlusher !== undefined;
|
355 | if (isSessionAggregatesMode) {
|
356 | var requestSession = _scope.getRequestSession();
|
357 |
|
358 |
|
359 |
|
360 | if (requestSession && requestSession.status !== undefined)
|
361 | requestSession.status = RequestSessionStatus.Crashed;
|
362 | }
|
363 | }
|
364 | var eventId = captureException(error);
|
365 |
|
366 | res.sentry = eventId;
|
367 | next(error);
|
368 | });
|
369 | return;
|
370 | }
|
371 | next(error);
|
372 | };
|
373 | }
|
374 |
|
\ | No newline at end of file |