use-github-pat.patch 15 KB

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