@nestjs/observe 0.0.1
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/LICENSE +23 -0
- package/README.md +135 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/agent/detached-observe-worker.d.ts +1 -0
- package/dist/agent/detached-observe-worker.js +104 -0
- package/dist/agent/observe-agent.shared-buffer.d.ts +42 -0
- package/dist/agent/observe-agent.shared-buffer.js +211 -0
- package/dist/agent/observe-agent.worker.d.ts +25 -0
- package/dist/agent/observe-agent.worker.js +213 -0
- package/dist/custom-metrics/counter.d.ts +39 -0
- package/dist/custom-metrics/counter.js +128 -0
- package/dist/custom-metrics/gauge.d.ts +40 -0
- package/dist/custom-metrics/gauge.js +134 -0
- package/dist/custom-metrics/index.d.ts +3 -0
- package/dist/custom-metrics/index.js +3 -0
- package/dist/custom-metrics/summary.d.ts +38 -0
- package/dist/custom-metrics/summary.js +106 -0
- package/dist/encoders/custom-metrics.encoder.d.ts +25 -0
- package/dist/encoders/custom-metrics.encoder.js +50 -0
- package/dist/encoders/job-snapshot.encoder.d.ts +28 -0
- package/dist/encoders/job-snapshot.encoder.js +28 -0
- package/dist/encoders/remap-keys.util.d.ts +1 -0
- package/dist/encoders/remap-keys.util.js +10 -0
- package/dist/encoders/request-snapshot.encoder.d.ts +33 -0
- package/dist/encoders/request-snapshot.encoder.js +32 -0
- package/dist/encoders/runtime-metrics.encoder.d.ts +63 -0
- package/dist/encoders/runtime-metrics.encoder.js +55 -0
- package/dist/encoders/trace.encoder.d.ts +19 -0
- package/dist/encoders/trace.encoder.js +20 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/instrument/create-instance-decorator.instrument.d.ts +7 -0
- package/dist/instrument/create-instance-decorator.instrument.js +165 -0
- package/dist/interfaces/custom-metric.interface.d.ts +18 -0
- package/dist/interfaces/custom-metric.interface.js +1 -0
- package/dist/interfaces/graphql.interfaces.d.ts +12 -0
- package/dist/interfaces/graphql.interfaces.js +1 -0
- package/dist/interfaces/index.d.ts +7 -0
- package/dist/interfaces/index.js +7 -0
- package/dist/interfaces/job-snapshot.interface.d.ts +23 -0
- package/dist/interfaces/job-snapshot.interface.js +1 -0
- package/dist/interfaces/node-runtime-metrics.interface.d.ts +37 -0
- package/dist/interfaces/node-runtime-metrics.interface.js +1 -0
- package/dist/interfaces/observe-options.interface.d.ts +93 -0
- package/dist/interfaces/observe-options.interface.js +1 -0
- package/dist/interfaces/request-snapshot.interface.d.ts +23 -0
- package/dist/interfaces/request-snapshot.interface.js +1 -0
- package/dist/interfaces/trace-events.interfaces.d.ts +17 -0
- package/dist/interfaces/trace-events.interfaces.js +1 -0
- package/dist/interfaces/trace-span.interface.d.ts +12 -0
- package/dist/interfaces/trace-span.interface.js +1 -0
- package/dist/observe.constants.d.ts +2 -0
- package/dist/observe.constants.js +2 -0
- package/dist/observe.module.d.ts +20 -0
- package/dist/observe.module.js +181 -0
- package/dist/profiling/cpu-profiler.service.d.ts +45 -0
- package/dist/profiling/cpu-profiler.service.js +146 -0
- package/dist/profiling/fold-profile.util.d.ts +28 -0
- package/dist/profiling/fold-profile.util.js +0 -0
- package/dist/profiling/profile-uploader.d.ts +19 -0
- package/dist/profiling/profile-uploader.js +88 -0
- package/dist/profiling/span-slice-recorder.d.ts +18 -0
- package/dist/profiling/span-slice-recorder.js +78 -0
- package/dist/protocols/graphql-observe-agent.service.d.ts +58 -0
- package/dist/protocols/graphql-observe-agent.service.js +261 -0
- package/dist/protocols/graphql-operation-parser.d.ts +10 -0
- package/dist/protocols/graphql-operation-parser.js +174 -0
- package/dist/protocols/http-observe-agent.service.d.ts +31 -0
- package/dist/protocols/http-observe-agent.service.js +186 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +15 -0
- package/dist/protocols/queue-observe-agent.service.js +132 -0
- package/dist/protocols/rpc-observe-agent.service.d.ts +33 -0
- package/dist/protocols/rpc-observe-agent.service.js +183 -0
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.js +1 -0
- package/dist/services/logger-patcher.service.d.ts +12 -0
- package/dist/services/logger-patcher.service.js +76 -0
- package/dist/services/node-runtime-metrics.service.d.ts +23 -0
- package/dist/services/node-runtime-metrics.service.js +156 -0
- package/dist/services/operation-trace.registry.d.ts +49 -0
- package/dist/services/operation-trace.registry.js +364 -0
- package/dist/services/stdout-forwarder.service.d.ts +21 -0
- package/dist/services/stdout-forwarder.service.js +128 -0
- package/dist/services/trace-sampler.service.d.ts +19 -0
- package/dist/services/trace-sampler.service.js +38 -0
- package/dist/services/tracer.service.d.ts +48 -0
- package/dist/services/tracer.service.js +186 -0
- package/dist/trace-span.delegate.d.ts +10 -0
- package/dist/trace-span.delegate.js +24 -0
- package/dist/types/key-of.type.d.ts +1 -0
- package/dist/types/key-of.type.js +1 -0
- package/dist/types/path-value.type.d.ts +6 -0
- package/dist/types/path-value.type.js +1 -0
- package/dist/utils/assert-module-options.util.d.ts +2 -0
- package/dist/utils/assert-module-options.util.js +8 -0
- package/dist/utils/default-trace-id-generator.util.d.ts +1 -0
- package/dist/utils/default-trace-id-generator.util.js +11 -0
- package/dist/utils/log-line.parser.d.ts +9 -0
- package/dist/utils/log-line.parser.js +59 -0
- package/dist/utils/log-redactor.d.ts +11 -0
- package/dist/utils/log-redactor.js +150 -0
- package/dist/utils/redact-url-query.d.ts +2 -0
- package/dist/utils/redact-url-query.js +51 -0
- package/dist/utils/source-context.util.d.ts +11 -0
- package/dist/utils/source-context.util.js +130 -0
- package/dist/utils/source-map-resolver.util.d.ts +7 -0
- package/dist/utils/source-map-resolver.util.js +107 -0
- package/package.json +129 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
14
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
15
|
+
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
16
|
+
import { Gauge, Summary } from "../custom-metrics/index.js";
|
|
17
|
+
import { Counter } from "../custom-metrics/counter.js";
|
|
18
|
+
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
19
|
+
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
20
|
+
import { OperationTraceRegistry } from "./operation-trace.registry.js";
|
|
21
|
+
let TracerService = class TracerService {
|
|
22
|
+
operationTraceRegistry;
|
|
23
|
+
als;
|
|
24
|
+
observeAgentSharedBuffer;
|
|
25
|
+
options;
|
|
26
|
+
counters = new Map();
|
|
27
|
+
gauges = new Map();
|
|
28
|
+
summaries = new Map();
|
|
29
|
+
constructor(operationTraceRegistry, als, observeAgentSharedBuffer, options) {
|
|
30
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
31
|
+
this.als = als;
|
|
32
|
+
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
33
|
+
this.options = options;
|
|
34
|
+
}
|
|
35
|
+
async createSpan(name, callback) {
|
|
36
|
+
const store = this.als.getStore();
|
|
37
|
+
if (!store) {
|
|
38
|
+
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "createSpan" method within an async context.');
|
|
39
|
+
}
|
|
40
|
+
const traceId = this.requireTraceId(store, "createSpan");
|
|
41
|
+
const callerId = store.get(CALLER_METADATA_KEY);
|
|
42
|
+
return this.operationTraceRegistry.createManualSpan(traceId, callerId, name, callback);
|
|
43
|
+
}
|
|
44
|
+
async activeSpan() {
|
|
45
|
+
const store = this.als.getStore();
|
|
46
|
+
if (!store) {
|
|
47
|
+
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "activeSpan" method within an async context.');
|
|
48
|
+
}
|
|
49
|
+
const traceId = this.requireTraceId(store, "activeSpan");
|
|
50
|
+
const callerId = store.get(CALLER_METADATA_KEY);
|
|
51
|
+
const activeOngoingEvent = this.operationTraceRegistry.getActiveSpan(traceId, callerId);
|
|
52
|
+
if (!activeOngoingEvent) {
|
|
53
|
+
throw new Error(`No active span found for traceId: ${traceId}. Ensure that a span is created before calling "activeSpan".`);
|
|
54
|
+
}
|
|
55
|
+
let tags = activeOngoingEvent.tags;
|
|
56
|
+
if (!tags) {
|
|
57
|
+
tags = {};
|
|
58
|
+
activeOngoingEvent.tags = tags;
|
|
59
|
+
}
|
|
60
|
+
const traceSpanDelegate = new TraceSpanDelegate(activeOngoingEvent.spanId ?? "", activeOngoingEvent.name, tags);
|
|
61
|
+
return traceSpanDelegate;
|
|
62
|
+
}
|
|
63
|
+
async captureError(error, tags) {
|
|
64
|
+
const store = this.als.getStore();
|
|
65
|
+
if (!store) {
|
|
66
|
+
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
|
|
67
|
+
}
|
|
68
|
+
const traceId = store.get(this.options.traceIdKey);
|
|
69
|
+
if (typeof traceId !== "string") {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const callerId = store.get(CALLER_METADATA_KEY);
|
|
73
|
+
this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {});
|
|
74
|
+
}
|
|
75
|
+
counter(name, attributes) {
|
|
76
|
+
const existingRef = this.counters.get(name);
|
|
77
|
+
if (existingRef) {
|
|
78
|
+
const overridableRef = existingRef;
|
|
79
|
+
if (attributes?.description) {
|
|
80
|
+
overridableRef.description = attributes.description;
|
|
81
|
+
}
|
|
82
|
+
if (attributes?.labels) {
|
|
83
|
+
overridableRef.labels = attributes.labels;
|
|
84
|
+
}
|
|
85
|
+
if (attributes?.initialValue !== undefined &&
|
|
86
|
+
existingRef.getValue() === 0) {
|
|
87
|
+
overridableRef["value"] = attributes.initialValue;
|
|
88
|
+
}
|
|
89
|
+
return existingRef;
|
|
90
|
+
}
|
|
91
|
+
const counter = new Counter(name, attributes?.description, attributes?.initialValue, attributes?.labels);
|
|
92
|
+
this.registerCounterChangeHandler(counter);
|
|
93
|
+
this.counters.set(name, counter);
|
|
94
|
+
return counter;
|
|
95
|
+
}
|
|
96
|
+
gauge(name, attributes) {
|
|
97
|
+
const existingRef = this.gauges.get(name);
|
|
98
|
+
if (existingRef) {
|
|
99
|
+
const overridableRef = existingRef;
|
|
100
|
+
if (attributes?.description) {
|
|
101
|
+
overridableRef.description = attributes.description;
|
|
102
|
+
}
|
|
103
|
+
if (attributes?.labels) {
|
|
104
|
+
overridableRef.labels = attributes.labels;
|
|
105
|
+
}
|
|
106
|
+
if (attributes?.initialValue !== undefined &&
|
|
107
|
+
existingRef.getValue() === 0) {
|
|
108
|
+
overridableRef["value"] = attributes.initialValue;
|
|
109
|
+
}
|
|
110
|
+
if (attributes?.kind) {
|
|
111
|
+
overridableRef.kind = attributes.kind;
|
|
112
|
+
}
|
|
113
|
+
return existingRef;
|
|
114
|
+
}
|
|
115
|
+
const gauge = new Gauge(name, attributes ?? {});
|
|
116
|
+
this.registerGaugeChangeHandler(gauge);
|
|
117
|
+
this.gauges.set(name, gauge);
|
|
118
|
+
return gauge;
|
|
119
|
+
}
|
|
120
|
+
summary(name, attributes) {
|
|
121
|
+
const existingRef = this.summaries.get(name);
|
|
122
|
+
if (existingRef) {
|
|
123
|
+
const overridableRef = existingRef;
|
|
124
|
+
if (attributes?.description) {
|
|
125
|
+
overridableRef.description = attributes.description;
|
|
126
|
+
}
|
|
127
|
+
if (attributes?.labels) {
|
|
128
|
+
overridableRef.labels = attributes.labels;
|
|
129
|
+
}
|
|
130
|
+
return existingRef;
|
|
131
|
+
}
|
|
132
|
+
const summary = new Summary(name, attributes ?? {});
|
|
133
|
+
this.registerSummaryChangeHandler(summary);
|
|
134
|
+
this.summaries.set(name, summary);
|
|
135
|
+
return summary;
|
|
136
|
+
}
|
|
137
|
+
currentTraceId() {
|
|
138
|
+
const store = this.als.getStore();
|
|
139
|
+
const traceId = store?.get(this.options.traceIdKey);
|
|
140
|
+
return typeof traceId === "string" ? traceId : null;
|
|
141
|
+
}
|
|
142
|
+
setAttribute(key, value) {
|
|
143
|
+
const store = this.als.getStore();
|
|
144
|
+
if (!store) {
|
|
145
|
+
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "setAttribute" method within an async context.');
|
|
146
|
+
}
|
|
147
|
+
store.set(key, value);
|
|
148
|
+
}
|
|
149
|
+
getAttribute(key) {
|
|
150
|
+
const store = this.als.getStore();
|
|
151
|
+
if (!store) {
|
|
152
|
+
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "getAttribute" method within an async context.');
|
|
153
|
+
}
|
|
154
|
+
return store.get(key);
|
|
155
|
+
}
|
|
156
|
+
requireTraceId(store, method) {
|
|
157
|
+
const traceId = store.get(this.options.traceIdKey);
|
|
158
|
+
if (typeof traceId !== "string") {
|
|
159
|
+
throw new Error(`No trace id found in the current context. Ensure that you are using the "${method}" method within a traced operation.`);
|
|
160
|
+
}
|
|
161
|
+
return traceId;
|
|
162
|
+
}
|
|
163
|
+
registerCounterChangeHandler(counter) {
|
|
164
|
+
counter["_onChange"] = (self) => {
|
|
165
|
+
this.observeAgentSharedBuffer.upsertCustomMetric(self);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
registerGaugeChangeHandler(gauge) {
|
|
169
|
+
gauge["_onChange"] = (self) => {
|
|
170
|
+
this.observeAgentSharedBuffer.upsertCustomMetric(self);
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
registerSummaryChangeHandler(summary) {
|
|
174
|
+
summary["_onChange"] = (self) => {
|
|
175
|
+
this.observeAgentSharedBuffer.upsertCustomMetric(self);
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
TracerService = __decorate([
|
|
180
|
+
Injectable(),
|
|
181
|
+
__param(3, Inject(OBSERVE_OPTIONS)),
|
|
182
|
+
__metadata("design:paramtypes", [OperationTraceRegistry,
|
|
183
|
+
AsyncLocalStorage,
|
|
184
|
+
ObserveAgentSharedBuffer, Object])
|
|
185
|
+
], TracerService);
|
|
186
|
+
export { TracerService };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare class TraceSpanDelegate {
|
|
2
|
+
private readonly _id;
|
|
3
|
+
private readonly _name;
|
|
4
|
+
private readonly _tags;
|
|
5
|
+
get id(): string;
|
|
6
|
+
get name(): string | undefined;
|
|
7
|
+
constructor(_id: string, _name: string | undefined, _tags: Record<string, string | number | boolean>);
|
|
8
|
+
setTag(key: string, value: string | number | boolean): TraceSpanDelegate;
|
|
9
|
+
addTags(tags: Record<string, string | number | boolean>): TraceSpanDelegate;
|
|
10
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export class TraceSpanDelegate {
|
|
2
|
+
_id;
|
|
3
|
+
_name;
|
|
4
|
+
_tags;
|
|
5
|
+
get id() {
|
|
6
|
+
return this._id;
|
|
7
|
+
}
|
|
8
|
+
get name() {
|
|
9
|
+
return this._name;
|
|
10
|
+
}
|
|
11
|
+
constructor(_id, _name, _tags) {
|
|
12
|
+
this._id = _id;
|
|
13
|
+
this._name = _name;
|
|
14
|
+
this._tags = _tags;
|
|
15
|
+
}
|
|
16
|
+
setTag(key, value) {
|
|
17
|
+
this._tags[key] = value;
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
addTags(tags) {
|
|
21
|
+
Object.assign(this._tags, tags);
|
|
22
|
+
return this;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type KeyOf<T> = keyof T extends never ? string | symbol : keyof T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
type IsAny<T> = unknown extends T ? [keyof T] extends [never] ? false : true : false;
|
|
2
|
+
export type PathImpl<T, Key extends keyof T> = Key extends string ? IsAny<T[Key]> extends true ? never : T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;
|
|
3
|
+
export type PathImpl2<T> = PathImpl<T, keyof T> | keyof T;
|
|
4
|
+
export type Path<T> = keyof T extends string ? PathImpl2<T> extends infer P ? P extends string | keyof T ? P : keyof T : keyof T : never;
|
|
5
|
+
export type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
export function assertModuleOptions(options) {
|
|
3
|
+
if (!options) {
|
|
4
|
+
const errorMessage = `ObserveModule initialized without options. Ensure that you used the "forRoot" method to configure the module, as follows: "ObserveModule.forRoot()".`;
|
|
5
|
+
Logger.error(errorMessage);
|
|
6
|
+
throw new Error(errorMessage);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function defaultTraceIdGenerator(req: unknown): string;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { randomUUID } from "crypto";
|
|
2
|
+
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
3
|
+
export function defaultTraceIdGenerator(req) {
|
|
4
|
+
if (typeof req === "object" && req !== null && "headers" in req) {
|
|
5
|
+
const requestId = req.headers["x-request-id"];
|
|
6
|
+
if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
|
|
7
|
+
return requestId;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
return randomUUID();
|
|
11
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface ParsedLogLine {
|
|
2
|
+
level?: string;
|
|
3
|
+
context?: string;
|
|
4
|
+
message: string;
|
|
5
|
+
traceId?: string;
|
|
6
|
+
attributes?: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
export declare function stripAnsi(value: string): string;
|
|
9
|
+
export declare function parseLogLine(line: string): ParsedLogLine;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
|
|
2
|
+
const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+.+?\s{2,}(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
|
|
3
|
+
const TRACE_ID_SUFFIX_PATTERN = /\s*Trace ID:\s*(\S+)\s*$/;
|
|
4
|
+
const STRUCTURED_KEYS = new Set([
|
|
5
|
+
"level",
|
|
6
|
+
"message",
|
|
7
|
+
"context",
|
|
8
|
+
"traceId",
|
|
9
|
+
"timestamp",
|
|
10
|
+
"pid",
|
|
11
|
+
]);
|
|
12
|
+
export function stripAnsi(value) {
|
|
13
|
+
return value.replace(ANSI_PATTERN, "");
|
|
14
|
+
}
|
|
15
|
+
export function parseLogLine(line) {
|
|
16
|
+
const clean = stripAnsi(line).trimEnd();
|
|
17
|
+
return parseStructured(clean) ?? parseNestText(clean) ?? { message: clean };
|
|
18
|
+
}
|
|
19
|
+
function parseStructured(line) {
|
|
20
|
+
if (!line.startsWith("{")) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
let parsed;
|
|
24
|
+
try {
|
|
25
|
+
parsed = JSON.parse(line);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const record = parsed;
|
|
34
|
+
if (typeof record.message !== "string") {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const attributes = Object.fromEntries(Object.entries(record).filter(([key]) => !STRUCTURED_KEYS.has(key)));
|
|
38
|
+
return {
|
|
39
|
+
level: typeof record.level === "string" ? record.level : undefined,
|
|
40
|
+
context: typeof record.context === "string" ? record.context : undefined,
|
|
41
|
+
traceId: typeof record.traceId === "string" ? record.traceId : undefined,
|
|
42
|
+
message: record.message,
|
|
43
|
+
attributes: Object.keys(attributes).length > 0 ? attributes : undefined,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function parseNestText(line) {
|
|
47
|
+
const match = NEST_TEXT_PATTERN.exec(line);
|
|
48
|
+
if (!match) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const [, level, context, rest] = match;
|
|
52
|
+
const traceIdMatch = TRACE_ID_SUFFIX_PATTERN.exec(rest);
|
|
53
|
+
return {
|
|
54
|
+
level: level.toLowerCase(),
|
|
55
|
+
context: context || undefined,
|
|
56
|
+
traceId: traceIdMatch?.[1],
|
|
57
|
+
message: traceIdMatch ? rest.slice(0, traceIdMatch.index).trimEnd() : rest,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { RedactionOptions } from "../interfaces/observe-options.interface.js";
|
|
2
|
+
export declare class LogRedactor {
|
|
3
|
+
private readonly rules;
|
|
4
|
+
private readonly sensitiveKeys;
|
|
5
|
+
private readonly replacement;
|
|
6
|
+
private readonly redactCards;
|
|
7
|
+
constructor(options?: RedactionOptions);
|
|
8
|
+
redactMessage(message: string): string;
|
|
9
|
+
redactAttributes(attributes: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
|
|
10
|
+
private redactValue;
|
|
11
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
const DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
2
|
+
const DEFAULT_SENSITIVE_KEYS = [
|
|
3
|
+
"password",
|
|
4
|
+
"passwd",
|
|
5
|
+
"pwd",
|
|
6
|
+
"secret",
|
|
7
|
+
"token",
|
|
8
|
+
"accesstoken",
|
|
9
|
+
"refreshtoken",
|
|
10
|
+
"idtoken",
|
|
11
|
+
"apikey",
|
|
12
|
+
"authorization",
|
|
13
|
+
"auth",
|
|
14
|
+
"credential",
|
|
15
|
+
"credentials",
|
|
16
|
+
"privatekey",
|
|
17
|
+
"accesskey",
|
|
18
|
+
"secretkey",
|
|
19
|
+
"sessionid",
|
|
20
|
+
"cookie",
|
|
21
|
+
"setcookie",
|
|
22
|
+
];
|
|
23
|
+
const TEXT_KEY_ALTERNATION = [
|
|
24
|
+
"password",
|
|
25
|
+
"passwd",
|
|
26
|
+
"pwd",
|
|
27
|
+
"secret",
|
|
28
|
+
"token",
|
|
29
|
+
"access[_-]?token",
|
|
30
|
+
"refresh[_-]?token",
|
|
31
|
+
"id[_-]?token",
|
|
32
|
+
"api[_-]?key",
|
|
33
|
+
"authorization",
|
|
34
|
+
"auth",
|
|
35
|
+
"credentials?",
|
|
36
|
+
"private[_-]?key",
|
|
37
|
+
"access[_-]?key",
|
|
38
|
+
"secret[_-]?key",
|
|
39
|
+
"session[_-]?id",
|
|
40
|
+
"set-cookie",
|
|
41
|
+
"cookie",
|
|
42
|
+
].join("|");
|
|
43
|
+
function buildDefaultRules() {
|
|
44
|
+
return [
|
|
45
|
+
{
|
|
46
|
+
pattern: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,
|
|
47
|
+
replace: (replacement) => replacement,
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
pattern: /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi,
|
|
51
|
+
replace: (replacement, scheme) => `${scheme} ${replacement}`,
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
pattern: new RegExp(`((?:${TEXT_KEY_ALTERNATION})"?\\s*[:=]\\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic|Token)\\s+\\S+|[^\\s,;&}"']+)`, "gi"),
|
|
55
|
+
replace: (replacement, prefix) => `${prefix}${replacement}`,
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
pattern: /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
|
|
59
|
+
replace: (replacement) => replacement,
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
pattern: /\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ABIA|ACCA)[0-9A-Z]{16}\b/g,
|
|
63
|
+
replace: (replacement) => replacement,
|
|
64
|
+
},
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
const CARD_CANDIDATE = /\b\d(?:[ -]?\d){12,18}\b/g;
|
|
68
|
+
function isLuhnValid(digits) {
|
|
69
|
+
let sum = 0;
|
|
70
|
+
let double = false;
|
|
71
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
72
|
+
let digit = digits.charCodeAt(i) - 48;
|
|
73
|
+
if (double) {
|
|
74
|
+
digit *= 2;
|
|
75
|
+
if (digit > 9) {
|
|
76
|
+
digit -= 9;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
sum += digit;
|
|
80
|
+
double = !double;
|
|
81
|
+
}
|
|
82
|
+
return sum % 10 === 0;
|
|
83
|
+
}
|
|
84
|
+
const MAX_ATTRIBUTE_DEPTH = 8;
|
|
85
|
+
export class LogRedactor {
|
|
86
|
+
rules;
|
|
87
|
+
sensitiveKeys;
|
|
88
|
+
replacement;
|
|
89
|
+
redactCards;
|
|
90
|
+
constructor(options = {}) {
|
|
91
|
+
this.replacement = options.replacement ?? DEFAULT_REPLACEMENT;
|
|
92
|
+
this.redactCards = options.useDefaultPatterns !== false;
|
|
93
|
+
const defaults = options.useDefaultPatterns === false ? [] : buildDefaultRules();
|
|
94
|
+
const extra = (options.patterns ?? []).map((pattern) => ({
|
|
95
|
+
pattern: pattern.global
|
|
96
|
+
? pattern
|
|
97
|
+
: new RegExp(pattern.source, pattern.flags + "g"),
|
|
98
|
+
replace: (replacement) => replacement,
|
|
99
|
+
}));
|
|
100
|
+
this.rules = [...defaults, ...extra];
|
|
101
|
+
this.sensitiveKeys = new Set([...DEFAULT_SENSITIVE_KEYS, ...(options.keys ?? [])].map(normaliseKey));
|
|
102
|
+
}
|
|
103
|
+
redactMessage(message) {
|
|
104
|
+
let output = message;
|
|
105
|
+
for (const rule of this.rules) {
|
|
106
|
+
output = output.replace(rule.pattern, (...args) => {
|
|
107
|
+
const groups = args.slice(1, -2).map((group) => group ?? "");
|
|
108
|
+
return rule.replace(this.replacement, ...groups);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
if (this.redactCards) {
|
|
112
|
+
output = output.replace(CARD_CANDIDATE, (match) => {
|
|
113
|
+
const digits = match.replace(/[ -]/g, "");
|
|
114
|
+
return digits.length >= 13 && isLuhnValid(digits)
|
|
115
|
+
? this.replacement
|
|
116
|
+
: match;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return output;
|
|
120
|
+
}
|
|
121
|
+
redactAttributes(attributes) {
|
|
122
|
+
if (!attributes) {
|
|
123
|
+
return attributes;
|
|
124
|
+
}
|
|
125
|
+
return this.redactValue(attributes, 0);
|
|
126
|
+
}
|
|
127
|
+
redactValue(value, depth) {
|
|
128
|
+
if (depth > MAX_ATTRIBUTE_DEPTH) {
|
|
129
|
+
return this.replacement;
|
|
130
|
+
}
|
|
131
|
+
if (typeof value === "string") {
|
|
132
|
+
return this.redactMessage(value);
|
|
133
|
+
}
|
|
134
|
+
if (Array.isArray(value)) {
|
|
135
|
+
return value.map((item) => this.redactValue(item, depth + 1));
|
|
136
|
+
}
|
|
137
|
+
if (value && typeof value === "object") {
|
|
138
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
139
|
+
key,
|
|
140
|
+
this.sensitiveKeys.has(normaliseKey(key))
|
|
141
|
+
? this.replacement
|
|
142
|
+
: this.redactValue(item, depth + 1),
|
|
143
|
+
]));
|
|
144
|
+
}
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function normaliseKey(key) {
|
|
149
|
+
return key.toLowerCase().replace(/[-_]/g, "");
|
|
150
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const SENSITIVE_QUERY_KEYS = new Set([
|
|
2
|
+
"password",
|
|
3
|
+
"passwd",
|
|
4
|
+
"pwd",
|
|
5
|
+
"secret",
|
|
6
|
+
"token",
|
|
7
|
+
"accesstoken",
|
|
8
|
+
"refreshtoken",
|
|
9
|
+
"idtoken",
|
|
10
|
+
"apikey",
|
|
11
|
+
"apitoken",
|
|
12
|
+
"authorization",
|
|
13
|
+
"auth",
|
|
14
|
+
"code",
|
|
15
|
+
"credential",
|
|
16
|
+
"credentials",
|
|
17
|
+
"privatekey",
|
|
18
|
+
"accesskey",
|
|
19
|
+
"secretkey",
|
|
20
|
+
"sessionid",
|
|
21
|
+
"sig",
|
|
22
|
+
"signature",
|
|
23
|
+
"state",
|
|
24
|
+
]);
|
|
25
|
+
export const REDACTED = "[REDACTED]";
|
|
26
|
+
function normaliseKey(key) {
|
|
27
|
+
return key.toLowerCase().replace(/[-_]/g, "");
|
|
28
|
+
}
|
|
29
|
+
export function redactUrlQuery(url) {
|
|
30
|
+
const separator = url.indexOf("?");
|
|
31
|
+
if (separator === -1) {
|
|
32
|
+
return url;
|
|
33
|
+
}
|
|
34
|
+
const path = url.slice(0, separator);
|
|
35
|
+
const rest = url.slice(separator + 1);
|
|
36
|
+
const hashAt = rest.indexOf("#");
|
|
37
|
+
const query = hashAt === -1 ? rest : rest.slice(0, hashAt);
|
|
38
|
+
const fragment = hashAt === -1 ? "" : rest.slice(hashAt);
|
|
39
|
+
const params = new URLSearchParams(query);
|
|
40
|
+
let redactedAny = false;
|
|
41
|
+
for (const key of [...params.keys()]) {
|
|
42
|
+
if (SENSITIVE_QUERY_KEYS.has(normaliseKey(key))) {
|
|
43
|
+
params.set(key, REDACTED);
|
|
44
|
+
redactedAny = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!redactedAny) {
|
|
48
|
+
return url;
|
|
49
|
+
}
|
|
50
|
+
return `${path}?${params.toString()}${fragment}`;
|
|
51
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface CodeFrame {
|
|
2
|
+
file: string;
|
|
3
|
+
line: number;
|
|
4
|
+
firstLine: number;
|
|
5
|
+
lines: string[];
|
|
6
|
+
}
|
|
7
|
+
export declare function collectCodeFrames(stack: string | undefined, options?: {
|
|
8
|
+
linesOfContext?: number;
|
|
9
|
+
maxFrames?: number;
|
|
10
|
+
sourceMaps?: boolean;
|
|
11
|
+
}): CodeFrame[] | undefined;
|