@lucaapp/service-utils 5.39.0 → 5.40.0

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.
@@ -0,0 +1,24 @@
1
+ import * as Sentry from '@sentry/node';
2
+ import type { ErrorRequestHandler } from 'express';
3
+ export type ErrorReportingOptions = {
4
+ dsn?: string;
5
+ serviceName: string;
6
+ environment?: string;
7
+ release?: string;
8
+ flushTimeoutMs?: number;
9
+ };
10
+ export type ServerErrorContext = {
11
+ method?: string;
12
+ route?: string;
13
+ reqId?: string;
14
+ };
15
+ export declare const scrubString: (value: string) => string;
16
+ export declare const scrubValue: (value: unknown, depth?: number) => unknown;
17
+ export declare const scrubEvent: <T extends Sentry.Event>(event: T) => T;
18
+ export declare const initErrorReporting: (options: ErrorReportingOptions) => boolean;
19
+ export declare const isErrorReportingEnabled: () => boolean;
20
+ export declare const statusOf: (error: unknown) => number;
21
+ export declare const captureServerError: (error: unknown, context?: ServerErrorContext) => void;
22
+ export declare const errorReportingHandler: ErrorRequestHandler;
23
+ export declare const exitAfterReport: (error: unknown) => void;
24
+ export declare const closeErrorReporting: () => Promise<void>;
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.closeErrorReporting = exports.exitAfterReport = exports.errorReportingHandler = exports.captureServerError = exports.statusOf = exports.isErrorReportingEnabled = exports.initErrorReporting = exports.scrubEvent = exports.scrubValue = exports.scrubString = void 0;
37
+ const Sentry = __importStar(require("@sentry/node"));
38
+ const boom_1 = require("@hapi/boom");
39
+ const DEFAULT_FLUSH_TIMEOUT_MS = 800;
40
+ const MAX_DEPTH = 8;
41
+ const FILTERED = '[Filtered]';
42
+ const SENSITIVE_KEY = /auth|cookie|token|secret|passw|passcode|^pin$|session|e-?mail|phone|iban|card|(^|_)pan($|_|number)|cvc|cvv|shopper|reservation|booking|confirmation|(^|_)name$|surname|(first|last|full|guest|holder)_?name|address|birth|passport|signature|tax_?id|vat|api_?key/i;
43
+ const digitCount = (value) => value.replaceAll(/\D/g, '').length;
44
+ const STRING_PATTERNS = [
45
+ [/eyJ[\w-]+\.[\w-]+\.[\w-]+(?:\.[\w-]+\.[\w-]+)?/g, () => '[jwt]'],
46
+ [
47
+ /\b(bearer|basic)\s+[\w+./=~-]+/gi,
48
+ (_match, scheme) => `${scheme} ${FILTERED}`,
49
+ ],
50
+ [/[\w+.-]+@[\w-]+\.[\w.-]+/g, () => '[email]'],
51
+ [
52
+ /\b[A-Z]{2}\d{2}[\d A-Z]{11,32}\b/gi,
53
+ match => (digitCount(match) >= 10 ? '[iban]' : match),
54
+ ],
55
+ [
56
+ /\d[\d -]{11,}\d/g,
57
+ match => {
58
+ const digits = digitCount(match);
59
+ return digits >= 13 && digits <= 19 ? '[number]' : match;
60
+ },
61
+ ],
62
+ ];
63
+ let enabled = false;
64
+ let flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS;
65
+ const scrubString = (value) => {
66
+ let result = value;
67
+ for (const [pattern, replacement] of STRING_PATTERNS) {
68
+ result = result.replace(pattern, replacement);
69
+ }
70
+ return result;
71
+ };
72
+ exports.scrubString = scrubString;
73
+ const scrubValue = (value, depth = 0) => {
74
+ if (typeof value === 'string')
75
+ return (0, exports.scrubString)(value);
76
+ if (value === null || typeof value !== 'object')
77
+ return value;
78
+ if (depth >= MAX_DEPTH)
79
+ return FILTERED;
80
+ if (Buffer.isBuffer(value))
81
+ return '[Buffer]';
82
+ if (value instanceof Date)
83
+ return Number.isNaN(value.getTime())
84
+ ? '[Invalid Date]'
85
+ : value.toISOString();
86
+ if (Array.isArray(value))
87
+ return value.map(item => (0, exports.scrubValue)(item, depth + 1));
88
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
89
+ key,
90
+ SENSITIVE_KEY.test(key) ? FILTERED : (0, exports.scrubValue)(item, depth + 1),
91
+ ]));
92
+ };
93
+ exports.scrubValue = scrubValue;
94
+ const scrubBreadcrumb = (breadcrumb) => ({
95
+ ...breadcrumb,
96
+ ...(breadcrumb.message && { message: (0, exports.scrubString)(breadcrumb.message) }),
97
+ ...(breadcrumb.data && {
98
+ data: (0, exports.scrubValue)(breadcrumb.data),
99
+ }),
100
+ });
101
+ const scrubEvent = (event) => {
102
+ const { message, extra, contexts, tags, breadcrumbs, exception, request, user, } = event;
103
+ return {
104
+ ...event,
105
+ ...(message && { message: (0, exports.scrubString)(message) }),
106
+ ...(extra && { extra: (0, exports.scrubValue)(extra) }),
107
+ ...(contexts && { contexts: (0, exports.scrubValue)(contexts) }),
108
+ ...(tags && { tags: (0, exports.scrubValue)(tags) }),
109
+ ...(breadcrumbs && {
110
+ breadcrumbs: breadcrumbs.map(breadcrumb => scrubBreadcrumb(breadcrumb)),
111
+ }),
112
+ ...(exception?.values && {
113
+ exception: {
114
+ ...exception,
115
+ values: exception.values.map(value => ({
116
+ ...value,
117
+ ...(value.value && { value: (0, exports.scrubString)(value.value) }),
118
+ })),
119
+ },
120
+ }),
121
+ request: request && {
122
+ method: request.method,
123
+ url: request.url && (0, exports.scrubString)(request.url.split(/[?#]/, 1)[0] ?? ''),
124
+ },
125
+ user: user?.id === undefined ? undefined : { id: user.id },
126
+ };
127
+ };
128
+ exports.scrubEvent = scrubEvent;
129
+ const initErrorReporting = (options) => {
130
+ if (!options.dsn) {
131
+ enabled = false;
132
+ return false;
133
+ }
134
+ Sentry.init({
135
+ dsn: options.dsn,
136
+ environment: options.environment,
137
+ release: options.release,
138
+ serverName: options.serviceName,
139
+ sendDefaultPii: false,
140
+ skipOpenTelemetrySetup: true,
141
+ defaultIntegrations: false,
142
+ integrations: [
143
+ Sentry.eventFiltersIntegration(),
144
+ Sentry.functionToStringIntegration(),
145
+ Sentry.linkedErrorsIntegration(),
146
+ Sentry.dedupeIntegration(),
147
+ Sentry.contextLinesIntegration(),
148
+ Sentry.nodeContextIntegration(),
149
+ ],
150
+ beforeSend: event => (0, exports.scrubEvent)(event),
151
+ beforeBreadcrumb: breadcrumb => scrubBreadcrumb(breadcrumb),
152
+ });
153
+ flushTimeoutMs = options.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS;
154
+ enabled = true;
155
+ return true;
156
+ };
157
+ exports.initErrorReporting = initErrorReporting;
158
+ const isErrorReportingEnabled = () => enabled;
159
+ exports.isErrorReportingEnabled = isErrorReportingEnabled;
160
+ const statusOf = (error) => {
161
+ if ((0, boom_1.isBoom)(error))
162
+ return error.output.statusCode;
163
+ if (error instanceof Error &&
164
+ (error.name === 'SessionError' || error.constructor.name === 'SessionError'))
165
+ return 401;
166
+ const { statusCode, status } = (error ?? {});
167
+ if (typeof statusCode === 'number')
168
+ return statusCode;
169
+ if (typeof status === 'number')
170
+ return status;
171
+ return 500;
172
+ };
173
+ exports.statusOf = statusOf;
174
+ const captureServerError = (error, context = {}) => {
175
+ if (!enabled || (0, exports.statusOf)(error) < 500)
176
+ return;
177
+ const tags = Object.fromEntries(Object.entries(context).filter(([, value]) => value !== undefined));
178
+ Sentry.captureException(error, { tags });
179
+ };
180
+ exports.captureServerError = captureServerError;
181
+ const routeOf = (request) => request.route?.path
182
+ ? `${request.baseUrl ?? ''}${request.route.path}`
183
+ : '[unmatched]';
184
+ const errorReportingHandler = (error, request, _response, next) => {
185
+ try {
186
+ (0, exports.captureServerError)(error, {
187
+ method: request.method,
188
+ route: routeOf(request),
189
+ ...(request.id !== undefined && { reqId: String(request.id) }),
190
+ });
191
+ }
192
+ catch { }
193
+ next(error);
194
+ };
195
+ exports.errorReportingHandler = errorReportingHandler;
196
+ const exitAfterReport = (error) => {
197
+ if (enabled) {
198
+ try {
199
+ Sentry.captureException(error, { level: 'fatal' });
200
+ Sentry.flush(flushTimeoutMs)
201
+ .then(() => process.exit(1))
202
+ .catch(() => process.exit(1));
203
+ }
204
+ catch {
205
+ process.exit(1);
206
+ }
207
+ }
208
+ else {
209
+ process.exit(1);
210
+ }
211
+ };
212
+ exports.exitAfterReport = exitAfterReport;
213
+ const closeErrorReporting = async () => {
214
+ if (enabled) {
215
+ enabled = false;
216
+ await Sentry.close(flushTimeoutMs);
217
+ }
218
+ };
219
+ exports.closeErrorReporting = closeErrorReporting;
@@ -0,0 +1,4 @@
1
+ {
2
+ "main": "../dist/lib/errorReporting/index.js",
3
+ "types": "../dist/lib/errorReporting/index.d.ts"
4
+ }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@lucaapp/service-utils",
3
- "version": "5.39.0",
3
+ "version": "5.40.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [
7
- "dist/**/*"
7
+ "dist/**/*",
8
+ "errorReporting/package.json"
8
9
  ],
9
10
  "license": "Apache-2.0",
10
11
  "author": "Culture4Life <hello@luca-app.de> (https://www.luca-app.de/)",
@@ -59,7 +60,7 @@
59
60
  "pg-boss": "12.14.0"
60
61
  },
61
62
  "devDependencies": {
62
- "@sentry/node": "^9.10.1",
63
+ "@sentry/node": "10.76.2",
63
64
  "@types/busboy": "^1.5.4",
64
65
  "@types/lodash": "^4.14.187",
65
66
  "@types/negotiator": "^0.6.4",
@@ -85,7 +86,7 @@
85
86
  "yarn-osv-audit": "1.0.0"
86
87
  },
87
88
  "peerDependencies": {
88
- "@sentry/node": "^9.10.1",
89
+ "@sentry/node": "^9.10.1 || ^10.0.0",
89
90
  "pino-sentry-transport": "^1.5.1"
90
91
  },
91
92
  "peerDependenciesMeta": {