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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isStandalone } from 'vs/base/browser/browser';
import { CancellationToken } from 'vs/base/common/cancellation';
import { parse } from 'vs/base/common/marshalling';
import { Emitter } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { isEqual } from 'vs/base/common/resources';
import { URI, UriComponents } from 'vs/base/common/uri';
import { request } from 'vs/base/parts/request/browser/request';
import product from 'vs/platform/product/common/product';
import { isFolderToOpen, isWorkspaceToOpen } from 'vs/platform/window/common/window';
import { create, ICredentialsProvider, IURLCallbackProvider, IWorkbenchConstructionOptions, IWorkspace, IWorkspaceProvider } from 'vs/workbench/workbench.web.main';
import { posix } from 'vs/base/common/path';
import { ltrim } from 'vs/base/common/strings';
interface ICredential {
service: string;
account: string;
password: string;
}
class LocalStorageCredentialsProvider implements ICredentialsProvider {
private static readonly CREDENTIALS_STORAGE_KEY = 'credentials.provider';
private readonly authService: string | undefined;
constructor() {
let authSessionInfo: { readonly id: string; readonly accessToken: string; readonly providerId: string; readonly canSignOut?: boolean; readonly scopes: string[][] } | undefined;
const authSessionElement = document.getElementById('vscode-workbench-auth-session');
const authSessionElementAttribute = authSessionElement ? authSessionElement.getAttribute('data-settings') : undefined;
if (authSessionElementAttribute) {
try {
authSessionInfo = JSON.parse(authSessionElementAttribute);
} catch (error) { /* Invalid session is passed. Ignore. */ }
}
if (authSessionInfo) {
// Settings Sync Entry
this.setPassword(`${product.urlProtocol}.login`, 'account', JSON.stringify(authSessionInfo));
// Auth extension Entry
this.authService = `${product.urlProtocol}-${authSessionInfo.providerId}.login`;
this.setPassword(this.authService, 'account', JSON.stringify(authSessionInfo.scopes.map(scopes => ({
id: authSessionInfo!.id,
scopes,
accessToken: authSessionInfo!.accessToken
}))));
}
}
private _credentials: ICredential[] | undefined;
private get credentials(): ICredential[] {
if (!this._credentials) {
try {
const serializedCredentials = window.localStorage.getItem(LocalStorageCredentialsProvider.CREDENTIALS_STORAGE_KEY);
if (serializedCredentials) {
this._credentials = JSON.parse(serializedCredentials);
}
} catch (error) {
// ignore
}
if (!Array.isArray(this._credentials)) {
this._credentials = [];
}
}
return this._credentials;
}
private save(): void {
window.localStorage.setItem(LocalStorageCredentialsProvider.CREDENTIALS_STORAGE_KEY, JSON.stringify(this.credentials));
}
async getPassword(service: string, account: string): Promise<string | null> {
return this.doGetPassword(service, account);
}
private async doGetPassword(service: string, account?: string): Promise<string | null> {
for (const credential of this.credentials) {
if (credential.service === service) {
if (typeof account !== 'string' || account === credential.account) {
return credential.password;
}
}
}
return null;
}
async setPassword(service: string, account: string, password: string): Promise<void> {
this.doDeletePassword(service, account);
this.credentials.push({ service, account, password });
this.save();
try {
if (password && service === this.authService) {
const value = JSON.parse(password);
if (Array.isArray(value) && value.length === 0) {
await this.logout(service);
}
}
} catch (error) {
console.log(error);
}
}
async deletePassword(service: string, account: string): Promise<boolean> {
const result = await this.doDeletePassword(service, account);
if (result && service === this.authService) {
try {
await this.logout(service);
} catch (error) {
console.log(error);
}
}
return result;
}
private async doDeletePassword(service: string, account: string): Promise<boolean> {
let found = false;
this._credentials = this.credentials.filter(credential => {
if (credential.service === service && credential.account === account) {
found = true;
return false;
}
return true;
});
if (found) {
this.save();
}
return found;
}
async findPassword(service: string): Promise<string | null> {
return this.doGetPassword(service);
}
async findCredentials(service: string): Promise<Array<{ account: string; password: string }>> {
return this.credentials
.filter(credential => credential.service === service)
.map(({ account, password }) => ({ account, password }));
}
private async logout(service: string): Promise<void> {
const queryValues: Map<string, string> = new Map();
queryValues.set('logout', String(true));
queryValues.set('service', service);
await request({
url: doCreateUri('/auth/logout', queryValues).toString(true)
}, CancellationToken.None);
}
async clear(): Promise<void> {
window.localStorage.removeItem(LocalStorageCredentialsProvider.CREDENTIALS_STORAGE_KEY);
}
}
class LocalStorageURLCallbackProvider extends Disposable implements IURLCallbackProvider {
private static REQUEST_ID = 0;
private static QUERY_KEYS: ('scheme' | 'authority' | 'path' | 'query' | 'fragment')[] = [
'scheme',
'authority',
'path',
'query',
'fragment'
];
private readonly _onCallback = this._register(new Emitter<URI>());
readonly onCallback = this._onCallback.event;
private pendingCallbacks = new Set<number>();
private lastTimeChecked = Date.now();
private checkCallbacksTimeout: unknown | undefined = undefined;
private onDidChangeLocalStorageDisposable: IDisposable | undefined;
constructor(private readonly _callbackRoute: string) {
super();
}
create(options: Partial<UriComponents> = {}): URI {
const id = ++LocalStorageURLCallbackProvider.REQUEST_ID;
const queryParams: string[] = [`vscode-reqid=${id}`];
for (const key of LocalStorageURLCallbackProvider.QUERY_KEYS) {
const value = options[key];
if (value) {
queryParams.push(`vscode-${key}=${encodeURIComponent(value)}`);
}
}
// TODO@joao remove eventually
// https://github.com/microsoft/vscode-dev/issues/62
// https://github.com/microsoft/vscode/blob/159479eb5ae451a66b5dac3c12d564f32f454796/extensions/github-authentication/src/githubServer.ts#L50-L50
if (!(options.authority === 'vscode.github-authentication' && options.path === '/dummy')) {
const key = `vscode-web.url-callbacks[${id}]`;
window.localStorage.removeItem(key);
this.pendingCallbacks.add(id);
this.startListening();
}
return URI.parse(window.location.href).with({ path: this._callbackRoute, query: queryParams.join('&') });
}
private startListening(): void {
if (this.onDidChangeLocalStorageDisposable) {
return;
}
const fn = () => this.onDidChangeLocalStorage();
window.addEventListener('storage', fn);
this.onDidChangeLocalStorageDisposable = { dispose: () => window.removeEventListener('storage', fn) };
}
private stopListening(): void {
this.onDidChangeLocalStorageDisposable?.dispose();
this.onDidChangeLocalStorageDisposable = undefined;
}
// this fires every time local storage changes, but we
// don't want to check more often than once a second
private async onDidChangeLocalStorage(): Promise<void> {
const ellapsed = Date.now() - this.lastTimeChecked;
if (ellapsed > 1000) {
this.checkCallbacks();
} else if (this.checkCallbacksTimeout === undefined) {
this.checkCallbacksTimeout = setTimeout(() => {
this.checkCallbacksTimeout = undefined;
this.checkCallbacks();
}, 1000 - ellapsed);
}
}
private checkCallbacks(): void {
let pendingCallbacks: Set<number> | undefined;
for (const id of this.pendingCallbacks) {
const key = `vscode-web.url-callbacks[${id}]`;
const result = window.localStorage.getItem(key);
if (result !== null) {
try {
this._onCallback.fire(URI.revive(JSON.parse(result)));
} catch (error) {
console.error(error);
}
pendingCallbacks = pendingCallbacks ?? new Set(this.pendingCallbacks);
pendingCallbacks.delete(id);
window.localStorage.removeItem(key);
}
}
if (pendingCallbacks) {
this.pendingCallbacks = pendingCallbacks;
if (this.pendingCallbacks.size === 0) {
this.stopListening();
}
}
this.lastTimeChecked = Date.now();
}
}
class WorkspaceProvider implements IWorkspaceProvider {
private static QUERY_PARAM_EMPTY_WINDOW = 'ew';
private static QUERY_PARAM_FOLDER = 'folder';
private static QUERY_PARAM_WORKSPACE = 'workspace';
private static QUERY_PARAM_PAYLOAD = 'payload';
static create(config: IWorkbenchConstructionOptions & { folderUri?: UriComponents; workspaceUri?: UriComponents }) {
let foundWorkspace = false;
let workspace: IWorkspace;
let payload = Object.create(null);
const query = new URL(document.location.href).searchParams;
query.forEach((value, key) => {
switch (key) {
// Folder
case WorkspaceProvider.QUERY_PARAM_FOLDER:
if (config.remoteAuthority && value.startsWith(posix.sep)) {
// when connected to a remote and having a value
// that is a path (begins with a `/`), assume this
// is a vscode-remote resource as simplified URL.
workspace = { folderUri: URI.from({ scheme: Schemas.vscodeRemote, path: value, authority: config.remoteAuthority }) };
} else {
workspace = { folderUri: URI.parse(value) };
}
foundWorkspace = true;
break;
// Workspace
case WorkspaceProvider.QUERY_PARAM_WORKSPACE:
if (config.remoteAuthority && value.startsWith(posix.sep)) {
// when connected to a remote and having a value
// that is a path (begins with a `/`), assume this
// is a vscode-remote resource as simplified URL.
workspace = { workspaceUri: URI.from({ scheme: Schemas.vscodeRemote, path: value, authority: config.remoteAuthority }) };
} else {
workspace = { workspaceUri: URI.parse(value) };
}
foundWorkspace = true;
break;
// Empty
case WorkspaceProvider.QUERY_PARAM_EMPTY_WINDOW:
workspace = undefined;
foundWorkspace = true;
break;
// Payload
case WorkspaceProvider.QUERY_PARAM_PAYLOAD:
try {
payload = parse(value); // use marshalling#parse() to revive potential URIs
} catch (error) {
console.error(error); // possible invalid JSON
}
break;
}
});
// If no workspace is provided through the URL, check for config
// attribute from server
if (!foundWorkspace) {
if (config.folderUri) {
workspace = { folderUri: URI.revive(config.folderUri) };
} else if (config.workspaceUri) {
workspace = { workspaceUri: URI.revive(config.workspaceUri) };
}
}
return new WorkspaceProvider(workspace, payload, config);
}
readonly trusted = true;
private constructor(
readonly workspace: IWorkspace,
readonly payload: object,
private readonly config: IWorkbenchConstructionOptions
) {
}
async open(workspace: IWorkspace, options?: { reuse?: boolean; payload?: object }): Promise<boolean> {
if (options?.reuse && !options.payload && this.isSame(this.workspace, workspace)) {
return true; // return early if workspace and environment is not changing and we are reusing window
}
const targetHref = this.createTargetUrl(workspace, options);
if (targetHref) {
if (options?.reuse) {
window.location.href = targetHref;
return true;
} else {
let result;
if (isStandalone()) {
result = window.open(targetHref, '_blank', 'toolbar=no'); // ensures to open another 'standalone' window!
} else {
result = window.open(targetHref);
}
return !!result;
}
}
return false;
}
private createTargetUrl(workspace: IWorkspace, options?: { reuse?: boolean; payload?: object }): string | undefined {
// Empty
let targetHref: string | undefined = undefined;
if (!workspace) {
targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_EMPTY_WINDOW}=true`;
}
// Folder
else if (isFolderToOpen(workspace)) {
let queryParamFolder: string;
if (this.config.remoteAuthority && workspace.folderUri.scheme === Schemas.vscodeRemote) {
// when connected to a remote and having a folder
// for that remote, only use the path as query
// value to form shorter, nicer URLs.
// ensure paths are absolute (begin with `/`)
// clipboard: ltrim(workspace.folderUri.path, posix.sep)
queryParamFolder = `${posix.sep}${ltrim(workspace.folderUri.path, posix.sep)}`;
} else {
queryParamFolder = encodeURIComponent(workspace.folderUri.toString(true));
}
targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_FOLDER}=${queryParamFolder}`;
}
// Workspace
else if (isWorkspaceToOpen(workspace)) {
let queryParamWorkspace: string;
if (this.config.remoteAuthority && workspace.workspaceUri.scheme === Schemas.vscodeRemote) {
// when connected to a remote and having a workspace
// for that remote, only use the path as query
// value to form shorter, nicer URLs.
// ensure paths are absolute (begin with `/`)
queryParamWorkspace = `${posix.sep}${ltrim(workspace.workspaceUri.path, posix.sep)}`;
} else {
queryParamWorkspace = encodeURIComponent(workspace.workspaceUri.toString(true));
}
targetHref = `${document.location.origin}${document.location.pathname}?${WorkspaceProvider.QUERY_PARAM_WORKSPACE}=${queryParamWorkspace}`;
}
// Append payload if any
if (options?.payload) {
targetHref += `&${WorkspaceProvider.QUERY_PARAM_PAYLOAD}=${encodeURIComponent(JSON.stringify(options.payload))}`;
}
return targetHref;
}
private isSame(workspaceA: IWorkspace, workspaceB: IWorkspace): boolean {
if (!workspaceA || !workspaceB) {
return workspaceA === workspaceB; // both empty
}
if (isFolderToOpen(workspaceA) && isFolderToOpen(workspaceB)) {
return isEqual(workspaceA.folderUri, workspaceB.folderUri); // same workspace
}
if (isWorkspaceToOpen(workspaceA) && isWorkspaceToOpen(workspaceB)) {
return isEqual(workspaceA.workspaceUri, workspaceB.workspaceUri); // same workspace
}
return false;
}
hasRemote(): boolean {
if (this.workspace) {
if (isFolderToOpen(this.workspace)) {
return this.workspace.folderUri.scheme === Schemas.vscodeRemote;
}
if (isWorkspaceToOpen(this.workspace)) {
return this.workspace.workspaceUri.scheme === Schemas.vscodeRemote;
}
}
return true;
}
}
function doCreateUri(path: string, queryValues: Map<string, string>): URI {
let query: string | undefined = undefined;
if (queryValues) {
let index = 0;
queryValues.forEach((value, key) => {
if (!query) {
query = '';
}
const prefix = (index++ === 0) ? '' : '&';
query += `${prefix}${key}=${encodeURIComponent(value)}`;
});
}
return URI.parse(window.location.href).with({ path, query });
}
(function () {
// Find config by checking for DOM
const configElement = document.getElementById('vscode-workbench-web-configuration');
const configElementAttribute = configElement ? configElement.getAttribute('data-settings') : undefined;
if (!configElement || !configElementAttribute) {
throw new Error('Missing web configuration element');
}
const config: IWorkbenchConstructionOptions & { folderUri?: UriComponents; workspaceUri?: UriComponents; callbackRoute: string } = JSON.parse(configElementAttribute);
// Create workbench
create(document.body, {
...config,
settingsSyncOptions: config.settingsSyncOptions ? {
enabled: config.settingsSyncOptions.enabled,
} : undefined,
workspaceProvider: WorkspaceProvider.create(config),
urlCallbackProvider: new LocalStorageURLCallbackProvider(config.callbackRoute),
credentialsProvider: config.remoteAuthority ? undefined : new LocalStorageCredentialsProvider() // with a remote, we don't use a local credentials provider
});
})();
|