-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
102 lines (91 loc) · 2.96 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
const {
sendPayloadToTreblle,
generateFieldsToMask,
maskSensitiveValues,
getRequestDuration,
generateTrebllePayload,
getResponsePayload,
} = require('@treblle/utils')
const { version: sdkVersion } = require('./package.json')
module.exports = treblle
/**
* Expose the Treblle middleware
* @param {{apiKey?: string, projectId?: string, additionalFieldsToMask?: string[], blocklistPaths?: (string[]|RegExp)}} options - Middleware options.
* @returns {Function} - treblle-express middleware.
*/
function treblle({
apiKey = process.env.TREBLLE_API_KEY,
projectId = process.env.TREBLLE_PROJECT_ID,
additionalFieldsToMask = [],
blocklistPaths = [],
} = {}) {
return function treblleMiddleware(req, res, next) {
// Track when this request was received.
const requestStartTime = process.hrtime()
// Intercept response body
const originalSend = res.send
res.send = function sendOverWrite(body) {
this._treblleResponsebody = body
originalSend.call(this, body)
}
res.on('finish', function onceFinish() {
// Check if the request path is blocked
const isPathBlocked =
blocklistPaths instanceof RegExp
? blocklistPaths.test(req.path)
: blocklistPaths.some((path) => req.path.startsWith(`/${path}`))
if (isPathBlocked) {
return next()
}
let errors = []
const body = req.body || {}
const query = req.query || {}
const requestPayload = { ...body, ...query }
const fieldsToMask = generateFieldsToMask(additionalFieldsToMask)
const maskedRequestPayload = maskSensitiveValues(requestPayload, fieldsToMask)
const protocol = `${req.protocol}/${req.httpVersion}`
const { payload: maskedResponseBody, error: invalidResponseBodyError } = getResponsePayload(
res._treblleResponsebody,
fieldsToMask
)
if (invalidResponseBodyError) {
errors.push(invalidResponseBodyError)
}
const trebllePayload = generateTrebllePayload(
{
api_key: apiKey,
project_id: projectId,
sdk: 'express',
version: sdkVersion,
},
{
server: {
protocol,
},
request: {
ip: req.ip,
url: `${req.protocol}://${req.headers['host']}${req.originalUrl}`,
user_agent: req.headers['user-agent'],
method: req.method,
headers: maskSensitiveValues(req.headers, fieldsToMask),
body: maskedRequestPayload,
},
response: {
headers: maskSensitiveValues(res.getHeaders(), fieldsToMask),
code: res.statusCode,
size: res.get('content-length'),
load_time: getRequestDuration(requestStartTime),
body: maskedResponseBody,
},
errors,
}
)
try {
sendPayloadToTreblle(trebllePayload, apiKey)
} catch (error) {
console.error(error)
}
})
next()
}
}