use-github-pat.patch 17 KB

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