feat(logging): establish trace diagnostics contract

Make short-lived TRACE sessions complete and correlatable without adding a persistent trace channel or changing the existing file-log safety boundary.

Protect ordinary console, subscriber, and file logs from authentication material while preserving the one documented first-start credential notice. Keep action breadcrumbs useful through bounded summaries and a narrow diagnostic name for the emoji-like pagination offset.

Lock the contract with regressions for byte-complete rendering, lazy execution, request-context reuse, credential redaction, unredacted TRACE data, and non-persistence of TRACE records.
This commit is contained in:
DrSmoothl committed 2026-07-30 12:07:32 +08:00
1 parent 1d65623475
commit b9104f0a5b
8 files changed
+712 -87

No files matched your search

+246 -51
View File
@@ -1,7 +1,39 @@
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
const SENSITIVE_SEGMENTS = new Set([
'authorization',
'cookie',
'credential',
'credentials',
'password',
'passwd',
'secret',
'token',
'apikey',
'privatekey',
'sessionkey',
]);
function valueRepr(v: unknown): string {
function isSensitiveKey(key: string): boolean {
const segments = key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.split(/[-_.\s]+/)
.filter(Boolean)
.map((segment) => segment.toLowerCase());
return segments.some((segment, index) => {
if (SENSITIVE_SEGMENTS.has(segment)) return true;
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
);
});
}
function valueRepr(v: unknown, key?: string): string {
if (key !== undefined && isSensitiveKey(key)) return '"***"';
if (v === null) return 'null';
if (v === undefined) return 'undefined';
switch (typeof v) {
@@ -31,83 +63,246 @@ export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
return s.length > MAX_TOTAL
? `${s.slice(0, MAX_TOTAL - 3)}...`
: s;
}
if (Array.isArray(params)) return `[len=${params.length}]`;
const out: string[] = [];
let total = 0;
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
const entry = `${k}=${valueRepr(v)}`;
// +1 accounts for the separating space we'd insert when joining.
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
out.push('...');
break;
const entry = `${k}=${valueRepr(v, k)}`;
const separatorLength = out.length > 0 ? 1 : 0;
if (total + separatorLength + entry.length > MAX_TOTAL) {
if (out.length === 0) {
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
}
const rendered = out.join(' ');
return rendered.length + 4 <= MAX_TOTAL
? `${rendered} ...`
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
}
out.push(entry);
total += entry.length + (out.length > 1 ? 1 : 0);
total += separatorLength + entry.length;
}
return out.join(' ');
}
const VERBOSE_STRING_MAX = 200;
const VERBOSE_TOTAL_MAX = 1500;
// Keys whose values must never be rendered — tokens, passwords, secrets.
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
'authorization',
'cookie',
'password',
'passwd',
'secret',
'token',
'apikey',
'privatekey',
'sessionkey',
]);
function keySegments(key: string): string[] {
return key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.split(/[-_.\s]+/)
.filter(Boolean)
.map((segment) => segment.toLowerCase());
}
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
return keySegments(key).includes(kind);
}
function isAuthorizationBoundaryKey(key: string): boolean {
const segments = keySegments(key);
return segments.some((segment, index) => {
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
);
});
}
function quotedValueEnd(message: string, start: number): number | undefined {
const quote = message[start];
if (quote !== '"' && quote !== "'") return undefined;
for (let index = start + 1; index < message.length; index += 1) {
if (message[index] === '\\') {
index += 1;
} else if (message[index] === quote) {
return index + 1;
}
}
return message.length;
}
function cookieValueEnd(message: string, start: number): number {
const initialQuotedEnd = quotedValueEnd(message, start);
let end: number;
if (initialQuotedEnd !== undefined) {
end = initialQuotedEnd;
} else {
end = start;
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
}
while (end < message.length) {
let semicolon: number = end;
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
semicolon += 1;
}
if (message[semicolon] !== ';') break;
let nameStart = semicolon + 1;
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
nameStart += 1;
}
let nameEnd = nameStart;
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
if (nameEnd === nameStart) break;
end = nameEnd;
if (message[end] !== '=') continue;
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
const valueStart = end + 1;
const quotedEnd = quotedValueEnd(message, valueStart);
if (quotedEnd !== undefined) {
end = quotedEnd;
continue;
}
if (attribute !== 'expires') {
end = valueStart;
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
continue;
}
end = valueStart;
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
assignments.lastIndex = valueStart;
const nextField = assignments.exec(message);
if (nextField && nextField.index < end) end = nextField.index;
}
return end;
}
function genericValueEnd(message: string, start: number): number {
const quotedEnd = quotedValueEnd(message, start);
if (quotedEnd !== undefined) return quotedEnd;
let end = start;
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
return end;
}
function authorizationValueEnd(
message: string,
start: number,
query: boolean,
): number {
const quotedEnd = quotedValueEnd(message, start);
if (quotedEnd !== undefined) return quotedEnd;
if (query) {
const queryEnd = message.indexOf('&', start);
return queryEnd >= 0 ? queryEnd : message.length;
}
let end = message.length;
const structural = message.slice(start).search(/[\r\n}\]]/);
if (structural >= 0) end = start + structural;
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
const remaining = message.slice(start, end);
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
if (isAuthorizationBoundaryKey(match[3]!)) {
end = start + match.index;
break;
}
}
return end;
}
/** Redact explicit authentication assignments in ordinary formatted logs. */
export function redactLogMessage(message: string): string {
let out = '';
let cursor = 0;
ASSIGNMENT_START.lastIndex = 0;
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
const key = match[3]!;
if (!isSensitiveKey(key)) {
ASSIGNMENT_START.lastIndex = Math.max(
match.index + 1,
ASSIGNMENT_START.lastIndex - 1,
);
continue;
}
const valueStart = ASSIGNMENT_START.lastIndex;
const valueEnd = isKeyKind(key, 'authorization')
? authorizationValueEnd(
message,
valueStart,
match[1] === '?' || match[1] === '&',
)
: isKeyKind(key, 'cookie')
? cookieValueEnd(message, valueStart)
: genericValueEnd(message, valueStart);
out += message.slice(cursor, valueStart) + '***';
cursor = valueEnd;
ASSIGNMENT_START.lastIndex = valueEnd;
}
return out + message.slice(cursor);
}
/**
* Deep, debug-grade render of a params object for the `trace` level: shows the
* full nested structure (message segments, nested objects) so a reproduction
* is legible — unlike {@link summarizeParams}, which collapses nested values.
*
* Three guards keep it safe and bounded:
* - per-string cap (long values like base64 image data become `"…<N B>"`),
* - total output budget (so a giant payload can't flood the buffer),
* - key-based redaction (token / password / secret → `"***"`).
* Lossless nested renderer for explicit TRACE diagnostics. TRACE is an
* operator-enabled, memory-only mode and intentionally leaves values
* unredacted so a reproduction contains the complete business input.
*/
export function renderParamsVerbose(params: unknown): string {
const seen = new WeakSet<object>();
let budget = VERBOSE_TOTAL_MAX;
const walk = (value: unknown, key?: string): string => {
if (budget <= 0) return '…';
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
const walk = (value: unknown): string => {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
switch (typeof value) {
case 'string': {
const truncated =
value.length > VERBOSE_STRING_MAX
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
: value;
const out = JSON.stringify(truncated);
budget -= out.length;
return out;
}
case 'string':
return JSON.stringify(value);
case 'number':
case 'boolean':
case 'bigint': {
const out = String(value);
budget -= out.length;
return out;
}
case 'bigint':
return String(value);
case 'object': {
if (seen.has(value as object)) return '"[circular]"';
seen.add(value as object);
const parts: string[] = [];
if (Array.isArray(value)) {
for (const item of value) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(walk(item));
}
return `[${parts.join(',')}]`;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(`${k}:${walk(v, k)}`);
}
return `{${parts.join(',')}}`;
const out = Array.isArray(value)
? `[${value.map((item) => walk(item)).join(',')}]`
: `{${Object.entries(value as Record<string, unknown>)
.map(([key, item]) => `${key}:${walk(item)}`)
.join(',')}}`;
seen.delete(value as object);
return out;
}
default:
return typeof value;
+25 -12
View File
@@ -1,7 +1,8 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
import { redactLogMessage } from './log-summary';
import { sanitizeLogLine } from './log-sanitize';
import { currentRequestId } from './request-context';
import { currentRequestId, nextRequestId, runWithRequestId } from './request-context';
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
type FileLogLevel = Exclude<LogLevel, 'trace'>;
@@ -181,8 +182,7 @@ function currentTime(): string {
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
const message = format(...args);
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
@@ -209,12 +209,13 @@ function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
forceFile = false,
forceInitialCredentials = false,
): void {
// Console / subscriber and file filters are independent. If no destination
// accepts the record, stop before formatting or building a LogEntry.
const passesConsole = forceFile || shouldLog(level);
const passesFile = level !== 'trace' && (forceFile || shouldLogToFile(level));
const passesConsole = forceInitialCredentials || shouldLog(level);
const passesFile = level !== 'trace'
&& (forceInitialCredentials || shouldLogToFile(level));
if (!passesConsole && !passesFile) return;
// `trace` is the high-volume full-chain diagnostic stream, intentionally
@@ -232,8 +233,11 @@ function emit(
}
const reqId = currentRequestId();
const message = format(...realArgs);
const line = render(level, options, realArgs, reqId);
const formattedMessage = format(...realArgs);
const message = level === 'trace' || forceInitialCredentials
? formattedMessage
: redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
@@ -341,6 +345,15 @@ export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}
export function renderTraceBytes(body: Uint8Array): string {
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
}
export function runWithTraceRequest<T>(fn: () => T): T {
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
return runWithRequestId(nextRequestId(), fn);
}
export function logInitialWebuiCredentials(password: string): void {
emit(
'info',
@@ -350,7 +363,7 @@ export function logInitialWebuiCredentials(password: string): void {
);
}
// Request-correlation helpers live alongside the logger since `[req#N]`
// stamping is a logging concern. Re-exported here so callers import the
// whole logging surface from one place.
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
// Request-correlation primitives remain available for callers that already own
// an explicit request id. New semantic entrypoints should prefer
// runWithTraceRequest() so disabled TRACE does not allocate one.
export { nextRequestId, runWithRequestId, currentRequestId };
+185 -12
View File
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
import {
redactLogMessage,
renderParamsVerbose,
summarizeParams,
} from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
@@ -24,29 +28,191 @@ describe('summarizeParams', () => {
.toBe(`s="${'x'.repeat(40)}..."`);
});
it('redacts authentication fields without exposing their values', () => {
const out = summarizeParams({
token: 'token-value',
Cookie: 'cookie-value',
Authorization: 'Bearer authorization-value',
user_password: 'password-value',
apiKey: 'key-value',
group_id: 12345,
});
expect(out).toContain('token="***"');
expect(out).toContain('Cookie="***"');
expect(out).toContain('Authorization="***"');
expect(out).toContain('user_password="***"');
expect(out).toContain('apiKey="***"');
expect(out).toContain('group_id=12345');
expect(out).not.toMatch(
/token-value|cookie-value|authorization-value|password-value|key-value/,
);
});
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
expect(summarizeParams({
retoken: 'visible',
cookietown: 'visible',
myauthorization: 'visible',
})).toBe(
'retoken="visible" cookietown="visible" myauthorization="visible"',
);
});
it('caps total output and appends "..." on overflow', () => {
const big: Record<string, number> = {};
for (let i = 0; i < 60; i++) big['key' + i] = i;
const out = summarizeParams(big);
expect(out.startsWith('key0=0')).toBe(true);
expect(out.endsWith('...')).toBe(true);
expect(out.length).toBeLessThanOrEqual(200);
});
it('caps a single oversized first key and top-level primitive', () => {
const oversizedKey = 'k'.repeat(300);
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
const primitiveOut = summarizeParams('x'.repeat(300));
expect(objectOut).toHaveLength(200);
expect(objectOut.endsWith('...')).toBe(true);
expect(primitiveOut).toHaveLength(200);
expect(primitiveOut.endsWith('...')).toBe(true);
});
});
describe('redactLogMessage', () => {
it('redacts explicit authentication assignments without changing prose', () => {
const out = redactLogMessage(
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
);
expect(out).toBe(
'password=*** Authorization: *** cookie=*** password change required',
);
});
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
const out = redactLogMessage(
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
);
const expires = redactLogMessage(
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
);
expect(out).toContain('json={"authorization":***}');
expect(out).toContain("object={ 'api-key': *** }");
expect(out).toContain('Authorization: *** Cookie=***');
expect(expires).toBe('Cookie=*** safe=visible');
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
});
it('redacts complete multi-parameter Authorization values', () => {
const out = redactLogMessage(
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
);
expect(out).toBe(
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
);
expect(out).not.toMatch(
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
);
});
it('redacts camelCase authentication keys without matching larger words', () => {
const out = redactLogMessage(
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
);
expect(out).toBe(
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
);
expect(out).not.toMatch(
/auth-secret|id-secret|client-secret|password-secret/,
);
expect(redactLogMessage(
'retoken=value cookietown=value myauthorization=value',
)).toBe('retoken=value cookietown=value myauthorization=value');
});
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
expect(redactLogMessage(
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
});
it('redacts nested assignments inside non-sensitive wrapper values', () => {
expect(redactLogMessage(
'params=authToken=auth-secret params=cookie="cookie-secret"',
)).toBe('params=authToken=*** params=cookie=***');
});
it('redacts the entire Authorization value when it starts with a marker', () => {
expect(redactLogMessage('Authorization: *** secret-value'))
.toBe('Authorization: ***');
});
it('redacts property paths and URL query authentication values', () => {
const out = redactLogMessage(
'headers.authorization=Basic dXNlcjpwYXNz '
+ 'request.token=plain-token '
+ 'GET /callback?access_token=query-secret&x=1 '
+ 'url=https://host/?api_key=url-secret',
);
expect(out).toContain('headers.authorization=***');
expect(out).toContain('request.token=***');
expect(out).toContain('/callback?access_token=***&x=1');
expect(out).toContain('https://host/?api_key=***');
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
});
it('redacts prefixed authentication keys without matching larger words', () => {
const redacted = redactLogMessage(
'x-api-key=api-secret user_password=password-secret '
+ 'headers.authorization=Basic auth-secret '
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
);
expect(redacted).toContain('x-api-key=***');
expect(redacted).toContain('user_password=***');
expect(redacted).toContain('headers.authorization=***');
expect(redacted).toContain('x-cookie=***');
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
expect(redactLogMessage(
'retoken=value cookietown=value myauthorization=value',
)).toBe('retoken=value cookietown=value myauthorization=value');
});
});
describe('renderParamsVerbose', () => {
it('redacts token / password / secret keys at any depth', () => {
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
expect(out).toContain('token:"***"');
expect(out).toContain('password:"***"');
expect(out).toContain('secret:"***"');
expect(out).toContain('ok:"v"');
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
const out = renderParamsVerbose({
token: 'token-value',
Cookie: 'cookie-value',
password: 'password-value',
apiKey: 'key-value',
});
expect(out).toContain('token:"token-value"');
expect(out).toContain('Cookie:"cookie-value"');
expect(out).toContain('password:"password-value"');
expect(out).toContain('apiKey:"key-value"');
expect(out).not.toContain('"***"');
});
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
expect(out).toContain('…<500B>');
expect(out).not.toContain('...<500B>');
it('does not truncate TRACE values or their enclosing object', () => {
const unicodeValue = '雪'.repeat(800);
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
expect(out).toContain('tail:"complete"');
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
});
it('guards against circular references', () => {
@@ -55,6 +221,13 @@ describe('renderParamsVerbose', () => {
expect(renderParamsVerbose(o)).toContain('"[circular]"');
});
it('renders shared non-cyclic references in every branch', () => {
const shared = { value: 1 };
expect(renderParamsVerbose({ left: shared, right: shared }))
.toBe('{left:{value:1},right:{value:1}}');
});
it('renders nested structure with primitives intact', () => {
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
});
+86 -1
View File
@@ -176,7 +176,7 @@ describe('file output gating', () => {
expect(fileWriteSpy).not.toHaveBeenCalled();
});
it('keeps trace out of files at every file threshold', async () => {
it('keeps trace out of files in an explicit file-threshold check', async () => {
const fresh = await loadLoggerForFileLevel('debug');
fresh.setLogLevel('trace');
@@ -185,6 +185,91 @@ describe('file output gating', () => {
expect(fileWriteSpy).not.toHaveBeenCalled();
});
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
const fresh = await loadLoggerForFileLevel('debug');
fresh.setLogLevel('trace');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const log = fresh.createLogger('Test');
log.info(
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
'ordinary-password',
'ordinary-authorization',
'ordinary-cookie',
'ordinary-token',
'visible',
);
log.trace(
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
'trace-password',
'trace-authorization',
'trace-cookie',
'trace-token',
);
log.info(
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
);
log.info(
'headers.authorization=Basic dotted-auth request.token=dotted-token '
+ 'GET /callback?access_token=query-secret&x=1 '
+ 'url=https://host/?api_key=url-secret',
);
log.info(
'Authorization: Digest username="alice", response="digest-secret"\n'
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
);
log.info(
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
+ `json={"userPassword":"camel-password"}`,
);
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
log.info('Authorization: *** marker-secret');
log.trace(
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
);
unsubscribe();
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
expect(ordinary).toContain('password=***');
expect(ordinary).toContain('Authorization: ***');
expect(ordinary).toContain('Cookie=***');
expect(ordinary).toContain('token=***');
expect(ordinary).toContain('headers.authorization=***');
expect(ordinary).toContain('request.token=***');
expect(ordinary).toContain('/callback?access_token=***&x=1');
expect(ordinary).toContain('https://host/?api_key=***');
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
expect(ordinary).toContain('authToken=***');
expect(ordinary).toContain('idToken=***');
expect(ordinary).toContain('clientSecret=***');
expect(ordinary).toContain(`json={"userPassword":***}`);
expect(ordinary).toContain('_token=***');
expect(ordinary).toContain('--password=***');
expect(ordinary).toContain('2faToken=***');
expect(ordinary).toContain('Authorization: ***');
expect(ordinary).toContain('safe=visible');
expect(ordinary).not.toMatch(
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
);
const trace = entries.filter((entry) => entry.level === 'trace')
.map((entry) => entry.message)
.join('\n');
expect(trace).toContain('trace-password');
expect(trace).toContain('trace-authorization');
expect(trace).toContain('trace-cookie');
expect(trace).toContain('trace-token');
expect(trace).toContain('trace-json-auth');
expect(trace).toContain('trace-header-auth');
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
expect(persisted).not.toMatch(
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
);
});
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
@@ -0,0 +1,102 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
createLogger,
currentRequestId,
getLogLevel,
nextRequestId,
renderTraceBytes,
runWithRequestId,
runWithTraceRequest,
setLogLevel,
} from '../src/logger';
const originalLevel = getLogLevel();
afterEach(() => {
setLogLevel(originalLevel);
});
describe('TRACE diagnostics contract', () => {
it('renders every byte as continuous lowercase hexadecimal', () => {
expect(renderTraceBytes(new Uint8Array())).toBe('');
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff])))
.toBe('00010f10ff');
});
it('renders only the addressed Uint8Array view', () => {
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
});
it('does not render bytes while TRACE is disabled', () => {
setLogLevel('info');
let rendered = false;
createLogger('Trace.Contract').trace(() => {
rendered = true;
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
});
expect(rendered).toBe(false);
});
it('creates distinct request contexts that survive asynchronous work', async () => {
setLogLevel('info');
const beforeDisabled = nextRequestId();
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
const afterDisabled = nextRequestId();
expect(afterDisabled).toBe(beforeDisabled + 1);
setLogLevel('trace');
const observeContext = () => runWithTraceRequest(async () => {
const before = currentRequestId();
await Promise.resolve();
const after = currentRequestId();
expect(after).toBe(before);
return after;
});
const first = await observeContext();
expect(currentRequestId()).toBeUndefined();
const second = await observeContext();
expect(currentRequestId()).toBeUndefined();
expect(first).toEqual(expect.any(Number));
expect(first).toBeGreaterThan(0);
expect(second).toEqual(expect.any(Number));
expect(second).toBeGreaterThan(0);
expect(second).not.toBe(first);
});
it('allocates once for nested TRACE contexts and reuses the request id', () => {
setLogLevel('trace');
const before = nextRequestId();
const observed = runWithTraceRequest(() => {
const outer = currentRequestId();
const inner = runWithTraceRequest(() => currentRequestId());
return { outer, inner };
});
const after = nextRequestId();
expect(observed.outer).toEqual(expect.any(Number));
expect(observed.inner).toBe(observed.outer);
expect(observed.outer).toBe(before + 1);
expect(after).toBe(before + 2);
expect(currentRequestId()).toBeUndefined();
});
it('reuses an existing request context even while TRACE is disabled', async () => {
setLogLevel('info');
await runWithRequestId(4242, async () => {
const observed = await runWithTraceRequest(async () => {
await Promise.resolve();
return currentRequestId();
});
expect(observed).toBe(4242);
});
});
});
+18 -1
View File
@@ -16,6 +16,23 @@ import { RETCODE, failedResponse, okResponse } from './types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming';
const moduleLog = createLogger('Bridge.Action');
function summarizeActionParams(action: string, params: JsonObject): string {
if (action !== 'fetch_emoji_like') return summarizeParams(params);
const safeParams: JsonObject = { ...params };
const cursor = params.cookie;
if (typeof cursor !== 'string' || !/^\d+$/.test(cursor)) {
return summarizeParams(safeParams);
}
const offset = Number(cursor);
if (!Number.isSafeInteger(offset)) return summarizeParams(safeParams);
delete safeParams.cookie;
safeParams.emoji_like_offset = offset;
return summarizeParams(safeParams);
}
export interface MessageSendResult {
messageId: number;
@@ -264,7 +281,7 @@ export class ApiHandler {
): Promise<import('./types').ApiResponse> {
// Terse breadcrumb to the log file (debug, which is written to disk under the default
// file level): lets the operator grep "what did the bot get asked to do" in post-mortems.
this.log.debug('%s params=%s', action, summarizeParams(params));
this.log.debug('%s params=%s', action, summarizeActionParams(action, params));
// Full request shape, memory-only (trace). Lazy producer → the deep render
// only runs when trace is live.
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
@@ -93,6 +93,47 @@ describe('ApiHandler dispatch logging', () => {
expect(entry!.message).toContain('message=[len=3]');
});
it('logs the parsed emoji-like offset without exposing its cookie cursor', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('fetch_emoji_like', async () => ({ status: 'ok', retcode: 0, data: null })),
], 12345);
await handler.handle('fetch_emoji_like', {
message_id: 1,
emojiId: '66',
cookie: '40',
});
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry?.message).toContain('emoji_like_offset=40');
expect(entry?.message).not.toContain('cookie=');
});
it('keeps malformed emoji-like cookies redacted instead of parsing prefixes', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('fetch_emoji_like', async () => ({ status: 'ok', retcode: 0, data: null })),
], 12345);
await handler.handle('fetch_emoji_like', { cookie: '123.session=secret' });
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry?.message).toContain('cookie=***');
expect(entry?.message).not.toContain('emoji_like_offset=');
expect(entry?.message).not.toContain('session=secret');
});
it('keeps cookie parameters redacted for every other action', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('other_action', async () => ({ status: 'ok', retcode: 0, data: null })),
], 12345);
await handler.handle('other_action', { cookie: '40' });
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry?.message).toContain('cookie=***');
expect(entry?.message).not.toContain('cookie=40');
});
it('emits a warn line with the error stack when the handler throws', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('boom', async () => { throw new Error('kapow'); }),
+9 -10
View File
@@ -21,24 +21,23 @@ describe('renderParamsVerbose', () => {
expect(out).toContain('"456"');
});
it('truncates long strings (e.g. base64) with a size marker', () => {
it('preserves long strings such as inline base64 data', () => {
const big = 'A'.repeat(5000);
const out = renderParamsVerbose({ file: `base64://${big}` });
expect(out).toContain('base64://');
expect(out).toContain('…<'); // truncation marker
expect(out).toContain('B>');
expect(out.length).toBeLessThan(2000); // bounded by the total budget
expect(out).toContain(`file:"base64://${big}"`);
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
});
it('redacts sensitive keys at any depth', () => {
it('keeps sensitive fields visible in explicit TRACE diagnostics', () => {
const out = renderParamsVerbose({
access_token: 'super-secret-value',
nested: { password: 'hunter2', SECRET: 'x', ok: 'visible' },
});
expect(out).not.toContain('super-secret-value');
expect(out).not.toContain('hunter2');
expect(out).toContain('"***"');
expect(out).toContain('"visible"'); // non-sensitive keys still rendered
expect(out).toContain('super-secret-value');
expect(out).toContain('hunter2');
expect(out).toContain('SECRET:"x"');
expect(out).not.toContain('"***"');
expect(out).toContain('"visible"');
});
it('handles circular references without throwing', () => {