-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
authenticationService.ts
776 lines (661 loc) · 31.5 KB
/
authenticationService.ts
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { flatten } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { Disposable, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { isWeb } from 'vs/base/common/platform';
import { isFalsyOrWhitespace } from 'vs/base/common/strings';
import { isString } from 'vs/base/common/types';
import { AuthenticationProviderInformation, AuthenticationSession, AuthenticationSessionsChangeEvent } from 'vs/editor/common/languages';
import * as nls from 'vs/nls';
import { MenuId, MenuRegistry } from 'vs/platform/actions/common/actions';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ICredentialsService } from 'vs/platform/credentials/common/credentials';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Severity } from 'vs/platform/notification/common/notification';
import { IProductService } from 'vs/platform/product/common/productService';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { MainThreadAuthenticationProvider } from 'vs/workbench/api/browser/mainThreadAuthentication';
import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity';
import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService';
import { ActivationKind, IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
export function getAuthenticationProviderActivationEvent(id: string): string { return `onAuthenticationRequest:${id}`; }
export interface IAccountUsage {
extensionId: string;
extensionName: string;
lastUsed: number;
}
const VSO_ALLOWED_EXTENSIONS = [
'github.vscode-pull-request-github',
'github.vscode-pull-request-github-insiders',
'vscode.git',
'ms-vsonline.vsonline',
'github.remotehub',
'github.remotehub-insiders',
'github.codespaces',
'ms-vsliveshare.vsliveshare'
];
export function readAccountUsages(storageService: IStorageService, providerId: string, accountName: string,): IAccountUsage[] {
const accountKey = `${providerId}-${accountName}-usages`;
const storedUsages = storageService.get(accountKey, StorageScope.GLOBAL);
let usages: IAccountUsage[] = [];
if (storedUsages) {
try {
usages = JSON.parse(storedUsages);
} catch (e) {
// ignore
}
}
return usages;
}
export function removeAccountUsage(storageService: IStorageService, providerId: string, accountName: string): void {
const accountKey = `${providerId}-${accountName}-usages`;
storageService.remove(accountKey, StorageScope.GLOBAL);
}
export function addAccountUsage(storageService: IStorageService, providerId: string, accountName: string, extensionId: string, extensionName: string) {
const accountKey = `${providerId}-${accountName}-usages`;
const usages = readAccountUsages(storageService, providerId, accountName);
const existingUsageIndex = usages.findIndex(usage => usage.extensionId === extensionId);
if (existingUsageIndex > -1) {
usages.splice(existingUsageIndex, 1, {
extensionId,
extensionName,
lastUsed: Date.now()
});
} else {
usages.push({
extensionId,
extensionName,
lastUsed: Date.now()
});
}
storageService.store(accountKey, JSON.stringify(usages), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
export type AuthenticationSessionInfo = { readonly id: string, readonly accessToken: string, readonly providerId: string, readonly canSignOut?: boolean };
export async function getCurrentAuthenticationSessionInfo(credentialsService: ICredentialsService, productService: IProductService): Promise<AuthenticationSessionInfo | undefined> {
const authenticationSessionValue = await credentialsService.getPassword(`${productService.urlProtocol}.login`, 'account');
if (authenticationSessionValue) {
const authenticationSessionInfo: AuthenticationSessionInfo = JSON.parse(authenticationSessionValue);
if (authenticationSessionInfo
&& isString(authenticationSessionInfo.id)
&& isString(authenticationSessionInfo.accessToken)
&& isString(authenticationSessionInfo.providerId)
) {
return authenticationSessionInfo;
}
}
return undefined;
}
export const IAuthenticationService = createDecorator<IAuthenticationService>('IAuthenticationService');
export interface IAuthenticationService {
readonly _serviceBrand: undefined;
isAuthenticationProviderRegistered(id: string): boolean;
getProviderIds(): string[];
registerAuthenticationProvider(id: string, provider: MainThreadAuthenticationProvider): void;
unregisterAuthenticationProvider(id: string): void;
isAccessAllowed(providerId: string, accountName: string, extensionId: string): boolean | undefined;
updatedAllowedExtension(providerId: string, accountName: string, extensionId: string, extensionName: string, isAllowed: boolean): Promise<void>;
showGetSessionPrompt(providerId: string, accountName: string, extensionId: string, extensionName: string): Promise<boolean>;
selectSession(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: readonly AuthenticationSession[]): Promise<AuthenticationSession>;
requestSessionAccess(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: readonly AuthenticationSession[]): void;
completeSessionAccessRequest(providerId: string, extensionId: string, extensionName: string, scopes: string[]): Promise<void>
requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string): Promise<void>;
sessionsUpdate(providerId: string, event: AuthenticationSessionsChangeEvent): void;
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidChangeSessions: Event<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }>;
// TODO @RMacfarlane completely remove this property
declaredProviders: AuthenticationProviderInformation[];
readonly onDidChangeDeclaredProviders: Event<AuthenticationProviderInformation[]>;
getSessions(id: string, scopes?: string[], activateImmediate?: boolean): Promise<ReadonlyArray<AuthenticationSession>>;
getLabel(providerId: string): string;
supportsMultipleAccounts(providerId: string): boolean;
createSession(providerId: string, scopes: string[], activateImmediate?: boolean): Promise<AuthenticationSession>;
removeSession(providerId: string, sessionId: string): Promise<void>;
manageTrustedExtensionsForAccount(providerId: string, accountName: string): Promise<void>;
removeAccountSessions(providerId: string, accountName: string, sessions: AuthenticationSession[]): Promise<void>;
}
export interface AllowedExtension {
id: string;
name: string;
allowed?: boolean;
}
export function readAllowedExtensions(storageService: IStorageService, providerId: string, accountName: string): AllowedExtension[] {
let trustedExtensions: AllowedExtension[] = [];
try {
const trustedExtensionSrc = storageService.get(`${providerId}-${accountName}`, StorageScope.GLOBAL);
if (trustedExtensionSrc) {
trustedExtensions = JSON.parse(trustedExtensionSrc);
}
} catch (err) { }
return trustedExtensions;
}
// OAuth2 spec prohibits space in a scope, so use that to join them.
const SCOPESLIST_SEPARATOR = ' ';
interface SessionRequest {
disposables: IDisposable[];
requestingExtensionIds: string[];
}
interface SessionRequestInfo {
[scopesList: string]: SessionRequest;
}
CommandsRegistry.registerCommand('workbench.getCodeExchangeProxyEndpoints', function (accessor, _) {
const environmentService = accessor.get(IBrowserWorkbenchEnvironmentService);
return environmentService.options?.codeExchangeProxyEndpoints;
});
const authenticationDefinitionSchema: IJSONSchema = {
type: 'object',
additionalProperties: false,
properties: {
id: {
type: 'string',
description: nls.localize('authentication.id', 'The id of the authentication provider.')
},
label: {
type: 'string',
description: nls.localize('authentication.label', 'The human readable name of the authentication provider.'),
}
}
};
const authenticationExtPoint = ExtensionsRegistry.registerExtensionPoint<AuthenticationProviderInformation[]>({
extensionPoint: 'authentication',
jsonSchema: {
description: nls.localize({ key: 'authenticationExtensionPoint', comment: [`'Contributes' means adds here`] }, 'Contributes authentication'),
type: 'array',
items: authenticationDefinitionSchema
}
});
export class AuthenticationService extends Disposable implements IAuthenticationService {
declare readonly _serviceBrand: undefined;
private _placeholderMenuItem: IDisposable | undefined;
private _signInRequestItems = new Map<string, SessionRequestInfo>();
private _sessionAccessRequestItems = new Map<string, { [extensionId: string]: { disposables: IDisposable[], possibleSessions: AuthenticationSession[] } }>();
private _accountBadgeDisposable = this._register(new MutableDisposable());
private _authenticationProviders: Map<string, MainThreadAuthenticationProvider> = new Map<string, MainThreadAuthenticationProvider>();
/**
* All providers that have been statically declared by extensions. These may not be registered.
*/
declaredProviders: AuthenticationProviderInformation[] = [];
private _onDidRegisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this._register(new Emitter<AuthenticationProviderInformation>());
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidRegisterAuthenticationProvider.event;
private _onDidUnregisterAuthenticationProvider: Emitter<AuthenticationProviderInformation> = this._register(new Emitter<AuthenticationProviderInformation>());
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this._onDidUnregisterAuthenticationProvider.event;
private _onDidChangeSessions: Emitter<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }> = this._register(new Emitter<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }>());
readonly onDidChangeSessions: Event<{ providerId: string, label: string, event: AuthenticationSessionsChangeEvent }> = this._onDidChangeSessions.event;
private _onDidChangeDeclaredProviders: Emitter<AuthenticationProviderInformation[]> = this._register(new Emitter<AuthenticationProviderInformation[]>());
readonly onDidChangeDeclaredProviders: Event<AuthenticationProviderInformation[]> = this._onDidChangeDeclaredProviders.event;
constructor(
@IActivityService private readonly activityService: IActivityService,
@IExtensionService private readonly extensionService: IExtensionService,
@IStorageService private readonly storageService: IStorageService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IDialogService private readonly dialogService: IDialogService,
@IQuickInputService private readonly quickInputService: IQuickInputService
) {
super();
this._placeholderMenuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
command: {
id: 'noAuthenticationProviders',
title: nls.localize('loading', "Loading..."),
precondition: ContextKeyExpr.false()
},
});
authenticationExtPoint.setHandler((extensions, { added, removed }) => {
added.forEach(point => {
for (const provider of point.value) {
if (isFalsyOrWhitespace(provider.id)) {
point.collector.error(nls.localize('authentication.missingId', 'An authentication contribution must specify an id.'));
continue;
}
if (isFalsyOrWhitespace(provider.label)) {
point.collector.error(nls.localize('authentication.missingLabel', 'An authentication contribution must specify a label.'));
continue;
}
if (!this.declaredProviders.some(p => p.id === provider.id)) {
this.declaredProviders.push(provider);
} else {
point.collector.error(nls.localize('authentication.idConflict', "This authentication id '{0}' has already been registered", provider.id));
}
}
});
const removedExtPoints = flatten(removed.map(r => r.value));
removedExtPoints.forEach(point => {
const index = this.declaredProviders.findIndex(provider => provider.id === point.id);
if (index > -1) {
this.declaredProviders.splice(index, 1);
}
});
this._onDidChangeDeclaredProviders.fire(this.declaredProviders);
});
}
getProviderIds(): string[] {
const providerIds: string[] = [];
this._authenticationProviders.forEach(provider => {
providerIds.push(provider.id);
});
return providerIds;
}
isAuthenticationProviderRegistered(id: string): boolean {
return this._authenticationProviders.has(id);
}
registerAuthenticationProvider(id: string, authenticationProvider: MainThreadAuthenticationProvider): void {
this._authenticationProviders.set(id, authenticationProvider);
this._onDidRegisterAuthenticationProvider.fire({ id, label: authenticationProvider.label });
if (this._placeholderMenuItem) {
this._placeholderMenuItem.dispose();
this._placeholderMenuItem = undefined;
}
}
unregisterAuthenticationProvider(id: string): void {
const provider = this._authenticationProviders.get(id);
if (provider) {
provider.dispose();
this._authenticationProviders.delete(id);
this._onDidUnregisterAuthenticationProvider.fire({ id, label: provider.label });
const accessRequests = this._sessionAccessRequestItems.get(id) || {};
Object.keys(accessRequests).forEach(extensionId => {
this.removeAccessRequest(id, extensionId);
});
}
if (!this._authenticationProviders.size) {
this._placeholderMenuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
command: {
id: 'noAuthenticationProviders',
title: nls.localize('loading', "Loading..."),
precondition: ContextKeyExpr.false()
},
});
}
}
async sessionsUpdate(id: string, event: AuthenticationSessionsChangeEvent): Promise<void> {
const provider = this._authenticationProviders.get(id);
if (provider) {
this._onDidChangeSessions.fire({ providerId: id, label: provider.label, event: event });
if (event.added) {
await this.updateNewSessionRequests(provider, event.added);
}
if (event.removed) {
await this.updateAccessRequests(id, event.removed);
}
this.updateBadgeCount();
}
}
private async updateNewSessionRequests(provider: MainThreadAuthenticationProvider, addedSessions: readonly AuthenticationSession[]): Promise<void> {
const existingRequestsForProvider = this._signInRequestItems.get(provider.id);
if (!existingRequestsForProvider) {
return;
}
Object.keys(existingRequestsForProvider).forEach(requestedScopes => {
if (addedSessions.some(session => session.scopes.slice().join(SCOPESLIST_SEPARATOR) === requestedScopes)) {
const sessionRequest = existingRequestsForProvider[requestedScopes];
sessionRequest?.disposables.forEach(item => item.dispose());
delete existingRequestsForProvider[requestedScopes];
if (Object.keys(existingRequestsForProvider).length === 0) {
this._signInRequestItems.delete(provider.id);
} else {
this._signInRequestItems.set(provider.id, existingRequestsForProvider);
}
}
});
}
private async updateAccessRequests(providerId: string, removedSessions: readonly AuthenticationSession[]) {
const providerRequests = this._sessionAccessRequestItems.get(providerId);
if (providerRequests) {
Object.keys(providerRequests).forEach(extensionId => {
removedSessions.forEach(removed => {
const indexOfSession = providerRequests[extensionId].possibleSessions.findIndex(session => session.id === removed.id);
if (indexOfSession) {
providerRequests[extensionId].possibleSessions.splice(indexOfSession, 1);
}
});
if (!providerRequests[extensionId].possibleSessions.length) {
this.removeAccessRequest(providerId, extensionId);
}
});
}
}
private updateBadgeCount(): void {
this._accountBadgeDisposable.clear();
let numberOfRequests = 0;
this._signInRequestItems.forEach(providerRequests => {
Object.keys(providerRequests).forEach(request => {
numberOfRequests += providerRequests[request].requestingExtensionIds.length;
});
});
this._sessionAccessRequestItems.forEach(accessRequest => {
numberOfRequests += Object.keys(accessRequest).length;
});
if (numberOfRequests > 0) {
const badge = new NumberBadge(numberOfRequests, () => nls.localize('sign in', "Sign in requested"));
this._accountBadgeDisposable.value = this.activityService.showAccountsActivity({ badge });
}
}
private removeAccessRequest(providerId: string, extensionId: string): void {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
if (providerRequests[extensionId]) {
providerRequests[extensionId].disposables.forEach(d => d.dispose());
delete providerRequests[extensionId];
this.updateBadgeCount();
}
}
/**
* Check extension access to an account
* @param providerId The id of the authentication provider
* @param accountName The account name that access is checked for
* @param extensionId The id of the extension requesting access
* @returns Returns true or false if the user has opted to permanently grant or disallow access, and undefined
* if they haven't made a choice yet
*/
isAccessAllowed(providerId: string, accountName: string, extensionId: string): boolean | undefined {
const allowList = readAllowedExtensions(this.storageService, providerId, accountName);
const extensionData = allowList.find(extension => extension.id === extensionId);
if (extensionData) {
// This property didn't exist on this data previously, inclusion in the list at all indicates allowance
return extensionData.allowed !== undefined
? extensionData.allowed
: true;
}
const remoteConnection = this.remoteAgentService.getConnection();
const isVSO = remoteConnection !== null
? remoteConnection.remoteAuthority.startsWith('vsonline') || remoteConnection.remoteAuthority.startsWith('codespaces')
: isWeb;
if (isVSO && VSO_ALLOWED_EXTENSIONS.includes(extensionId)) {
return true;
}
return undefined;
}
async updatedAllowedExtension(providerId: string, accountName: string, extensionId: string, extensionName: string, isAllowed: boolean): Promise<void> {
const allowList = readAllowedExtensions(this.storageService, providerId, accountName);
const index = allowList.findIndex(extension => extension.id === extensionId);
if (index === -1) {
allowList.push({ id: extensionId, name: extensionName, allowed: isAllowed });
} else {
allowList[index].allowed = isAllowed;
}
await this.storageService.store(`${providerId}-${accountName}`, JSON.stringify(allowList), StorageScope.GLOBAL, StorageTarget.USER);
}
async showGetSessionPrompt(providerId: string, accountName: string, extensionId: string, extensionName: string): Promise<boolean> {
const providerName = this.getLabel(providerId);
const { choice } = await this.dialogService.show(
Severity.Info,
nls.localize('confirmAuthenticationAccess', "The extension '{0}' wants to access the {1} account '{2}'.", extensionName, providerName, accountName),
[nls.localize('allow', "Allow"), nls.localize('deny', "Deny"), nls.localize('cancel', "Cancel")],
{
cancelId: 2
}
);
const cancelled = choice === 2;
const allowed = choice === 0;
if (!cancelled) {
this.updatedAllowedExtension(providerId, accountName, extensionId, extensionName, allowed);
this.removeAccessRequest(providerId, extensionId);
}
return allowed;
}
async selectSession(providerId: string, extensionId: string, extensionName: string, scopes: string[], availableSessions: AuthenticationSession[]): Promise<AuthenticationSession> {
return new Promise((resolve, reject) => {
// This function should be used only when there are sessions to disambiguate.
if (!availableSessions.length) {
reject('No available sessions');
}
const quickPick = this.quickInputService.createQuickPick<{ label: string, session?: AuthenticationSession }>();
quickPick.ignoreFocusOut = true;
const items: { label: string, session?: AuthenticationSession }[] = availableSessions.map(session => {
return {
label: session.account.label,
session: session
};
});
items.push({
label: nls.localize('useOtherAccount', "Sign in to another account")
});
const providerName = this.getLabel(providerId);
quickPick.items = items;
quickPick.title = nls.localize(
{
key: 'selectAccount',
comment: ['The placeholder {0} is the name of an extension. {1} is the name of the type of account, such as Microsoft or GitHub.']
},
"The extension '{0}' wants to access a {1} account",
extensionName,
providerName);
quickPick.placeholder = nls.localize('getSessionPlateholder', "Select an account for '{0}' to use or Esc to cancel", extensionName);
quickPick.onDidAccept(async _ => {
const session = quickPick.selectedItems[0].session ?? await this.createSession(providerId, scopes);
const accountName = session.account.label;
this.updatedAllowedExtension(providerId, accountName, extensionId, extensionName, true);
this.removeAccessRequest(providerId, extensionId);
this.storageService.store(`${extensionName}-${providerId}`, session.id, StorageScope.GLOBAL, StorageTarget.MACHINE);
quickPick.dispose();
resolve(session);
});
quickPick.onDidHide(_ => {
if (!quickPick.selectedItems[0]) {
reject('User did not consent to account access');
}
quickPick.dispose();
});
quickPick.show();
});
}
async completeSessionAccessRequest(providerId: string, extensionId: string, extensionName: string, scopes: string[]): Promise<void> {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
const existingRequest = providerRequests[extensionId];
if (!existingRequest) {
return;
}
const possibleSessions = existingRequest.possibleSessions;
const supportsMultipleAccounts = this.supportsMultipleAccounts(providerId);
let session: AuthenticationSession | undefined;
if (supportsMultipleAccounts) {
try {
session = await this.selectSession(providerId, extensionId, extensionName, scopes, possibleSessions);
} catch (_) {
// ignore cancel
}
} else {
const approved = await this.showGetSessionPrompt(providerId, possibleSessions[0].account.label, extensionId, extensionName);
if (approved) {
session = possibleSessions[0];
}
}
if (session) {
addAccountUsage(this.storageService, providerId, session.account.label, extensionId, extensionName);
const providerName = this.getLabel(providerId);
this._onDidChangeSessions.fire({ providerId, label: providerName, event: { added: [], removed: [], changed: [session] } });
}
}
requestSessionAccess(providerId: string, extensionId: string, extensionName: string, scopes: string[], possibleSessions: AuthenticationSession[]): void {
const providerRequests = this._sessionAccessRequestItems.get(providerId) || {};
const hasExistingRequest = providerRequests[extensionId];
if (hasExistingRequest) {
return;
}
const menuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
group: '3_accessRequests',
command: {
id: `${providerId}${extensionId}Access`,
title: nls.localize({
key: 'accessRequest',
comment: [`The placeholder {0} will be replaced with an authentication provider''s label. {1} will be replaced with an extension name. (1) is to indicate that this menu item contributes to a badge count`]
},
"Grant access to {0} for {1}... (1)",
this.getLabel(providerId),
extensionName)
}
});
const accessCommand = CommandsRegistry.registerCommand({
id: `${providerId}${extensionId}Access`,
handler: async (accessor) => {
const authenticationService = accessor.get(IAuthenticationService);
authenticationService.completeSessionAccessRequest(providerId, extensionId, extensionName, scopes);
}
});
providerRequests[extensionId] = { possibleSessions, disposables: [menuItem, accessCommand] };
this._sessionAccessRequestItems.set(providerId, providerRequests);
this.updateBadgeCount();
}
async requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string): Promise<void> {
let provider = this._authenticationProviders.get(providerId);
if (!provider) {
// Activate has already been called for the authentication provider, but it cannot block on registering itself
// since this is sync and returns a disposable. So, wait for registration event to fire that indicates the
// provider is now in the map.
await new Promise<void>((resolve, _) => {
this.onDidRegisterAuthenticationProvider(e => {
if (e.id === providerId) {
provider = this._authenticationProviders.get(providerId);
resolve();
}
});
});
}
if (!provider) {
return;
}
const providerRequests = this._signInRequestItems.get(providerId);
const scopesList = scopes.join(SCOPESLIST_SEPARATOR);
const extensionHasExistingRequest = providerRequests
&& providerRequests[scopesList]
&& providerRequests[scopesList].requestingExtensionIds.includes(extensionId);
if (extensionHasExistingRequest) {
return;
}
// Construct a commandId that won't clash with others generated here, nor likely with an extension's command
const commandId = `${providerId}:${extensionId}:signIn${Object.keys(providerRequests || []).length}`;
const menuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
group: '2_signInRequests',
command: {
id: commandId,
title: nls.localize({
key: 'signInRequest',
comment: [`The placeholder {0} will be replaced with an authentication provider's label. {1} will be replaced with an extension name. (1) is to indicate that this menu item contributes to a badge count.`]
},
"Sign in with {0} to use {1} (1)",
provider.label,
extensionName)
}
});
const signInCommand = CommandsRegistry.registerCommand({
id: commandId,
handler: async (accessor) => {
const authenticationService = accessor.get(IAuthenticationService);
const storageService = accessor.get(IStorageService);
const session = await authenticationService.createSession(providerId, scopes);
// Add extension to allow list since user explicitly signed in on behalf of it
this.updatedAllowedExtension(providerId, session.account.label, extensionId, extensionName, true);
// And also set it as the preferred account for the extension
storageService.store(`${extensionName}-${providerId}`, session.id, StorageScope.GLOBAL, StorageTarget.MACHINE);
}
});
if (providerRequests) {
const existingRequest = providerRequests[scopesList] || { disposables: [], requestingExtensionIds: [] };
providerRequests[scopesList] = {
disposables: [...existingRequest.disposables, menuItem, signInCommand],
requestingExtensionIds: [...existingRequest.requestingExtensionIds, extensionId]
};
this._signInRequestItems.set(providerId, providerRequests);
} else {
this._signInRequestItems.set(providerId, {
[scopesList]: {
disposables: [menuItem, signInCommand],
requestingExtensionIds: [extensionId]
}
});
}
this.updateBadgeCount();
}
getLabel(id: string): string {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.label;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
supportsMultipleAccounts(id: string): boolean {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.supportsMultipleAccounts;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
private async tryActivateProvider(providerId: string, activateImmediate: boolean): Promise<MainThreadAuthenticationProvider> {
await this.extensionService.activateByEvent(getAuthenticationProviderActivationEvent(providerId), activateImmediate ? ActivationKind.Immediate : ActivationKind.Normal);
let provider = this._authenticationProviders.get(providerId);
if (provider) {
return provider;
}
// When activate has completed, the extension has made the call to `registerAuthenticationProvider`.
// However, activate cannot block on this, so the renderer may not have gotten the event yet.
const didRegister: Promise<MainThreadAuthenticationProvider> = new Promise((resolve, _) => {
this.onDidRegisterAuthenticationProvider(e => {
if (e.id === providerId) {
provider = this._authenticationProviders.get(providerId);
if (provider) {
resolve(provider);
} else {
throw new Error(`No authentication provider '${providerId}' is currently registered.`);
}
}
});
});
const didTimeout: Promise<MainThreadAuthenticationProvider> = new Promise((_, reject) => {
setTimeout(() => {
reject('Timed out waiting for authentication provider to register');
}, 5000);
});
return Promise.race([didRegister, didTimeout]);
}
async getSessions(id: string, scopes?: string[], activateImmediate: boolean = false): Promise<ReadonlyArray<AuthenticationSession>> {
const authProvider = this._authenticationProviders.get(id) || await this.tryActivateProvider(id, activateImmediate);
if (authProvider) {
return await authProvider.getSessions(scopes);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async createSession(id: string, scopes: string[], activateImmediate: boolean = false): Promise<AuthenticationSession> {
const authProvider = this._authenticationProviders.get(id) || await this.tryActivateProvider(id, activateImmediate);
if (authProvider) {
return await authProvider.createSession(scopes);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async removeSession(id: string, sessionId: string): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.removeSession(sessionId);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async manageTrustedExtensionsForAccount(id: string, accountName: string): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.manageTrustedExtensions(accountName);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async removeAccountSessions(id: string, accountName: string, sessions: AuthenticationSession[]): Promise<void> {
const authProvider = this._authenticationProviders.get(id);
if (authProvider) {
return authProvider.removeAccountSessions(accountName, sessions);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
}
registerSingleton(IAuthenticationService, AuthenticationService);