-
Notifications
You must be signed in to change notification settings - Fork 29.4k
/
extensionUrlHandler.ts
414 lines (331 loc) · 16.4 KB
/
extensionUrlHandler.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize, localize2 } from '../../../../nls.js';
import { IDisposable, combinedDisposable } from '../../../../base/common/lifecycle.js';
import { URI } from '../../../../base/common/uri.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';
import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js';
import { createDecorator, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { IURLHandler, IURLService, IOpenURLOptions } from '../../../../platform/url/common/url.js';
import { IHostService } from '../../host/browser/host.js';
import { ActivationKind, IExtensionService } from '../common/extensions.js';
import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js';
import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js';
import { IWorkbenchContribution, WorkbenchPhase, registerWorkbenchContribution2 } from '../../../common/contributions.js';
import { Action2, MenuId, registerAction2 } from '../../../../platform/actions/common/actions.js';
import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js';
import { IsWebContext } from '../../../../platform/contextkey/common/contextkeys.js';
import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js';
import { IProductService } from '../../../../platform/product/common/productService.js';
import { disposableWindowInterval } from '../../../../base/browser/dom.js';
import { mainWindow } from '../../../../base/browser/window.js';
import { ICommandService } from '../../../../platform/commands/common/commands.js';
import { isCancellationError } from '../../../../base/common/errors.js';
import { INotificationService } from '../../../../platform/notification/common/notification.js';
import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js';
const FIVE_MINUTES = 5 * 60 * 1000;
const THIRTY_SECONDS = 30 * 1000;
const URL_TO_HANDLE = 'extensionUrlHandler.urlToHandle';
const USER_TRUSTED_EXTENSIONS_CONFIGURATION_KEY = 'extensions.confirmedUriHandlerExtensionIds';
const USER_TRUSTED_EXTENSIONS_STORAGE_KEY = 'extensionUrlHandler.confirmedExtensions';
function isExtensionId(value: string): boolean {
return /^[a-z0-9][a-z0-9\-]*\.[a-z0-9][a-z0-9\-]*$/i.test(value);
}
class UserTrustedExtensionIdStorage {
get extensions(): string[] {
const userTrustedExtensionIdsJson = this.storageService.get(USER_TRUSTED_EXTENSIONS_STORAGE_KEY, StorageScope.PROFILE, '[]');
try {
return JSON.parse(userTrustedExtensionIdsJson);
} catch {
return [];
}
}
constructor(private storageService: IStorageService) { }
has(id: string): boolean {
return this.extensions.indexOf(id) > -1;
}
add(id: string): void {
this.set([...this.extensions, id]);
}
set(ids: string[]): void {
this.storageService.store(USER_TRUSTED_EXTENSIONS_STORAGE_KEY, JSON.stringify(ids), StorageScope.PROFILE, StorageTarget.MACHINE);
}
}
export const IExtensionUrlHandler = createDecorator<IExtensionUrlHandler>('extensionUrlHandler');
export interface IExtensionContributedURLHandler extends IURLHandler {
extensionDisplayName: string;
}
export interface IExtensionUrlHandler {
readonly _serviceBrand: undefined;
registerExtensionHandler(extensionId: ExtensionIdentifier, handler: IExtensionContributedURLHandler): void;
unregisterExtensionHandler(extensionId: ExtensionIdentifier): void;
}
export interface ExtensionUrlHandlerEvent {
readonly extensionId: string;
}
type ExtensionUrlHandlerClassification = {
owner: 'joaomoreno';
readonly extensionId: { classification: 'PublicNonPersonalData'; purpose: 'FeatureInsight'; comment: 'The ID of the extension that should handle the URI' };
comment: 'This is used to understand the drop funnel of extension URI handling by the OS & VS Code.';
};
interface ExtensionUrlReloadHandlerEvent {
readonly extensionId: string;
readonly isRemote: boolean;
}
type ExtensionUrlReloadHandlerClassification = {
owner: 'sandy081';
readonly extensionId: { classification: 'PublicNonPersonalData'; purpose: 'FeatureInsight'; comment: 'The ID of the extension that should handle the URI' };
readonly isRemote: { classification: 'PublicNonPersonalData'; purpose: 'FeatureInsight'; comment: 'Whether the current window is a remote window' };
comment: 'This is used to understand the drop funnel of extension URI handling by the OS & VS Code.';
};
/**
* This class handles URLs which are directed towards extensions.
* If a URL is directed towards an inactive extension, it buffers it,
* activates the extension and re-opens the URL once the extension registers
* a URL handler. If the extension never registers a URL handler, the urls
* will eventually be garbage collected.
*
* It also makes sure the user confirms opening URLs directed towards extensions.
*/
class ExtensionUrlHandler implements IExtensionUrlHandler, IURLHandler {
readonly _serviceBrand: undefined;
private extensionHandlers = new Map<string, IExtensionContributedURLHandler>();
private uriBuffer = new Map<string, { timestamp: number; uri: URI }[]>();
private userTrustedExtensionsStorage: UserTrustedExtensionIdStorage;
private disposable: IDisposable;
constructor(
@IURLService urlService: IURLService,
@IExtensionService private readonly extensionService: IExtensionService,
@IDialogService private readonly dialogService: IDialogService,
@ICommandService private readonly commandService: ICommandService,
@IHostService private readonly hostService: IHostService,
@IStorageService private readonly storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@INotificationService private readonly notificationService: INotificationService,
@IProductService private readonly productService: IProductService,
@IWorkbenchEnvironmentService private readonly workbenchEnvironmentService: IWorkbenchEnvironmentService
) {
this.userTrustedExtensionsStorage = new UserTrustedExtensionIdStorage(storageService);
const interval = disposableWindowInterval(mainWindow, () => this.garbageCollect(), THIRTY_SECONDS);
const urlToHandleValue = this.storageService.get(URL_TO_HANDLE, StorageScope.WORKSPACE);
if (urlToHandleValue) {
this.storageService.remove(URL_TO_HANDLE, StorageScope.WORKSPACE);
this.handleURL(URI.revive(JSON.parse(urlToHandleValue)), { trusted: true });
}
this.disposable = combinedDisposable(
urlService.registerHandler(this),
interval
);
const cache = ExtensionUrlBootstrapHandler.cache;
setTimeout(() => cache.forEach(([uri, option]) => this.handleURL(uri, option)));
}
async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
if (!isExtensionId(uri.authority)) {
return false;
}
const extensionId = uri.authority;
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/start', { extensionId });
const initialHandler = this.extensionHandlers.get(ExtensionIdentifier.toKey(extensionId));
let extensionDisplayName: string;
if (!initialHandler) {
// The extension is not yet activated, so let's check if it is installed and enabled
const extension = await this.extensionService.getExtension(extensionId);
if (!extension) {
await this.handleUnhandledURL(uri, extensionId, options);
return true;
} else {
extensionDisplayName = extension.displayName ?? '';
}
} else {
extensionDisplayName = initialHandler.extensionDisplayName;
}
const trusted = options?.trusted
|| this.productService.trustedExtensionProtocolHandlers?.includes(extensionId)
|| this.didUserTrustExtension(ExtensionIdentifier.toKey(extensionId));
if (!trusted) {
let uriString = uri.toString(false);
if (uriString.length > 40) {
uriString = `${uriString.substring(0, 30)}...${uriString.substring(uriString.length - 5)}`;
}
const result = await this.dialogService.confirm({
message: localize('confirmUrl', "Allow '{0}' extension to open this URI?", extensionDisplayName),
checkbox: {
label: localize('rememberConfirmUrl', "Do not ask me again for this extension"),
},
detail: uriString,
primaryButton: localize({ key: 'open', comment: ['&& denotes a mnemonic'] }, "&&Open")
});
if (!result.confirmed) {
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/cancel', { extensionId });
return true;
}
if (result.checkboxChecked) {
this.userTrustedExtensionsStorage.add(ExtensionIdentifier.toKey(extensionId));
}
}
const handler = this.extensionHandlers.get(ExtensionIdentifier.toKey(extensionId));
if (handler) {
if (!initialHandler) {
// forward it directly
return await this.handleURLByExtension(extensionId, handler, uri, options);
}
// let the ExtensionUrlHandler instance handle this
return false;
}
// collect URI for eventual extension activation
const timestamp = new Date().getTime();
let uris = this.uriBuffer.get(ExtensionIdentifier.toKey(extensionId));
if (!uris) {
uris = [];
this.uriBuffer.set(ExtensionIdentifier.toKey(extensionId), uris);
}
uris.push({ timestamp, uri });
// activate the extension using ActivationKind.Immediate because URI handling might be part
// of resolving authorities (via authentication extensions)
await this.extensionService.activateByEvent(`onUri:${ExtensionIdentifier.toKey(extensionId)}`, ActivationKind.Immediate);
return true;
}
registerExtensionHandler(extensionId: ExtensionIdentifier, handler: IExtensionContributedURLHandler): void {
this.extensionHandlers.set(ExtensionIdentifier.toKey(extensionId), handler);
const uris = this.uriBuffer.get(ExtensionIdentifier.toKey(extensionId)) || [];
for (const { uri } of uris) {
this.handleURLByExtension(extensionId, handler, uri);
}
this.uriBuffer.delete(ExtensionIdentifier.toKey(extensionId));
}
unregisterExtensionHandler(extensionId: ExtensionIdentifier): void {
this.extensionHandlers.delete(ExtensionIdentifier.toKey(extensionId));
}
private async handleURLByExtension(extensionId: ExtensionIdentifier | string, handler: IURLHandler, uri: URI, options?: IOpenURLOptions): Promise<boolean> {
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/end', { extensionId: ExtensionIdentifier.toKey(extensionId) });
return await handler.handleURL(uri, options);
}
private async handleUnhandledURL(uri: URI, extensionId: string, options?: IOpenURLOptions): Promise<void> {
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/install_extension/start', { extensionId });
try {
await this.commandService.executeCommand('workbench.extensions.installExtension', extensionId, {
justification: {
reason: `${localize('installDetail', "This extension wants to open a URI:")}\n${uri.toString()}`,
action: localize('openUri', "Open URI")
},
enable: true
});
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/install_extension/accept', { extensionId });
} catch (error) {
if (isCancellationError(error)) {
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/install_extension/cancel', { extensionId });
} else {
this.telemetryService.publicLog2<ExtensionUrlHandlerEvent, ExtensionUrlHandlerClassification>('uri_invoked/install_extension/error', { extensionId });
this.notificationService.error(error);
}
return;
}
const extension = await this.extensionService.getExtension(extensionId);
if (extension) {
await this.handleURL(uri, { ...options, trusted: true });
}
/* Extension cannot be added and require window reload */
else {
this.telemetryService.publicLog2<ExtensionUrlReloadHandlerEvent, ExtensionUrlReloadHandlerClassification>('uri_invoked/install_extension/reload', { extensionId, isRemote: !!this.workbenchEnvironmentService.remoteAuthority });
const result = await this.dialogService.confirm({
message: localize('reloadAndHandle', "Extension '{0}' is not loaded. Would you like to reload the window to load the extension and open the URL?", extensionId),
primaryButton: localize({ key: 'reloadAndOpen', comment: ['&& denotes a mnemonic'] }, "&&Reload Window and Open")
});
if (!result.confirmed) {
return;
}
this.storageService.store(URL_TO_HANDLE, JSON.stringify(uri.toJSON()), StorageScope.WORKSPACE, StorageTarget.MACHINE);
await this.hostService.reload();
}
}
// forget about all uris buffered more than 5 minutes ago
private garbageCollect(): void {
const now = new Date().getTime();
const uriBuffer = new Map<string, { timestamp: number; uri: URI }[]>();
this.uriBuffer.forEach((uris, extensionId) => {
uris = uris.filter(({ timestamp }) => now - timestamp < FIVE_MINUTES);
if (uris.length > 0) {
uriBuffer.set(extensionId, uris);
}
});
this.uriBuffer = uriBuffer;
}
private didUserTrustExtension(id: string): boolean {
if (this.userTrustedExtensionsStorage.has(id)) {
return true;
}
return this.getConfirmedTrustedExtensionIdsFromConfiguration().indexOf(id) > -1;
}
private getConfirmedTrustedExtensionIdsFromConfiguration(): Array<string> {
const trustedExtensionIds = this.configurationService.getValue(USER_TRUSTED_EXTENSIONS_CONFIGURATION_KEY);
if (!Array.isArray(trustedExtensionIds)) {
return [];
}
return trustedExtensionIds;
}
dispose(): void {
this.disposable.dispose();
this.extensionHandlers.clear();
this.uriBuffer.clear();
}
}
registerSingleton(IExtensionUrlHandler, ExtensionUrlHandler, InstantiationType.Eager);
/**
* This class handles URLs before `ExtensionUrlHandler` is instantiated.
* More info: https://github.com/microsoft/vscode/issues/73101
*/
class ExtensionUrlBootstrapHandler implements IWorkbenchContribution, IURLHandler {
static readonly ID = 'workbench.contrib.extensionUrlBootstrapHandler';
private static _cache: [URI, IOpenURLOptions | undefined][] = [];
private static disposable: IDisposable;
static get cache(): [URI, IOpenURLOptions | undefined][] {
ExtensionUrlBootstrapHandler.disposable.dispose();
const result = ExtensionUrlBootstrapHandler._cache;
ExtensionUrlBootstrapHandler._cache = [];
return result;
}
constructor(@IURLService urlService: IURLService) {
ExtensionUrlBootstrapHandler.disposable = urlService.registerHandler(this);
}
async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
if (!isExtensionId(uri.authority)) {
return false;
}
ExtensionUrlBootstrapHandler._cache.push([uri, options]);
return true;
}
}
registerWorkbenchContribution2(ExtensionUrlBootstrapHandler.ID, ExtensionUrlBootstrapHandler, WorkbenchPhase.BlockRestore /* registration only */);
class ManageAuthorizedExtensionURIsAction extends Action2 {
constructor() {
super({
id: 'workbench.extensions.action.manageAuthorizedExtensionURIs',
title: localize2('manage', 'Manage Authorized Extension URIs...'),
category: localize2('extensions', 'Extensions'),
menu: {
id: MenuId.CommandPalette,
when: IsWebContext.toNegated()
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const storageService = accessor.get(IStorageService);
const quickInputService = accessor.get(IQuickInputService);
const storage = new UserTrustedExtensionIdStorage(storageService);
const items = storage.extensions.map((label): IQuickPickItem => ({ label, picked: true }));
if (items.length === 0) {
await quickInputService.pick([{ label: localize('no', 'There are currently no authorized extension URIs.') }]);
return;
}
const result = await quickInputService.pick(items, { canPickMany: true });
if (!result) {
return;
}
storage.set(result.map(item => item.label));
}
}
registerAction2(ManageAuthorizedExtensionURIsAction);