@qrvey/telemetry 0.0.2 → 1.0.0-806

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.ts ADDED
@@ -0,0 +1,15 @@
1
+ export default {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ collectCoverageFrom: ['src/**/*.ts', '!src/**/*.test.ts', '!src/**/*.spec.ts', '!src/types/**/*', '!src/interfaces/**/*', '!src/index.ts'],
5
+ coverageDirectory: 'coverage',
6
+ coverageReporters: ['text', 'lcov', 'html'],
7
+ testMatch: ['**/__tests__/**/*.ts', '**/*.test.ts', '**/*.spec.ts'],
8
+ moduleFileExtensions: ['ts', 'js', 'json'],
9
+ transform: {
10
+ '^.+\\.ts$': 'ts-jest',
11
+ },
12
+ clearMocks: true,
13
+ resetMocks: true,
14
+ restoreMocks: true,
15
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qrvey/telemetry",
3
- "version": "0.0.2",
3
+ "version": "1.0.0-806",
4
4
  "types": "dist/types/index.d.ts",
5
5
  "main": "dist/cjs/index.js",
6
6
  "exports": {
@@ -11,7 +11,9 @@
11
11
  }
12
12
  },
13
13
  "scripts": {
14
- "test": "echo \"Error: no test specified\" && exit 1",
14
+ "test": "jest",
15
+ "test:watch": "jest --watch",
16
+ "test:coverage": "jest --coverage",
15
17
  "lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
16
18
  "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
17
19
  "type-check": "tsc",
@@ -24,7 +26,7 @@
24
26
  "build:compile": "yarn build:compile:cjs && yarn build:compile:esm && yarn build:compile:types",
25
27
  "build": "yarn build:clean && yarn build:compile",
26
28
  "prepare-publish": "yarn install && yarn build",
27
- "publish-package": "yarn prepare-publish && npm publish"
29
+ "publish-package": "yarn prepare-publish && npm publish --tag latest"
28
30
  },
29
31
  "dependencies": {
30
32
  "@opentelemetry/api-logs": "0.205.0",
@@ -41,9 +43,12 @@
41
43
  "pino-pretty": "13.1.1"
42
44
  },
43
45
  "devDependencies": {
46
+ "@types/jest": "29.5.12",
44
47
  "eslint": "8.48.0",
45
48
  "eslint-import-resolver-typescript": "3.8.0",
46
49
  "eslint-plugin-import": "2.31.0",
50
+ "jest": "29.7.0",
51
+ "ts-jest": "29.1.4",
47
52
  "tsup": "8.0.2",
48
53
  "typescript": "5.9.2"
49
54
  },
package/src/index.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  export { default as LoggerService } from './lib/services/loggerService';
2
2
  export { default as InstrumentationService } from './lib/services/instrumentationService';
3
+ export { MiddlewareService } from './lib/services/middlewareService';
4
+
@@ -9,14 +9,15 @@ export const LOG_LEVELS = {
9
9
 
10
10
  export const ENVIRONMENT = {
11
11
  LOG_LEVEL: process.env.LOG_LEVEL || LOG_LEVELS.DEBUG.name,
12
- ENABLE_CONSOLE_LOGS: process.env.ENABLE_CONSOLE_LOGS ? Boolean(process.env.ENABLE_CONSOLE_LOGS) : true,
13
- ENABLE_OTLP_TRACE: process.env.ENABLE_OTLP_TRACE ? Boolean(process.env.ENABLE_OTLP_TRACE) : true,
14
- ENABLE_OTLP_METRIC: process.env.ENABLE_OTLP_METRIC ? Boolean(process.env.ENABLE_OTLP_METRIC) : true,
15
- ENABLE_OTLP_LOG: process.env.ENABLE_OTLP_LOG ? Boolean(process.env.ENABLE_OTLP_LOG) : true,
12
+ ENABLE_CONSOLE_LOGS: process.env.ENABLE_CONSOLE_LOGS?.toLowerCase() === 'true',
13
+ ENABLE_OTLP_TRACE: process.env.ENABLE_OTLP_TRACE?.toLowerCase() === 'true',
14
+ ENABLE_OTLP_METRIC: process.env.ENABLE_OTLP_METRIC?.toLowerCase() === 'true',
15
+ ENABLE_OTLP_LOG: process.env.ENABLE_OTLP_LOG?.toLowerCase() === 'true',
16
16
  OTLP_TRACE_URL: process.env.OTLP_TRACE_URL || 'http://localhost:4320/v1/traces',
17
17
  OTLP_METRIC_URL: process.env.OTLP_METRIC_URL || 'http://localhost:4318/v1/metrics',
18
18
  OTLP_LOG_URL: process.env.OTLP_LOG_URL || 'http://localhost:4320/v1/logs',
19
19
  QRVEY_SERVICE_NAME: process.env.QRVEY_SERVICE_NAME || 'Default-Service-name',
20
20
  QRVEY_SERVICE_VERSION: process.env.QRVEY_SERVICE_VERSION || '0.0.0',
21
+ SENSITIVE_FIELDS: process.env.SENSITIVE_FIELDS ? process.env.SENSITIVE_FIELDS.split(',') : [] as string[],
21
22
  EXPORT_METRICS_INTERVAL_MILLIS: process.env.EXPORT_METRICS_INTERVAL_MILLIS ? parseInt(process.env.EXPORT_METRICS_INTERVAL_MILLIS, 10) : 10000,
22
23
  } as const;
@@ -3,6 +3,8 @@ import pino, { LogFn, Logger as PinoLogger } from 'pino';
3
3
 
4
4
  import { DEFAULT_CONTEXT_SCOPE_NAME, ENVIRONMENT, LOG_LEVELS } from '../constants';
5
5
 
6
+ import { cleanSensitiveData } from '../utils/dataSanitizer';
7
+
6
8
  type MetadataLog = LogAttributes | Record<string, unknown>;
7
9
 
8
10
  export default class LoggerService {
@@ -22,9 +24,9 @@ export default class LoggerService {
22
24
  transport:
23
25
  ENVIRONMENT.LOG_LEVEL === LOG_LEVELS.DEBUG.name
24
26
  ? {
25
- target: 'pino-pretty',
26
- options: { colorize: true },
27
- }
27
+ target: 'pino-pretty',
28
+ options: { colorize: true },
29
+ }
28
30
  : undefined,
29
31
  });
30
32
  this.otelLogger = logs.getLogger(serviceName);
@@ -36,6 +38,8 @@ export default class LoggerService {
36
38
  * @param meta - Optional additional arguments to include in the log
37
39
  */
38
40
  debug(message: string, meta?: MetadataLog) {
41
+ message = cleanSensitiveData(message);
42
+ meta = cleanSensitiveData(meta);
39
43
  this.consoleLogger(this.pinoLogger.debug.bind(this.pinoLogger), message, meta);
40
44
  if (ENVIRONMENT.LOG_LEVEL === LOG_LEVELS.DEBUG.name) this.emitterLogger(LOG_LEVELS.DEBUG.severity, message, meta);
41
45
  }
@@ -46,6 +50,8 @@ export default class LoggerService {
46
50
  * @param meta - Optional additional arguments to include in the log
47
51
  */
48
52
  info(message: string, meta?: MetadataLog) {
53
+ message = cleanSensitiveData(message);
54
+ meta = cleanSensitiveData(meta);
49
55
  this.consoleLogger(this.pinoLogger.info.bind(this.pinoLogger), message, meta);
50
56
  this.emitterLogger(LOG_LEVELS.INFO.severity, message, meta);
51
57
  }
@@ -56,6 +62,8 @@ export default class LoggerService {
56
62
  * @param meta - Optional additional arguments to include in the log
57
63
  */
58
64
  warn(message: string, meta?: MetadataLog) {
65
+ message = cleanSensitiveData(message);
66
+ meta = cleanSensitiveData(meta);
59
67
  this.consoleLogger(this.pinoLogger.warn.bind(this.pinoLogger), message, meta);
60
68
  this.emitterLogger(LOG_LEVELS.WARN.severity, message, meta);
61
69
  }
@@ -66,6 +74,8 @@ export default class LoggerService {
66
74
  * @param meta - Optional additional arguments to include in the log
67
75
  */
68
76
  error(message: string, meta?: MetadataLog) {
77
+ message = cleanSensitiveData(message);
78
+ meta = cleanSensitiveData(meta);
69
79
  this.consoleLogger(this.pinoLogger.error.bind(this.pinoLogger), message, meta);
70
80
  this.emitterLogger(LOG_LEVELS.ERROR.severity, message, meta);
71
81
  }
@@ -77,17 +87,12 @@ export default class LoggerService {
77
87
  * @param meta - Optional additional arguments to include in the log
78
88
  */
79
89
  private consoleLogger(logger: LogFn, message: string, meta?: MetadataLog) {
90
+ message = cleanSensitiveData(message);
91
+ meta = cleanSensitiveData(meta);
80
92
  if (!this.enableConsole) return;
81
93
 
82
- if (meta && typeof meta === 'object') {
83
- if (Array.isArray(meta)) {
84
- logger({ data: meta }, message);
85
- } else {
86
- logger(meta, message);
87
- }
88
- } else {
89
- logger(message);
90
- }
94
+ if (meta && typeof meta === 'string' && message && typeof message === 'string') meta = { data: meta };
95
+ logger(meta, message);
91
96
  }
92
97
 
93
98
  /**
@@ -97,6 +102,8 @@ export default class LoggerService {
97
102
  * @param meta - Optional additional arguments to include in the log
98
103
  */
99
104
  private emitterLogger(severityNumber: number, message: string, meta?: MetadataLog) {
105
+ message = cleanSensitiveData(message);
106
+ meta = cleanSensitiveData(meta);
100
107
  this.otelLogger.emit({
101
108
  body: message,
102
109
  severityNumber,
@@ -0,0 +1,213 @@
1
+ import LoggerService from './loggerService';
2
+
3
+ export interface MiddlewareConfig {
4
+ serviceName?: string;
5
+ excludePaths?: string[];
6
+ logRequestBody?: boolean;
7
+ logResponseBody?: boolean;
8
+ maxBodySize?: number;
9
+ logRequestBodyFields?: string[];
10
+ }
11
+
12
+ export class MiddlewareService {
13
+ private readonly logger: LoggerService;
14
+ private readonly config: Required<MiddlewareConfig>;
15
+
16
+ constructor(config?: MiddlewareConfig) {
17
+ this.config = {
18
+ serviceName: config?.serviceName || 'MiddlewareLogger',
19
+ excludePaths: config?.excludePaths || [],
20
+ logRequestBody: config?.logRequestBody || false,
21
+ logResponseBody: config?.logResponseBody || false,
22
+ maxBodySize: config?.maxBodySize || 10000,
23
+ logRequestBodyFields: config?.logRequestBodyFields || [],
24
+ };
25
+
26
+ this.logger = new LoggerService(this.config.serviceName);
27
+ }
28
+
29
+ logExpressApiCall = (req: any, res: any, next: any): void => {
30
+ // Skip excluded paths
31
+ if (this.shouldExcludePath(req.path)) {
32
+ return next();
33
+ }
34
+
35
+ const startTime = Date.now();
36
+ let responseBody: any;
37
+
38
+ // Log incoming request
39
+ this.logRequest(req);
40
+
41
+ // Capture response body if logging is enabled
42
+ if (this.config.logResponseBody === true) {
43
+ const originalSend = res.send.bind(res);
44
+ const originalJson = res.json.bind(res);
45
+
46
+ res.send = function (body: any): Response {
47
+ responseBody = body;
48
+ return originalSend(body);
49
+ };
50
+
51
+ res.json = function (body: any): Response {
52
+ responseBody = body;
53
+ return originalJson(body);
54
+ };
55
+ }
56
+
57
+ // Log response when finished
58
+ res.on('finish', () => {
59
+ const duration = Date.now() - startTime;
60
+ this.logResponse(req, res, duration, this.parsePayload(responseBody));
61
+ });
62
+
63
+ // Handle errors
64
+ res.on('error', (error: Error) => {
65
+ const duration = Date.now() - startTime;
66
+ this.logError(req, res, error, duration);
67
+ });
68
+
69
+ next();
70
+ };
71
+
72
+ // Fastify hook: register in preHandler to capture parsed request body
73
+ logFastifyPreHandler = async (request: any, _reply: any): Promise<void> => {
74
+ const path = request.routerPath || request.routeOptions?.url || request.url || '';
75
+ if (this.shouldExcludePath(path)) {
76
+ return;
77
+ }
78
+
79
+ const normalizedReq = {
80
+ method: request.method,
81
+ path,
82
+ url: request.url,
83
+ ip: request.ip || request.socket?.remoteAddress,
84
+ query: request.query,
85
+ body: request.body,
86
+ };
87
+
88
+ this.logRequest(normalizedReq);
89
+ return;
90
+ };
91
+
92
+ // Fastify hook: register in onSend to capture actual serialized response payload
93
+ logFastifyOnSend = async (request: any, reply: any, payload: any): Promise<any> => {
94
+ const path = request.routerPath || request.routeOptions?.url || request.url || '';
95
+ if (this.shouldExcludePath(path)) {
96
+ return payload;
97
+ }
98
+
99
+ const startTime = Date.now();
100
+ const duration = Date.now() - startTime;
101
+
102
+ const normalizedReq = {
103
+ method: request.method,
104
+ path,
105
+ url: request.url,
106
+ ip: request.ip || request.socket?.remoteAddress,
107
+ query: request.query,
108
+ body: request.body,
109
+ };
110
+
111
+ const normalizedRes = {
112
+ statusCode: reply.statusCode,
113
+ };
114
+
115
+ this.logResponse(normalizedReq, normalizedRes, duration, this.parsePayload(payload));
116
+ return payload;
117
+ };
118
+
119
+ private shouldExcludePath(path: string): boolean {
120
+ return this.config.excludePaths.some((excludePath) => {
121
+ if (excludePath.includes('*')) {
122
+ const regex = new RegExp('^' + excludePath.replace(/\*/g, '.*') + '$');
123
+ return regex.test(path);
124
+ }
125
+ return path === excludePath;
126
+ });
127
+ }
128
+
129
+ private filterBodyFields(body: any): any {
130
+ if (!body || typeof body !== 'object') return body;
131
+
132
+ // If no specific fields configured, return entire body
133
+ if (!this.config.logRequestBodyFields || this.config.logRequestBodyFields.length === 0) {
134
+ return body;
135
+ }
136
+
137
+ // Filter to only include specified fields
138
+ const filtered: any = {};
139
+ for (const field of this.config.logRequestBodyFields) {
140
+ if (field in body) {
141
+ filtered[field] = body[field];
142
+ }
143
+ }
144
+ return filtered;
145
+ }
146
+
147
+ private truncateBody(body: any): any {
148
+ if (!body) return body;
149
+ const str = typeof body === 'string' ? body : JSON.stringify(body);
150
+ return str.length > this.config.maxBodySize ? str.substring(0, this.config.maxBodySize) + '...[truncated]' : body;
151
+ }
152
+
153
+ private parsePayload(payload: any): any {
154
+ if (payload === undefined || payload === null) return payload;
155
+ if (typeof payload !== 'string') return payload;
156
+
157
+ try {
158
+ return JSON.parse(payload);
159
+ } catch {
160
+ return payload;
161
+ }
162
+ }
163
+
164
+ private logRequest(req: any): void {
165
+ const logData: any = {
166
+ method: req.method,
167
+ path: req.path,
168
+ url: req.url,
169
+ ip: req.ip || req.socket.remoteAddress,
170
+ };
171
+
172
+ if (req.query && Object.keys(req.query).length > 0) {
173
+ logData.query = req.query;
174
+ }
175
+
176
+ if (this.config.logRequestBody && req.body) {
177
+ const bodyToLog = this.filterBodyFields(req.body);
178
+ logData.body = this.truncateBody(bodyToLog);
179
+ }
180
+
181
+ this.logger.info(`Incoming: ${req.method} ${req.path}`, logData);
182
+ }
183
+
184
+ private logResponse(req: any, res: any, duration: number, responseBody?: any): void {
185
+ const logData: any = {
186
+ method: req.method,
187
+ path: req.path,
188
+ statusCode: res.statusCode,
189
+ duration,
190
+ };
191
+
192
+ if (this.config.logResponseBody && responseBody !== undefined) {
193
+ logData.responseBody = this.truncateBody(responseBody);
194
+ }
195
+
196
+ const logLevel = res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info';
197
+ this.logger[logLevel](`Response: ${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`, logData);
198
+ }
199
+
200
+ private logError(req: any, res: any, error: Error, duration: number): void {
201
+ this.logger.error(`Error: ${req.method} ${req.path}`, {
202
+ method: req.method,
203
+ path: req.path,
204
+ statusCode: res.statusCode,
205
+ duration,
206
+ error: {
207
+ name: error.name,
208
+ message: error.message,
209
+ stack: error.stack,
210
+ },
211
+ });
212
+ }
213
+ }
@@ -0,0 +1,41 @@
1
+ import { ENVIRONMENT } from "../constants";
2
+
3
+ /**
4
+ * Cleans sensitive data from an object by redacting values of keys that contain sensitive keywords.
5
+ * This utility can be used by middleware/interceptors before logging HTTP request/response data.
6
+ */
7
+ export function cleanSensitiveData(obj: any): any {
8
+ if (obj === null || obj === undefined) {
9
+ return obj;
10
+ }
11
+
12
+ if (typeof obj === 'string') {
13
+ return obj;
14
+ }
15
+
16
+ if (Array.isArray(obj)) {
17
+ return obj.map(item => cleanSensitiveData(item));
18
+ }
19
+
20
+ if (typeof obj === 'object') {
21
+ const keywords = ENVIRONMENT.SENSITIVE_FIELDS;
22
+ const cleaned: any = {};
23
+
24
+ for (const [key, value] of Object.entries(obj)) {
25
+ const lowerKey = key.toLowerCase();
26
+ const isSensitive = keywords.some(keyword =>
27
+ lowerKey.includes(keyword.toLowerCase())
28
+ );
29
+ if (isSensitive) {
30
+ cleaned[key] = '***REDACTED***';
31
+ } else if (typeof value === 'object' && value !== null) {
32
+ cleaned[key] = cleanSensitiveData(value);
33
+ } else {
34
+ cleaned[key] = value;
35
+ }
36
+ }
37
+ return cleaned;
38
+ }
39
+
40
+ return obj;
41
+ }