forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubServer.ts
More file actions
178 lines (157 loc) · 5.38 KB
/
Copy pathgithubServer.ts
File metadata and controls
178 lines (157 loc) · 5.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import * as vscode from 'vscode';
import { IHostConfiguration, HostHelper } from './configuration';
import * as https from 'https';
import Logger from '../common/logger';
import { handler as uriHandler } from '../common/uri';
import { PromiseAdapter, promiseFromEmitter } from '../common/utils';
import axios from 'axios';
const SCOPES: string = 'read:user user:email repo write:discussion';
const GHE_OPTIONAL_SCOPES: object = {'write:discussion': true};
const AUTH_RELAY_SERVER = 'https://vscode-auth.github.com';
const EXTENSION_ID = 'GitHub.vscode-pull-request-github';
const CALLBACK_PATH = '/did-authenticate';
const CALLBACK_URI = vscode.version.endsWith('-insider')
? `vscode-insiders://${EXTENSION_ID}${CALLBACK_PATH}`
: `vscode://${EXTENSION_ID}${CALLBACK_PATH}`;
const MAX_TOKEN_RESPONSE_AGE = 5 * (1000 * 60 /* minutes in ms */);
export class GitHubManager {
private _servers: Map<string, boolean> = new Map().set('github.com', true);
private static GitHubScopesTable: { [key: string]: string[] } = {
repo: ['repo:status', 'repo_deployment', 'public_repo', 'repo:invite'],
'admin:org': ['write:org', 'read:org'],
'admin:public_key': ['write:public_key', 'read:public_key'],
'admin:org_hook': [],
gist: [],
notifications: [],
user: ['read:user', 'user:email', 'user:follow'],
delete_repo: [],
'write:discussion': ['read:discussion'],
'admin:gpg_key': ['write:gpg_key', 'read:gpg_key']
};
public static AppScopes: string[] = SCOPES.split(' ');
public async isGitHub(host: vscode.Uri): Promise<boolean> {
if (host === null) {
return false;
}
if (this._servers.has(host.authority)) {
return this._servers.get(host.authority);
}
const options = GitHubManager.getOptions(host, 'HEAD', '/rate_limit');
return new Promise<boolean>((resolve, _) => {
const get = https.request(options, res => {
const ret = res.headers['x-github-request-id'];
resolve(ret !== undefined);
});
get.end();
get.on('error', err => {
resolve(false);
});
}).then(isGitHub => {
this._servers.set(host.authority, isGitHub);
return isGitHub;
});
}
public static getOptions(hostUri: vscode.Uri, method: string = 'GET', path: string, token?: string) {
const headers: {
'user-agent': string;
authorization?: string;
} = {
'user-agent': 'GitHub VSCode Pull Requests',
};
if (token) {
headers.authorization = `token ${token}`;
}
return {
host: HostHelper.getApiHost(hostUri).authority,
port: 443,
method,
path: HostHelper.getApiPath(hostUri, path),
headers,
};
}
public static validateScopes(host: vscode.Uri, scopes: string): boolean {
if (!scopes) {
return false;
}
const tokenScopes = scopes.split(', ');
return this.AppScopes.every(x =>
tokenScopes.indexOf(x) >= 0 ||
tokenScopes.indexOf(this.getScopeSuperset(x)) >= 0 ||
// some scopes don't exist on older versions of GHE, treat them as optional
(this.isDotCom(host) || GHE_OPTIONAL_SCOPES[x])
);
}
private static getScopeSuperset(scope: string): string {
for (let key in this.GitHubScopesTable) {
if (this.GitHubScopesTable[key].indexOf(scope) >= 0) {
return key;
}
}
return scope;
}
private static isDotCom(host: vscode.Uri): boolean {
return host && host.authority.toLowerCase() === 'github.com';
}
}
class ResponseExpired extends Error {
get message() { return 'Token response expired'; }
}
const verifyToken: (host: string) => PromiseAdapter<vscode.Uri, IHostConfiguration> =
host => async (uri, resolve, reject) => {
if (uri.path !== CALLBACK_PATH) { return; }
const rsp = await axios.get(`${AUTH_RELAY_SERVER}/verify?${uri.query}`);
if (rsp.status !== 200) { return; }
const {ts, access_token: token} = rsp.data.token;
if (Date.now() - ts > MAX_TOKEN_RESPONSE_AGE) {
return reject(new ResponseExpired);
}
resolve({host, username: 'oauth', token});
};
export class GitHubServer {
public hostConfiguration: IHostConfiguration;
private hostUri: vscode.Uri;
public constructor(host: string) {
host = host.toLocaleLowerCase();
this.hostConfiguration = { host, username: 'oauth', token: undefined };
this.hostUri = vscode.Uri.parse(host);
}
public login(): Promise<IHostConfiguration> {
const host = this.hostUri.toString();
const uri = vscode.Uri.parse(
`${AUTH_RELAY_SERVER}/authorize?authServer=${host}&callbackUri=${CALLBACK_URI}&scope=${SCOPES}`
);
vscode.commands.executeCommand('vscode.open', uri);
return promiseFromEmitter(uriHandler, verifyToken(host));
}
public async validate(username?: string, token?: string): Promise<IHostConfiguration> {
if (!username) {
username = this.hostConfiguration.username;
}
if (!token) {
token = this.hostConfiguration.token;
}
const options = GitHubManager.getOptions(this.hostUri, 'GET', '/user', token);
return new Promise<IHostConfiguration>((resolve, _) => {
const get = https.request(options, res => {
let hostConfig: IHostConfiguration | undefined;
try {
if (res.statusCode === 200) {
const scopes = res.headers['x-oauth-scopes'] as string;
if (GitHubManager.validateScopes(this.hostUri, scopes)) {
this.hostConfiguration.username = username;
this.hostConfiguration.token = token;
hostConfig = this.hostConfiguration;
}
}
} catch (e) {
Logger.appendLine(`validate() error ${e}`);
}
resolve(hostConfig);
});
get.end();
get.on('error', err => {
resolve(undefined);
});
});
}
}