-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathapi.mts
More file actions
708 lines (645 loc) · 20.5 KB
/
api.mts
File metadata and controls
708 lines (645 loc) · 20.5 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/**
* 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 { messageWithCauses } from 'pony-cause'
import { debug, debugDir } from '@socketsecurity/lib/debug'
import { getSocketCliApiBaseUrl } from '@socketsecurity/lib/env/socket-cli'
import { httpRequest } from '@socketsecurity/lib/http-request'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
import { isNonEmptyString } from '@socketsecurity/lib/strings'
import { getDefaultApiToken, getExtraCaCerts } from './sdk.mts'
import type { HttpRequestOptions, HttpResponse } from '@socketsecurity/lib/http-request'
import { CONFIG_KEY_API_BASE_URL } from '../../constants/config.mts'
import {
HTTP_STATUS_BAD_REQUEST,
HTTP_STATUS_FORBIDDEN,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_TOO_MANY_REQUESTS,
HTTP_STATUS_UNAUTHORIZED,
} from '../../constants/http.mts'
import {
API_V0_URL,
SOCKET_CLI_ISSUES_URL,
SOCKET_PRICING_URL,
SOCKET_SETTINGS_API_TOKENS_URL,
SOCKET_STATUS_URL,
} from '../../constants/socket.mts'
import { getConfigValueOrUndef } from '../config.mts'
import { debugApiResponse } from '../debug.mts'
import {
getRequirements,
getRequirementsKey,
} from '../ecosystem/requirements.mts'
import {
buildErrorCause,
getNetworkErrorDiagnostics,
} from '../error/errors.mts'
import type { CResult } from '../../types.mts'
import type { Spinner } from '@socketsecurity/lib/spinner'
import type {
SocketSdkErrorResult,
SocketSdkOperations,
SocketSdkSuccessResult,
} from '@socketsecurity/sdk'
const logger = getDefaultLogger()
const NO_ERROR_MESSAGE = 'No error message returned'
// Wraps httpRequest with extra CA certificates from SSL_CERT_FILE.
export async function socketHttpRequest(
url: string,
options?: HttpRequestOptions | undefined,
): Promise<HttpResponse> {
const ca = getExtraCaCerts()
if (ca) {
return await httpRequest(url, { ...(options ?? {}), ca })
}
return await httpRequest(url, options)
}
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 with actionable guidance.
*
* @param cmdPath - Command path to look up requirements for (e.g., "socket fix", "socket scan:create")
*/
export function logPermissionsFor403(cmdPath?: string | undefined): void {
const requirements = getCommandRequirements(cmdPath)
logger.error('')
if (requirements?.permissions?.length) {
logger.group('🔐 Required API Permissions:')
for (const permission of requirements.permissions) {
logger.error(permission)
}
logger.groupEnd()
logger.error('')
logger.group('💡 To fix this:')
logger.error(`Visit ${SOCKET_SETTINGS_API_TOKENS_URL}`)
logger.error('Edit your API token to grant the permissions listed above')
logger.error('Re-run your command')
logger.groupEnd()
} else {
// No specific permissions found, provide general guidance.
logger.group('🔐 Permission Requirements:')
logger.error(
'Your API token lacks the required permissions for this operation.',
)
logger.groupEnd()
logger.error('')
logger.group('💡 To fix this:')
logger.error(`Visit ${SOCKET_SETTINGS_API_TOKENS_URL}`)
logger.error('Check your API token has the necessary permissions')
logger.error(
`Run \`socket ${cmdPath?.replace(/^socket[: ]/, '') || 'help'} --help\` to see required permissions`,
)
logger.error('Re-run your command after updating permissions')
logger.groupEnd()
}
logger.error('')
}
// The Socket API server that should be used for operations.
export function getDefaultApiBaseUrl(): string | undefined {
const baseUrl =
getSocketCliApiBaseUrl() || getConfigValueOrUndef(CONFIG_KEY_API_BASE_URL)
if (isNonEmptyString(baseUrl)) {
return baseUrl
}
return API_V0_URL
}
/**
* Get user-friendly error message for HTTP status codes with actionable guidance.
*/
export async function getErrorMessageForHttpStatusCode(code: number) {
if (code === HTTP_STATUS_BAD_REQUEST) {
return (
'❌ Invalid request: One of the options or parameters may be incorrect.\n' +
'💡 Try: Check your command syntax and parameter values.'
)
}
if (code === HTTP_STATUS_UNAUTHORIZED) {
return (
'❌ Authentication failed: Your Socket API token appears to be invalid, expired, or revoked.\n' +
'💡 Try:\n' +
' • Run `socket whoami` to verify your current token\n' +
' • Run `socket login` to re-authenticate\n' +
` • Manage tokens at ${SOCKET_SETTINGS_API_TOKENS_URL}`
)
}
if (code === HTTP_STATUS_FORBIDDEN) {
return (
'❌ Access denied: Your API token lacks required permissions or organization access.\n' +
'💡 Try:\n' +
' • Run `socket whoami` to verify your account and organization\n' +
` • Check your API token permissions at ${SOCKET_SETTINGS_API_TOKENS_URL}\n` +
" • Ensure you're accessing the correct organization with `--org` flag\n" +
` • Verify your plan includes this feature at ${SOCKET_PRICING_URL}`
)
}
if (code === HTTP_STATUS_NOT_FOUND) {
return (
"❌ Not found: The requested endpoint or resource doesn't exist.\n" +
'💡 Try:\n' +
' • Verify resource names (package, repository, organization)\n' +
' • Check if the resource was deleted or moved\n' +
' • Update to the latest CLI version: `socket self-update` (SEA) or `npm update -g socket`\n' +
` • Report persistent issues at ${SOCKET_CLI_ISSUES_URL}`
)
}
if (code === HTTP_STATUS_TOO_MANY_REQUESTS) {
return (
'❌ Rate limit exceeded: Too many API requests.\n' +
'💡 Try:\n' +
` • Free plan: Wait a few minutes for quota reset or upgrade at ${SOCKET_PRICING_URL}\n` +
' • Paid plan: Contact support if rate limits seem incorrect\n' +
' • Check current quota: `socket organization quota`\n' +
' • Reduce request frequency or batch operations'
)
}
if (code === HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return (
'❌ Server error: Socket API encountered an internal problem (HTTP 500).\n' +
'💡 Try:\n' +
' • Wait a few minutes and retry your command\n' +
` • Check Socket status: ${SOCKET_STATUS_URL}\n` +
` • Report persistent issues: ${SOCKET_CLI_ISSUES_URL}`
)
}
return (
`❌ HTTP ${code}: Server responded with unexpected status code.\n` +
`💡 Try: Check Socket status at ${SOCKET_STATUS_URL} or report the issue.`
)
}
export type HandleApiCallOptions = {
description?: string | undefined
spinner?: Spinner | 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<any>,
options?: HandleApiCallOptions | undefined,
): Promise<ApiCallResult<T>> {
const { commandPath, description, spinner } = {
__proto__: null,
...options,
} as HandleApiCallOptions
if (description) {
spinner?.start(`Requesting ${description} from API...`)
} else {
spinner?.start()
}
let sdkResult: any
try {
sdkResult = await value
spinner?.stop()
// Only log success messages if a spinner was provided (opt-in to output).
if (description && spinner) {
const message = `Received Socket API response (after requesting ${description}).`
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),
}
if (description) {
logger.fail(`An error was thrown while requesting ${description}`)
debugApiResponse(description, undefined, e)
} else {
debugApiResponse('Socket API', undefined, e)
}
debugDir({ 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(endpoint, sdkResult.status as number)
debugDir({ 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 cause = await buildErrorCause(
sdkResult.status as number,
message,
reason,
)
const causeWithEndpoint = description
? `${cause} (endpoint: ${description})`
: cause
const socketSdkErrorResult: ApiCallResult<T> = {
ok: false,
message: 'Socket API error',
cause: causeWithEndpoint,
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<any>,
description: string,
): Promise<CResult<SocketSdkSuccessResult<T>['data']>> {
let sdkResult: any
try {
sdkResult = await value
} catch (e) {
debug(`API request failed: ${description}`)
debugDir(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) {
debug(`fail: ${description} bad response`)
debugDir({ 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 cause = await buildErrorCause(
sdkResult.status as number,
message,
reason,
)
const causeWithEndpoint = description
? `${cause} (endpoint: ${description})`
: cause
return {
ok: false,
message: 'Socket API error',
cause: causeWithEndpoint,
data: {
code: sdkResult.status,
},
}
}
const sdkSuccessResult = sdkResult as SocketSdkSuccessResult<T>
return {
ok: true,
data: sdkSuccessResult.data,
}
}
export async function queryApi(path: string, apiToken: string) {
const baseUrl = getDefaultApiBaseUrl()
if (!baseUrl) {
throw new Error('Socket API base URL is not configured.')
}
return await socketHttpRequest(
`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`,
{
method: 'GET',
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
},
timeout: 30_000,
},
)
}
/**
* 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 = getDefaultSpinner()
if (description) {
spinner?.start(`Requesting ${description} from API...`)
}
const baseUrl = getDefaultApiBaseUrl()
const fullUrl = `${baseUrl}${baseUrl?.endsWith('/') ? '' : '/'}${path}`
const startTime = Date.now()
const requestedAt = new Date(startTime).toISOString()
let result: any
try {
result = await queryApi(path, apiToken)
const durationMs = Date.now() - startTime
if (description) {
spinner?.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
// Log success for debugging.
debugApiResponse(description || 'Query API', result.status, undefined, {
method: 'GET',
url: fullUrl,
durationMs,
requestedAt,
headers: { Authorization: '[REDACTED]' },
})
} catch (e) {
const durationMs = Date.now() - startTime
if (description) {
spinner?.failAndStop(
`An error was thrown while requesting ${description}.`,
)
}
debug('Query API request failed')
debugApiResponse(description || 'Query API', undefined, e, {
method: 'GET',
url: fullUrl,
durationMs,
requestedAt,
headers: { Authorization: '[REDACTED]' },
})
// Provide detailed network diagnostics for fetch errors.
const networkDiagnostics = getNetworkErrorDiagnostics(e, durationMs)
const message = 'API request failed'
return {
ok: false,
message,
cause: `${networkDiagnostics} (path: ${path})`,
}
}
if (!result.ok) {
const { status } = result
const durationMs = Date.now() - startTime
// Log detailed error information — include response headers (for
// cf-ray) and a truncated body so support tickets have everything
// needed to file against Cloudflare or backend teams.
debugApiResponse(description || 'Query API', status, undefined, {
method: 'GET',
url: fullUrl,
durationMs,
requestedAt,
headers: { Authorization: '[REDACTED]' },
responseHeaders: result.headers,
responseBody: result.text?.(),
})
// 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 = result.text()
return {
ok: true,
data,
}
} catch (e) {
debug('Failed to read API response text')
debugDir(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) || '').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 = getDefaultSpinner()
if (description) {
spinner?.start(`Requesting ${description} from API...`)
}
const fullUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`
const startTime = Date.now()
const requestedAt = new Date(startTime).toISOString()
let result: any
try {
result = await socketHttpRequest(fullUrl, {
body: body ? JSON.stringify(body) : undefined,
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
'Content-Type': 'application/json',
},
method,
timeout: 60_000,
})
const durationMs = Date.now() - startTime
if (description) {
spinner?.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
// Log success for debugging.
debugApiResponse(
description || 'Send API Request',
result.status,
undefined,
{
method,
url: fullUrl,
durationMs,
requestedAt,
headers: {
Authorization: '[REDACTED]',
'Content-Type': 'application/json',
},
},
)
} catch (e) {
const durationMs = Date.now() - startTime
if (description) {
spinner?.failAndStop(
`An error was thrown while requesting ${description}.`,
)
}
debug(`API ${method} request failed`)
debugApiResponse(description || 'Send API Request', undefined, e, {
method,
url: fullUrl,
durationMs,
requestedAt,
headers: {
Authorization: '[REDACTED]',
'Content-Type': 'application/json',
},
})
// Provide detailed network diagnostics for fetch errors.
const networkDiagnostics = getNetworkErrorDiagnostics(e, durationMs)
const message = 'API request failed'
return {
ok: false,
message,
cause: `${networkDiagnostics} (path: ${path})`,
}
}
if (!result.ok) {
const { status } = result
const durationMs = Date.now() - startTime
// Log detailed error information — include response headers (for
// cf-ray) and a truncated body so support tickets have everything
// needed to file against Cloudflare or backend teams.
debugApiResponse(description || 'Send API Request', status, undefined, {
method,
url: fullUrl,
durationMs,
requestedAt,
headers: {
Authorization: '[REDACTED]',
'Content-Type': 'application/json',
},
responseHeaders: result.headers,
responseBody: result.text?.(),
})
// 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 = result.json()
return {
ok: true,
data: data as T,
}
} catch (e) {
debug('Failed to parse API response JSON')
debugDir(e)
return {
ok: false,
message: 'API request failed',
cause: `Unexpected error parsing response JSON (path: ${path})`,
}
}
}