use-github-pat.patch 16 KB

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