-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathdiagnostics-format.ts
More file actions
252 lines (239 loc) · 9.06 KB
/
Copy pathdiagnostics-format.ts
File metadata and controls
252 lines (239 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import type {
BackendDumpNetworkResult,
BackendMeasurePerfResult,
BackendNetworkIncludeMode,
BackendReadLogsResult,
} from '../backend.ts';
import type {
DiagnosticsLogsCommandResult,
DiagnosticsNetworkCommandResult,
DiagnosticsPerfCommandResult,
} from './diagnostics-types.ts';
const PAYLOAD_MAX_CHARS = 2048;
const MESSAGE_MAX_CHARS = 4096;
const SECRET_KEY_PATTERN = /(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;
export function formatLogsResult(result: BackendReadLogsResult): DiagnosticsLogsCommandResult {
let redacted = result.redacted === true;
const entries = result.entries.map((entry) => {
const message = redactAndTruncate(entry.message, MESSAGE_MAX_CHARS);
const metadata = redactUnknown(entry.metadata);
redacted ||= message.redacted || metadata.redacted;
return {
...(entry.timestamp ? { timestamp: entry.timestamp } : {}),
...(entry.level ? { level: entry.level } : {}),
message: message.value ?? '',
...(entry.source ? { source: entry.source } : {}),
...(metadata.value ? { metadata: metadata.value as Record<string, unknown> } : {}),
};
});
return {
kind: 'diagnosticsLogs',
entries,
...(result.nextCursor ? { nextCursor: result.nextCursor } : {}),
...(result.timeWindow ? { timeWindow: result.timeWindow } : {}),
...(result.backend ? { backend: result.backend } : {}),
redacted,
...(result.notes ? { notes: result.notes } : {}),
};
}
export function formatNetworkResult(
result: BackendDumpNetworkResult,
include: BackendNetworkIncludeMode,
): DiagnosticsNetworkCommandResult {
let redacted = result.redacted === true;
const entries = result.entries.map((entry) => {
const url = entry.url ? redactUrl(entry.url) : undefined;
const requestHeaders =
include === 'headers' || include === 'all' ? redactHeaders(entry.requestHeaders) : undefined;
const responseHeaders =
include === 'headers' || include === 'all' ? redactHeaders(entry.responseHeaders) : undefined;
const requestBody =
include === 'body' || include === 'all' ? redactPayload(entry.requestBody) : undefined;
const responseBody =
include === 'body' || include === 'all' ? redactPayload(entry.responseBody) : undefined;
const metadata = redactUnknown(entry.metadata);
redacted ||=
(url?.redacted ?? false) ||
(requestHeaders?.redacted ?? false) ||
(responseHeaders?.redacted ?? false) ||
(requestBody?.redacted ?? false) ||
(responseBody?.redacted ?? false) ||
metadata.redacted;
return {
...(entry.timestamp ? { timestamp: entry.timestamp } : {}),
...(entry.method ? { method: entry.method } : {}),
...(url ? { url: url.value } : {}),
...(entry.status !== undefined ? { status: entry.status } : {}),
...(entry.durationMs !== undefined ? { durationMs: entry.durationMs } : {}),
...(requestHeaders?.value ? { requestHeaders: requestHeaders.value } : {}),
...(responseHeaders?.value ? { responseHeaders: responseHeaders.value } : {}),
...(requestBody?.value !== undefined ? { requestBody: requestBody.value } : {}),
...(responseBody?.value !== undefined ? { responseBody: responseBody.value } : {}),
...(metadata.value ? { metadata: metadata.value as Record<string, unknown> } : {}),
};
});
return {
kind: 'diagnosticsNetwork',
entries,
...(result.nextCursor ? { nextCursor: result.nextCursor } : {}),
...(result.timeWindow ? { timeWindow: result.timeWindow } : {}),
...(result.backend ? { backend: result.backend } : {}),
redacted,
...(result.notes ? { notes: result.notes } : {}),
};
}
export function formatPerfResult(result: BackendMeasurePerfResult): DiagnosticsPerfCommandResult {
let redacted = result.redacted === true;
return {
kind: 'diagnosticsPerf',
metrics: result.metrics.map((metric) => {
const message = redactAndTruncate(metric.message, MESSAGE_MAX_CHARS);
const metadata = redactUnknown(metric.metadata);
redacted ||= message.redacted || metadata.redacted;
return {
name: metric.name,
...(metric.value !== undefined ? { value: metric.value } : {}),
...(metric.unit ? { unit: metric.unit } : {}),
...(metric.status ? { status: metric.status } : {}),
...(message.value !== undefined ? { message: message.value } : {}),
...(metadata.value ? { metadata: metadata.value as Record<string, unknown> } : {}),
};
}),
...(result.startedAt ? { startedAt: result.startedAt } : {}),
...(result.endedAt ? { endedAt: result.endedAt } : {}),
...(result.backend ? { backend: result.backend } : {}),
redacted,
...(result.notes ? { notes: result.notes } : {}),
};
}
function redactHeaders(headers: Record<string, string> | undefined): {
value?: Record<string, string>;
redacted: boolean;
} {
if (!headers) return { redacted: false };
let redacted = false;
const next: Record<string, string> = {};
for (const [key, value] of Object.entries(headers)) {
if (SECRET_KEY_PATTERN.test(key)) {
next[key] = '[REDACTED]';
redacted = true;
} else {
const result = redactAndTruncate(value, PAYLOAD_MAX_CHARS);
next[key] = result.value ?? '';
redacted ||= result.redacted;
}
}
return { value: next, redacted };
}
function redactUrl(url: string): { value: string; redacted: boolean } {
try {
const parsed = new URL(url);
let redacted = false;
for (const key of Array.from(parsed.searchParams.keys())) {
if (SECRET_KEY_PATTERN.test(key)) {
parsed.searchParams.set(key, '[REDACTED]');
redacted = true;
}
}
return { value: parsed.toString(), redacted };
} catch {
return redactAndTruncate(url, PAYLOAD_MAX_CHARS) as { value: string; redacted: boolean };
}
}
function redactPayload(value: string | undefined): { value?: string; redacted: boolean } {
if (value === undefined) return { redacted: false };
const structured = redactJsonPayload(value);
return structured ?? redactAndTruncate(value, PAYLOAD_MAX_CHARS);
}
function redactJsonPayload(value: string): { value?: string; redacted: boolean } | undefined {
try {
const parsed = JSON.parse(value);
const result = redactValue(parsed, redactText);
return truncateRedacted(JSON.stringify(result.value), PAYLOAD_MAX_CHARS, result.redacted);
} catch {
return undefined;
}
}
function redactUnknown(value: unknown): { value?: unknown; redacted: boolean } {
return redactValue(value, (entry) => redactAndTruncate(entry, PAYLOAD_MAX_CHARS));
}
function redactValue(
value: unknown,
redactString: (value: string) => { value?: string; redacted: boolean },
): { value?: unknown; redacted: boolean } {
if (value === undefined) return { redacted: false };
if (typeof value === 'string') return redactString(value);
if (!value || typeof value !== 'object') return { value, redacted: false };
if (Array.isArray(value)) {
let redacted = false;
const next = value.map((entry) => {
const result = redactValue(entry, redactString);
redacted ||= result.redacted;
return result.value;
});
return { value: next, redacted };
}
let redacted = false;
const next: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(value)) {
if (SECRET_KEY_PATTERN.test(key)) {
next[key] = '[REDACTED]';
redacted = true;
continue;
}
const result = redactValue(entry, redactString);
next[key] = result.value;
redacted ||= result.redacted;
}
return { value: next, redacted };
}
function redactAndTruncate(
value: string | undefined,
maxChars: number,
): { value?: string; redacted: boolean } {
if (value === undefined) return { redacted: false };
const result = redactText(value);
return truncateRedacted(result.value, maxChars, result.redacted);
}
function redactText(value: string): { value: string; redacted: boolean } {
let redacted = false;
let next = value.replaceAll(
/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,
(_match, key) => {
redacted = true;
return `${String(key)}=[REDACTED]`;
},
);
next = next.replaceAll(
/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,
(_match, prefix, _value, suffix) => {
redacted = true;
return `${String(prefix)}[REDACTED]${String(suffix)}`;
},
);
next = next.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi, (_match, prefix) => {
redacted = true;
return `${String(prefix)}[REDACTED]`;
});
next = next.replaceAll(
/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;]+)/gi,
(_match, prefix) => {
redacted = true;
return `${String(prefix)}[REDACTED]`;
},
);
return { value: next, redacted };
}
function truncateRedacted(
value: string | undefined,
maxChars: number,
redacted: boolean,
): { value?: string; redacted: boolean } {
if (value === undefined) return { redacted };
let next = value;
if (next.length > maxChars) {
next = `${next.slice(0, maxChars)}...[truncated]`;
redacted = true;
}
return { value: next, redacted };
}