-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathattempt-login.mts
More file actions
314 lines (283 loc) · 9.45 KB
/
attempt-login.mts
File metadata and controls
314 lines (283 loc) · 9.45 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
import { joinAnd } from '@socketsecurity/lib/arrays'
import { SOCKET_PUBLIC_API_TOKEN } from '@socketsecurity/lib/constants/socket'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { confirm, password, select } from '@socketsecurity/lib/stdio/prompts'
import { isNonEmptyString } from '@socketsecurity/lib/strings'
import { applyLogin } from './apply-login.mts'
import { oauthLogin } from './oauth-login.mts'
import {
CONFIG_KEY_API_BASE_URL,
CONFIG_KEY_API_PROXY,
CONFIG_KEY_API_TOKEN,
CONFIG_KEY_AUTH_BASE_URL,
CONFIG_KEY_DEFAULT_ORG,
CONFIG_KEY_OAUTH_CLIENT_ID,
CONFIG_KEY_OAUTH_REDIRECT_URI,
CONFIG_KEY_OAUTH_SCOPES,
} from '../../constants/config.mts'
import ENV from '../../constants/env.mts'
import {
getConfigValueOrUndef,
isConfigFromFlag,
updateConfigValue,
} from '../../utils/config.mts'
import { deriveAuthBaseUrlFromApiBaseUrl } from '../../utils/auth/oauth.mts'
import { failMsgWithBadge } from '../../utils/error/fail-msg-with-badge.mts'
import { getEnterpriseOrgs, getOrgSlugs } from '../../utils/organization.mts'
import { setupSdk } from '../../utils/socket/sdk.mjs'
import { socketDocsLink } from '../../utils/terminal/link.mts'
import { setupTabCompletion } from '../install/setup-tab-completion.mts'
import { fetchOrganization } from '../organization/fetch-organization-list.mts'
import type { Choice } from '@socketsecurity/lib/stdio/prompts'
import requirements from '../../../data/command-api-requirements.json' with {
type: 'json',
}
const logger = getDefaultLogger()
type OrgChoice = Choice<string>
type OrgChoices = OrgChoice[]
type LoginMethod = 'oauth' | 'token'
function getDefaultOAuthScopes(): string[] {
const permissions: string[] = []
const api = (requirements as any)?.api ?? {}
for (const value of Object.values(api) as any[]) {
const perms = (value?.permissions ?? []) as unknown
if (Array.isArray(perms)) {
for (const p of perms) {
if (typeof p === 'string' && p) {
permissions.push(p)
}
}
}
}
return [...new Set(permissions)].sort()
}
function parseScopes(value: unknown): string[] | undefined {
if (Array.isArray(value)) {
return value
.filter((v): v is string => typeof v === 'string' && v.length > 0)
.sort()
}
if (!isNonEmptyString(String(value ?? ''))) {
return undefined
}
const raw = String(value)
return raw
.split(/[,\s]+/u)
.map(s => s.trim())
.filter(Boolean)
}
export async function attemptLogin(
apiBaseUrl: string | undefined,
apiProxy: string | undefined,
options?: {
method?: LoginMethod | undefined
authBaseUrl?: string | undefined
oauthClientId?: string | undefined
oauthRedirectUri?: string | undefined
oauthScopes?: string | undefined
},
) {
apiBaseUrl ??= getConfigValueOrUndef(CONFIG_KEY_API_BASE_URL) ?? undefined
apiProxy ??= getConfigValueOrUndef(CONFIG_KEY_API_PROXY) ?? undefined
const method: LoginMethod = options?.method ?? 'oauth'
let apiToken: string
let oauthRefreshToken: string | null | undefined
let oauthTokenExpiresAt: number | null | undefined
let authBaseUrl: string | null | undefined
let oauthClientId: string | null | undefined
let oauthRedirectUri: string | null | undefined
let oauthScopes: string[] | null | undefined
if (method === 'token') {
const apiTokenInput = await password({
message: `Enter your ${socketDocsLink('/docs/api-keys', 'Socket.dev API token')} (leave blank to use a limited public token)`,
})
if (apiTokenInput === undefined) {
logger.fail('Canceled by user')
return { ok: false, message: 'Canceled', cause: 'Canceled by user' }
}
apiToken = apiTokenInput || SOCKET_PUBLIC_API_TOKEN
// Explicitly disable OAuth refresh flow when using a legacy org-wide token.
oauthRefreshToken = null
oauthTokenExpiresAt = null
authBaseUrl = null
oauthClientId = null
oauthRedirectUri = null
oauthScopes = null
} else {
const resolvedAuthBaseUrl =
options?.authBaseUrl ||
ENV.SOCKET_CLI_AUTH_BASE_URL ||
getConfigValueOrUndef(CONFIG_KEY_AUTH_BASE_URL) ||
deriveAuthBaseUrlFromApiBaseUrl(apiBaseUrl)
if (!isNonEmptyString(resolvedAuthBaseUrl)) {
process.exitCode = 1
logger.fail(
'OAuth auth base URL is not configured. Provide --auth-base-url or set SOCKET_CLI_AUTH_BASE_URL.',
)
return
}
const resolvedClientId =
options?.oauthClientId ||
ENV.SOCKET_CLI_OAUTH_CLIENT_ID ||
getConfigValueOrUndef(CONFIG_KEY_OAUTH_CLIENT_ID) ||
'socket-cli'
const resolvedRedirectUri =
options?.oauthRedirectUri ||
ENV.SOCKET_CLI_OAUTH_REDIRECT_URI ||
getConfigValueOrUndef(CONFIG_KEY_OAUTH_REDIRECT_URI) ||
'http://127.0.0.1:53682/callback'
const resolvedScopes =
parseScopes(
options?.oauthScopes ||
ENV.SOCKET_CLI_OAUTH_SCOPES ||
getConfigValueOrUndef(CONFIG_KEY_OAUTH_SCOPES) ||
getDefaultOAuthScopes(),
) ?? []
logger.log(
`Opening your browser to complete login (client_id: ${resolvedClientId})...`,
)
const oauthResult = await oauthLogin({
authBaseUrl: resolvedAuthBaseUrl,
clientId: resolvedClientId,
redirectUri: resolvedRedirectUri,
scopes: resolvedScopes,
apiProxy,
})
if (!oauthResult.ok) {
process.exitCode = 1
logger.fail(failMsgWithBadge(oauthResult.message, oauthResult.cause))
return
}
apiToken = oauthResult.data.accessToken
oauthRefreshToken = oauthResult.data.refreshToken
oauthTokenExpiresAt = oauthResult.data.expiresAt
authBaseUrl = resolvedAuthBaseUrl
oauthClientId = resolvedClientId
oauthRedirectUri = resolvedRedirectUri
oauthScopes = resolvedScopes
}
const sockSdkCResult = await setupSdk({ apiBaseUrl, apiProxy, apiToken })
if (!sockSdkCResult.ok) {
process.exitCode = 1
logger.fail(failMsgWithBadge(sockSdkCResult.message, sockSdkCResult.cause))
return
}
const sockSdk = sockSdkCResult.data
const orgsCResult = await fetchOrganization({
description: 'token verification',
sdk: sockSdk,
})
if (!orgsCResult.ok) {
process.exitCode = 1
logger.fail(failMsgWithBadge(orgsCResult.message, orgsCResult.cause))
return
}
const { organizations } = orgsCResult.data
const orgSlugs = getOrgSlugs(organizations)
logger.success(`API token verified: ${joinAnd(orgSlugs)}`)
const enterpriseOrgs = getEnterpriseOrgs(organizations)
const enforcedChoices: OrgChoices = enterpriseOrgs.map(org => ({
name: org['name'] ?? 'undefined',
value: org['id'],
}))
let enforcedOrgs: string[] = []
if (enforcedChoices.length > 1) {
const id = await select({
message:
"Which organization's policies should Socket enforce system-wide?",
choices: [
...enforcedChoices,
{
name: 'None',
value: '',
description: 'Pick "None" if this is a personal device',
},
],
})
if (id === undefined) {
logger.fail('Canceled by user')
return { ok: false, message: 'Canceled', cause: 'Canceled by user' }
}
if (id) {
enforcedOrgs = [id]
}
} else if (enforcedChoices.length) {
const shouldEnforce = await confirm({
message: `Should Socket enforce ${(enforcedChoices[0] as OrgChoice)?.name}'s security policies system-wide?`,
default: true,
})
if (shouldEnforce === undefined) {
logger.fail('Canceled by user')
return { ok: false, message: 'Canceled', cause: 'Canceled by user' }
}
if (shouldEnforce) {
const existing = enforcedChoices[0] as OrgChoice
if (existing) {
enforcedOrgs = [existing.value]
}
}
}
const wantToComplete = await select({
message: 'Would you like to install bash tab completion?',
choices: [
{
name: 'Yes',
value: true,
description:
'Sets up tab completion for "socket" in your bash env. If you\'re unsure, this is probably what you want.',
},
{
name: 'No',
value: false,
description:
'Will skip tab completion setup. Does not change how Socket works.',
},
],
})
if (wantToComplete === undefined) {
logger.fail('Canceled by user')
return { ok: false, message: 'Canceled', cause: 'Canceled by user' }
}
if (wantToComplete) {
logger.log('')
logger.log('Setting up tab completion...')
const setupCResult = await setupTabCompletion('socket')
if (setupCResult.ok) {
logger.success(
'Tab completion will be enabled after restarting your terminal',
)
} else {
logger.fail(
'Failed to install tab completion script. Try `socket install completion` later.',
)
}
}
updateConfigValue(CONFIG_KEY_DEFAULT_ORG, orgSlugs[0])
const previousPersistedToken = getConfigValueOrUndef(CONFIG_KEY_API_TOKEN)
try {
applyLogin({
apiToken,
enforcedOrgs,
apiBaseUrl,
apiProxy,
authBaseUrl,
oauthClientId,
oauthRedirectUri,
oauthRefreshToken,
oauthScopes,
oauthTokenExpiresAt,
})
logger.success(
`API credentials ${previousPersistedToken === apiToken ? 'refreshed' : previousPersistedToken ? 'updated' : 'set'}`,
)
if (isConfigFromFlag()) {
logger.log('')
logger.warn(
'Note: config is in read-only mode, at least one key was overridden through flag/env, so the login was not persisted!',
)
}
} catch {
process.exitCode = 1
logger.fail('API login failed')
}
}