-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathdebug.mts
More file actions
278 lines (265 loc) · 8.74 KB
/
Copy pathdebug.mts
File metadata and controls
278 lines (265 loc) · 8.74 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* Debug utilities for Socket CLI. Provides structured debugging with
* categorized levels and helpers.
*
* Debug Categories: DEFAULT (shown with SOCKET_CLI_DEBUG=1):
*
* - 'error': Critical errors that prevent operation
* - 'warn': Important warnings that may affect behavior
* - 'notice': Notable events and state changes
* - 'silly': Very verbose debugging info
*
* OPT-IN ONLY (require explicit DEBUG='category' even with SOCKET_CLI_DEBUG=1):
*
* - 'inspect': Detailed object inspection (DEBUG='inspect' or DEBUG='*')
* - 'stdio': Command execution logs (DEBUG='stdio' or DEBUG='*')
*
* These opt-in categories are intentionally excluded from default debug output
* to reduce noise. Enable them explicitly when needed for deep debugging.
*/
import {
debug,
debugCache,
debugDir,
debugDirNs,
debugNs,
} from '@socketsecurity/lib-stable/debug/output'
import { isDebug, isDebugNs } from '@socketsecurity/lib-stable/debug/namespace'
import { errorMessage } from '@socketsecurity/lib-stable/errors/message'
import type { IncomingHttpHeaders } from 'node:http'
export type ApiRequestDebugInfo = {
durationMs?: number | undefined
headers?: Record<string, string> | undefined
method?: string | undefined
// ISO-8601 timestamp of when the request was initiated. Useful when
// correlating failures with server-side logs.
requestedAt?: string | undefined
// Response body string; truncated by the helper to a safe length so
// logs don't balloon on megabyte payloads.
responseBody?: string | undefined
// Response headers from the failed request. The helper extracts the
// cf-ray trace id as a first-class field so support can look it up in
// the Cloudflare dashboard without eyeballing the whole header dump.
responseHeaders?: IncomingHttpHeaders | undefined
url?: string | undefined
}
const RESPONSE_BODY_TRUNCATE_LENGTH = 2000
/**
* Build the structured debug payload shared by the error + failure-status
* branches of `debugApiResponse`. Extracted so both paths log the same shape.
*/
export function buildApiDebugDetails(
base: Record<string, unknown>,
requestInfo?: ApiRequestDebugInfo | undefined,
): Record<string, unknown> {
// `__proto__: null` keeps the payload free of prototype-chain keys
// when callers iterate over the debug output.
const details: Record<string, unknown> = {
__proto__: null,
...base,
}
if (!requestInfo) {
return details
}
if (requestInfo.requestedAt) {
details['requestedAt'] = requestInfo.requestedAt
}
if (requestInfo.method) {
details['method'] = requestInfo.method
}
if (requestInfo.url) {
details['url'] = requestInfo.url
}
if (requestInfo.durationMs !== undefined) {
details['durationMs'] = requestInfo.durationMs
}
if (requestInfo.headers) {
details['headers'] = sanitizeHeaders(requestInfo.headers)
}
if (requestInfo.responseHeaders) {
const cfRay =
requestInfo.responseHeaders['cf-ray'] ??
requestInfo.responseHeaders['CF-Ray']
if (cfRay) {
// First-class field so it's obvious when filing a support ticket
// that points at a Cloudflare trace.
details['cfRay'] = cfRay
}
details['responseHeaders'] = sanitizeHeaders(requestInfo.responseHeaders)
}
if (requestInfo.responseBody !== undefined) {
const body = requestInfo.responseBody
// `.length` / `.slice` operate on UTF-16 code units, not bytes, so
// the counter and truncation are both reported in "chars" to stay
// consistent with what we actually measured.
details['responseBody'] =
body.length > RESPONSE_BODY_TRUNCATE_LENGTH
? `${body.slice(0, RESPONSE_BODY_TRUNCATE_LENGTH)}… (truncated, ${body.length} chars)`
: body
}
return details
}
/**
* Debug an API request start. Logs essential info without exposing sensitive
* data.
*/
export function debugApiRequest(
method: string,
endpoint: string,
timeout?: number | undefined,
): void {
if (isDebugNs('silly')) {
const timeoutStr = timeout !== undefined ? ` (timeout: ${timeout}ms)` : ''
debugNs(
'silly',
`[${new Date().toISOString()}] request started: ${method} ${endpoint}${timeoutStr}`,
)
}
}
export interface DebugApiResponseOptions {
status?: number | undefined
// oxlint-disable-next-line typescript/no-redundant-type-constituents -- fleet optional-explicit-undefined convention: the explicit | undefined on an optional is intentional, not redundant.
error?: unknown | undefined
requestInfo?: ApiRequestDebugInfo | undefined
}
/**
* Debug an API response. Failed requests (error or status >= 400) log under the
* `error` namespace; successful responses optionally log a one-liner under
* `notice`.
*
* Request and response headers are sanitized via `sanitizeHeaders` so
* Authorization and `*api-key*` values are redacted.
*/
export function debugApiResponse(
endpoint: string,
options?: DebugApiResponseOptions | undefined,
): void {
const { error, requestInfo, status } = {
__proto__: null,
...options,
} as DebugApiResponseOptions
if (error) {
debugDirNs(
'error',
buildApiDebugDetails(
{
endpoint,
error: errorMessage(error),
},
requestInfo,
),
)
} else if (status && status >= 400) {
if (requestInfo) {
debugDirNs(
'error',
buildApiDebugDetails({ endpoint, status }, requestInfo),
)
} else {
debugNs('error', `API ${endpoint}: HTTP ${status}`)
}
/* c8 ignore start - notice-level debug ns rarely enabled in tests */
} else if (isDebugNs('notice')) {
debugNs('notice', `API ${endpoint}: ${status || 'pending'}`)
}
/* c8 ignore stop */
}
/**
* Debug configuration loading.
*/
// Collapsing into an options object would change call sites in
// src/util/config.mts and test/unit/util/debug.test.mts, which are out of
// scope for this pass.
export function debugConfig(
source: string,
// oxlint-disable-next-line socket/no-boolean-trap-param -- out of scope
found: boolean,
// Fleet optional-explicit-undefined convention: the explicit | undefined on
// an optional is intentional, not redundant.
// oxlint-disable-next-line typescript/no-redundant-type-constituents -- convention
error?: unknown | undefined,
): void {
if (error) {
debugDir({
source,
error: errorMessage(error),
})
} else if (found) {
debug(`Config loaded: ${source}`)
/* c8 ignore start - silly-level debug ns rarely enabled in tests */
} else if (isDebugNs('silly')) {
debugNs('silly', `Config not found: ${source}`)
}
/* c8 ignore stop */
}
/**
* Debug file operation. Logs file operations with appropriate level.
*/
export function debugFileOp(
operation: 'read' | 'write' | 'delete' | 'create',
filepath: string,
// Fleet optional-explicit-undefined convention: the explicit | undefined on
// an optional is intentional, not redundant.
// oxlint-disable-next-line typescript/no-redundant-type-constituents -- convention
error?: unknown | undefined,
): void {
if (error) {
debugDir({
operation,
filepath,
error: errorMessage(error),
})
/* c8 ignore start - silly-level debug ns rarely enabled in tests */
} else if (isDebugNs('silly')) {
debugNs('silly', `File ${operation}: ${filepath}`)
}
/* c8 ignore stop */
}
/**
* Debug git operations. Only logs important git operations, not every command.
*/
// Collapsing into an options object would change call sites in
// src/util/git/operations.mts and test/unit/util/debug.test.mts, which are
// out of scope for this pass.
export function debugGit(
operation: string,
// oxlint-disable-next-line socket/no-boolean-trap-param -- out of scope
success: boolean,
details?: Record<string, unknown> | undefined,
): void {
if (!success) {
debugDir({
git_op: operation,
...details,
})
} else if (
(isDebugNs('notice') && operation.includes('push')) ||
operation.includes('commit')
) {
// Only log important operations like push and commit.
debugNs('notice', `Git ${operation} succeeded`)
} else if (isDebugNs('silly')) {
debugNs('silly', `Git ${operation}`)
}
}
/**
* Sanitize headers to remove sensitive information. Redacts Authorization and
* API key headers.
*
* Callers must gate truthy — passing an empty/undefined map skips the loop.
*/
export function sanitizeHeaders(
headers: IncomingHttpHeaders,
): IncomingHttpHeaders {
const sanitized: IncomingHttpHeaders = Object.create(null)
for (const [key, value] of Object.entries(headers)) {
const lowerKey = key.toLowerCase()
if (lowerKey === 'authorization' || lowerKey.includes('api-key')) {
sanitized[key] = '[REDACTED]'
} else {
sanitized[key] = value
}
}
return sanitized
}
export { debug, debugCache, debugDir, debugDirNs, debugNs, isDebug, isDebugNs }