use-github-pat.patch 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. diff --git a/extensions/github-authentication/src/githubServer.ts b/extensions/github-authentication/src/githubServer.ts
  2. index c366ff3..75f32da 100644
  3. --- a/extensions/github-authentication/src/githubServer.ts
  4. +++ b/extensions/github-authentication/src/githubServer.ts
  5. @@ -3,27 +3,13 @@
  6. * Licensed under the MIT License. See License.txt in the project root for license information.
  7. *--------------------------------------------------------------------------------------------*/
  8. -import * as nls from 'vscode-nls';
  9. import * as vscode from 'vscode';
  10. import fetch, { Response } from 'node-fetch';
  11. -import { v4 as uuid } from 'uuid';
  12. -import { PromiseAdapter, promiseFromEvent } from './common/utils';
  13. import { ExperimentationTelemetry } from './experimentationService';
  14. import { AuthProviderType } from './github';
  15. import { Log } from './common/logger';
  16. -import { isSupportedEnvironment } from './common/env';
  17. -import { LoopbackAuthServer } from './authServer';
  18. -import path = require('path');
  19. -
  20. -const localize = nls.loadMessageBundle();
  21. -const CLIENT_ID = '01ab8ac9400c4e429b23';
  22. -const GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize';
  23. -// TODO: change to stable when that happens
  24. -const GITHUB_TOKEN_URL = 'https://vscode.dev/codeExchangeProxyEndpoints/github/login/oauth/access_token';
  25. -const NETWORK_ERROR = 'network error';
  26. -const REDIRECT_URL_STABLE = 'https://vscode.dev/redirect';
  27. -const REDIRECT_URL_INSIDERS = 'https://insiders.vscode.dev/redirect';
  28. +const NETWORK_ERROR = 'network error';
  29. class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.UriHandler {
  30. constructor(private readonly Logger: Log) {
  31. @@ -43,14 +29,6 @@ export interface IGitHubServer extends vscode.Disposable {
  32. friendlyName: string;
  33. type: AuthProviderType;
  34. }
  35. -
  36. -interface IGitHubDeviceCodeResponse {
  37. - device_code: string;
  38. - user_code: string;
  39. - verification_uri: string;
  40. - interval: number;
  41. -}
  42. -
  43. async function getScopes(token: string, serverUri: vscode.Uri, logger: Log): Promise<string[]> {
  44. try {
  45. logger.info('Getting token scopes...');
  46. @@ -118,23 +96,11 @@ export class GitHubServer implements IGitHubServer {
  47. friendlyName = 'GitHub';
  48. type = AuthProviderType.github;
  49. - private _pendingNonces = new Map<string, string[]>();
  50. - private _codeExchangePromises = new Map<string, { promise: Promise<string>; cancel: vscode.EventEmitter<void> }>();
  51. private _disposable: vscode.Disposable;
  52. private _uriHandler = new UriEventHandler(this._logger);
  53. - private readonly getRedirectEndpoint: Thenable<string>;
  54. - constructor(private readonly _supportDeviceCodeFlow: boolean, private readonly _logger: Log, private readonly _telemetryReporter: ExperimentationTelemetry) {
  55. + constructor(_supportDeviceCodeFlow: boolean, private readonly _logger: Log, private readonly _telemetryReporter: ExperimentationTelemetry) {
  56. this._disposable = vscode.window.registerUriHandler(this._uriHandler);
  57. -
  58. - this.getRedirectEndpoint = vscode.commands.executeCommand<{ [providerId: string]: string } | undefined>('workbench.getCodeExchangeProxyEndpoints').then((proxyEndpoints) => {
  59. - // If we are running in insiders vscode.dev, then ensure we use the redirect route on that.
  60. - let redirectUri = REDIRECT_URL_STABLE;
  61. - if (proxyEndpoints?.github && new URL(proxyEndpoints.github).hostname === 'insiders.vscode.dev') {
  62. - redirectUri = REDIRECT_URL_INSIDERS;
  63. - }
  64. - return redirectUri;
  65. - });
  66. }
  67. dispose() {
  68. @@ -152,181 +118,17 @@ export class GitHubServer implements IGitHubServer {
  69. // Used for showing a friendlier message to the user when the explicitly cancel a flow.
  70. let userCancelled: boolean | undefined;
  71. - const yes = localize('yes', "Yes");
  72. - const no = localize('no', "No");
  73. - const promptToContinue = async () => {
  74. - if (userCancelled === undefined) {
  75. - // We haven't had a failure yet so wait to prompt
  76. - return;
  77. - }
  78. - const message = userCancelled
  79. - ? localize('userCancelledMessage', "Having trouble logging in? Would you like to try a different way?")
  80. - : localize('otherReasonMessage', "You have not yet finished authorizing this extension to use GitHub. Would you like to keep trying?");
  81. - const result = await vscode.window.showWarningMessage(message, yes, no);
  82. - if (result !== yes) {
  83. - throw new Error('Cancelled');
  84. - }
  85. - };
  86. -
  87. - const nonce = uuid();
  88. - const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate?nonce=${encodeURIComponent(nonce)}`));
  89. -
  90. - const supported = isSupportedEnvironment(callbackUri);
  91. - if (supported) {
  92. - try {
  93. - return await this.doLoginWithoutLocalServer(scopes, nonce, callbackUri);
  94. - } catch (e) {
  95. - this._logger.error(e);
  96. - userCancelled = e.message ?? e === 'User Cancelled';
  97. - }
  98. - }
  99. -
  100. - // Starting a local server isn't supported in web
  101. - if (vscode.env.uiKind === vscode.UIKind.Desktop) {
  102. - try {
  103. - await promptToContinue();
  104. - return await this.doLoginWithLocalServer(scopes);
  105. - } catch (e) {
  106. - this._logger.error(e);
  107. - userCancelled = e.message ?? e === 'User Cancelled';
  108. - }
  109. - }
  110. - if (this._supportDeviceCodeFlow) {
  111. - try {
  112. - await promptToContinue();
  113. - return await this.doLoginDeviceCodeFlow(scopes);
  114. - } catch (e) {
  115. - this._logger.error(e);
  116. - userCancelled = e.message ?? e === 'User Cancelled';
  117. - }
  118. - } else if (!supported) {
  119. - try {
  120. - await promptToContinue();
  121. - return await this.doLoginWithPat(scopes);
  122. - } catch (e) {
  123. - this._logger.error(e);
  124. - userCancelled = e.message ?? e === 'User Cancelled';
  125. - }
  126. + try {
  127. + return await this.doLoginWithPat(scopes);
  128. + } catch (e) {
  129. + this._logger.error(e);
  130. + userCancelled = e.message ?? e === 'User Cancelled';
  131. }
  132. throw new Error(userCancelled ? 'Cancelled' : 'No auth flow succeeded.');
  133. }
  134. - private async doLoginWithoutLocalServer(scopes: string, nonce: string, callbackUri: vscode.Uri): Promise<string> {
  135. - this._logger.info(`Trying without local server... (${scopes})`);
  136. - return await vscode.window.withProgress<string>({
  137. - location: vscode.ProgressLocation.Notification,
  138. - title: localize('signingIn', "Signing in to github.com..."),
  139. - cancellable: true
  140. - }, async (_, token) => {
  141. - const existingNonces = this._pendingNonces.get(scopes) || [];
  142. - this._pendingNonces.set(scopes, [...existingNonces, nonce]);
  143. - const redirectUri = await this.getRedirectEndpoint;
  144. - const searchParams = new URLSearchParams([
  145. - ['client_id', CLIENT_ID],
  146. - ['redirect_uri', redirectUri],
  147. - ['scope', scopes],
  148. - ['state', encodeURIComponent(callbackUri.toString(true))]
  149. - ]);
  150. - const uri = vscode.Uri.parse(`${GITHUB_AUTHORIZE_URL}?${searchParams.toString()}`);
  151. - await vscode.env.openExternal(uri);
  152. -
  153. - // Register a single listener for the URI callback, in case the user starts the login process multiple times
  154. - // before completing it.
  155. - let codeExchangePromise = this._codeExchangePromises.get(scopes);
  156. - if (!codeExchangePromise) {
  157. - codeExchangePromise = promiseFromEvent(this._uriHandler.event, this.handleUri(scopes));
  158. - this._codeExchangePromises.set(scopes, codeExchangePromise);
  159. - }
  160. -
  161. - try {
  162. - return await Promise.race([
  163. - codeExchangePromise.promise,
  164. - new Promise<string>((_, reject) => setTimeout(() => reject('Cancelled'), 60000)),
  165. - promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject('User Cancelled'); }).promise
  166. - ]);
  167. - } finally {
  168. - this._pendingNonces.delete(scopes);
  169. - codeExchangePromise?.cancel.fire();
  170. - this._codeExchangePromises.delete(scopes);
  171. - }
  172. - });
  173. - }
  174. -
  175. - private async doLoginWithLocalServer(scopes: string): Promise<string> {
  176. - this._logger.info(`Trying with local server... (${scopes})`);
  177. - return await vscode.window.withProgress<string>({
  178. - location: vscode.ProgressLocation.Notification,
  179. - title: localize('signingInAnotherWay', "Signing in to github.com..."),
  180. - cancellable: true
  181. - }, async (_, token) => {
  182. - const redirectUri = await this.getRedirectEndpoint;
  183. - const searchParams = new URLSearchParams([
  184. - ['client_id', CLIENT_ID],
  185. - ['redirect_uri', redirectUri],
  186. - ['scope', scopes],
  187. - ]);
  188. - const loginUrl = `${GITHUB_AUTHORIZE_URL}?${searchParams.toString()}`;
  189. - const server = new LoopbackAuthServer(path.join(__dirname, '../media'), loginUrl);
  190. - const port = await server.start();
  191. -
  192. - let codeToExchange;
  193. - try {
  194. - vscode.env.openExternal(vscode.Uri.parse(`http://127.0.0.1:${port}/signin?nonce=${encodeURIComponent(server.nonce)}`));
  195. - const { code } = await Promise.race([
  196. - server.waitForOAuthResponse(),
  197. - new Promise<any>((_, reject) => setTimeout(() => reject('Cancelled'), 60000)),
  198. - promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject('User Cancelled'); }).promise
  199. - ]);
  200. - codeToExchange = code;
  201. - } finally {
  202. - setTimeout(() => {
  203. - void server.stop();
  204. - }, 5000);
  205. - }
  206. -
  207. - const accessToken = await this.exchangeCodeForToken(codeToExchange);
  208. - return accessToken;
  209. - });
  210. - }
  211. -
  212. - private async doLoginDeviceCodeFlow(scopes: string): Promise<string> {
  213. - this._logger.info(`Trying device code flow... (${scopes})`);
  214. -
  215. - // Get initial device code
  216. - const uri = `https://github.com/login/device/code?client_id=${CLIENT_ID}&scope=${scopes}`;
  217. - const result = await fetch(uri, {
  218. - method: 'POST',
  219. - headers: {
  220. - Accept: 'application/json'
  221. - }
  222. - });
  223. - if (!result.ok) {
  224. - throw new Error(`Failed to get one-time code: ${await result.text()}`);
  225. - }
  226. -
  227. - const json = await result.json() as IGitHubDeviceCodeResponse;
  228. -
  229. -
  230. - const modalResult = await vscode.window.showInformationMessage(
  231. - localize('code.title', "Your Code: {0}", json.user_code),
  232. - {
  233. - modal: true,
  234. - detail: localize('code.detail', "To finish authenticating, navigate to GitHub and paste in the above one-time code.")
  235. - }, 'Copy & Continue to GitHub');
  236. -
  237. - if (modalResult !== 'Copy & Continue to GitHub') {
  238. - throw new Error('User Cancelled');
  239. - }
  240. -
  241. - await vscode.env.clipboard.writeText(json.user_code);
  242. -
  243. - const uriToOpen = await vscode.env.asExternalUri(vscode.Uri.parse(json.verification_uri));
  244. - await vscode.env.openExternal(uriToOpen);
  245. -
  246. - return await this.waitForDeviceCodeAccessToken(json);
  247. - }
  248. private async doLoginWithPat(scopes: string): Promise<string> {
  249. this._logger.info(`Trying to retrieve PAT... (${scopes})`);
  250. @@ -351,118 +153,6 @@ export class GitHubServer implements IGitHubServer {
  251. return token;
  252. }
  253. - private async waitForDeviceCodeAccessToken(
  254. - json: IGitHubDeviceCodeResponse,
  255. - ): Promise<string> {
  256. - return await vscode.window.withProgress<string>({
  257. - location: vscode.ProgressLocation.Notification,
  258. - cancellable: true,
  259. - title: localize(
  260. - 'progress',
  261. - "Open [{0}]({0}) in a new tab and paste your one-time code: {1}",
  262. - json.verification_uri,
  263. - json.user_code)
  264. - }, async (_, token) => {
  265. - const refreshTokenUri = `https://github.com/login/oauth/access_token?client_id=${CLIENT_ID}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`;
  266. -
  267. - // Try for 2 minutes
  268. - const attempts = 120 / json.interval;
  269. - for (let i = 0; i < attempts; i++) {
  270. - await new Promise(resolve => setTimeout(resolve, json.interval * 1000));
  271. - if (token.isCancellationRequested) {
  272. - throw new Error('User Cancelled');
  273. - }
  274. - let accessTokenResult;
  275. - try {
  276. - accessTokenResult = await fetch(refreshTokenUri, {
  277. - method: 'POST',
  278. - headers: {
  279. - Accept: 'application/json'
  280. - }
  281. - });
  282. - } catch {
  283. - continue;
  284. - }
  285. -
  286. - if (!accessTokenResult.ok) {
  287. - continue;
  288. - }
  289. -
  290. - const accessTokenJson = await accessTokenResult.json();
  291. -
  292. - if (accessTokenJson.error === 'authorization_pending') {
  293. - continue;
  294. - }
  295. -
  296. - if (accessTokenJson.error) {
  297. - throw new Error(accessTokenJson.error_description);
  298. - }
  299. -
  300. - return accessTokenJson.access_token;
  301. - }
  302. -
  303. - throw new Error('Cancelled');
  304. - });
  305. - }
  306. -
  307. - private handleUri: (scopes: string) => PromiseAdapter<vscode.Uri, string> =
  308. - (scopes) => (uri, resolve, reject) => {
  309. - const query = new URLSearchParams(uri.query);
  310. - const code = query.get('code');
  311. - const nonce = query.get('nonce');
  312. - if (!code) {
  313. - reject(new Error('No code'));
  314. - return;
  315. - }
  316. - if (!nonce) {
  317. - reject(new Error('No nonce'));
  318. - return;
  319. - }
  320. -
  321. - const acceptedNonces = this._pendingNonces.get(scopes) || [];
  322. - if (!acceptedNonces.includes(nonce)) {
  323. - // A common scenario of this happening is if you:
  324. - // 1. Trigger a sign in with one set of scopes
  325. - // 2. Before finishing 1, you trigger a sign in with a different set of scopes
  326. - // In this scenario we should just return and wait for the next UriHandler event
  327. - // to run as we are probably still waiting on the user to hit 'Continue'
  328. - this._logger.info('Nonce not found in accepted nonces. Skipping this execution...');
  329. - return;
  330. - }
  331. -
  332. - resolve(this.exchangeCodeForToken(code));
  333. - };
  334. -
  335. - private async exchangeCodeForToken(code: string): Promise<string> {
  336. - this._logger.info('Exchanging code for token...');
  337. -
  338. - const proxyEndpoints: { [providerId: string]: string } | undefined = await vscode.commands.executeCommand('workbench.getCodeExchangeProxyEndpoints');
  339. - const endpointUrl = proxyEndpoints?.github ? `${proxyEndpoints.github}login/oauth/access_token` : GITHUB_TOKEN_URL;
  340. -
  341. - const body = `code=${code}`;
  342. - const result = await fetch(endpointUrl, {
  343. - method: 'POST',
  344. - headers: {
  345. - Accept: 'application/json',
  346. - 'Content-Type': 'application/x-www-form-urlencoded',
  347. - 'Content-Length': body.toString()
  348. -
  349. - },
  350. - body
  351. - });
  352. -
  353. - if (result.ok) {
  354. - const json = await result.json();
  355. - this._logger.info('Token exchange success!');
  356. - return json.access_token;
  357. - } else {
  358. - const text = await result.text();
  359. - const error = new Error(text);
  360. - error.name = 'GitHubTokenExchangeError';
  361. - throw error;
  362. - }
  363. - }
  364. -
  365. private getServerUri(path: string = '') {
  366. const apiUri = vscode.Uri.parse('https://api.github.com');
  367. return vscode.Uri.parse(`${apiUri.scheme}://${apiUri.authority}${path}`);
  368. diff --git a/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts b/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts
  369. index 36647e6..55e722b 100644
  370. --- a/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts
  371. +++ b/src/vs/workbench/browser/parts/activitybar/activitybarActions.ts
  372. @@ -271,7 +271,7 @@ export class AccountsActivityActionViewItem extends MenuActivityActionViewItem {
  373. }
  374. });
  375. - if (providers.length && !menus.length) {
  376. + if (!menus.length) {
  377. const noAccountsAvailableAction = disposables.add(new Action('noAccountsAvailable', localize('noAccounts', "You are not signed in to any accounts"), undefined, false));
  378. menus.push(noAccountsAvailableAction);
  379. }
  380. diff --git a/src/vs/workbench/services/authentication/browser/authenticationService.ts b/src/vs/workbench/services/authentication/browser/authenticationService.ts
  381. index f543021..ad40bc3 100644
  382. --- a/src/vs/workbench/services/authentication/browser/authenticationService.ts
  383. +++ b/src/vs/workbench/services/authentication/browser/authenticationService.ts
  384. @@ -272,16 +272,6 @@ export class AuthenticationService extends Disposable implements IAuthentication
  385. this.removeAccessRequest(id, extensionId);
  386. });
  387. }
  388. -
  389. - if (!this._authenticationProviders.size) {
  390. - this._placeholderMenuItem = MenuRegistry.appendMenuItem(MenuId.AccountsContext, {
  391. - command: {
  392. - id: 'noAuthenticationProviders',
  393. - title: nls.localize('loading', "Loading..."),
  394. - precondition: ContextKeyExpr.false()
  395. - },
  396. - });
  397. - }
  398. }
  399. async sessionsUpdate(id: string, event: AuthenticationSessionsChangeEvent): Promise<void> {