|
| 1 | +import { Event, ExtractedNodeRequestData, PolymorphicRequest, Transaction, TransactionSource } from '@sentry/types'; |
| 2 | +import { isPlainObject, isString, normalize, stripUrlQueryAndFragment } from '@sentry/utils/'; |
| 3 | +import * as cookie from 'cookie'; |
| 4 | +import * as url from 'url'; |
| 5 | + |
| 6 | +const DEFAULT_INCLUDES = { |
| 7 | + ip: false, |
| 8 | + request: true, |
| 9 | + transaction: true, |
| 10 | + user: true, |
| 11 | +}; |
| 12 | +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; |
| 13 | +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; |
| 14 | + |
| 15 | +/** |
| 16 | + * Options deciding what parts of the request to use when enhancing an event |
| 17 | + */ |
| 18 | +export interface AddRequestDataToEventOptions { |
| 19 | + /** Flags controlling whether each type of data should be added to the event */ |
| 20 | + include?: { |
| 21 | + ip?: boolean; |
| 22 | + request?: boolean | Array<typeof DEFAULT_REQUEST_INCLUDES[number]>; |
| 23 | + transaction?: boolean | TransactionNamingScheme; |
| 24 | + user?: boolean | Array<typeof DEFAULT_USER_INCLUDES[number]>; |
| 25 | + }; |
| 26 | +} |
| 27 | + |
| 28 | +type TransactionNamingScheme = 'path' | 'methodPath' | 'handler'; |
| 29 | + |
| 30 | +/** |
| 31 | + * Sets parameterized route as transaction name e.g.: `GET /users/:id` |
| 32 | + * Also adds more context data on the transaction from the request |
| 33 | + */ |
| 34 | +export function addRequestDataToTransaction(transaction: Transaction | undefined, req: PolymorphicRequest): void { |
| 35 | + if (!transaction) return; |
| 36 | + if (!transaction.metadata.source || transaction.metadata.source === 'url') { |
| 37 | + // Attempt to grab a parameterized route off of the request |
| 38 | + transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); |
| 39 | + } |
| 40 | + transaction.setData('url', req.originalUrl || req.url); |
| 41 | + if (req.baseUrl) { |
| 42 | + transaction.setData('baseUrl', req.baseUrl); |
| 43 | + } |
| 44 | + transaction.setData('query', extractQueryParams(req)); |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. |
| 49 | + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. |
| 50 | + * |
| 51 | + * Additionally, this function determines and returns the transaction name source |
| 52 | + * |
| 53 | + * eg. GET /mountpoint/user/:id |
| 54 | + * |
| 55 | + * @param req A request object |
| 56 | + * @param options What to include in the transaction name (method, path, or a custom route name to be |
| 57 | + * used instead of the request's route) |
| 58 | + * |
| 59 | + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') |
| 60 | + */ |
| 61 | +export function extractPathForTransaction( |
| 62 | + req: PolymorphicRequest, |
| 63 | + options: { path?: boolean; method?: boolean; customRoute?: string } = {}, |
| 64 | +): [string, TransactionSource] { |
| 65 | + const method = req.method && req.method.toUpperCase(); |
| 66 | + |
| 67 | + let path = ''; |
| 68 | + let source: TransactionSource = 'url'; |
| 69 | + |
| 70 | + // Check to see if there's a parameterized route we can use (as there is in Express) |
| 71 | + if (options.customRoute || req.route) { |
| 72 | + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; |
| 73 | + source = 'route'; |
| 74 | + } |
| 75 | + |
| 76 | + // Otherwise, just take the original URL |
| 77 | + else if (req.originalUrl || req.url) { |
| 78 | + path = stripUrlQueryAndFragment(req.originalUrl || req.url || ''); |
| 79 | + } |
| 80 | + |
| 81 | + let name = ''; |
| 82 | + if (options.method && method) { |
| 83 | + name += method; |
| 84 | + } |
| 85 | + if (options.method && options.path) { |
| 86 | + name += ' '; |
| 87 | + } |
| 88 | + if (options.path && path) { |
| 89 | + name += path; |
| 90 | + } |
| 91 | + |
| 92 | + return [name, source]; |
| 93 | +} |
| 94 | + |
| 95 | +/** JSDoc */ |
| 96 | +function extractTransaction(req: PolymorphicRequest, type: boolean | TransactionNamingScheme): string { |
| 97 | + switch (type) { |
| 98 | + case 'path': { |
| 99 | + return extractPathForTransaction(req, { path: true })[0]; |
| 100 | + } |
| 101 | + case 'handler': { |
| 102 | + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; |
| 103 | + } |
| 104 | + case 'methodPath': |
| 105 | + default: { |
| 106 | + return extractPathForTransaction(req, { path: true, method: true })[0]; |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +/** JSDoc */ |
| 112 | +function extractUserData( |
| 113 | + user: { |
| 114 | + [key: string]: unknown; |
| 115 | + }, |
| 116 | + keys: boolean | string[], |
| 117 | +): { [key: string]: unknown } { |
| 118 | + const extractedUser: { [key: string]: unknown } = {}; |
| 119 | + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; |
| 120 | + |
| 121 | + attributes.forEach(key => { |
| 122 | + if (user && key in user) { |
| 123 | + extractedUser[key] = user[key]; |
| 124 | + } |
| 125 | + }); |
| 126 | + |
| 127 | + return extractedUser; |
| 128 | +} |
| 129 | + |
| 130 | +/** |
| 131 | + * Normalize data from the request object |
| 132 | + * |
| 133 | + * @param req The request object from which to extract data |
| 134 | + * @param options.include An optional array of keys to include in the normalized data. Defaults to |
| 135 | + * DEFAULT_REQUEST_INCLUDES if not provided. |
| 136 | + * @param options.deps Injected, platform-specific dependencies |
| 137 | + * |
| 138 | + * @returns An object containing normalized request data |
| 139 | + */ |
| 140 | +export function extractRequestData( |
| 141 | + req: PolymorphicRequest, |
| 142 | + options?: { |
| 143 | + include?: string[]; |
| 144 | + }, |
| 145 | +): ExtractedNodeRequestData { |
| 146 | + const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; |
| 147 | + const requestData: { [key: string]: unknown } = {}; |
| 148 | + |
| 149 | + // headers: |
| 150 | + // node, express, koa, nextjs: req.headers |
| 151 | + const headers = (req.headers || {}) as { |
| 152 | + host?: string; |
| 153 | + cookie?: string; |
| 154 | + }; |
| 155 | + // method: |
| 156 | + // node, express, koa, nextjs: req.method |
| 157 | + const method = req.method; |
| 158 | + // host: |
| 159 | + // express: req.hostname in > 4 and req.host in < 4 |
| 160 | + // koa: req.host |
| 161 | + // node, nextjs: req.headers.host |
| 162 | + const host = req.hostname || req.host || headers.host || '<no host>'; |
| 163 | + // protocol: |
| 164 | + // node, nextjs: <n/a> |
| 165 | + // express, koa: req.protocol |
| 166 | + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; |
| 167 | + // url (including path and query string): |
| 168 | + // node, express: req.originalUrl |
| 169 | + // koa, nextjs: req.url |
| 170 | + const originalUrl = req.originalUrl || req.url || ''; |
| 171 | + // absolute url |
| 172 | + const absoluteUrl = `${protocol}://${host}${originalUrl}`; |
| 173 | + include.forEach(key => { |
| 174 | + switch (key) { |
| 175 | + case 'headers': { |
| 176 | + requestData.headers = headers; |
| 177 | + break; |
| 178 | + } |
| 179 | + case 'method': { |
| 180 | + requestData.method = method; |
| 181 | + break; |
| 182 | + } |
| 183 | + case 'url': { |
| 184 | + requestData.url = absoluteUrl; |
| 185 | + break; |
| 186 | + } |
| 187 | + case 'cookies': { |
| 188 | + // cookies: |
| 189 | + // node, express, koa: req.headers.cookie |
| 190 | + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies |
| 191 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
| 192 | + requestData.cookies = |
| 193 | + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can |
| 194 | + // come off in v8 |
| 195 | + req.cookies || (headers.cookie && cookie.parse(headers.cookie)) || {}; |
| 196 | + break; |
| 197 | + } |
| 198 | + case 'query_string': { |
| 199 | + // query string: |
| 200 | + // node: req.url (raw) |
| 201 | + // express, koa, nextjs: req.query |
| 202 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
| 203 | + requestData.query_string = extractQueryParams(req); |
| 204 | + break; |
| 205 | + } |
| 206 | + case 'data': { |
| 207 | + if (method === 'GET' || method === 'HEAD') { |
| 208 | + break; |
| 209 | + } |
| 210 | + // body data: |
| 211 | + // express, koa, nextjs: req.body |
| 212 | + // |
| 213 | + // when using node by itself, you have to read the incoming stream(see |
| 214 | + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know |
| 215 | + // where they're going to store the final result, so they'll have to capture this data themselves |
| 216 | + if (req.body !== undefined) { |
| 217 | + requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body)); |
| 218 | + } |
| 219 | + break; |
| 220 | + } |
| 221 | + default: { |
| 222 | + if ({}.hasOwnProperty.call(req, key)) { |
| 223 | + requestData[key] = (req as { [key: string]: unknown })[key]; |
| 224 | + } |
| 225 | + } |
| 226 | + } |
| 227 | + }); |
| 228 | + |
| 229 | + return requestData; |
| 230 | +} |
| 231 | + |
| 232 | +/** |
| 233 | + * Add data from the given request to the given event |
| 234 | + * |
| 235 | + * @param event The event to which the request data will be added |
| 236 | + * @param req Request object |
| 237 | + * @param options.include Flags to control what data is included |
| 238 | + * |
| 239 | + * @returns The mutated `Event` object |
| 240 | + */ |
| 241 | +export function addRequestDataToEvent( |
| 242 | + event: Event, |
| 243 | + req: PolymorphicRequest, |
| 244 | + options?: AddRequestDataToEventOptions, |
| 245 | +): Event { |
| 246 | + const include = { |
| 247 | + ...DEFAULT_INCLUDES, |
| 248 | + ...options?.include, |
| 249 | + }; |
| 250 | + |
| 251 | + if (include.request) { |
| 252 | + const extractedRequestData = Array.isArray(include.request) |
| 253 | + ? extractRequestData(req, { include: include.request }) |
| 254 | + : extractRequestData(req); |
| 255 | + |
| 256 | + event.request = { |
| 257 | + ...event.request, |
| 258 | + ...extractedRequestData, |
| 259 | + }; |
| 260 | + } |
| 261 | + |
| 262 | + if (include.user) { |
| 263 | + const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, include.user) : {}; |
| 264 | + |
| 265 | + if (Object.keys(extractedUser).length) { |
| 266 | + event.user = { |
| 267 | + ...event.user, |
| 268 | + ...extractedUser, |
| 269 | + }; |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + // client ip: |
| 274 | + // node, nextjs: req.socket.remoteAddress |
| 275 | + // express, koa: req.ip |
| 276 | + if (include.ip) { |
| 277 | + const ip = req.ip || (req.socket && req.socket.remoteAddress); |
| 278 | + if (ip) { |
| 279 | + event.user = { |
| 280 | + ...event.user, |
| 281 | + ip_address: ip, |
| 282 | + }; |
| 283 | + } |
| 284 | + } |
| 285 | + |
| 286 | + if (include.transaction && !event.transaction) { |
| 287 | + // TODO do we even need this anymore? |
| 288 | + // TODO make this work for nextjs |
| 289 | + event.transaction = extractTransaction(req, include.transaction); |
| 290 | + } |
| 291 | + |
| 292 | + return event; |
| 293 | +} |
| 294 | + |
| 295 | +function extractQueryParams(req: PolymorphicRequest): string | Record<string, unknown> | undefined { |
| 296 | + // url (including path and query string): |
| 297 | + // node, express: req.originalUrl |
| 298 | + // koa, nextjs: req.url |
| 299 | + let originalUrl = req.originalUrl || req.url || ''; |
| 300 | + |
| 301 | + if (!originalUrl) { |
| 302 | + return; |
| 303 | + } |
| 304 | + |
| 305 | + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and |
| 306 | + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. |
| 307 | + if (originalUrl.startsWith('/')) { |
| 308 | + originalUrl = `http://dogs.are.great${originalUrl}`; |
| 309 | + } |
| 310 | + |
| 311 | + return ( |
| 312 | + req.query || |
| 313 | + (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || |
| 314 | + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node |
| 315 | + url.parse(originalUrl).query || |
| 316 | + undefined |
| 317 | + ); |
| 318 | +} |
0 commit comments