use-github-pat.patch 17 KB

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