-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathapi.mts
More file actions
387 lines (343 loc) · 10.5 KB
/
api.mts
File metadata and controls
387 lines (343 loc) · 10.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
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 constants from '../constants.mts'
import { getDefaultToken } 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 NO_ERROR_MESSAGE = 'No error message returned'
export type HandleApiCallOptions = {
desc?: string | undefined
spinner?: Spinner | undefined
}
export async function handleApiCall<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
options?: HandleApiCallOptions | undefined,
): Promise<CResult<SocketSdkSuccessResult<T>['data']>> {
const { desc, spinner } = {
__proto__: null,
...options,
} as HandleApiCallOptions
if (desc) {
spinner?.start(`Requesting ${desc} from API...`)
} else {
spinner?.start()
}
let sdkResult: SocketSdkResult<T>
try {
sdkResult = await value
spinner?.stop()
if (desc) {
const message = `Received Socket API response (after requesting ${desc}).`
if (sdkResult.success) {
logger.success(message)
} else {
logger.info(message)
}
}
} catch (e) {
spinner?.stop()
if (desc) {
logger.fail(`An error was thrown while requesting ${desc}`)
debugFn('error', `caught: ${desc} error`)
} else {
debugFn('error', `caught: Socket API request error`)
}
debugDir('inspect', { error: e })
return {
ok: false,
message: 'Socket API returned an error',
cause: messageWithCauses(e as Error),
}
}
// Note: TS can't narrow down the type of result due to generics.
if (sdkResult.success === false) {
const errorResult = sdkResult as SocketSdkErrorResult<T>
const message = `${errorResult.error || NO_ERROR_MESSAGE}`
const { cause: reason } = errorResult
if (desc) {
debugFn('error', `fail: ${desc} bad response`)
} else {
debugFn('error', 'fail: bad response')
}
debugDir('inspect', { sdkResult })
return {
ok: false,
message: 'Socket API returned an error',
cause: `${message}${reason ? ` ( Reason: ${reason} )` : ''}`,
data: {
code: sdkResult.status,
},
}
} else {
const { data } = sdkResult as SocketSdkSuccessResult<T>
return {
ok: true,
data,
}
}
}
export async function handleApiCallNoSpinner<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
description: string,
): Promise<CResult<SocketSdkSuccessResult<T>['data']>> {
let result: SocketSdkResult<T>
try {
result = await value
} catch (e) {
const message = `${e || NO_ERROR_MESSAGE}`
const reason = `${e || NO_ERROR_MESSAGE}`
debugFn('error', `caught: ${description} error`)
debugDir('inspect', { error: e })
return {
ok: false,
message: 'Socket API returned an error',
cause: `${message}${reason ? ` ( Reason: ${reason} )` : ''}`,
}
}
// Note: TS can't narrow down the type of result due to generics
if (result.success === false) {
const error = result as SocketSdkErrorResult<T>
const message = `${error.error || NO_ERROR_MESSAGE}`
debugFn('error', `fail: ${description} bad response`)
debugDir('inspect', { error })
return {
ok: false,
message: 'Socket API returned an error',
cause: `${message}${error.cause ? ` ( Reason: ${error.cause} )` : ''}`,
data: {
code: result.status,
},
}
} else {
const ok = result as SocketSdkSuccessResult<T>
return {
ok: true,
data: ok.data,
}
}
}
export async function getErrorMessageForHttpStatusCode(code: number) {
if (code === 400) {
return 'One of the options passed might be incorrect'
}
if (code === 403 || code === 401) {
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 === 404) {
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 === 500) {
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}`
}
// The Socket API server that should be used for operations.
export function getDefaultApiBaseUrl(): string | undefined {
const baseUrl =
// Lazily access constants.ENV.SOCKET_CLI_API_BASE_URL.
constants.ENV.SOCKET_CLI_API_BASE_URL || getConfigValueOrUndef('apiBaseUrl')
if (isNonEmptyString(baseUrl)) {
return baseUrl
}
// Lazily access constants.API_V0_URL.
const API_V0_URL = constants.API_V0_URL
return API_V0_URL
}
export async function queryApi(path: string, apiToken: string) {
const baseUrl = getDefaultApiBaseUrl() || ''
if (!baseUrl) {
logger.warn(
'API endpoint is not set and default was empty. Request is likely to fail.',
)
}
return await fetch(`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`, {
method: 'GET',
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
},
})
}
export async function queryApiSafeText(
path: string,
fetchSpinnerDesc?: string,
): Promise<CResult<string>> {
const apiToken = getDefaultToken()
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.',
}
}
// Lazily access constants.spinner.
const { spinner } = constants
if (fetchSpinnerDesc) {
spinner.start(`Requesting ${fetchSpinnerDesc} from API...`)
}
let result
try {
result = await queryApi(path, apiToken)
if (fetchSpinnerDesc) {
spinner.successAndStop(
`Received Socket API response (after requesting ${fetchSpinnerDesc}).`,
)
}
} catch (e) {
if (fetchSpinnerDesc) {
spinner.failAndStop(
`An error was thrown while requesting ${fetchSpinnerDesc}.`,
)
}
const cause = (e as undefined | { message: string })?.message
debugFn('error', 'caught: await queryApi() error')
debugDir('inspect', { error: e })
return {
ok: false,
message: 'API Request failed to complete',
...(cause ? { cause } : {}),
}
}
if (!result.ok) {
const cause = await getErrorMessageForHttpStatusCode(result.status)
return {
ok: false,
message: 'Socket API returned an error',
cause: `${result.statusText}${cause ? ` (cause: ${cause})` : ''}`,
}
}
try {
const data = await result.text()
return {
ok: true,
data,
}
} catch (e) {
debugFn('error', 'caught: await result.text() error')
debugDir('inspect', { error: e })
return {
ok: false,
message: 'API Request failed to complete',
cause: 'There was an unexpected error trying to read the response text',
}
}
}
export async function queryApiSafeJson<T>(
path: string,
fetchSpinnerDesc = '',
): Promise<CResult<T>> {
const result = await queryApiSafeText(path, fetchSpinnerDesc)
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>').trim() + (result.data?.length > 100 ? '...' : '')}\``,
}
}
}
export async function sendApiRequest<T>(
path: string,
options: {
method: 'POST' | 'PUT'
body?: unknown
fetchSpinnerDesc?: string
},
): Promise<CResult<T>> {
const apiToken = getDefaultToken()
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) {
logger.warn(
'API endpoint is not set and default was empty. Request is likely to fail.',
)
}
// Lazily access constants.spinner.
const { spinner } = constants
if (options.fetchSpinnerDesc) {
spinner.start(`Requesting ${options.fetchSpinnerDesc} from API...`)
}
let result
try {
const fetchOptions = {
method: options.method,
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
'Content-Type': 'application/json',
},
...(options.body ? { body: JSON.stringify(options.body) } : {}),
}
result = await fetch(
`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`,
fetchOptions,
)
if (options.fetchSpinnerDesc) {
spinner.successAndStop(
`Received Socket API response (after requesting ${options.fetchSpinnerDesc}).`,
)
}
} catch (e) {
if (options.fetchSpinnerDesc) {
spinner.failAndStop(
`An error was thrown while requesting ${options.fetchSpinnerDesc}.`,
)
}
const cause = (e as undefined | { message: string })?.message
debugFn('error', `caught: await fetch() ${options.method} error`)
debugDir('inspect', { error: e })
return {
ok: false,
message: 'API Request failed to complete',
...(cause ? { cause } : {}),
}
}
if (!result.ok) {
const cause = await getErrorMessageForHttpStatusCode(result.status)
return {
ok: false,
message: 'Socket API returned an error',
cause: `${result.statusText}${cause ? ` (cause: ${cause})` : ''}`,
data: {
code: result.status,
},
}
}
try {
const data = await result.json()
return {
ok: true,
data: data as T,
}
} catch (e) {
debugFn('error', 'caught: await result.json() error')
debugDir('inspect', { error: e })
return {
ok: false,
message: 'API Request failed to complete',
cause: 'There was an unexpected error trying to parse the response JSON',
}
}
}