@yieldkit/logger 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +256 -2
- package/dist/callback-logger.d.ts +78 -0
- package/dist/callback-logger.js +104 -0
- package/dist/config.d.ts +29 -0
- package/dist/config.js +264 -0
- package/dist/context.d.ts +60 -0
- package/dist/context.js +100 -0
- package/dist/crash.d.ts +114 -0
- package/dist/crash.js +215 -0
- package/dist/credentials.d.ts +57 -0
- package/dist/credentials.js +267 -0
- package/dist/error.d.ts +27 -0
- package/dist/error.js +173 -0
- package/dist/formatters.d.ts +53 -0
- package/dist/formatters.js +137 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +15 -0
- package/dist/layer.d.ts +31 -0
- package/dist/layer.js +78 -0
- package/dist/line-cap.d.ts +6 -0
- package/dist/line-cap.js +367 -0
- package/dist/log-fan-out.d.ts +24 -0
- package/dist/log-fan-out.js +83 -0
- package/dist/metrics.d.ts +19 -0
- package/dist/metrics.js +45 -0
- package/dist/omit-undefined.js +10 -0
- package/dist/otlp/flush.d.ts +8 -0
- package/dist/otlp/flush.js +11 -0
- package/dist/otlp/index.d.ts +4 -0
- package/dist/otlp/index.js +4 -0
- package/dist/otlp/telemetry.d.ts +86 -0
- package/dist/otlp/telemetry.js +230 -0
- package/dist/otlp/tracing.d.ts +11 -0
- package/dist/otlp/tracing.js +13 -0
- package/dist/redact-cause.js +92 -0
- package/dist/redact-walk.d.ts +19 -0
- package/dist/redact-walk.js +290 -0
- package/dist/redact.d.ts +104 -0
- package/dist/redact.js +271 -0
- package/dist/request-id.d.ts +21 -0
- package/dist/request-id.js +28 -0
- package/dist/testing/index.d.ts +55 -0
- package/dist/testing/index.js +42 -0
- package/dist/types.d.ts +212 -0
- package/docs/callback-logger.md +38 -0
- package/docs/configuration.md +56 -0
- package/docs/crash-and-startup.md +57 -0
- package/docs/durations-and-request-ids.md +30 -0
- package/docs/formats.md +78 -0
- package/docs/logging.md +53 -0
- package/docs/redaction.md +87 -0
- package/docs/telemetry.md +78 -0
- package/docs/testing.md +60 -0
- package/package.json +74 -3
package/dist/crash.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { logFatal } from "./context.js";
|
|
2
|
+
import { defaultLogRedaction, makeLogRedaction } from "./redact.js";
|
|
3
|
+
import { Cause, Duration, Effect, Exit, Layer, Option, Predicate, Redactable, Runtime } from "effect";
|
|
4
|
+
// src/crash.ts
|
|
5
|
+
/**
|
|
6
|
+
* Default `CrashHandlerOptions.flushTimeout`.
|
|
7
|
+
*/
|
|
8
|
+
const DEFAULT_FLUSH_TIMEOUT = "5 seconds";
|
|
9
|
+
/**
|
|
10
|
+
* Exit code used after a crash.
|
|
11
|
+
*/
|
|
12
|
+
const CRASH_EXIT_CODE = 1;
|
|
13
|
+
/**
|
|
14
|
+
* Exit code used after a program fails to start or fails later with a non-interrupt cause.
|
|
15
|
+
*/
|
|
16
|
+
const STARTUP_FAILURE_EXIT_CODE = 1;
|
|
17
|
+
/**
|
|
18
|
+
* Message of the Fatal line written for a crash.
|
|
19
|
+
*/
|
|
20
|
+
const CRASH_MESSAGE = "process.crashed";
|
|
21
|
+
/**
|
|
22
|
+
* `crashValue` annotation of the fallback Fatal line written when the crash value itself cannot be
|
|
23
|
+
* logged.
|
|
24
|
+
*/
|
|
25
|
+
const UNLOGGABLE_CRASH_VALUE = "unloggable";
|
|
26
|
+
/**
|
|
27
|
+
* True when `value` has the `on`, `off` and `exit` functions of a process object.
|
|
28
|
+
*/
|
|
29
|
+
const isProcessGlobal = (value) => typeof value === "object" && Predicate.hasProperty(value, "on") && typeof value.on === "function" && Predicate.hasProperty(value, "off") && typeof value.off === "function" && Predicate.hasProperty(value, "exit") && typeof value.exit === "function";
|
|
30
|
+
/**
|
|
31
|
+
* Reads the global `process`, or returns undefined in a runtime that has none.
|
|
32
|
+
*/
|
|
33
|
+
const readProcessGlobal = () => {
|
|
34
|
+
const candidate = Predicate.hasProperty(globalThis, "process") ? globalThis.process : void 0;
|
|
35
|
+
return isProcessGlobal(candidate) ? candidate : void 0;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Resolves the target and exit function from `options`, falling back to the global `process`. Dies
|
|
39
|
+
* when one is missing and the runtime has no `process`.
|
|
40
|
+
*/
|
|
41
|
+
const resolveCrashRuntime = (options) => Effect.suspend(() => {
|
|
42
|
+
const processGlobal = readProcessGlobal();
|
|
43
|
+
const target = options.target ?? processGlobal;
|
|
44
|
+
const exit = options.exit ?? processGlobal?.exit.bind(processGlobal);
|
|
45
|
+
if (target === void 0 || exit === void 0) return Effect.die(/* @__PURE__ */ new Error("crash handlers need a global `process`, or both `target` and `exit` options"));
|
|
46
|
+
return Effect.succeed({
|
|
47
|
+
target,
|
|
48
|
+
exit
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
/**
|
|
52
|
+
* Logs the crash at Fatal. When that fails or dies (a logger that throws, say), a fixed Fatal line
|
|
53
|
+
* without the crash value is tried instead, and a failure of that one is dropped, so reporting
|
|
54
|
+
* never stops before the flush.
|
|
55
|
+
*/
|
|
56
|
+
const logCrash = (kind, error) => logFatal(CRASH_MESSAGE, Cause.die(error), { crashKind: kind }).pipe(Effect.catchCause(() => logFatal(CRASH_MESSAGE, void 0, {
|
|
57
|
+
crashKind: kind,
|
|
58
|
+
crashValue: UNLOGGABLE_CRASH_VALUE
|
|
59
|
+
})), Effect.ignoreCause);
|
|
60
|
+
/**
|
|
61
|
+
* Logs the crash at Fatal and then runs `flush`. Logging never fails, so the flush runs even when
|
|
62
|
+
* the crash value could not be logged. Neither step is made uninterruptible here, so the flush
|
|
63
|
+
* timeout interrupts an interruptible flush; one that is not interruptible keeps running, and the
|
|
64
|
+
* separate deadline fiber exits without waiting for it.
|
|
65
|
+
*/
|
|
66
|
+
const reportCrash = (kind, error, flush) => logCrash(kind, error).pipe(Effect.andThen(flush));
|
|
67
|
+
/**
|
|
68
|
+
* Decodes `flushTimeout`, dying with a message that names the option when it is not a finite,
|
|
69
|
+
* positive duration. `NaN` (from `Number` of an unset variable) decodes to zero, which would exit
|
|
70
|
+
* before the Fatal line is written, and an infinite timeout would never exit.
|
|
71
|
+
*/
|
|
72
|
+
const decodeFlushTimeout = (flushTimeout) => Effect.suspend(() => {
|
|
73
|
+
const decoded = Duration.fromInput(flushTimeout ?? DEFAULT_FLUSH_TIMEOUT);
|
|
74
|
+
if (Option.isNone(decoded) || !Duration.isFinite(decoded.value) || !Duration.isPositive(decoded.value)) return Effect.die(/* @__PURE__ */ new Error("invalid crash handler flushTimeout: expected a finite, positive duration"));
|
|
75
|
+
return Effect.succeed(decoded.value);
|
|
76
|
+
});
|
|
77
|
+
/**
|
|
78
|
+
* Adds `listener` to `target` for `event` until the current scope closes. Each listener is acquired
|
|
79
|
+
* on its own, so when adding a later one throws, the earlier ones are still removed.
|
|
80
|
+
*/
|
|
81
|
+
const listenScoped = (target, event, listener) => Effect.acquireRelease(Effect.sync(() => {
|
|
82
|
+
target.on(event, listener);
|
|
83
|
+
}), () => Effect.sync(() => {
|
|
84
|
+
target.off(event, listener);
|
|
85
|
+
}));
|
|
86
|
+
/**
|
|
87
|
+
* Registers `uncaughtException` and `unhandledRejection` listeners while the layer is up and
|
|
88
|
+
* removes them when its scope closes.
|
|
89
|
+
*
|
|
90
|
+
* Each crash is logged at Fatal as `process.crashed` with a die cause and a `crashKind` annotation,
|
|
91
|
+
* through the loggers and annotations that were in the context when the layer was built, and then
|
|
92
|
+
* `options.flush` runs in that same context. When a logger throws on the crash value, a Fatal line
|
|
93
|
+
* with `crashValue: 'unloggable'` is written instead; the loggers `makeLoggerLayer` installs never
|
|
94
|
+
* throw, and write `process.crashed` without the cause and annotations. The flush runs either way,
|
|
95
|
+
* bounded together with the log line by `flushTimeout`, and `exit(1)` runs once, when reporting
|
|
96
|
+
* ends or when `flushTimeout` has passed, whichever comes first. The deadline runs on its own
|
|
97
|
+
* fiber, so a log line or flush that cannot be interrupted does not delay the exit; only code that
|
|
98
|
+
* blocks the thread synchronously (a busy loop in a logger or flusher) can, since no timer fires
|
|
99
|
+
* until it returns. A second crash while the first is being handled does nothing, so the first
|
|
100
|
+
* handler still exits.
|
|
101
|
+
*
|
|
102
|
+
* Registering a listener replaces Node's own crash, which is why the handler exits itself. Build
|
|
103
|
+
* this layer with the logger layers provided to it (`Layer.provide`), because a sibling in
|
|
104
|
+
* `Layer.mergeAll` does not see the loggers its sibling installs.
|
|
105
|
+
*/
|
|
106
|
+
const makeCrashHandlersLayer = (options = {}) => Layer.effectDiscard(Effect.gen(function* () {
|
|
107
|
+
const { target, exit } = yield* resolveCrashRuntime(options);
|
|
108
|
+
const flushTimeout = yield* decodeFlushTimeout(options.flushTimeout);
|
|
109
|
+
const run = Effect.runForkWith(yield* Effect.context());
|
|
110
|
+
let handling = false;
|
|
111
|
+
/**
|
|
112
|
+
* Builds the listener for one kind of crash. It ignores every crash after the first.
|
|
113
|
+
*/
|
|
114
|
+
const handler = (kind) => (error) => {
|
|
115
|
+
if (handling) return;
|
|
116
|
+
handling = true;
|
|
117
|
+
let exited = false;
|
|
118
|
+
/**
|
|
119
|
+
* Calls `exit(1)` the first time it runs and does nothing after that, so the deadline and
|
|
120
|
+
* the end of reporting can both reach it.
|
|
121
|
+
*/
|
|
122
|
+
const exitOnce = Effect.sync(() => {
|
|
123
|
+
if (!exited) {
|
|
124
|
+
exited = true;
|
|
125
|
+
exit(CRASH_EXIT_CODE);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
/**
|
|
129
|
+
* Exits once `flushTimeout` has passed. It runs on its own fiber, so an uninterruptible
|
|
130
|
+
* log line or flush cannot hold it back; it is interrupted when reporting ends first.
|
|
131
|
+
*/
|
|
132
|
+
const deadline = run(Effect.sleep(flushTimeout).pipe(Effect.andThen(exitOnce)));
|
|
133
|
+
run(reportCrash(kind, error, options.flush ?? Effect.void).pipe(Effect.timeout(flushTimeout), Effect.ignoreCause, Effect.ensuring(exitOnce.pipe(Effect.andThen(Effect.sync(() => {
|
|
134
|
+
deadline.interruptUnsafe();
|
|
135
|
+
}))))));
|
|
136
|
+
};
|
|
137
|
+
const onException = handler("uncaughtException");
|
|
138
|
+
const onRejection = handler("unhandledRejection");
|
|
139
|
+
yield* listenScoped(target, "uncaughtException", onException);
|
|
140
|
+
yield* listenScoped(target, "unhandledRejection", onRejection);
|
|
141
|
+
}));
|
|
142
|
+
/**
|
|
143
|
+
* `makeCrashHandlersLayer()` with the default options: the global `process`, `process.exit` and a
|
|
144
|
+
* five second flush timeout.
|
|
145
|
+
*/
|
|
146
|
+
const CrashHandlersLive = makeCrashHandlersLayer();
|
|
147
|
+
/**
|
|
148
|
+
* Line written when a startup failure cannot be described at all.
|
|
149
|
+
*/
|
|
150
|
+
const UNDESCRIBABLE_STARTUP_FAILURE = "failed to start: [Unserializable]";
|
|
151
|
+
/**
|
|
152
|
+
* Returns the message of an Effect `Config.ConfigError` (a `ConfigError` tag and a string
|
|
153
|
+
* `message`), or `undefined` for any other value. A `Redactable` value is not read here, so it is
|
|
154
|
+
* described by its redacted form like any other failure. Each property is read once, and a value
|
|
155
|
+
* that throws while it is read is not a `ConfigError`. `ConfigError` is not a Schema class, so
|
|
156
|
+
* `Schema.is` cannot check it.
|
|
157
|
+
*/
|
|
158
|
+
const configErrorMessage = (value) => {
|
|
159
|
+
try {
|
|
160
|
+
if (Redactable.isRedactable(value) || !Predicate.isTagged(value, "ConfigError") || !Predicate.hasProperty(value, "message")) return;
|
|
161
|
+
const message = value.message;
|
|
162
|
+
return typeof message === "string" ? message : void 0;
|
|
163
|
+
} catch {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Renders a failure to build the app (for example a bad `LOG_LEVEL`) as console text, for use where
|
|
169
|
+
* the loggers are not available. When every reason of the cause is a `ConfigError` failure, the
|
|
170
|
+
* text is `invalid configuration: ` plus their redacted messages. Any other cause, including a
|
|
171
|
+
* `ConfigError` next to a defect, becomes `failed to start: ` plus the sanitized pretty cause, so
|
|
172
|
+
* no reason is hidden and a secret in an error message or span name never reaches the terminal.
|
|
173
|
+
* Redacts with the built-in sensitive names plus `redaction`.
|
|
174
|
+
*/
|
|
175
|
+
const describeStartupFailure = (cause, redaction) => {
|
|
176
|
+
const rules = redaction === void 0 ? defaultLogRedaction : makeLogRedaction(redaction);
|
|
177
|
+
const messages = cause.reasons.flatMap((reason) => {
|
|
178
|
+
const message = Cause.isFailReason(reason) ? configErrorMessage(reason.error) : void 0;
|
|
179
|
+
return message === void 0 ? [] : [message];
|
|
180
|
+
});
|
|
181
|
+
if (messages.length > 0 && messages.length === cause.reasons.length) return `invalid configuration: ${messages.map((message) => rules.redactString(message)).join("; ")}`;
|
|
182
|
+
return `failed to start: ${Cause.pretty(rules.sanitizeCause(cause))}`;
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Builds a `Runtime.Teardown` for `runMain` that reports a failed program with
|
|
186
|
+
* {@link describeStartupFailure}, redacting with the built-in sensitive names plus
|
|
187
|
+
* `options.redaction`. A success or an interrupt-only exit (Ctrl-C, `SIGTERM`) goes to
|
|
188
|
+
* `Runtime.defaultTeardown`, which keeps its exit code. Any other failure is passed to `write`
|
|
189
|
+
* once, as one string, and exits with code 1, even when the failure cannot be described or `write`
|
|
190
|
+
* throws. Pair it with `disableErrorReporting: true`, or `runMain` also prints the raw, unredacted
|
|
191
|
+
* cause.
|
|
192
|
+
*/
|
|
193
|
+
const makeStartupFailureTeardown = (write, options = {}) => (exit, onExit) => {
|
|
194
|
+
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
|
|
195
|
+
Runtime.defaultTeardown(exit, onExit);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
let line = UNDESCRIBABLE_STARTUP_FAILURE;
|
|
199
|
+
try {
|
|
200
|
+
line = describeStartupFailure(exit.cause, options.redaction);
|
|
201
|
+
} catch {}
|
|
202
|
+
try {
|
|
203
|
+
write(line);
|
|
204
|
+
} finally {
|
|
205
|
+
onExit(STARTUP_FAILURE_EXIT_CODE);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* {@link makeStartupFailureTeardown} writing to `console.error`, for `BunRuntime.runMain({
|
|
210
|
+
* disableErrorReporting: true, teardown: startupFailureTeardown })`.
|
|
211
|
+
*/
|
|
212
|
+
const startupFailureTeardown = makeStartupFailureTeardown((line) => {
|
|
213
|
+
console.error(line);
|
|
214
|
+
});
|
|
215
|
+
export { CrashHandlersLive, describeStartupFailure, makeCrashHandlersLayer, makeStartupFailureTeardown, startupFailureTeardown };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text written in place of a secret. It matches what Effect prints for a `Redacted` value, so a
|
|
3
|
+
* masked key and a `Redacted` field look the same in every format.
|
|
4
|
+
*/
|
|
5
|
+
export declare const REDACTED_LOG_VALUE = "<redacted>";
|
|
6
|
+
/**
|
|
7
|
+
* Options for the redaction rules. Each list adds to the built-in one, never replacing it.
|
|
8
|
+
*
|
|
9
|
+
* A string entry matches a whole key whose letters and digits are the same, ignoring case and the
|
|
10
|
+
* separators `-`, `_`, `.` and spaces, so `'tokenType'` also matches `token_type` and `TOKEN-TYPE`
|
|
11
|
+
* but not `refreshTokenType`.
|
|
12
|
+
*/
|
|
13
|
+
export interface RedactionOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Keys whose values are always masked, numbers and booleans included, on top of the built-in
|
|
16
|
+
* list. A `RegExp` entry is tested against the key as written (its `g` and `y` flags are
|
|
17
|
+
* ignored). A key matched here is masked even when it is also in {@link allowKeys}.
|
|
18
|
+
*/
|
|
19
|
+
readonly sensitiveKeys?: ReadonlyArray<string | RegExp> | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Keys that match a built-in sensitive name but hold no secret (`tokenType`, `expiresIn`). A
|
|
22
|
+
* value under one is redacted by its own content like a value under any other key.
|
|
23
|
+
*/
|
|
24
|
+
readonly allowKeys?: ReadonlyArray<string> | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Runs on every text the built-in shapes run on (string values, messages, span names and labels,
|
|
27
|
+
* error summaries, rendered causes), after them. It must return the text to write. When it
|
|
28
|
+
* throws, the text is written as {@link REDACTED_LOG_VALUE}.
|
|
29
|
+
*/
|
|
30
|
+
readonly scrubText?: ((text: string) => string) | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Tells whether `key` contains a built-in sensitive name, in any case or separator style
|
|
34
|
+
* (`client_secret`, `clientSecret`, `X-Api-Key`, `set-cookie`, `sessionId`, `tokenCount`). A value
|
|
35
|
+
* under such a key is masked unless it is a `number`, a `boolean`, `null` or `undefined`.
|
|
36
|
+
*/
|
|
37
|
+
export declare const isSensitiveLogKey: (key: string) => boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Tells whether the value of a URL query or fragment parameter called `name` is a credential, using
|
|
40
|
+
* the built-in names: its percent-decoded name, in any case, is `key`, `apikey`, `auth`, `code`,
|
|
41
|
+
* `sig`, `signature`, `token`, `x-amz-signature`, `x-amz-credential`, `x-amz-security-token` or
|
|
42
|
+
* `x-goog-signature`, or {@link isSensitiveLogKey} accepts it (`access_token`, `client_secret`,
|
|
43
|
+
* `creds[token]`). {@link redactLogString} masks query values by this rule.
|
|
44
|
+
*/
|
|
45
|
+
export declare const isSensitiveQueryParamName: (name: string) => boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Masks a fixed list of credential shapes in `text`, and nothing else:
|
|
48
|
+
*
|
|
49
|
+
* - URL userinfo becomes `scheme://<redacted>@`;
|
|
50
|
+
* - `Bearer <token>` and `Basic <credentials>` keep the scheme word;
|
|
51
|
+
* - URL query, matrix and fragment values (after `?`, `&`, `;` or `#`) under a name
|
|
52
|
+
* {@link isSensitiveQueryParamName} accepts.
|
|
53
|
+
*
|
|
54
|
+
* Every other way of writing a secret into text is written as it is. The cost is linear in the
|
|
55
|
+
* length of `text`, and running it twice gives the same result as running it once.
|
|
56
|
+
*/
|
|
57
|
+
export declare const redactLogString: (text: string) => string;
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// src/credentials.ts
|
|
2
|
+
/**
|
|
3
|
+
* Text written in place of a secret. It matches what Effect prints for a `Redacted` value, so a
|
|
4
|
+
* masked key and a `Redacted` field look the same in every format.
|
|
5
|
+
*/
|
|
6
|
+
const REDACTED_LOG_VALUE = "<redacted>";
|
|
7
|
+
/**
|
|
8
|
+
* Built-in sensitive names, tested on the normalized key (lowercase, separators removed), so every
|
|
9
|
+
* casing and separator style matches (`client_secret`, `clientSecret`, `X-Api-Key`, `set-cookie`).
|
|
10
|
+
*/
|
|
11
|
+
const SENSITIVE_KEY_PATTERN = /passw(?:or)?d|passphrase|pwd|secret|token|authori[sz]ation|cookie|(?:api|access|private|auth|client|signing|encryption|master)key|session|signature|credential|bearer|jwt/;
|
|
12
|
+
/**
|
|
13
|
+
* Query parameter names that carry a credential in a URL although they are ordinary words
|
|
14
|
+
* elsewhere: API keys, URL signatures (AWS and Google signed URLs among them), OAuth's
|
|
15
|
+
* authorization `code` and `auth`. Lower case; compared with the decoded name in lower case.
|
|
16
|
+
*/
|
|
17
|
+
const QUERY_CREDENTIAL_NAMES = /* @__PURE__ */ new Set([
|
|
18
|
+
"key",
|
|
19
|
+
"apikey",
|
|
20
|
+
"auth",
|
|
21
|
+
"code",
|
|
22
|
+
"sig",
|
|
23
|
+
"signature",
|
|
24
|
+
"token",
|
|
25
|
+
"x-amz-signature",
|
|
26
|
+
"x-amz-credential",
|
|
27
|
+
"x-amz-security-token",
|
|
28
|
+
"x-goog-signature"
|
|
29
|
+
]);
|
|
30
|
+
/**
|
|
31
|
+
* Text that may hold one of the convenience shapes: a `=` (query values), a `://` (userinfo) or an
|
|
32
|
+
* auth scheme word. Other text is returned without running any of them.
|
|
33
|
+
*/
|
|
34
|
+
const MAYBE_SHAPE_PATTERN = /=|:\/\/|b(?:earer|asic)/i;
|
|
35
|
+
/**
|
|
36
|
+
* Characters ignored when keys are compared.
|
|
37
|
+
*/
|
|
38
|
+
const KEY_SEPARATOR_PATTERN = /[-_.\s]/g;
|
|
39
|
+
/**
|
|
40
|
+
* Most key verdicts remembered per set of rules. The cache is emptied when it is full, so a stream
|
|
41
|
+
* of distinct keys cannot grow it without bound.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_CACHED_KEYS = 4096;
|
|
44
|
+
/**
|
|
45
|
+
* Longest key whose verdict is remembered.
|
|
46
|
+
*/
|
|
47
|
+
const MAX_CACHED_KEY_LENGTH = 128;
|
|
48
|
+
/**
|
|
49
|
+
* An `Authorization`-style credential: the scheme word, whitespace and an optional quote (group 1,
|
|
50
|
+
* kept), then the token up to the next space, quote, comma or semicolon.
|
|
51
|
+
*/
|
|
52
|
+
const AUTH_SCHEME_PATTERN = /\b((?:Bearer|Basic)\s+["']?)[^\s"',;]+/gi;
|
|
53
|
+
/**
|
|
54
|
+
* The name of a URL query, matrix or fragment parameter (group 1), after its separator and up to
|
|
55
|
+
* its `=`. The name is bounded and the value is not consumed, so a parameter nested in another
|
|
56
|
+
* one's value (`?next=https://h/cb?token=x`) is found too, and the scan stays linear.
|
|
57
|
+
*/
|
|
58
|
+
const QUERY_NAME_PATTERN = /[?&;#]([\w.%+[\]-]{1,128})=/g;
|
|
59
|
+
/**
|
|
60
|
+
* A query parameter value: everything up to `&`, `#` or whitespace, so `?token=a;b` and
|
|
61
|
+
* `?password=ab?cd` are hidden whole.
|
|
62
|
+
*/
|
|
63
|
+
const QUERY_VALUE_PATTERN = /[^&#\s]*/y;
|
|
64
|
+
/**
|
|
65
|
+
* Characters of a URL scheme after its first letter.
|
|
66
|
+
*/
|
|
67
|
+
const SCHEME_CHAR_PATTERN = /[a-z0-9+.-]/i;
|
|
68
|
+
/**
|
|
69
|
+
* An ASCII letter, which a URL scheme must start with.
|
|
70
|
+
*/
|
|
71
|
+
const SCHEME_START_PATTERN = /[a-z]/i;
|
|
72
|
+
/**
|
|
73
|
+
* The run after `://` that may hold userinfo: everything up to whitespace or `/`.
|
|
74
|
+
*/
|
|
75
|
+
const USERINFO_RUN_PATTERN = /[^\s/]*/y;
|
|
76
|
+
/**
|
|
77
|
+
* Percent-decodes a query parameter name (`+` as a space), keeping it as written when it is not
|
|
78
|
+
* valid percent-encoding.
|
|
79
|
+
*/
|
|
80
|
+
const decodeParamName = (name) => {
|
|
81
|
+
if (!name.includes("%") && !name.includes("+")) return name;
|
|
82
|
+
try {
|
|
83
|
+
return decodeURIComponent(name.replaceAll("+", " "));
|
|
84
|
+
} catch {
|
|
85
|
+
return name;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Lowercases `key` and drops its separators, so `token_type` and `tokenType` compare equal.
|
|
90
|
+
*/
|
|
91
|
+
const normalizeKey = (key) => key.replaceAll(KEY_SEPARATOR_PATTERN, "").toLowerCase();
|
|
92
|
+
/**
|
|
93
|
+
* Turns `sensitiveKeys` entries into one predicate: strings compared normalized and whole, regexes
|
|
94
|
+
* tested on the key as written.
|
|
95
|
+
*/
|
|
96
|
+
const keyMatcher = (entries) => {
|
|
97
|
+
if (entries === void 0 || entries.length === 0) return () => false;
|
|
98
|
+
const names = /* @__PURE__ */ new Set();
|
|
99
|
+
const patterns = [];
|
|
100
|
+
for (const entry of entries) if (typeof entry === "string") names.add(normalizeKey(entry));
|
|
101
|
+
else patterns.push(new RegExp(entry.source, entry.flags.replaceAll(/[gy]/g, "")));
|
|
102
|
+
return (key, normalized) => names.has(normalized) || patterns.some((pattern) => pattern.test(key));
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Masks the userinfo of every URL in `text`: from the `://` of a scheme that starts with a letter
|
|
106
|
+
* to the last `@` before the next whitespace or `/`, so a password holding a raw `@`, `?` or `#` is
|
|
107
|
+
* hidden whole. It jumps from one `://` to the next and looks for each `@` once, so its time is
|
|
108
|
+
* linear in `text`.
|
|
109
|
+
*/
|
|
110
|
+
const maskUserinfo = (text) => {
|
|
111
|
+
let output = "";
|
|
112
|
+
let cursor = 0;
|
|
113
|
+
let nextAt = -1;
|
|
114
|
+
let separator = text.indexOf("://");
|
|
115
|
+
while (separator !== -1) {
|
|
116
|
+
let schemeStart = separator;
|
|
117
|
+
while (schemeStart > 0 && SCHEME_CHAR_PATTERN.test(text.charAt(schemeStart - 1))) schemeStart -= 1;
|
|
118
|
+
const start = separator + 3;
|
|
119
|
+
if (nextAt < start) {
|
|
120
|
+
const following = text.indexOf("@", start);
|
|
121
|
+
nextAt = following === -1 ? text.length : following;
|
|
122
|
+
}
|
|
123
|
+
USERINFO_RUN_PATTERN.lastIndex = start;
|
|
124
|
+
const runEnd = start + (USERINFO_RUN_PATTERN.exec(text)?.[0].length ?? 0);
|
|
125
|
+
const at = nextAt < runEnd ? text.lastIndexOf("@", runEnd - 1) : -1;
|
|
126
|
+
if (schemeStart < separator && SCHEME_START_PATTERN.test(text.charAt(schemeStart)) && at > start) {
|
|
127
|
+
output += text.slice(cursor, start) + REDACTED_LOG_VALUE;
|
|
128
|
+
cursor = at;
|
|
129
|
+
separator = text.indexOf("://", at + 1);
|
|
130
|
+
} else separator = text.indexOf("://", separator + 1);
|
|
131
|
+
}
|
|
132
|
+
return cursor === 0 ? text : output + text.slice(cursor);
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Builds the {@link CredentialRules} for `options`. Key verdicts are cached, since the same field
|
|
136
|
+
* names come back on every line.
|
|
137
|
+
*/
|
|
138
|
+
const makeCredentialRules = (options = {}) => {
|
|
139
|
+
const configured = keyMatcher(options.sensitiveKeys);
|
|
140
|
+
const allowed = new Set(options.allowKeys?.map(normalizeKey));
|
|
141
|
+
const scrub = options.scrubText;
|
|
142
|
+
const cache = /* @__PURE__ */ new Map();
|
|
143
|
+
/**
|
|
144
|
+
* Classifies `key` without the cache.
|
|
145
|
+
*/
|
|
146
|
+
const computeClass = (key) => {
|
|
147
|
+
const normalized = normalizeKey(key);
|
|
148
|
+
if (configured(key, normalized)) return "configured";
|
|
149
|
+
return SENSITIVE_KEY_PATTERN.test(normalized) && !allowed.has(normalized) ? "builtin" : "plain";
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Classifies `key`, remembering the verdict for keys up to {@link MAX_CACHED_KEY_LENGTH}.
|
|
153
|
+
*/
|
|
154
|
+
const keyClass = (key) => {
|
|
155
|
+
const cached = cache.get(key);
|
|
156
|
+
if (cached !== void 0) return cached;
|
|
157
|
+
const computed = computeClass(key);
|
|
158
|
+
if (key.length <= MAX_CACHED_KEY_LENGTH) {
|
|
159
|
+
if (cache.size >= MAX_CACHED_KEYS) cache.clear();
|
|
160
|
+
cache.set(key, computed);
|
|
161
|
+
}
|
|
162
|
+
return computed;
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* See {@link CredentialRules.isSensitiveKey}.
|
|
166
|
+
*/
|
|
167
|
+
const isSensitiveKey = (key) => keyClass(key) !== "plain";
|
|
168
|
+
/**
|
|
169
|
+
* See {@link CredentialRules.masksEntry}.
|
|
170
|
+
*/
|
|
171
|
+
const masksEntry = (key, value) => {
|
|
172
|
+
if (value === null || value === void 0) return false;
|
|
173
|
+
const verdict = keyClass(key);
|
|
174
|
+
if (verdict !== "builtin") return verdict === "configured";
|
|
175
|
+
return typeof value !== "number" && typeof value !== "boolean";
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* See {@link CredentialRules.isSensitiveQueryParamName}.
|
|
179
|
+
*/
|
|
180
|
+
const isSensitiveQueryParamName = (name) => {
|
|
181
|
+
const decoded = decodeParamName(name);
|
|
182
|
+
return QUERY_CREDENTIAL_NAMES.has(decoded.toLowerCase()) || isSensitiveKey(decoded);
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Masks the convenience shapes: sensitive query values first (so a value holding `@` is not read
|
|
186
|
+
* as userinfo), then URL userinfo, then auth schemes. Text without a `=`, `://` or auth scheme
|
|
187
|
+
* word is returned at once.
|
|
188
|
+
*/
|
|
189
|
+
const maskShapes = (text) => {
|
|
190
|
+
if (!MAYBE_SHAPE_PATTERN.test(text)) return text;
|
|
191
|
+
const withoutQueryValues = text.includes("=") ? maskQueryValues(text) : text;
|
|
192
|
+
return (withoutQueryValues.includes("://") ? maskUserinfo(withoutQueryValues) : withoutQueryValues).replaceAll(AUTH_SCHEME_PATTERN, (_, scheme) => `${scheme}${REDACTED_LOG_VALUE}`);
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Masks the value of every query, matrix or fragment parameter whose name
|
|
196
|
+
* {@link isSensitiveQueryParamName} accepts. A masked value is skipped as a whole. It drives the
|
|
197
|
+
* shared {@link QUERY_NAME_PATTERN} from index 0; nothing it calls in the loop uses that regex.
|
|
198
|
+
*/
|
|
199
|
+
const maskQueryValues = (text) => {
|
|
200
|
+
let output = "";
|
|
201
|
+
let cursor = 0;
|
|
202
|
+
const names = QUERY_NAME_PATTERN;
|
|
203
|
+
names.lastIndex = 0;
|
|
204
|
+
for (let match = names.exec(text); match !== null; match = names.exec(text)) {
|
|
205
|
+
if (!isSensitiveQueryParamName(match[1] ?? "")) continue;
|
|
206
|
+
const start = match.index + match[0].length;
|
|
207
|
+
QUERY_VALUE_PATTERN.lastIndex = start;
|
|
208
|
+
const end = start + (QUERY_VALUE_PATTERN.exec(text)?.[0].length ?? 0);
|
|
209
|
+
if (end > start) {
|
|
210
|
+
output += text.slice(cursor, start) + REDACTED_LOG_VALUE;
|
|
211
|
+
cursor = end;
|
|
212
|
+
names.lastIndex = end;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return cursor === 0 ? text : output + text.slice(cursor);
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* See {@link CredentialRules.redactText}.
|
|
219
|
+
*/
|
|
220
|
+
const redactText = (text) => {
|
|
221
|
+
const masked = maskShapes(text);
|
|
222
|
+
if (scrub === void 0) return masked;
|
|
223
|
+
try {
|
|
224
|
+
return scrub(masked);
|
|
225
|
+
} catch {
|
|
226
|
+
return REDACTED_LOG_VALUE;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
return {
|
|
230
|
+
masksEntry,
|
|
231
|
+
isSensitiveKey,
|
|
232
|
+
isSensitiveQueryParamName,
|
|
233
|
+
redactText
|
|
234
|
+
};
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* The rules with only the built-in list, behind every function of this package that takes no
|
|
238
|
+
* {@link RedactionOptions}.
|
|
239
|
+
*/
|
|
240
|
+
const defaultCredentialRules = makeCredentialRules();
|
|
241
|
+
/**
|
|
242
|
+
* Tells whether `key` contains a built-in sensitive name, in any case or separator style
|
|
243
|
+
* (`client_secret`, `clientSecret`, `X-Api-Key`, `set-cookie`, `sessionId`, `tokenCount`). A value
|
|
244
|
+
* under such a key is masked unless it is a `number`, a `boolean`, `null` or `undefined`.
|
|
245
|
+
*/
|
|
246
|
+
const isSensitiveLogKey = (key) => defaultCredentialRules.isSensitiveKey(key);
|
|
247
|
+
/**
|
|
248
|
+
* Tells whether the value of a URL query or fragment parameter called `name` is a credential, using
|
|
249
|
+
* the built-in names: its percent-decoded name, in any case, is `key`, `apikey`, `auth`, `code`,
|
|
250
|
+
* `sig`, `signature`, `token`, `x-amz-signature`, `x-amz-credential`, `x-amz-security-token` or
|
|
251
|
+
* `x-goog-signature`, or {@link isSensitiveLogKey} accepts it (`access_token`, `client_secret`,
|
|
252
|
+
* `creds[token]`). {@link redactLogString} masks query values by this rule.
|
|
253
|
+
*/
|
|
254
|
+
const isSensitiveQueryParamName = (name) => defaultCredentialRules.isSensitiveQueryParamName(name);
|
|
255
|
+
/**
|
|
256
|
+
* Masks a fixed list of credential shapes in `text`, and nothing else:
|
|
257
|
+
*
|
|
258
|
+
* - URL userinfo becomes `scheme://<redacted>@`;
|
|
259
|
+
* - `Bearer <token>` and `Basic <credentials>` keep the scheme word;
|
|
260
|
+
* - URL query, matrix and fragment values (after `?`, `&`, `;` or `#`) under a name
|
|
261
|
+
* {@link isSensitiveQueryParamName} accepts.
|
|
262
|
+
*
|
|
263
|
+
* Every other way of writing a secret into text is written as it is. The cost is linear in the
|
|
264
|
+
* length of `text`, and running it twice gives the same result as running it once.
|
|
265
|
+
*/
|
|
266
|
+
const redactLogString = (text) => defaultCredentialRules.redactText(text);
|
|
267
|
+
export { REDACTED_LOG_VALUE, defaultCredentialRules, isSensitiveLogKey, isSensitiveQueryParamName, makeCredentialRules, redactLogString };
|
package/dist/error.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "./redact.js";
|
|
2
|
+
import { ErrorSummary, LogFields } from "./types.js";
|
|
3
|
+
import { Cause } from "effect";
|
|
4
|
+
/**
|
|
5
|
+
* Returns a message for an unknown error, and never throws. A `Redactable` value is described by
|
|
6
|
+
* its redacted form. An `Error` gives its message, or its name when the message is empty. Another
|
|
7
|
+
* object gives its `message` or `_tag` string, or else its JSON form with sensitive keys masked
|
|
8
|
+
* (see `redactLogValue`), after its class name, such as `Credentials
|
|
9
|
+
* {"user":"u","password":"<redacted>"}`. Its own `toString` is never called. Other values give
|
|
10
|
+
* `String(value)`. The result is not passed through `redactLogString`; callers that log it should
|
|
11
|
+
* do that.
|
|
12
|
+
*/
|
|
13
|
+
export declare const describeError: (error: unknown) => string;
|
|
14
|
+
/**
|
|
15
|
+
* Returns annotation fields for `error`, read from the redacted form of a `Redactable` value:
|
|
16
|
+
* `errorMessage`, `errorTag`, `errorName` and `errorStatus`, each when present. The message, tag
|
|
17
|
+
* and name are masked with `redactLogString`. An object with no `message` or `_tag` gets no
|
|
18
|
+
* `errorMessage`: its JSON form is redacted with the built-in names only, so it could reveal a
|
|
19
|
+
* value under a name the logger layer adds, and the line's cause already carries that object
|
|
20
|
+
* redacted with the layer's rules. Never throws.
|
|
21
|
+
*/
|
|
22
|
+
export declare const extractErrorFields: (error: unknown) => LogFields;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the first fail, otherwise the first die, otherwise the first interrupt. An empty cause
|
|
25
|
+
* returns `undefined`. The summary's message, tag and name are masked with `redactLogString`.
|
|
26
|
+
*/
|
|
27
|
+
export declare const extractCauseSummary: (cause: Cause.Cause<unknown>) => ErrorSummary | undefined;
|