@c9up/spectrum 0.1.18 → 0.1.20
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/README.md +33 -7
- package/dist/Logger.d.ts +6 -2
- package/dist/Logger.d.ts.map +1 -1
- package/dist/Logger.js +214 -80
- package/dist/Logger.js.map +1 -1
- package/dist/LoggerManager.d.ts +5 -0
- package/dist/LoggerManager.d.ts.map +1 -1
- package/dist/LoggerManager.js +10 -3
- package/dist/LoggerManager.js.map +1 -1
- package/dist/RustLogBridge.d.ts +27 -2
- package/dist/RustLogBridge.d.ts.map +1 -1
- package/dist/RustLogBridge.js +45 -31
- package/dist/RustLogBridge.js.map +1 -1
- package/dist/SpectrumProvider.d.ts +6 -2
- package/dist/SpectrumProvider.d.ts.map +1 -1
- package/dist/SpectrumProvider.js +18 -12
- package/dist/SpectrumProvider.js.map +1 -1
- package/dist/channels/ConsoleChannel.d.ts +8 -1
- package/dist/channels/ConsoleChannel.d.ts.map +1 -1
- package/dist/channels/ConsoleChannel.js +18 -14
- package/dist/channels/ConsoleChannel.js.map +1 -1
- package/dist/channels/FileChannel.d.ts +32 -9
- package/dist/channels/FileChannel.d.ts.map +1 -1
- package/dist/channels/FileChannel.js +264 -202
- package/dist/channels/FileChannel.js.map +1 -1
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/jsonLine.d.ts +49 -0
- package/dist/jsonLine.d.ts.map +1 -0
- package/dist/jsonLine.js +165 -0
- package/dist/jsonLine.js.map +1 -0
- package/dist/redact.d.ts +16 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +121 -10
- package/dist/redact.js.map +1 -1
- package/dist/sanitize.d.ts +11 -5
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +36 -12
- package/dist/sanitize.js.map +1 -1
- package/dist/services/main.d.ts.map +1 -1
- package/dist/services/main.js +12 -1
- package/dist/services/main.js.map +1 -1
- package/dist/stdSerializers.d.ts +48 -0
- package/dist/stdSerializers.d.ts.map +1 -0
- package/dist/stdSerializers.js +129 -0
- package/dist/stdSerializers.js.map +1 -0
- package/dist/stringify.d.ts +33 -0
- package/dist/stringify.d.ts.map +1 -0
- package/dist/stringify.js +148 -0
- package/dist/stringify.js.map +1 -0
- package/dist/targets.d.ts +29 -7
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +130 -31
- package/dist/targets.js.map +1 -1
- package/dist/testing/FakeLogger.js +20 -5
- package/dist/testing/FakeLogger.js.map +1 -1
- package/dist/types.d.ts +71 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +21 -3
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/Logger.ts +277 -85
- package/src/LoggerManager.ts +10 -3
- package/src/RustLogBridge.ts +59 -30
- package/src/SpectrumProvider.ts +31 -18
- package/src/channels/ConsoleChannel.ts +30 -14
- package/src/channels/FileChannel.ts +319 -220
- package/src/errors.ts +13 -0
- package/src/index.ts +17 -3
- package/src/jsonLine.ts +223 -0
- package/src/redact.ts +133 -9
- package/src/sanitize.ts +36 -12
- package/src/services/main.ts +13 -1
- package/src/stdSerializers.ts +147 -0
- package/src/stringify.ts +175 -0
- package/src/targets.ts +193 -42
- package/src/testing/FakeLogger.ts +23 -5
- package/src/types.ts +100 -5
- package/stubs/config/logger.stub +11 -1
package/src/jsonLine.ts
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The JSON line a structured channel writes: pino's shape.
|
|
3
|
+
*
|
|
4
|
+
* {"level":30,"time":1731000000000,"pid":4242,"hostname":"web-1","module":"app","userId":7,"msg":"signed in"}
|
|
5
|
+
*
|
|
6
|
+
* Numeric `level`, epoch-millisecond `time`, `pid` and `hostname` from `base`,
|
|
7
|
+
* bindings and merged fields at the root, the message under `msg` — what a
|
|
8
|
+
* dashboard, an alert rule or `pino-pretty` reads from a pino line. The keys
|
|
9
|
+
* and the time format follow the logger's `messageKey`, `timestamp`, `base`
|
|
10
|
+
* and `formatters` options, as they do upstream.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { hostname } from "node:os";
|
|
14
|
+
import { SpectrumError } from "./errors.js";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_STRINGIFY_LIMITS,
|
|
17
|
+
type StringifyLimits,
|
|
18
|
+
stringifyRecord,
|
|
19
|
+
} from "./stringify.js";
|
|
20
|
+
import type { LogEntry, LogLevel } from "./types.js";
|
|
21
|
+
import { LOG_LEVEL_ORDER, logEntryExtras } from "./types.js";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How `time` is written: `'epoch'` (ms, the default), `'iso'`, `'unix'`
|
|
25
|
+
* (seconds), `false` to leave it out, or a function returning the raw
|
|
26
|
+
* fragment to append (`,"time":…`), as upstream's time functions do.
|
|
27
|
+
*/
|
|
28
|
+
export type TimestampOption =
|
|
29
|
+
| "epoch"
|
|
30
|
+
| "iso"
|
|
31
|
+
| "unix"
|
|
32
|
+
| boolean
|
|
33
|
+
| (() => string);
|
|
34
|
+
|
|
35
|
+
export interface LineFormatters {
|
|
36
|
+
/** The level's part of the line. Default `{ level: <number> }`. */
|
|
37
|
+
level?: (label: LogLevel, number: number) => Record<string, unknown>;
|
|
38
|
+
/** Reshape the merged fields (bindings and merging object) before writing. */
|
|
39
|
+
log?: (object: Record<string, unknown>) => Record<string, unknown>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface JsonLineOptions {
|
|
43
|
+
messageKey: string;
|
|
44
|
+
timestamp: TimestampOption;
|
|
45
|
+
/** Fields written on every line; `null` for none. */
|
|
46
|
+
base: Record<string, unknown> | null;
|
|
47
|
+
formatters: LineFormatters;
|
|
48
|
+
limits: StringifyLimits;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const DEFAULT_BASE: Record<string, unknown> = {
|
|
52
|
+
pid: process.pid,
|
|
53
|
+
hostname: hostname(),
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export const DEFAULT_LINE_OPTIONS: JsonLineOptions = {
|
|
57
|
+
messageKey: "msg",
|
|
58
|
+
timestamp: "epoch",
|
|
59
|
+
base: DEFAULT_BASE,
|
|
60
|
+
formatters: {},
|
|
61
|
+
limits: DEFAULT_STRINGIFY_LIMITS,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The options a logger configured for its entries. Channels are built
|
|
66
|
+
* independently of the logger writing to them, so the options travel with the
|
|
67
|
+
* entry; weak, so a written entry leaves nothing behind.
|
|
68
|
+
*/
|
|
69
|
+
const entryOptions = new WeakMap<object, JsonLineOptions>();
|
|
70
|
+
|
|
71
|
+
/** @internal Attach a logger's line options to an entry it is about to write. */
|
|
72
|
+
export function attachLineOptions(
|
|
73
|
+
entry: object,
|
|
74
|
+
options: JsonLineOptions,
|
|
75
|
+
): void {
|
|
76
|
+
entryOptions.set(entry, options);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The line options for this entry: its logger's, else the defaults. */
|
|
80
|
+
export function lineOptionsFor(entry: object): JsonLineOptions {
|
|
81
|
+
return entryOptions.get(entry) ?? DEFAULT_LINE_OPTIONS;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function invalid(detail: string): SpectrumError {
|
|
85
|
+
return new SpectrumError("E_SPECTRUM_INVALID_LINE_OPTIONS", detail);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
89
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Check the line options a config declares, filling in the defaults. */
|
|
93
|
+
export function resolveLineOptions(config: {
|
|
94
|
+
messageKey?: string;
|
|
95
|
+
timestamp?: TimestampOption;
|
|
96
|
+
base?: Record<string, unknown> | null;
|
|
97
|
+
formatters?: LineFormatters;
|
|
98
|
+
limits: StringifyLimits;
|
|
99
|
+
}): JsonLineOptions {
|
|
100
|
+
const { messageKey, timestamp, base, formatters } = config;
|
|
101
|
+
if (
|
|
102
|
+
messageKey !== undefined &&
|
|
103
|
+
(typeof messageKey !== "string" || messageKey === "")
|
|
104
|
+
) {
|
|
105
|
+
throw invalid("messageKey must be a non-empty string");
|
|
106
|
+
}
|
|
107
|
+
if (
|
|
108
|
+
timestamp !== undefined &&
|
|
109
|
+
typeof timestamp !== "boolean" &&
|
|
110
|
+
typeof timestamp !== "function" &&
|
|
111
|
+
timestamp !== "epoch" &&
|
|
112
|
+
timestamp !== "iso" &&
|
|
113
|
+
timestamp !== "unix"
|
|
114
|
+
) {
|
|
115
|
+
throw invalid(
|
|
116
|
+
`timestamp must be 'epoch', 'iso', 'unix', a boolean or a function, got ${String(timestamp)}`,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
if (base !== undefined && base !== null && !isRecord(base)) {
|
|
120
|
+
throw invalid("base must be an object or null");
|
|
121
|
+
}
|
|
122
|
+
// Checked at run time too: a JavaScript config is not held to the types.
|
|
123
|
+
if (formatters !== undefined && !isRecord(formatters)) {
|
|
124
|
+
throw invalid("formatters must be an object");
|
|
125
|
+
}
|
|
126
|
+
const level: unknown = formatters?.level;
|
|
127
|
+
const log: unknown = formatters?.log;
|
|
128
|
+
if (level !== undefined && typeof level !== "function") {
|
|
129
|
+
throw invalid("formatters.level must be a function");
|
|
130
|
+
}
|
|
131
|
+
if (log !== undefined && typeof log !== "function") {
|
|
132
|
+
throw invalid("formatters.log must be a function");
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
messageKey: messageKey ?? DEFAULT_LINE_OPTIONS.messageKey,
|
|
136
|
+
timestamp: timestamp ?? DEFAULT_LINE_OPTIONS.timestamp,
|
|
137
|
+
base: base === undefined ? DEFAULT_BASE : base,
|
|
138
|
+
formatters: guardFormatters(formatters ?? {}),
|
|
139
|
+
limits: config.limits,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Formatters whose output is checked: one returning something other than an
|
|
145
|
+
* object would otherwise break the line it formats.
|
|
146
|
+
*/
|
|
147
|
+
function guardFormatters(formatters: LineFormatters): LineFormatters {
|
|
148
|
+
const { level, log } = formatters;
|
|
149
|
+
return {
|
|
150
|
+
...(level !== undefined
|
|
151
|
+
? {
|
|
152
|
+
level: (label: LogLevel, number: number) => {
|
|
153
|
+
const out: unknown = level(label, number);
|
|
154
|
+
return isRecord(out) ? out : { level: number };
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
: {}),
|
|
158
|
+
...(log !== undefined
|
|
159
|
+
? {
|
|
160
|
+
log: (object: Record<string, unknown>) => {
|
|
161
|
+
const out: unknown = log(object);
|
|
162
|
+
return isRecord(out) ? out : object;
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
: {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The `,"time":…` fragment, or "" when time is not written. */
|
|
170
|
+
function timeFragment(option: TimestampOption, iso: string): string {
|
|
171
|
+
if (option === false) return "";
|
|
172
|
+
if (typeof option === "function") return String(option());
|
|
173
|
+
const ms = Date.parse(iso);
|
|
174
|
+
// A hand-built entry may carry a timestamp that is no date: written as
|
|
175
|
+
// given rather than as `NaN`, which is not JSON and would break the line.
|
|
176
|
+
if (option === "iso" || !Number.isFinite(ms)) {
|
|
177
|
+
return `,"time":${JSON.stringify(iso)}`;
|
|
178
|
+
}
|
|
179
|
+
if (option === "unix") return `,"time":${Math.round(ms / 1000)}`;
|
|
180
|
+
return `,"time":${ms}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** `{…}` → `…`, so parts can be joined into one object. */
|
|
184
|
+
function inner(json: string): string {
|
|
185
|
+
return json.slice(1, -1);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** One JSON line (no trailing newline) for an entry. */
|
|
189
|
+
export function jsonLine(entry: LogEntry): string {
|
|
190
|
+
const options = lineOptionsFor(entry);
|
|
191
|
+
const number = LOG_LEVEL_ORDER[entry.level];
|
|
192
|
+
const levelPart = options.formatters.level
|
|
193
|
+
? options.formatters.level(entry.level, number)
|
|
194
|
+
: { level: number };
|
|
195
|
+
|
|
196
|
+
let fields: Record<string, unknown> = {
|
|
197
|
+
...(options.base ?? {}),
|
|
198
|
+
module: entry.module,
|
|
199
|
+
correlationId: entry.correlationId,
|
|
200
|
+
data: entry.data,
|
|
201
|
+
...logEntryExtras(entry),
|
|
202
|
+
};
|
|
203
|
+
if (options.formatters.log) fields = options.formatters.log(fields);
|
|
204
|
+
// A merged field named like the level, the time or the message would be
|
|
205
|
+
// read as the line's own (JSON.parse keeps the last duplicate), so a
|
|
206
|
+
// merging object could forge them. They are written once, by the logger.
|
|
207
|
+
const levelKeys = new Set(Object.keys(levelPart));
|
|
208
|
+
// Null prototype, so a merged `__proto__` key is written, not swallowed.
|
|
209
|
+
const rest: Record<string, unknown> = Object.create(null);
|
|
210
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
211
|
+
if (levelKeys.has(key) || key === "time" || key === options.messageKey)
|
|
212
|
+
continue;
|
|
213
|
+
rest[key] = value;
|
|
214
|
+
}
|
|
215
|
+
rest[options.messageKey] = entry.message;
|
|
216
|
+
|
|
217
|
+
const parts = [
|
|
218
|
+
inner(stringifyRecord(levelPart, options.limits)),
|
|
219
|
+
timeFragment(options.timestamp, entry.timestamp).replace(/^,/, ""),
|
|
220
|
+
inner(stringifyRecord(rest, options.limits)),
|
|
221
|
+
].filter((part) => part !== "");
|
|
222
|
+
return `{${parts.join(",")}}`;
|
|
223
|
+
}
|
package/src/redact.ts
CHANGED
|
@@ -9,12 +9,67 @@
|
|
|
9
9
|
* password is written out in full.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { SpectrumError } from "./errors.js";
|
|
13
|
+
|
|
12
14
|
/**
|
|
13
15
|
* fast-redact's own tokenizer: a run of characters that is not `.`, `[` or
|
|
14
16
|
* `]`, or anything between a pair of brackets.
|
|
15
17
|
*/
|
|
16
18
|
const PATH_TOKEN = /[^.[\]]+|\[(?:.)*?\]/g;
|
|
17
19
|
|
|
20
|
+
function invalidPath(detail: string): SpectrumError {
|
|
21
|
+
return new SpectrumError("E_SPECTRUM_INVALID_REDACT_PATH", detail);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Refuse a path the tokenizer would read as something else.
|
|
26
|
+
*
|
|
27
|
+
* `password,token` used to parse as one key with a comma in it, match nothing,
|
|
28
|
+
* and write both fields in clear under a config that reads as censoring them.
|
|
29
|
+
* These are upstream's rules (empty, `..`, `,`, unbalanced brackets), checked
|
|
30
|
+
* when the logger is built so a typo fails at boot instead of in production.
|
|
31
|
+
*/
|
|
32
|
+
function validateRedactPath(path: string): void {
|
|
33
|
+
if (path === "" || path.includes("..") || path.includes(",")) {
|
|
34
|
+
throw invalidPath(`Invalid redaction path (${path})`);
|
|
35
|
+
}
|
|
36
|
+
let depth = 0;
|
|
37
|
+
let quote = "";
|
|
38
|
+
for (const char of path) {
|
|
39
|
+
if ((char === '"' || char === "'") && depth > 0) {
|
|
40
|
+
if (quote === "") quote = char;
|
|
41
|
+
else if (char === quote) quote = "";
|
|
42
|
+
} else if (char === "[" && quote === "") {
|
|
43
|
+
depth += 1;
|
|
44
|
+
} else if (char === "]" && quote === "") {
|
|
45
|
+
depth -= 1;
|
|
46
|
+
if (depth < 0) throw invalidPath(`Invalid redaction path (${path})`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (depth !== 0) throw invalidPath(`Invalid redaction path (${path})`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The paths of a `redact` option, checked: an array of strings, or an object
|
|
54
|
+
* whose `paths` is one.
|
|
55
|
+
*/
|
|
56
|
+
export function redactPathsOf(redact: unknown): string[][] {
|
|
57
|
+
if (redact === undefined) return [];
|
|
58
|
+
const paths =
|
|
59
|
+
typeof redact === "object" && redact !== null && "paths" in redact
|
|
60
|
+
? redact.paths
|
|
61
|
+
: redact;
|
|
62
|
+
if (!Array.isArray(paths)) {
|
|
63
|
+
throw invalidPath("redact must contain an array of strings");
|
|
64
|
+
}
|
|
65
|
+
return paths.map((path: unknown) => {
|
|
66
|
+
if (typeof path !== "string") {
|
|
67
|
+
throw invalidPath("Redaction paths must be (non-empty) strings");
|
|
68
|
+
}
|
|
69
|
+
return parseRedactPath(path);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
18
73
|
/**
|
|
19
74
|
* Split a redaction path into the keys it names.
|
|
20
75
|
*
|
|
@@ -22,6 +77,7 @@ const PATH_TOKEN = /[^.[\]]+|\[(?:.)*?\]/g;
|
|
|
22
77
|
* notation, not part of the name.
|
|
23
78
|
*/
|
|
24
79
|
export function parseRedactPath(path: string): string[] {
|
|
80
|
+
validateRedactPath(path);
|
|
25
81
|
const tokens = path.match(PATH_TOKEN);
|
|
26
82
|
if (!tokens) return [];
|
|
27
83
|
return tokens.map((token) => {
|
|
@@ -31,8 +87,17 @@ export function parseRedactPath(path: string): string[] {
|
|
|
31
87
|
}
|
|
32
88
|
|
|
33
89
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
90
|
+
* What a matched value becomes: the censor's answer for the value and the
|
|
91
|
+
* concrete path it was found at (wildcards resolved), as upstream calls a
|
|
92
|
+
* censor function — or nothing at all, with `remove`.
|
|
93
|
+
*/
|
|
94
|
+
export interface RedactAction {
|
|
95
|
+
censor: (value: unknown, path: string[]) => unknown;
|
|
96
|
+
remove: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Replace everything `tokens` selects, without touching the input.
|
|
36
101
|
*
|
|
37
102
|
* Copy-on-write, and the copy is only made once something actually matched —
|
|
38
103
|
* so an entry with no redacted field is passed through by reference, which is
|
|
@@ -43,8 +108,9 @@ export function parseRedactPath(path: string): string[] {
|
|
|
43
108
|
export function redactPath(
|
|
44
109
|
node: unknown,
|
|
45
110
|
tokens: readonly string[],
|
|
46
|
-
|
|
111
|
+
action: RedactAction,
|
|
47
112
|
depth = 0,
|
|
113
|
+
trail: readonly string[] = [],
|
|
48
114
|
): unknown {
|
|
49
115
|
const segment = tokens[depth];
|
|
50
116
|
if (segment === undefined || node === null || typeof node !== "object") {
|
|
@@ -58,16 +124,34 @@ export function redactPath(
|
|
|
58
124
|
let copy: Record<string, unknown> | unknown[] | null = null;
|
|
59
125
|
for (const key of keys) {
|
|
60
126
|
const current = readKey(node, key);
|
|
127
|
+
const path = [...trail, key];
|
|
128
|
+
if (isLast && action.remove) {
|
|
129
|
+
copy ??= Array.isArray(node) ? [...node] : copyObject(node);
|
|
130
|
+
removeKey(copy, key);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
61
133
|
const next = isLast
|
|
62
|
-
? censor
|
|
63
|
-
: redactPath(current, tokens,
|
|
134
|
+
? action.censor(current, path)
|
|
135
|
+
: redactPath(current, tokens, action, depth + 1, path);
|
|
64
136
|
if (next === current) continue;
|
|
65
|
-
|
|
137
|
+
copy ??= Array.isArray(node) ? [...node] : copyObject(node);
|
|
66
138
|
writeKey(copy, key, next);
|
|
67
139
|
}
|
|
68
140
|
return copy ?? node;
|
|
69
141
|
}
|
|
70
142
|
|
|
143
|
+
function removeKey(
|
|
144
|
+
node: Record<string, unknown> | unknown[],
|
|
145
|
+
key: string,
|
|
146
|
+
): void {
|
|
147
|
+
if (Array.isArray(node)) {
|
|
148
|
+
const index = Number(key);
|
|
149
|
+
if (Number.isInteger(index)) node[index] = undefined;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
Reflect.deleteProperty(node, key);
|
|
153
|
+
}
|
|
154
|
+
|
|
71
155
|
/**
|
|
72
156
|
* The own keys a path segment selects.
|
|
73
157
|
*
|
|
@@ -81,9 +165,44 @@ function selectKeys(node: object, segment: string): string[] {
|
|
|
81
165
|
return Object.hasOwn(node, segment) ? [segment] : [];
|
|
82
166
|
}
|
|
83
167
|
|
|
168
|
+
/**
|
|
169
|
+
* A shallow copy that is still what the original was.
|
|
170
|
+
*
|
|
171
|
+
* A spread made a plain object: the class prototype went, and its `toJSON`
|
|
172
|
+
* with it, so a model whose serialization hides its password hash wrote every
|
|
173
|
+
* field the moment a redaction path matched inside it. Keeping the prototype
|
|
174
|
+
* is what upstream's redactor does. Values are defined, not assigned, so a
|
|
175
|
+
* setter on the prototype is not run against the copy.
|
|
176
|
+
*/
|
|
177
|
+
function copyObject(node: object): Record<string, unknown> {
|
|
178
|
+
const copy: Record<string, unknown> = {};
|
|
179
|
+
Reflect.setPrototypeOf(copy, Reflect.getPrototypeOf(node));
|
|
180
|
+
for (const key of Object.keys(node)) {
|
|
181
|
+
Object.defineProperty(copy, key, {
|
|
182
|
+
value: readKey(node, key),
|
|
183
|
+
enumerable: true,
|
|
184
|
+
writable: true,
|
|
185
|
+
configurable: true,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return copy;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* An own key's value, getter included.
|
|
193
|
+
*
|
|
194
|
+
* Reading the descriptor's `value` answered `undefined` for an accessor, so
|
|
195
|
+
* the walk stopped there while the line, written later, ran the getter and
|
|
196
|
+
* printed the secret behind it in clear. Upstream reads `source[key]`; so does
|
|
197
|
+
* this. A getter that throws cannot be written either, and is not allowed to
|
|
198
|
+
* take the line down with it.
|
|
199
|
+
*/
|
|
84
200
|
function readKey(node: object, key: string): unknown {
|
|
85
|
-
|
|
86
|
-
|
|
201
|
+
try {
|
|
202
|
+
return Reflect.get(node, key);
|
|
203
|
+
} catch {
|
|
204
|
+
return "[unreadable]";
|
|
205
|
+
}
|
|
87
206
|
}
|
|
88
207
|
|
|
89
208
|
function writeKey(
|
|
@@ -96,5 +215,10 @@ function writeKey(
|
|
|
96
215
|
if (Number.isInteger(index)) node[index] = value;
|
|
97
216
|
return;
|
|
98
217
|
}
|
|
99
|
-
node
|
|
218
|
+
Object.defineProperty(node, key, {
|
|
219
|
+
value,
|
|
220
|
+
enumerable: true,
|
|
221
|
+
writable: true,
|
|
222
|
+
configurable: true,
|
|
223
|
+
});
|
|
100
224
|
}
|
package/src/sanitize.ts
CHANGED
|
@@ -1,16 +1,40 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Escape
|
|
3
|
-
* attacker-controlled value (a channel name, a message, an error string
|
|
4
|
-
*
|
|
5
|
-
* `ConsoleChannel` and `Logger`'s
|
|
6
|
-
* the same protection.
|
|
2
|
+
* Escape what a terminal or a log viewer would act on, so an
|
|
3
|
+
* attacker-controlled value (a channel name, a message, an error string, a
|
|
4
|
+
* correlation id from a request header) can neither inject extra log lines
|
|
5
|
+
* nor drive the terminal. Shared by `ConsoleChannel` and `Logger`'s
|
|
6
|
+
* channel-failure fallback so both paths get the same protection.
|
|
7
|
+
*
|
|
8
|
+
* Covered: every C0 control but TAB (CR/LF forge lines, BS overwrites what
|
|
9
|
+
* was printed, ESC starts a sequence), DEL, every C1 control (U+009B and
|
|
10
|
+
* U+009D are CSI and OSC on terminals that honour 8-bit controls, so
|
|
11
|
+
* `\u009b2J` clears the screen), and U+2028/U+2029, which viewers treat as
|
|
12
|
+
* line breaks.
|
|
7
13
|
*/
|
|
8
14
|
export function sanitizeLogValue(str: string): string {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
.
|
|
15
|
-
|
|
15
|
+
let out = "";
|
|
16
|
+
let from = 0;
|
|
17
|
+
for (let i = 0; i < str.length; i++) {
|
|
18
|
+
const code = str.charCodeAt(i);
|
|
19
|
+
if (!isUnsafe(code)) continue;
|
|
20
|
+
out += str.slice(from, i) + escapeCode(code);
|
|
21
|
+
from = i + 1;
|
|
22
|
+
}
|
|
23
|
+
return from === 0 ? str : out + str.slice(from);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isUnsafe(code: number): boolean {
|
|
27
|
+
return (
|
|
28
|
+
(code < 0x20 && code !== 0x09) ||
|
|
29
|
+
(code >= 0x7f && code <= 0x9f) ||
|
|
30
|
+
code === 0x2028 ||
|
|
31
|
+
code === 0x2029
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function escapeCode(code: number): string {
|
|
36
|
+
if (code === 0x0d) return "\\r";
|
|
37
|
+
if (code === 0x0a) return "\\n";
|
|
38
|
+
if (code === 0x1b) return "[ESC]";
|
|
39
|
+
return `\\u${code.toString(16).padStart(4, "0")}`;
|
|
16
40
|
}
|
package/src/services/main.ts
CHANGED
|
@@ -35,8 +35,20 @@ export function clearLogger(): void {
|
|
|
35
35
|
instance = undefined;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
/** What the proxy stands on: nothing of its own, every read is trapped. */
|
|
39
|
+
const target: Logger = Object.create(null);
|
|
40
|
+
|
|
41
|
+
const logger: Logger = new Proxy(target, {
|
|
39
42
|
get(_target, prop) {
|
|
43
|
+
// A module loader inspects what it imports before anyone uses it: it reads
|
|
44
|
+
// `then` to decide whether the namespace is thenable, and various symbols
|
|
45
|
+
// for interop and formatting. Throwing on those turns a plain
|
|
46
|
+
// `import { setLogger } from '.../services/main'` into a crash at import
|
|
47
|
+
// time, far from any real use. They are not logger members, so answer
|
|
48
|
+
// undefined and let a genuine access be the one that reports.
|
|
49
|
+
if (typeof prop === "symbol" || prop === "then") {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
40
52
|
if (!instance) {
|
|
41
53
|
throw new Error(
|
|
42
54
|
"[spectrum] Logger singleton accessed before SpectrumProvider.boot() ran. " +
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standard serializers, in the shapes upstream's `stdSerializers` write:
|
|
3
|
+
* `err` for errors, `req` and `res` for Node's HTTP request and response.
|
|
4
|
+
*
|
|
5
|
+
* new Logger({ serializers: { req: stdSerializers.req, res: stdSerializers.res } })
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** How far down a chain of nested errors to follow. */
|
|
9
|
+
const MAX_CAUSE_DEPTH = 8;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Serialize an Error the way pino's `err` serializer does. Non-Error values
|
|
13
|
+
* pass through untouched.
|
|
14
|
+
*
|
|
15
|
+
* `{ name, message, stack }` threw away everything the error was carrying.
|
|
16
|
+
* `err.code` is usually the one field a log search is keyed on, and the `cause`
|
|
17
|
+
* of a wrapped error is the half that says what actually failed — both were
|
|
18
|
+
* dropped, silently, by a serializer whose job is to keep them.
|
|
19
|
+
*
|
|
20
|
+
* `path` holds the errors being serialized above this one. An error met again
|
|
21
|
+
* on its own path is a cycle and is written as `"[Circular]"`, as upstream
|
|
22
|
+
* skips an error it has already tagged; without it `err.self = err` was copied
|
|
23
|
+
* down to the depth limit, and an error with k such references cost k^8 copies
|
|
24
|
+
* on the logging call. An error shared by two branches is not a cycle and is
|
|
25
|
+
* written in both.
|
|
26
|
+
*/
|
|
27
|
+
export function serializeError(
|
|
28
|
+
value: unknown,
|
|
29
|
+
path: readonly Error[] = [],
|
|
30
|
+
): unknown {
|
|
31
|
+
if (!(value instanceof Error)) return value;
|
|
32
|
+
if (path.includes(value)) return "[Circular]";
|
|
33
|
+
if (path.length > MAX_CAUSE_DEPTH) return "[cause chain too deep]";
|
|
34
|
+
const below = [...path, value];
|
|
35
|
+
|
|
36
|
+
// Own ENUMERABLE properties only, which on an Error means the ones it was
|
|
37
|
+
// given: `message`, `stack` and `name` are not among them.
|
|
38
|
+
const out: Record<string, unknown> = { ...value };
|
|
39
|
+
for (const [key, nested] of Object.entries(out)) {
|
|
40
|
+
if (nested instanceof Error) out[key] = serializeError(nested, below);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Upstream reads the constructor rather than `name`, so a subclass that
|
|
44
|
+
// never assigns `this.name` is still reported as itself, and it names the
|
|
45
|
+
// field `type` — which is what an Adonis log pipeline reads.
|
|
46
|
+
out.type =
|
|
47
|
+
typeof value.constructor === "function"
|
|
48
|
+
? value.constructor.name
|
|
49
|
+
: value.name;
|
|
50
|
+
out.message = value.message;
|
|
51
|
+
out.stack = value.stack;
|
|
52
|
+
if (value instanceof AggregateError && Array.isArray(value.errors)) {
|
|
53
|
+
out.aggregateErrors = value.errors.map((each: unknown) =>
|
|
54
|
+
serializeError(each, below),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (value.cause !== undefined) {
|
|
58
|
+
out.cause = serializeError(value.cause, below);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
64
|
+
return typeof value === "object" && value !== null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* An HTTP request as upstream's `req` serializer writes it: id, method, url,
|
|
69
|
+
* query, params, headers and the remote address. Every header is written as
|
|
70
|
+
* it is, `cookie` and `authorization` included — censoring them is what
|
|
71
|
+
* `redact` is for, and the generated config lists them.
|
|
72
|
+
*/
|
|
73
|
+
export function serializeRequest(value: unknown): unknown {
|
|
74
|
+
if (!isRecord(value)) return value;
|
|
75
|
+
const info = Reflect.get(value, "info");
|
|
76
|
+
const connection = isRecord(info) ? info : Reflect.get(value, "socket");
|
|
77
|
+
const id = Reflect.get(value, "id");
|
|
78
|
+
const originalUrl = Reflect.get(value, "originalUrl");
|
|
79
|
+
const pathValue = Reflect.get(value, "path");
|
|
80
|
+
const url = Reflect.get(value, "url");
|
|
81
|
+
const query = Reflect.get(value, "query");
|
|
82
|
+
const params = Reflect.get(value, "params");
|
|
83
|
+
return {
|
|
84
|
+
id:
|
|
85
|
+
typeof id === "function"
|
|
86
|
+
? Reflect.apply(id, value, [])
|
|
87
|
+
: (id ?? (isRecord(info) ? Reflect.get(info, "id") : undefined)),
|
|
88
|
+
method: Reflect.get(value, "method"),
|
|
89
|
+
url: originalUrl
|
|
90
|
+
? originalUrl
|
|
91
|
+
: typeof pathValue === "string"
|
|
92
|
+
? pathValue
|
|
93
|
+
: isRecord(url)
|
|
94
|
+
? (Reflect.get(url, "path") ?? url)
|
|
95
|
+
: url,
|
|
96
|
+
...(query ? { query } : {}),
|
|
97
|
+
...(params ? { params } : {}),
|
|
98
|
+
headers: Reflect.get(value, "headers"),
|
|
99
|
+
remoteAddress: isRecord(connection)
|
|
100
|
+
? Reflect.get(connection, "remoteAddress")
|
|
101
|
+
: undefined,
|
|
102
|
+
remotePort: isRecord(connection)
|
|
103
|
+
? Reflect.get(connection, "remotePort")
|
|
104
|
+
: undefined,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** An HTTP response as upstream's `res` serializer writes it: status and headers. */
|
|
109
|
+
export function serializeResponse(value: unknown): unknown {
|
|
110
|
+
if (!isRecord(value)) return value;
|
|
111
|
+
const getHeaders = Reflect.get(value, "getHeaders");
|
|
112
|
+
return {
|
|
113
|
+
statusCode: Reflect.get(value, "headersSent")
|
|
114
|
+
? Reflect.get(value, "statusCode")
|
|
115
|
+
: null,
|
|
116
|
+
headers:
|
|
117
|
+
typeof getHeaders === "function"
|
|
118
|
+
? Reflect.apply(getHeaders, value, [])
|
|
119
|
+
: Reflect.get(value, "_headers"),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const stdSerializers: {
|
|
124
|
+
err: (value: unknown) => unknown;
|
|
125
|
+
req: (value: unknown) => unknown;
|
|
126
|
+
res: (value: unknown) => unknown;
|
|
127
|
+
} = {
|
|
128
|
+
err: (value) => serializeError(value),
|
|
129
|
+
req: serializeRequest,
|
|
130
|
+
res: serializeResponse,
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Upstream's time functions, for `timestamp`: each returns the `,"time":…`
|
|
135
|
+
* fragment a JSON line carries.
|
|
136
|
+
*/
|
|
137
|
+
export const stdTimeFunctions: {
|
|
138
|
+
epochTime: () => string;
|
|
139
|
+
unixTime: () => string;
|
|
140
|
+
isoTime: () => string;
|
|
141
|
+
nullTime: () => string;
|
|
142
|
+
} = {
|
|
143
|
+
epochTime: () => `,"time":${Date.now()}`,
|
|
144
|
+
unixTime: () => `,"time":${Math.round(Date.now() / 1000)}`,
|
|
145
|
+
isoTime: () => `,"time":"${new Date(Date.now()).toISOString()}"`,
|
|
146
|
+
nullTime: () => "",
|
|
147
|
+
};
|