@lucaapp/service-utils 5.38.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;
@@ -1,36 +1,35 @@
1
1
  export declare const FISCALIZED_PAYMENT_EVENT_VERSION = 1;
2
2
  export type FiscalizedPaymentEventVersion = typeof FISCALIZED_PAYMENT_EVENT_VERSION;
3
3
  /**
4
- * Emitted by backend-tse when a payment's fiscalization reaches a terminal
5
- * ready state (signed and receipt PDF materializable).
6
- * Consumers (e.g. backend-pay) use this instead of polling readiness.
7
- *
8
- * ID fields are intentionally distinct — they are not always equal:
9
- * - POS checkout fast-path can create `fiscal_payment_events` under a throwaway
10
- * Kafka uuid before `V3Payment` exists; TSE then reuses that fiscal row via
11
- * `checkoutId` and does not rewrite the fiscal id to `V3Payment.uuid`.
12
- * - Cash / HTTP paths often have no `V3Payment` at all.
4
+ * Final fiscalization outcome of a payment, decided by backend-tse:
5
+ * - `FISCALIZED`: the Kassenbeleg is final — signed with its receipt PDF
6
+ * materializable, or issued in Notfallmodus.
7
+ * - `NOT_FISCALIZED`: backend-tse will never fiscalize this payment (a luca-web
8
+ * QR / self-service payment at a location that does not fiscalize web
9
+ * orders). There is no fiscal row and no Kassenbeleg.
10
+ */
11
+ export type FiscalizedPaymentStatus = 'FISCALIZED' | 'NOT_FISCALIZED';
12
+ /**
13
+ * Emitted by backend-tse once a payment's fiscalization outcome is final, so
14
+ * consumers (backend-pay) need not poll readiness. Delivery is at least once:
15
+ * dedupe on the envelope `id` (the fiscal payment id, or the payment id when
16
+ * NOT_FISCALIZED).
13
17
  */
14
18
  export type FiscalizedPayment = {
15
19
  version: FiscalizedPaymentEventVersion;
20
+ status: FiscalizedPaymentStatus;
16
21
  /**
17
- * `fiscal_payment_events.id` — TSE primary key used for receipt-token /
18
- * readiness / PDF. Always present. Envelope `id` should match this.
19
- */
20
- fiscalPaymentEventId: string;
21
- locationId: string;
22
- /**
23
- * backend-pay `V3Payment.uuid` when TSE knows it (settled Kafka card/web
24
- * path). May differ from `fiscalPaymentEventId` after fast-path reuse.
25
- * Absent for cash / when only a throwaway Kafka uuid was seen.
22
+ * backend-pay `V3Payment.uuid` for luca-web QR / self-service payments. Null
23
+ * for POS card payments (backend-tse cannot tell the real uuid from the
24
+ * fast-path one) and cash; resolve those via `checkoutId`.
26
25
  */
27
- paymentId?: string | null;
26
+ paymentId: string | null;
28
27
  /**
29
- * backend-pay `V3Checkout.uuid` when known. Join key when
30
- * `fiscalPaymentEventId` ≠ `paymentId`.
28
+ * `fiscal_payment_events.id` — the key for the receipt token / PDF. Null when
29
+ * NOT_FISCALIZED.
31
30
  */
32
- checkoutId?: string | null;
33
- notfallmodus?: boolean;
34
- tseSigningEventId?: string | null;
35
- statusCompleteAt?: Date | null;
31
+ fiscalPaymentEventId: string | null;
32
+ locationId: string;
33
+ /** backend-pay `V3Checkout.uuid` for card / web payments. */
34
+ checkoutId: string | null;
36
35
  };
@@ -26,6 +26,19 @@ export type OrderEventItem = {
26
26
  tax?: number;
27
27
  subItems?: OrderEventItem[];
28
28
  };
29
+ /**
30
+ * Legal / billing details of the location group, printed as the Kassenbeleg
31
+ * issuer for mirrored web orders (LUCA-36795).
32
+ */
33
+ export type OrderEventIssuer = {
34
+ legalName?: string | null;
35
+ street?: string | null;
36
+ postalCode?: string | null;
37
+ city?: string | null;
38
+ country?: string | null;
39
+ taxNumber?: string | null;
40
+ vatId?: string | null;
41
+ };
29
42
  /**
30
43
  * Emitted by backend-pay when a luca-web order is created (LUCA-36037).
31
44
  * Carries the full order snapshot so consumers can mirror it without a callback.
@@ -45,4 +58,6 @@ export type OrderEvent = {
45
58
  note: string | null;
46
59
  createdAt: Date;
47
60
  items: OrderEventItem[];
61
+ /** Optional so older producers and consumers keep working. */
62
+ issuer?: OrderEventIssuer | null;
48
63
  };
@@ -3,8 +3,8 @@ export { KafkaTopic } from './events';
3
3
  export type { ConversationMessage } from './events/conversationMessage';
4
4
  export type { RefundEvent } from './events/refund';
5
5
  export { REFUND_EVENT_VERSION } from './events/refund';
6
- export type { OrderEvent, OrderEventItem, OrderEventType, OrderEventStatus, OrderEventTranslatableName, } from './events/order';
6
+ export type { OrderEvent, OrderEventIssuer, OrderEventItem, OrderEventType, OrderEventStatus, OrderEventTranslatableName, } from './events/order';
7
7
  export { ORDER_EVENT_VERSION } from './events/order';
8
- export type { FiscalizedPayment } from './events/fiscalizedPayment';
8
+ export type { FiscalizedPayment, FiscalizedPaymentStatus, } from './events/fiscalizedPayment';
9
9
  export { FISCALIZED_PAYMENT_EVENT_VERSION } from './events/fiscalizedPayment';
10
10
  export type { KafkaEvent, GenericKafkaEvent, EventPayloadHandler, GenericEventPayloadHandler, KafkaConfiguration, CustomTopicConfig, CustomTopicPoisonContext, CustomTopicPoisonHandler, } from './types';
@@ -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.38.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": {