-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathapi.mts
More file actions
692 lines (632 loc) · 19.9 KB
/
api.mts
File metadata and controls
692 lines (632 loc) · 19.9 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/**
* API utilities for Socket CLI.
* Provides consistent API communication with error handling and permissions management.
*
* Key Functions:
* - getDefaultApiBaseUrl: Get configured API endpoint
* - getErrorMessageForHttpStatusCode: User-friendly HTTP error messages
* - handleApiCall: Execute Socket SDK API calls with error handling
* - handleApiCallNoSpinner: Execute API calls without UI spinner
* - queryApi: Execute raw API queries with text response
*
* Error Handling:
* - Automatic permission requirement logging for 403 errors
* - Detailed error messages for common HTTP status codes
* - Integration with debug helpers for API response logging
*
* Configuration:
* - Respects SOCKET_CLI_API_BASE_URL environment variable
* - Falls back to configured apiBaseUrl or default API_V0_URL
*/
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https'
import { messageWithCauses } from 'pony-cause'
import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug'
import { logger } from '@socketsecurity/registry/lib/logger'
import { isNonEmptyString } from '@socketsecurity/registry/lib/strings'
import { getConfigValueOrUndef } from './config.mts'
import { debugApiRequest, debugApiResponse } from './debug.mts'
import constants, {
CONFIG_KEY_API_BASE_URL,
EMPTY_VALUE,
HTTP_STATUS_BAD_REQUEST,
HTTP_STATUS_FORBIDDEN,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_UNAUTHORIZED,
} from '../constants.mts'
import { getRequirements, getRequirementsKey } from './requirements.mts'
import { getDefaultApiToken, getExtraCaCerts } from './sdk.mts'
import type { CResult } from '../types.mts'
import type { Spinner } from '@socketsecurity/registry/lib/spinner'
import type {
SocketSdkErrorResult,
SocketSdkOperations,
SocketSdkResult,
SocketSdkSuccessResult,
} from '@socketsecurity/sdk'
const MAX_REDIRECTS = 20
const NO_ERROR_MESSAGE = 'No error message returned'
// Cached HTTPS agent for extra CA certificate support in direct API calls.
let _httpsAgent: HttpsAgent | undefined
let _httpsAgentResolved = false
// Returns an HTTPS agent configured with extra CA certificates when
// SSL_CERT_FILE is set but NODE_EXTRA_CA_CERTS is not.
function getHttpsAgent(): HttpsAgent | undefined {
if (_httpsAgentResolved) {
return _httpsAgent
}
_httpsAgentResolved = true
const ca = getExtraCaCerts()
if (!ca) {
return undefined
}
_httpsAgent = new HttpsAgent({ ca })
return _httpsAgent
}
// Wrapper around fetch that supports extra CA certificates via SSL_CERT_FILE.
// Uses node:https.request with a custom agent when extra CA certs are needed,
// falling back to regular fetch() otherwise. Follows redirects like fetch().
export type ApiFetchInit = {
body?: string | undefined
headers?: Record<string, string> | undefined
method?: string | undefined
}
// Internal httpsRequest-based fetch with redirect support.
function _httpsRequestFetch(
url: string,
init: ApiFetchInit,
agent: HttpsAgent,
redirectCount: number,
): Promise<Response> {
return new Promise((resolve, reject) => {
const headers: Record<string, string> = { ...init.headers }
// Set Content-Length for request bodies to avoid chunked transfer encoding.
if (init.body) {
headers['content-length'] = String(Buffer.byteLength(init.body))
}
const req = httpsRequest(
url,
{
method: init.method || 'GET',
headers,
agent,
},
res => {
const { statusCode } = res
// Follow redirects to match fetch() behavior.
if (
statusCode &&
statusCode >= 300 &&
statusCode < 400 &&
res.headers['location']
) {
// Consume the response body to free up memory.
res.resume()
if (redirectCount >= MAX_REDIRECTS) {
reject(new Error('Maximum redirect limit reached'))
return
}
const redirectUrl = new URL(res.headers['location'], url).href
// Strip sensitive headers on cross-origin redirects to match
// fetch() behavior per the Fetch spec.
const originalOrigin = new URL(url).origin
const redirectOrigin = new URL(redirectUrl).origin
let redirectHeaders = init.headers
if (originalOrigin !== redirectOrigin && redirectHeaders) {
redirectHeaders = { ...redirectHeaders }
for (const key of Object.keys(redirectHeaders)) {
const lower = key.toLowerCase()
if (
lower === 'authorization' ||
lower === 'cookie' ||
lower === 'proxy-authorization'
) {
delete redirectHeaders[key]
}
}
}
// 307 and 308 preserve the original method and body.
const preserveMethod = statusCode === 307 || statusCode === 308
resolve(
_httpsRequestFetch(
redirectUrl,
preserveMethod
? { ...init, headers: redirectHeaders }
: { headers: redirectHeaders, method: 'GET' },
agent,
redirectCount + 1,
),
)
return
}
const chunks: Buffer[] = []
res.on('data', (chunk: Buffer) => chunks.push(chunk))
res.on('end', () => {
const body = Buffer.concat(chunks)
const responseHeaders = new Headers()
for (const [key, value] of Object.entries(res.headers)) {
if (typeof value === 'string') {
responseHeaders.set(key, value)
} else if (Array.isArray(value)) {
for (const v of value) {
responseHeaders.append(key, v)
}
}
}
resolve(
new Response(body, {
status: statusCode ?? 0,
statusText: res.statusMessage ?? '',
headers: responseHeaders,
}),
)
})
res.on('error', reject)
},
)
if (init.body) {
req.write(init.body)
}
req.on('error', reject)
req.end()
})
}
export async function apiFetch(
url: string,
init: ApiFetchInit = {},
): Promise<Response> {
const agent = getHttpsAgent()
if (!agent) {
return await fetch(url, init as globalThis.RequestInit)
}
return await _httpsRequestFetch(url, init, agent, 0)
}
export type CommandRequirements = {
permissions?: string[] | undefined
quota?: number | undefined
}
/**
* Get command requirements from requirements.json based on command path.
*/
function getCommandRequirements(
cmdPath?: string | undefined,
): CommandRequirements | undefined {
if (!cmdPath) {
return undefined
}
const requirements = getRequirements()
const key = getRequirementsKey(cmdPath)
return (requirements.api as any)[key] || undefined
}
/**
* Log required permissions for a command when encountering 403 errors.
*/
function logPermissionsFor403(cmdPath?: string | undefined): void {
const requirements = getCommandRequirements(cmdPath)
if (!requirements?.permissions?.length) {
return
}
logger.error('This command requires the following API permissions:')
for (const permission of requirements.permissions) {
logger.error(` - ${permission}`)
}
logger.error('Please ensure your API token has the required permissions.')
}
// The Socket API server that should be used for operations.
export function getDefaultApiBaseUrl(): string | undefined {
const baseUrl =
constants.ENV.SOCKET_CLI_API_BASE_URL ||
getConfigValueOrUndef(CONFIG_KEY_API_BASE_URL)
if (isNonEmptyString(baseUrl)) {
return baseUrl
}
const API_V0_URL = constants.API_V0_URL
return API_V0_URL
}
/**
* Get user-friendly error message for HTTP status codes.
*/
export async function getErrorMessageForHttpStatusCode(code: number) {
if (code === HTTP_STATUS_BAD_REQUEST) {
return 'One of the options passed might be incorrect'
}
if (code === HTTP_STATUS_UNAUTHORIZED) {
return 'Your Socket API token appears to be invalid, expired, or revoked. Please verify your token is correct and active'
}
if (code === HTTP_STATUS_FORBIDDEN) {
return 'Your Socket API token may not have the required permissions for this command or you might be trying to access (data from) an organization that is not linked to the API token you are logged in with'
}
if (code === HTTP_STATUS_NOT_FOUND) {
return 'The requested Socket API endpoint was not found (404) or there was no result for the requested parameters. If unexpected, this could be a temporary problem caused by an incident or a bug in the CLI. If the problem persists please let us know.'
}
if (code === HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return 'There was an unknown server side problem with your request. This ought to be temporary. Please let us know if this problem persists.'
}
return `Server responded with status code ${code}`
}
export type HandleApiCallOptions = {
description?: string | undefined
spinner?: Spinner | undefined
silence?: boolean | undefined
commandPath?: string | undefined
}
export type ApiCallResult<T extends SocketSdkOperations> = CResult<
SocketSdkSuccessResult<T>['data']
>
/**
* Handle Socket SDK API calls with error handling and permission logging.
*/
export async function handleApiCall<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
options?: HandleApiCallOptions | undefined,
): Promise<ApiCallResult<T>> {
const {
commandPath,
description,
silence = false,
spinner,
} = {
__proto__: null,
...options,
} as HandleApiCallOptions
if (!silence) {
if (description) {
spinner?.start(`Requesting ${description} from API...`)
} else {
spinner?.start()
}
}
let sdkResult: SocketSdkResult<T>
try {
sdkResult = await value
if (!silence) {
spinner?.stop()
}
// Only log the message if spinner is provided (silence mode passes undefined).
if (description && !silence) {
const message = `Received Socket API response (after requesting ${description}).`
if (!silence) {
if (sdkResult.success) {
logger.success(message)
} else {
logger.info(message)
}
}
}
} catch (e) {
spinner?.stop()
const socketSdkErrorResult: ApiCallResult<T> = {
ok: false,
message: 'Socket API error',
cause: messageWithCauses(e as Error),
}
// Only log the message if spinner is provided (silence mode passes undefined).
if (description && !silence) {
logger.fail(`An error was thrown while requesting ${description}`)
}
debugDir('inspect', { socketSdkErrorResult })
return socketSdkErrorResult
}
// Note: TS can't narrow down the type of result due to generics.
if (sdkResult.success === false) {
const endpoint = description || 'Socket API'
debugApiResponse('API', endpoint, sdkResult.status as number)
debugDir('inspect', { sdkResult })
const errCResult = sdkResult as SocketSdkErrorResult<T>
const errStr = errCResult.error ? String(errCResult.error).trim() : ''
const message = errStr || NO_ERROR_MESSAGE
const reason = errCResult.cause || NO_ERROR_MESSAGE
const baseCause =
reason && message !== reason ? `${message} (reason: ${reason})` : message
const cause = errCResult.url
? `${baseCause} (url: ${errCResult.url})`
: baseCause
const socketSdkErrorResult: ApiCallResult<T> = {
ok: false,
message: 'Socket API error',
cause,
data: {
code: sdkResult.status,
},
}
// Log required permissions for 403 errors when in a command context.
if (commandPath && sdkResult.status === 403) {
logPermissionsFor403(commandPath)
}
return socketSdkErrorResult
}
const socketSdkSuccessResult: ApiCallResult<T> = {
ok: true,
data: (sdkResult as SocketSdkSuccessResult<T>).data,
}
return socketSdkSuccessResult
}
export async function handleApiCallNoSpinner<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
description: string,
): Promise<CResult<SocketSdkSuccessResult<T>['data']>> {
let sdkResult: SocketSdkResult<T>
try {
sdkResult = await value
} catch (e) {
debugFn('error', `API request failed: ${description}`)
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'Socket API error'
const rawCause = errStr || NO_ERROR_MESSAGE
const cause = message !== rawCause ? rawCause : ''
return {
ok: false,
message,
...(cause ? { cause } : {}),
}
}
// Note: TS can't narrow down the type of result due to generics
if (sdkResult.success === false) {
debugFn('error', `fail: ${description} bad response`)
debugDir('inspect', { sdkResult })
const sdkErrorResult = sdkResult as SocketSdkErrorResult<T>
const errStr = sdkErrorResult.error
? String(sdkErrorResult.error).trim()
: ''
const message = errStr || NO_ERROR_MESSAGE
const reason = sdkErrorResult.cause || NO_ERROR_MESSAGE
const baseCause =
reason && message !== reason ? `${message} (reason: ${reason})` : message
const cause = sdkErrorResult.url
? `${baseCause} (url: ${sdkErrorResult.url})`
: baseCause
return {
ok: false,
message: 'Socket API error',
cause,
data: {
code: sdkResult.status,
},
}
} else {
const sdkSuccessResult = sdkResult as SocketSdkSuccessResult<T>
return {
ok: true,
data: sdkSuccessResult.data,
}
}
}
async function queryApi(path: string, apiToken: string) {
const baseUrl = getDefaultApiBaseUrl()
if (!baseUrl) {
throw new Error('Socket API base URL is not configured.')
}
const url = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`
const result = await apiFetch(url, {
method: 'GET',
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
},
})
return result
}
/**
* Query Socket API endpoint and return text response with error handling.
*/
export async function queryApiSafeText(
path: string,
description?: string | undefined,
commandPath?: string | undefined,
): Promise<CResult<string>> {
const apiToken = getDefaultApiToken()
if (!apiToken) {
return {
ok: false,
message: 'Authentication Error',
cause:
'User must be authenticated to run this command. Run `socket login` and enter your Socket API token.',
}
}
const { spinner } = constants
if (description) {
spinner.start(`Requesting ${description} from API...`)
debugApiRequest('GET', path, constants.ENV.SOCKET_CLI_API_TIMEOUT)
}
let result
const startTime = Date.now()
try {
result = await queryApi(path, apiToken)
const duration = Date.now() - startTime
debugApiResponse(
'GET',
path,
result.status,
undefined,
duration,
Object.fromEntries(result.headers.entries()),
)
if (description) {
spinner.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
} catch (e) {
const duration = Date.now() - startTime
if (description) {
spinner.failAndStop(
`An error was thrown while requesting ${description}.`,
)
debugApiResponse('GET', path, undefined, e, duration)
}
debugFn('error', 'Query API request failed')
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'API request failed'
const rawCause = errStr || NO_ERROR_MESSAGE
const baseCause = message !== rawCause ? rawCause : ''
const cause = baseCause ? `${baseCause} (path: ${path})` : `(path: ${path})`
return {
ok: false,
message,
cause,
}
}
if (!result.ok) {
const { status } = result
// Log required permissions for 403 errors when in a command context.
if (commandPath && status === 403) {
logPermissionsFor403(commandPath)
}
return {
ok: false,
message: 'Socket API error',
cause: `${result.statusText} (reason: ${await getErrorMessageForHttpStatusCode(status)}) (path: ${path})`,
data: {
code: status,
},
}
}
try {
const data = await result.text()
return {
ok: true,
data,
}
} catch (e) {
debugFn('error', 'Failed to read API response text')
debugDir('error', e)
return {
ok: false,
message: 'API request failed',
cause: `Unexpected error reading response text (path: ${path})`,
}
}
}
/**
* Query Socket API endpoint and return parsed JSON response.
*/
export async function queryApiSafeJson<T>(
path: string,
description = '',
): Promise<CResult<T>> {
const result = await queryApiSafeText(path, description)
if (!result.ok) {
return result
}
try {
return {
ok: true,
data: JSON.parse(result.data) as T,
}
} catch (e) {
return {
ok: false,
message: 'Server returned invalid JSON',
cause: `Please report this. JSON.parse threw an error over the following response: \`${(result.data?.slice?.(0, 100) || EMPTY_VALUE).trim() + (result.data?.length > 100 ? '...' : '')}\``,
}
}
}
export type SendApiRequestOptions = {
method: 'POST' | 'PUT'
body?: unknown | undefined
description?: string | undefined
commandPath?: string | undefined
}
/**
* Send POST/PUT request to Socket API with JSON response handling.
*/
export async function sendApiRequest<T>(
path: string,
options?: SendApiRequestOptions | undefined,
): Promise<CResult<T>> {
const apiToken = getDefaultApiToken()
if (!apiToken) {
return {
ok: false,
message: 'Authentication Error',
cause:
'User must be authenticated to run this command. To log in, run the command `socket login` and enter your Socket API token.',
}
}
const baseUrl = getDefaultApiBaseUrl()
if (!baseUrl) {
return {
ok: false,
message: 'Configuration Error',
cause:
'Socket API endpoint is not configured. Please check your environment configuration.',
}
}
const { body, commandPath, description, method } = {
__proto__: null,
...options,
} as SendApiRequestOptions
const { spinner } = constants
if (description) {
spinner.start(`Requesting ${description} from API...`)
}
let result
try {
const fetchOptions = {
method,
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
'Content-Type': 'application/json',
},
...(body ? { body: JSON.stringify(body) } : {}),
}
result = await apiFetch(
`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`,
fetchOptions,
)
if (description) {
spinner.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
} catch (e) {
if (description) {
spinner.failAndStop(
`An error was thrown while requesting ${description}.`,
)
}
debugFn('error', `API ${method} request failed`)
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'API request failed'
const rawCause = errStr || NO_ERROR_MESSAGE
const baseCause = message !== rawCause ? rawCause : ''
const cause = baseCause ? `${baseCause} (path: ${path})` : `(path: ${path})`
return {
ok: false,
message,
cause,
}
}
if (!result.ok) {
const { status } = result
// Log required permissions for 403 errors when in a command context.
if (commandPath && status === 403) {
logPermissionsFor403(commandPath)
}
return {
ok: false,
message: 'Socket API error',
cause: `${result.statusText} (reason: ${await getErrorMessageForHttpStatusCode(status)}) (path: ${path})`,
data: {
code: status,
},
}
}
try {
const data = await result.json()
return {
ok: true,
data: data as T,
}
} catch (e) {
debugFn('error', 'Failed to parse API response JSON')
debugDir('error', e)
return {
ok: false,
message: 'API request failed',
cause: `Unexpected error parsing response JSON (path: ${path})`,
}
}
}