Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/github-authentication/src/flows.ts
5222 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as path from 'path';
7
import { ProgressLocation, Uri, commands, env, l10n, window, workspace } from 'vscode';
8
import { Log } from './common/logger';
9
import { Config } from './config';
10
import { UriEventHandler } from './github';
11
import { fetching } from './node/fetch';
12
import { crypto } from './node/crypto';
13
import { LoopbackAuthServer } from './node/authServer';
14
import { promiseFromEvent } from './common/utils';
15
import { isHostedGitHubEnterprise } from './common/env';
16
import { NETWORK_ERROR, TIMED_OUT_ERROR, USER_CANCELLATION_ERROR } from './common/errors';
17
18
interface IGitHubDeviceCodeResponse {
19
device_code: string;
20
user_code: string;
21
verification_uri: string;
22
interval: number;
23
}
24
25
interface IFlowOptions {
26
// GitHub.com
27
readonly supportsGitHubDotCom: boolean;
28
// A GitHub Enterprise Server that is hosted by an organization
29
readonly supportsGitHubEnterpriseServer: boolean;
30
// A GitHub Enterprise Server that is hosted by GitHub for an organization
31
readonly supportsHostedGitHubEnterprise: boolean;
32
33
// Runtimes - there are constraints on which runtimes support which flows
34
readonly supportsWebWorkerExtensionHost: boolean;
35
readonly supportsRemoteExtensionHost: boolean;
36
37
// Clients - see `isSupportedClient` in `common/env.ts` for what constitutes a supported client
38
readonly supportsSupportedClients: boolean;
39
readonly supportsUnsupportedClients: boolean;
40
41
// Configurations - some flows require a client secret
42
readonly supportsNoClientSecret: boolean;
43
}
44
45
export const enum GitHubTarget {
46
DotCom,
47
Enterprise,
48
HostedEnterprise
49
}
50
51
export const enum ExtensionHost {
52
WebWorker,
53
Remote,
54
Local
55
}
56
57
export interface IFlowQuery {
58
target: GitHubTarget;
59
extensionHost: ExtensionHost;
60
isSupportedClient: boolean;
61
}
62
63
interface IFlowTriggerOptions {
64
/**
65
* The scopes to request for the OAuth flow.
66
*/
67
scopes: string;
68
/**
69
* The base URI for the flow. This is used to determine which GitHub instance to authenticate against.
70
*/
71
baseUri: Uri;
72
/**
73
* The specific auth provider to use for the flow.
74
*/
75
signInProvider?: GitHubSocialSignInProvider;
76
/**
77
* Extra parameters to include in the OAuth flow.
78
*/
79
extraAuthorizeParameters?: Record<string, string>;
80
/**
81
* The Uri that the OAuth flow will redirect to. (i.e. vscode.dev/redirect)
82
*/
83
redirectUri: Uri;
84
/**
85
* The Uri to redirect to after redirecting to the redirect Uri. (i.e. vscode://....)
86
*/
87
callbackUri: Uri;
88
/**
89
* The enterprise URI for the flow, if applicable.
90
*/
91
enterpriseUri?: Uri;
92
/**
93
* The existing login which will be used to pre-fill the login prompt.
94
*/
95
existingLogin?: string;
96
/**
97
* The nonce for this particular flow. This is used to prevent replay attacks.
98
*/
99
nonce: string;
100
/**
101
* The instance of the Uri Handler for this extension
102
*/
103
uriHandler: UriEventHandler;
104
/**
105
* The logger to use for this flow.
106
*/
107
logger: Log;
108
}
109
110
interface IFlow {
111
label: string;
112
options: IFlowOptions;
113
trigger(options: IFlowTriggerOptions): Promise<string>;
114
}
115
116
/**
117
* Generates a cryptographically secure random string for PKCE code verifier.
118
* @param length The length of the string to generate
119
* @returns A random hex string
120
*/
121
function generateRandomString(length: number): string {
122
const array = new Uint8Array(length);
123
crypto.getRandomValues(array);
124
return Array.from(array)
125
.map(b => b.toString(16).padStart(2, '0'))
126
.join('')
127
.substring(0, length);
128
}
129
130
/**
131
* Generates a PKCE code challenge from a code verifier using SHA-256.
132
* @param codeVerifier The code verifier string
133
* @returns A base64url-encoded SHA-256 hash of the code verifier
134
*/
135
async function generateCodeChallenge(codeVerifier: string): Promise<string> {
136
const encoder = new TextEncoder();
137
const data = encoder.encode(codeVerifier);
138
const digest = await crypto.subtle.digest('SHA-256', data);
139
140
// Base64url encode the digest
141
const base64String = btoa(String.fromCharCode(...new Uint8Array(digest)));
142
return base64String
143
.replace(/\+/g, '-')
144
.replace(/\//g, '_')
145
.replace(/=+$/, '');
146
}
147
148
async function exchangeCodeForToken(
149
logger: Log,
150
endpointUri: Uri,
151
redirectUri: Uri,
152
code: string,
153
codeVerifier: string,
154
enterpriseUri?: Uri
155
): Promise<string> {
156
logger.info('Exchanging code for token...');
157
158
const clientSecret = Config.gitHubClientSecret;
159
if (!clientSecret) {
160
throw new Error('No client secret configured for GitHub authentication.');
161
}
162
163
const body = new URLSearchParams([
164
['code', code],
165
['client_id', Config.gitHubClientId],
166
['redirect_uri', redirectUri.toString(true)],
167
['client_secret', clientSecret],
168
['code_verifier', codeVerifier]
169
]);
170
if (enterpriseUri) {
171
body.append('github_enterprise', enterpriseUri.toString(true));
172
}
173
const result = await fetching(endpointUri.toString(true), {
174
logger,
175
retryFallbacks: true,
176
expectJSON: true,
177
method: 'POST',
178
headers: {
179
Accept: 'application/json',
180
'Content-Type': 'application/x-www-form-urlencoded',
181
},
182
body: body.toString()
183
});
184
185
if (result.ok) {
186
const json = await result.json();
187
logger.info('Token exchange success!');
188
return json.access_token;
189
} else {
190
const text = await result.text();
191
const error = new Error(text);
192
error.name = 'GitHubTokenExchangeError';
193
throw error;
194
}
195
}
196
197
class UrlHandlerFlow implements IFlow {
198
label = l10n.t('url handler');
199
options: IFlowOptions = {
200
supportsGitHubDotCom: true,
201
// Supporting GHES would be challenging because different versions
202
// used a different client ID. We could try to detect the version
203
// and use the right one, but that's a lot of work when we have
204
// other flows that work well.
205
supportsGitHubEnterpriseServer: false,
206
supportsHostedGitHubEnterprise: true,
207
supportsRemoteExtensionHost: true,
208
supportsWebWorkerExtensionHost: true,
209
// exchanging a code for a token requires a client secret
210
supportsNoClientSecret: false,
211
supportsSupportedClients: true,
212
supportsUnsupportedClients: false
213
};
214
215
async trigger({
216
scopes,
217
baseUri,
218
redirectUri,
219
callbackUri,
220
enterpriseUri,
221
nonce,
222
signInProvider,
223
extraAuthorizeParameters,
224
uriHandler,
225
existingLogin,
226
logger,
227
}: IFlowTriggerOptions): Promise<string> {
228
logger.info(`Trying without local server... (${scopes})`);
229
return await window.withProgress<string>({
230
location: ProgressLocation.Notification,
231
title: l10n.t({
232
message: 'Signing in to {0}...',
233
args: [baseUri.authority],
234
comment: ['The {0} will be a url, e.g. github.com']
235
}),
236
cancellable: true
237
}, async (_, token) => {
238
// Generate PKCE parameters
239
const codeVerifier = generateRandomString(64);
240
const codeChallenge = await generateCodeChallenge(codeVerifier);
241
242
const promise = uriHandler.waitForCode(logger, scopes, nonce, token);
243
244
const searchParams = new URLSearchParams([
245
['client_id', Config.gitHubClientId],
246
['redirect_uri', redirectUri.toString(true)],
247
['scope', scopes],
248
['state', encodeURIComponent(callbackUri.toString(true))],
249
['code_challenge', codeChallenge],
250
['code_challenge_method', 'S256']
251
]);
252
if (existingLogin) {
253
searchParams.append('login', existingLogin);
254
} else {
255
searchParams.append('prompt', 'select_account');
256
}
257
if (signInProvider) {
258
searchParams.append('provider', signInProvider);
259
}
260
if (extraAuthorizeParameters) {
261
for (const [key, value] of Object.entries(extraAuthorizeParameters)) {
262
searchParams.append(key, value);
263
}
264
}
265
266
// The extra toString, parse is apparently needed for env.openExternal
267
// to open the correct URL.
268
const uri = Uri.parse(baseUri.with({
269
path: '/login/oauth/authorize',
270
query: searchParams.toString()
271
}).toString(true));
272
await env.openExternal(uri);
273
274
const code = await promise;
275
276
const proxyEndpoints: { [providerId: string]: string } | undefined = await commands.executeCommand('workbench.getCodeExchangeProxyEndpoints');
277
const endpointUrl = proxyEndpoints?.github
278
? Uri.parse(`${proxyEndpoints.github}login/oauth/access_token`)
279
: baseUri.with({ path: '/login/oauth/access_token' });
280
281
const accessToken = await exchangeCodeForToken(logger, endpointUrl, redirectUri, code, codeVerifier, enterpriseUri);
282
return accessToken;
283
});
284
}
285
}
286
287
class LocalServerFlow implements IFlow {
288
label = l10n.t('local server');
289
options: IFlowOptions = {
290
supportsGitHubDotCom: true,
291
// Supporting GHES would be challenging because different versions
292
// used a different client ID. We could try to detect the version
293
// and use the right one, but that's a lot of work when we have
294
// other flows that work well.
295
supportsGitHubEnterpriseServer: false,
296
supportsHostedGitHubEnterprise: true,
297
// Opening a port on the remote side can't be open in the browser on
298
// the client side so this flow won't work in remote extension hosts
299
supportsRemoteExtensionHost: false,
300
// Web worker can't open a port to listen for the redirect
301
supportsWebWorkerExtensionHost: false,
302
// exchanging a code for a token requires a client secret
303
supportsNoClientSecret: false,
304
supportsSupportedClients: true,
305
supportsUnsupportedClients: true
306
};
307
async trigger({
308
scopes,
309
baseUri,
310
redirectUri,
311
callbackUri,
312
enterpriseUri,
313
signInProvider,
314
extraAuthorizeParameters,
315
existingLogin,
316
logger
317
}: IFlowTriggerOptions): Promise<string> {
318
logger.info(`Trying with local server... (${scopes})`);
319
return await window.withProgress<string>({
320
location: ProgressLocation.Notification,
321
title: l10n.t({
322
message: 'Signing in to {0}...',
323
args: [baseUri.authority],
324
comment: ['The {0} will be a url, e.g. github.com']
325
}),
326
cancellable: true
327
}, async (_, token) => {
328
// Generate PKCE parameters
329
const codeVerifier = generateRandomString(64);
330
const codeChallenge = await generateCodeChallenge(codeVerifier);
331
332
const searchParams = new URLSearchParams([
333
['client_id', Config.gitHubClientId],
334
['redirect_uri', redirectUri.toString(true)],
335
['scope', scopes],
336
['code_challenge', codeChallenge],
337
['code_challenge_method', 'S256']
338
]);
339
if (existingLogin) {
340
searchParams.append('login', existingLogin);
341
} else {
342
searchParams.append('prompt', 'select_account');
343
}
344
if (signInProvider) {
345
searchParams.append('provider', signInProvider);
346
}
347
if (extraAuthorizeParameters) {
348
for (const [key, value] of Object.entries(extraAuthorizeParameters)) {
349
searchParams.append(key, value);
350
}
351
}
352
353
const loginUrl = baseUri.with({
354
path: '/login/oauth/authorize',
355
query: searchParams.toString()
356
});
357
const server = new LoopbackAuthServer(path.join(__dirname, '../media'), loginUrl.toString(true), callbackUri.toString(true), env.isAppPortable);
358
const port = await server.start();
359
360
let codeToExchange;
361
try {
362
env.openExternal(Uri.parse(`http://127.0.0.1:${port}/signin?nonce=${encodeURIComponent(server.nonce)}`));
363
const { code } = await Promise.race([
364
server.waitForOAuthResponse(),
365
new Promise<any>((_, reject) => setTimeout(() => reject(TIMED_OUT_ERROR), 300_000)), // 5min timeout
366
promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject(USER_CANCELLATION_ERROR); }).promise
367
]);
368
codeToExchange = code;
369
} finally {
370
setTimeout(() => {
371
void server.stop();
372
}, 5000);
373
}
374
375
const accessToken = await exchangeCodeForToken(
376
logger,
377
baseUri.with({ path: '/login/oauth/access_token' }),
378
redirectUri,
379
codeToExchange,
380
codeVerifier,
381
enterpriseUri);
382
return accessToken;
383
});
384
}
385
}
386
387
class DeviceCodeFlow implements IFlow {
388
label = l10n.t('device code');
389
options: IFlowOptions = {
390
supportsGitHubDotCom: true,
391
supportsGitHubEnterpriseServer: true,
392
supportsHostedGitHubEnterprise: true,
393
supportsRemoteExtensionHost: true,
394
// CORS prevents this from working in web workers
395
supportsWebWorkerExtensionHost: false,
396
supportsNoClientSecret: true,
397
supportsSupportedClients: true,
398
supportsUnsupportedClients: true
399
};
400
async trigger({ scopes, baseUri, signInProvider, extraAuthorizeParameters, logger }: IFlowTriggerOptions) {
401
logger.info(`Trying device code flow... (${scopes})`);
402
403
// Get initial device code
404
const uri = baseUri.with({
405
path: '/login/device/code',
406
query: `client_id=${Config.gitHubClientId}&scope=${scopes}`
407
});
408
const result = await fetching(uri.toString(true), {
409
logger,
410
retryFallbacks: true,
411
expectJSON: true,
412
method: 'POST',
413
headers: {
414
Accept: 'application/json'
415
}
416
});
417
if (!result.ok) {
418
throw new Error(`Failed to get one-time code: ${await result.text()}`);
419
}
420
421
const json = await result.json() as IGitHubDeviceCodeResponse;
422
423
const button = l10n.t('Copy & Continue to {0}', signInProvider ? GitHubSocialSignInProviderLabels[signInProvider] : l10n.t('GitHub'));
424
const modalResult = await window.showInformationMessage(
425
l10n.t({ message: 'Your Code: {0}', args: [json.user_code], comment: ['The {0} will be a code, e.g. 123-456'] }),
426
{
427
modal: true,
428
detail: l10n.t('To finish authenticating, navigate to GitHub and paste in the above one-time code.')
429
}, button);
430
431
if (modalResult !== button) {
432
throw new Error(USER_CANCELLATION_ERROR);
433
}
434
435
await env.clipboard.writeText(json.user_code);
436
437
let open = Uri.parse(json.verification_uri);
438
const query = new URLSearchParams(open.query);
439
if (signInProvider) {
440
query.set('provider', signInProvider);
441
}
442
if (extraAuthorizeParameters) {
443
for (const [key, value] of Object.entries(extraAuthorizeParameters)) {
444
query.set(key, value);
445
}
446
}
447
if (signInProvider || extraAuthorizeParameters) {
448
open = open.with({ query: query.toString() });
449
}
450
const uriToOpen = await env.asExternalUri(open);
451
await env.openExternal(uriToOpen);
452
453
return await this.waitForDeviceCodeAccessToken(logger, baseUri, json);
454
}
455
456
private async waitForDeviceCodeAccessToken(
457
logger: Log,
458
baseUri: Uri,
459
json: IGitHubDeviceCodeResponse,
460
): Promise<string> {
461
return await window.withProgress<string>({
462
location: ProgressLocation.Notification,
463
cancellable: true,
464
title: l10n.t({
465
message: 'Open [{0}]({0}) in a new tab and paste your one-time code: {1}',
466
args: [json.verification_uri, json.user_code],
467
comment: [
468
'The [{0}]({0}) will be a url and the {1} will be a code, e.g. 123-456',
469
'{Locked="[{0}]({0})"}'
470
]
471
})
472
}, async (_, token) => {
473
const refreshTokenUri = baseUri.with({
474
path: '/login/oauth/access_token',
475
query: `client_id=${Config.gitHubClientId}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`
476
});
477
478
// Try for 2 minutes
479
const attempts = 120 / json.interval;
480
for (let i = 0; i < attempts; i++) {
481
await new Promise(resolve => setTimeout(resolve, json.interval * 1000));
482
if (token.isCancellationRequested) {
483
throw new Error(USER_CANCELLATION_ERROR);
484
}
485
let accessTokenResult;
486
try {
487
accessTokenResult = await fetching(refreshTokenUri.toString(true), {
488
logger,
489
retryFallbacks: true,
490
expectJSON: true,
491
method: 'POST',
492
headers: {
493
Accept: 'application/json'
494
}
495
});
496
} catch {
497
continue;
498
}
499
500
if (!accessTokenResult.ok) {
501
continue;
502
}
503
504
const accessTokenJson = await accessTokenResult.json();
505
506
if (accessTokenJson.error === 'authorization_pending') {
507
continue;
508
}
509
510
if (accessTokenJson.error) {
511
throw new Error(accessTokenJson.error_description);
512
}
513
514
return accessTokenJson.access_token;
515
}
516
517
throw new Error(TIMED_OUT_ERROR);
518
});
519
}
520
}
521
522
class PatFlow implements IFlow {
523
label = l10n.t('personal access token');
524
options: IFlowOptions = {
525
supportsGitHubDotCom: true,
526
supportsGitHubEnterpriseServer: true,
527
supportsHostedGitHubEnterprise: true,
528
supportsRemoteExtensionHost: true,
529
supportsWebWorkerExtensionHost: true,
530
supportsNoClientSecret: true,
531
// PATs can't be used with Settings Sync so we don't enable this flow
532
// for supported clients
533
supportsSupportedClients: false,
534
supportsUnsupportedClients: true
535
};
536
537
async trigger({ scopes, baseUri, logger, enterpriseUri }: IFlowTriggerOptions) {
538
logger.info(`Trying to retrieve PAT... (${scopes})`);
539
540
const button = l10n.t('Continue to GitHub');
541
const modalResult = await window.showInformationMessage(
542
l10n.t('Continue to GitHub to create a Personal Access Token (PAT)'),
543
{
544
modal: true,
545
detail: l10n.t('To finish authenticating, navigate to GitHub to create a PAT then paste the PAT into the input box.')
546
}, button);
547
548
if (modalResult !== button) {
549
throw new Error(USER_CANCELLATION_ERROR);
550
}
551
552
const description = `${env.appName} (${scopes})`;
553
const uriToOpen = await env.asExternalUri(baseUri.with({ path: '/settings/tokens/new', query: `description=${description}&scopes=${scopes.split(' ').join(',')}` }));
554
await env.openExternal(uriToOpen);
555
const token = await window.showInputBox({ placeHolder: `ghp_1a2b3c4...`, prompt: `GitHub Personal Access Token - ${scopes}`, ignoreFocusOut: true });
556
if (!token) { throw new Error(USER_CANCELLATION_ERROR); }
557
558
const appUri = !enterpriseUri || isHostedGitHubEnterprise(enterpriseUri)
559
? Uri.parse(`${baseUri.scheme}://api.${baseUri.authority}`)
560
: Uri.parse(`${baseUri.scheme}://${baseUri.authority}/api/v3`);
561
562
const tokenScopes = await this.getScopes(token, appUri, logger); // Example: ['repo', 'user']
563
const scopesList = scopes.split(' '); // Example: 'read:user repo user:email'
564
if (!scopesList.every(scope => {
565
const included = tokenScopes.includes(scope);
566
if (included || !scope.includes(':')) {
567
return included;
568
}
569
570
return scope.split(':').some(splitScopes => {
571
return tokenScopes.includes(splitScopes);
572
});
573
})) {
574
throw new Error(`The provided token does not match the requested scopes: ${scopes}`);
575
}
576
577
return token;
578
}
579
580
private async getScopes(token: string, serverUri: Uri, logger: Log): Promise<string[]> {
581
try {
582
logger.info('Getting token scopes...');
583
const result = await fetching(serverUri.toString(), {
584
logger,
585
retryFallbacks: true,
586
expectJSON: false,
587
headers: {
588
Authorization: `token ${token}`,
589
'User-Agent': `${env.appName} (${env.appHost})`
590
}
591
});
592
593
if (result.ok) {
594
const scopes = result.headers.get('X-OAuth-Scopes');
595
return scopes ? scopes.split(',').map(scope => scope.trim()) : [];
596
} else {
597
logger.error(`Getting scopes failed: ${result.statusText}`);
598
throw new Error(result.statusText);
599
}
600
} catch (ex) {
601
logger.error(ex.message);
602
throw new Error(NETWORK_ERROR);
603
}
604
}
605
}
606
607
const allFlows: IFlow[] = [
608
new LocalServerFlow(),
609
new UrlHandlerFlow(),
610
new DeviceCodeFlow(),
611
new PatFlow()
612
];
613
614
export function getFlows(query: IFlowQuery) {
615
const validFlows = allFlows.filter(flow => {
616
let useFlow: boolean = true;
617
switch (query.target) {
618
case GitHubTarget.DotCom:
619
useFlow &&= flow.options.supportsGitHubDotCom;
620
break;
621
case GitHubTarget.Enterprise:
622
useFlow &&= flow.options.supportsGitHubEnterpriseServer;
623
break;
624
case GitHubTarget.HostedEnterprise:
625
useFlow &&= flow.options.supportsHostedGitHubEnterprise;
626
break;
627
}
628
629
switch (query.extensionHost) {
630
case ExtensionHost.Remote:
631
useFlow &&= flow.options.supportsRemoteExtensionHost;
632
break;
633
case ExtensionHost.WebWorker:
634
useFlow &&= flow.options.supportsWebWorkerExtensionHost;
635
break;
636
}
637
638
if (!Config.gitHubClientSecret) {
639
useFlow &&= flow.options.supportsNoClientSecret;
640
}
641
642
if (query.isSupportedClient) {
643
// TODO: revisit how we support PAT in GHES but not DotCom... but this works for now since
644
// there isn't another flow that has supportsSupportedClients = false
645
useFlow &&= (flow.options.supportsSupportedClients || query.target !== GitHubTarget.DotCom);
646
} else {
647
useFlow &&= flow.options.supportsUnsupportedClients;
648
}
649
return useFlow;
650
});
651
652
const preferDeviceCodeFlow = workspace.getConfiguration('github-authentication').get<boolean>('preferDeviceCodeFlow', false);
653
if (preferDeviceCodeFlow) {
654
return [
655
...validFlows.filter(flow => flow instanceof DeviceCodeFlow),
656
...validFlows.filter(flow => !(flow instanceof DeviceCodeFlow))
657
];
658
}
659
660
return validFlows;
661
}
662
663
/**
664
* Social authentication providers for GitHub
665
*/
666
export const enum GitHubSocialSignInProvider {
667
Google = 'google',
668
Apple = 'apple',
669
}
670
671
const GitHubSocialSignInProviderLabels = {
672
[GitHubSocialSignInProvider.Google]: l10n.t('Google'),
673
[GitHubSocialSignInProvider.Apple]: l10n.t('Apple'),
674
};
675
676
export function isSocialSignInProvider(provider: unknown): provider is GitHubSocialSignInProvider {
677
return provider === GitHubSocialSignInProvider.Google || provider === GitHubSocialSignInProvider.Apple;
678
}
679
680