-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth.ts
More file actions
340 lines (319 loc) · 12.7 KB
/
auth.ts
File metadata and controls
340 lines (319 loc) · 12.7 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
import vscode from 'vscode'
import os from 'os'
import path from 'path'
import { DIAGNOSTIC_SOURCE_STR, EXTENSION_PREFIX } from './util'
import constants from '@socketsecurity/registry/lib/constants'
import https from 'node:https'
import { once } from 'node:events'
import { IncomingMessage } from 'node:http'
import { text } from 'node:stream/consumers'
import { randomUUID } from 'node:crypto'
const { SOCKET_PUBLIC_API_TOKEN } = constants
export type APIConfig = {
apiKey: string
}
type OrgInfo = {
id: string
name: string
image: string | null
plan: 'opensource' | 'team' | 'enterprise'
slug: string
}
type OrganizationsRecord = {
organizations: Record<string, OrgInfo>
}
type SettingsFile = {
apiKey?: string
[key: string]: unknown
}
async function getOrganizations(apiKey: string): Promise<OrganizationsRecord | null> {
const authHeader = getAuthHeader(apiKey)
const orgReq = https.get('https://api.socket.dev/v0/organizations', {
method: 'GET',
headers: {
Authorization: authHeader,
'Content-Type': 'application/json'
}
})
const [orgRes] = await once(orgReq, 'response') as [IncomingMessage]
if (orgRes.statusCode !== 200) {
return null
}
const orgs: OrganizationsRecord = JSON.parse(await text(orgRes))
return orgs
}
const orgSlugByApiKey = new Map<string, string>()
function getDefaultOrg(organizations: OrganizationsRecord): OrgInfo | null {
const org = Object.values(organizations.organizations)[0]
if (!org || !org.slug) {
return null
}
return org
}
export async function activate(context: vscode.ExtensionContext, disposables: Array<vscode.Disposable>) {
//#region file path/watching
// responsible for watching files to know when to sync from disk
let dataHome = process.platform === 'win32'
? process.env['LOCALAPPDATA']
: process.env['XDG_DATA_HOME']
if (!dataHome) {
if (process.platform === 'win32') throw new Error('missing %LOCALAPPDATA%')
const home = os.homedir()
dataHome = path.join(home, ...(process.platform === 'darwin'
? ['Library', 'Application Support']
: ['.local', 'share']
))
}
let pleaseLoginStatusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100)
pleaseLoginStatusBar.hide()
pleaseLoginStatusBar.text = `$(warning) Socket Security: Login`
pleaseLoginStatusBar.tooltip = 'Socket Security needs to login for full functionality'
pleaseLoginStatusBar.command = `${EXTENSION_PREFIX}.login`
let defaultSettingsPath = path.join(dataHome, 'socket', 'settings')
let settingsPath = vscode.workspace.getConfiguration(EXTENSION_PREFIX)
.get('settingsFile', defaultSettingsPath)
//#endregion
//#region session sync
// responsible for keeping disk an mem in sync
let liveSessions: Map<vscode.AuthenticationSession['accessToken'], vscode.AuthenticationSession> = new Map()
const diskSessionsChanges = new vscode.EventEmitter<vscode.AuthenticationProviderAuthenticationSessionsChangeEvent>()
const watcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(
path.dirname(settingsPath),
path.basename(settingsPath)
)
)
disposables?.push(
watcher,
watcher.onDidChange(() => syncLiveSessionFromDisk()),
watcher.onDidCreate(() => syncLiveSessionFromDisk()),
watcher.onDidDelete(() => { syncLiveSessionFromDisk() })
)
async function readExistingSettings(): Promise<SettingsFile> {
try {
const existingContent = await vscode.workspace.fs.readFile(vscode.Uri.file(settingsPath))
const decoded = Buffer.from(new TextDecoder().decode(existingContent), 'base64').toString('utf8')
const parsed = JSON.parse(decoded)
if (parsed && typeof parsed === 'object' && parsed !== null) {
return parsed
}
} catch {
// File doesn't exist or is invalid
}
return {}
}
async function syncLiveSessionFromDisk() {
let settings_on_disk: {apiKey?: string | null} = {
apiKey: null
}
try {
let fromDisk = JSON.parse(Buffer.from(
new TextDecoder().decode(await vscode.workspace.fs.readFile(vscode.Uri.file(settingsPath))),
'base64'
).toString('utf8'))
if (fromDisk && typeof fromDisk === 'object' && fromDisk !== null) {
settings_on_disk = fromDisk
}
} catch {}
const {
apiKey
} = settings_on_disk
const sessionOnDisk: typeof liveSessions = new Map<vscode.AuthenticationSession['accessToken'], vscode.AuthenticationSession>()
if (typeof apiKey === 'string' && apiKey.length > 0 && apiKey !== SOCKET_PUBLIC_API_TOKEN) {
const organizations = await getOrganizations(apiKey)
const defaultOrg = organizations ? getDefaultOrg(organizations) : null
if (defaultOrg) {
sessionOnDisk.set(
apiKey,
sessionFromAPIKey(apiKey, defaultOrg)
)
orgSlugByApiKey.set(apiKey, defaultOrg.slug)
}
}
let added: Array<vscode.AuthenticationSession> = []
let changed: Array<vscode.AuthenticationSession> = []
let removed: Array<vscode.AuthenticationSession> = []
for (const diskSession of sessionOnDisk.values()) {
// already have this access token in mem session
// remove from live sessions that haven't been sorted
if (liveSessions.has(diskSession.accessToken)) {
liveSessions.delete(diskSession.accessToken)
} else {
added.push(diskSession)
}
}
for (const liveSessionWithoutDiskSession of liveSessions.values()) {
removed.push(liveSessionWithoutDiskSession)
}
liveSessions = sessionOnDisk
if (added.length + changed.length + removed.length > 0) {
diskSessionsChanges.fire({
added,
changed,
removed
})
}
}
async function syncLiveSessionToDisk(session: vscode.AuthenticationSession) {
if (!session || !session.accessToken || session.accessToken === SOCKET_PUBLIC_API_TOKEN) {
return
}
// Read existing settings to preserve other fields (merge approach)
const existingSettings = await readExistingSettings()
// Merge new apiKey into existing settings
existingSettings.apiKey = session.accessToken
const contents = Buffer.from(JSON.stringify(existingSettings)).toString('base64')
return vscode.workspace.fs.writeFile(vscode.Uri.file(settingsPath), new TextEncoder().encode(contents))
}
//#endregion
//#region service glue
const service = vscode.authentication.registerAuthenticationProvider(`${EXTENSION_PREFIX}`, `${DIAGNOSTIC_SOURCE_STR}`, {
onDidChangeSessions(fn) {
return diskSessionsChanges.event(fn);
},
async getSessions(scopes: readonly string[] | undefined, options: vscode.AuthenticationProviderSessionOptions): Promise<vscode.AuthenticationSession[]> {
return Array.from(liveSessions.values())
},
async createSession(scopes: readonly string[], options: vscode.AuthenticationProviderSessionOptions): Promise<vscode.AuthenticationSession> {
let organizations: OrganizationsRecord | null = null
let defaultOrg: OrgInfo | null = null
let apiKey: string = await vscode.window.showInputBox({
title: 'Socket Security API Token',
placeHolder: 'Leave this blank to stay logged out',
ignoreFocusOut: true,
prompt: 'Enter your API token from https://socket.dev/',
async validateInput(value) {
if (!value) {
return
}
organizations = await getOrganizations(value)
if (!organizations) {
return 'Invalid API key'
}
defaultOrg = getDefaultOrg(organizations)
if (!defaultOrg) {
return 'No organizations found for API key'
}
}
}) ?? ''
if (!apiKey) {
throw new Error('User did not want to provide an API key')
}
if (!organizations) {
organizations = await getOrganizations(apiKey)
}
defaultOrg = defaultOrg ?? (organizations ? getDefaultOrg(organizations) : null)
if (!defaultOrg) {
throw new Error('No organizations found for API key')
}
const session = sessionFromAPIKey(apiKey, defaultOrg)
orgSlugByApiKey.set(apiKey, defaultOrg.slug)
let oldSessions = Array.from(liveSessions.values())
await syncLiveSessionToDisk(session)
liveSessions = new Map([
[apiKey, session]
])
pleaseLoginStatusBar.hide()
diskSessionsChanges.fire({
added: [session],
changed: [],
removed: oldSessions
})
return session
},
async removeSession(sessionId: string): Promise<void> {
const session = liveSessions.get(sessionId)
try {
pleaseLoginStatusBar.show()
} catch {}
try {
// Read existing settings to preserve other fields
const existingSettings = await readExistingSettings()
// Remove only the apiKey field, preserving other settings
delete existingSettings.apiKey
// If there are other settings remaining, write them back; otherwise delete the file
if (Object.keys(existingSettings).length > 0) {
const contents = Buffer.from(JSON.stringify(existingSettings)).toString('base64')
await vscode.workspace.fs.writeFile(vscode.Uri.file(settingsPath), new TextEncoder().encode(contents))
} else {
// No other settings, safe to delete the entire file
await vscode.workspace.fs.delete(vscode.Uri.file(settingsPath))
}
} catch {}
if (session) {
orgSlugByApiKey.delete(session.accessToken)
diskSessionsChanges.fire({
added: [],
changed: [],
removed: [session]
})
}
}
})
context.subscriptions.push(service)
vscode.commands.registerCommand(`${EXTENSION_PREFIX}.login`, async () => {
let session = await vscode.authentication.getSession(`${EXTENSION_PREFIX}`, [], {
createIfNone: true,
})
})
try {
await syncLiveSessionFromDisk()
} catch {}
let session
try {
session = await vscode.authentication.getSession(`${EXTENSION_PREFIX}`, [], {
createIfNone: false
})
} catch {}
if (!session) {
pleaseLoginStatusBar.show()
}
//#endregion
return {
}
}
export async function getAPIKey() {
const session = await vscode.authentication.getSession(`${EXTENSION_PREFIX}`, [], {
createIfNone: false,
})
if (session) {
return session?.accessToken
} else {
return SOCKET_PUBLIC_API_TOKEN
}
}
export async function getOrgSlug(apiKey?: string) {
const resolvedApiKey = apiKey ?? await getAPIKey()
if (!resolvedApiKey || resolvedApiKey === SOCKET_PUBLIC_API_TOKEN) {
return null
}
const cached = orgSlugByApiKey.get(resolvedApiKey)
if (cached) {
return cached
}
const organizations = await getOrganizations(resolvedApiKey)
const defaultOrg = organizations ? getDefaultOrg(organizations) : null
if (!defaultOrg) {
return null
}
orgSlugByApiKey.set(resolvedApiKey, defaultOrg.slug)
return defaultOrg.slug
}
export function getAuthHeader(apiKey: string) {
return `Bearer ${apiKey}`
}
function sessionFromAPIKey(apiKey: string, org: OrgInfo) {
// vscode auth does weird caching based upon ids
// if we don't change the id various things stop working
// like logging in and out with same account/api token
const uniqueId = `${apiKey}-${randomUUID()}`
return{
accessToken: apiKey,
id: `${uniqueId}.session`,
account: {
id: `${apiKey}.account`,
label: `${org.name} (${org.plan})`
},
scopes: [],
}
}