-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathdebug.mts
More file actions
290 lines (277 loc) · 8.09 KB
/
debug.mts
File metadata and controls
290 lines (277 loc) · 8.09 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
279
280
281
282
283
284
285
286
287
288
289
290
/**
* 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 { UNKNOWN_ERROR } from '@socketsecurity/lib/constants/core'
import {
debug,
debugCache,
debugDir,
debugDirNs,
debugNs,
isDebug,
isDebugNs,
} from '@socketsecurity/lib/debug'
export type ApiRequestDebugInfo = {
method?: string | undefined
url?: string | undefined
headers?: Record<string, string> | undefined
durationMs?: number | undefined
// ISO-8601 timestamp of when the request was initiated. Useful when
// correlating failures with server-side logs.
requestedAt?: 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?: Record<string, string> | undefined
// Response body string; truncated by the helper to a safe length so
// logs don't balloon on megabyte payloads.
responseBody?: string | undefined
}
const RESPONSE_BODY_TRUNCATE_LENGTH = 2_000
/**
* Sanitize headers to remove sensitive information.
* Redacts Authorization and API key headers.
*/
function sanitizeHeaders(
headers?: Record<string, string> | undefined,
): Record<string, string> | undefined {
if (!headers) {
return undefined
}
const sanitized: Record<string, string> = 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
}
/**
* 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}`,
)
}
}
/**
* Build the structured debug payload shared by the error + failure-status
* branches of `debugApiResponse`. Extracted so both paths log the same
* shape.
*/
function buildApiDebugDetails(
base: Record<string, unknown>,
requestInfo?: ApiRequestDebugInfo | undefined,
): Record<string, unknown> {
if (!requestInfo) {
return base
}
const details: Record<string, unknown> = { ...base }
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 response with detailed request information.
*
* For failed requests (status >= 400 or error), logs a structured
* object with:
* - endpoint (human-readable description)
* - requestedAt (ISO timestamp, if passed)
* - method, url, durationMs
* - sanitized request headers (Authorization redacted)
* - cfRay (extracted from response headers if present)
* - sanitized response headers
* - responseBody (truncated)
*
* All request-headers are sanitized to redact Authorization and
* `*api-key*` values.
*/
export function debugApiResponse(
endpoint: string,
status?: number | undefined,
error?: unknown | undefined,
requestInfo?: ApiRequestDebugInfo | undefined,
): void {
if (error) {
debugDir(
buildApiDebugDetails(
{
endpoint,
error: error instanceof Error ? error.message : UNKNOWN_ERROR,
},
requestInfo,
),
)
} else if (status && status >= 400) {
// For failed requests, log detailed information.
if (requestInfo) {
debugDir(buildApiDebugDetails({ endpoint, status }, requestInfo))
} else {
debug(`API ${endpoint}: HTTP ${status}`)
}
/* c8 ignore next 3 */
} else if (isDebugNs('notice')) {
debugNs('notice', `API ${endpoint}: ${status || 'pending'}`)
}
}
/**
* Debug file operation.
* Logs file operations with appropriate level.
*/
export function debugFileOp(
operation: 'read' | 'write' | 'delete' | 'create',
filepath: string,
error?: unknown | undefined,
): void {
if (error) {
debugDir({
operation,
filepath,
error: error instanceof Error ? error.message : UNKNOWN_ERROR,
})
/* c8 ignore next 3 */
} else if (isDebugNs('silly')) {
debugNs('silly', `File ${operation}: ${filepath}`)
}
}
/**
* Debug package scanning.
* Provides insight into security scanning.
*/
export function debugScan(
phase: 'start' | 'progress' | 'complete' | 'error',
packageCount?: number | undefined,
details?: unknown | undefined,
): void {
switch (phase) {
case 'start':
if (packageCount) {
debug(`Scanning ${packageCount} packages`)
}
break
case 'progress':
if (isDebugNs('silly') && packageCount) {
debugNs('silly', `Scan progress: ${packageCount} packages processed`)
}
break
case 'complete':
debugNs(
'notice',
`Scan complete${packageCount ? `: ${packageCount} packages` : ''}`,
)
break
case 'error':
debugDir({
phase: 'scan_error',
details,
})
break
}
}
/**
* Debug configuration loading.
*/
export function debugConfig(
source: string,
found: boolean,
error?: unknown | undefined,
): void {
if (error) {
debugDir({
source,
error: error instanceof Error ? error.message : UNKNOWN_ERROR,
})
} else if (found) {
debug(`Config loaded: ${source}`)
/* c8 ignore next 3 */
} else if (isDebugNs('silly')) {
debugNs('silly', `Config not found: ${source}`)
}
}
/**
* Debug git operations.
* Only logs important git operations, not every command.
*/
export function debugGit(
operation: string,
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}`)
}
}
export { debug, debugCache, debugDir, debugDirNs, debugNs, isDebug, isDebugNs }