use-github-pat.patch 16 KB

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