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
230 lines (202 loc) · 5.62 KB
/
Copy pathgithubServer.ts
File metadata and controls
230 lines (202 loc) · 5.62 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import * as vscode from 'vscode';
import { IHostConfiguration, HostHelper } from './configuration';
import * as ws from 'ws';
import * as https from 'https';
import Logger from '../common/logger';
const SCOPES: string = 'read:user user:email repo write:discussion';
const HOST: string = 'github-editor-auth.herokuapp.com';
const HTTP_PROTOCOL: string = 'https';
const WS_PROTOCOL: string = 'wss';
enum MessageType {
Host = 0x2,
Token = 0x8,
}
interface IMessage {
type: MessageType;
guid: string;
host?: string;
token?: string;
scopes?: string;
}
class Client {
private _guid?: string;
constructor(private host: string, private scopes: string) {}
public start(): Promise<string> {
return new Promise((resolve, reject) => {
const socket = new ws(`${WS_PROTOCOL}://${HOST}`);
socket.on('message', data => {
const message: IMessage = JSON.parse(data.toString());
switch (message.type) {
case MessageType.Host:
{
this._guid = message.guid;
socket.send(
JSON.stringify({
type: MessageType.Host,
guid: this._guid,
host: this.host,
scopes: this.scopes,
})
);
vscode.commands.executeCommand(
'vscode.open',
vscode.Uri.parse(`${HTTP_PROTOCOL}://${HOST}?state=action:login;guid:${this._guid}`)
);
}
break;
case MessageType.Token:
{
socket.close();
resolve(message.token);
}
break;
default: {
socket.close();
}
}
socket.on('close', (code, reason) => {
if (code !== 1000) {
reject(reason);
}
});
});
});
}
}
export class GitHubManager {
private servers: Map<string, boolean>;
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(' ');
constructor() {
this.servers = new Map().set('github.com', true);
}
public async isGitHub(host: vscode.Uri): Promise<boolean> {
if (this.servers.has(host.authority)) {
return this.servers.get(host.authority);
}
const options = GitHubManager.getOptions(host, 'HEAD');
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', 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, '/rate_limit'),
headers,
};
}
public static validateScopes(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));
}
private static getScopeSuperset(scope: string): string
{
for (let key in this.GitHubScopesTable) {
if (this.GitHubScopesTable[key].indexOf(scope) >= 0) {
return key;
}
}
return scope;
}
}
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 async login(): Promise<IHostConfiguration> {
return new Promise<IHostConfiguration>((resolve, reject) => {
new Client(this.hostConfiguration.host, SCOPES)
.start()
.then(token => {
this.hostConfiguration.token = token;
resolve(this.hostConfiguration);
})
.catch(reason => {
resolve(undefined);
});
});
}
public async checkAnonymousAccess(): Promise<boolean> {
const options = GitHubManager.getOptions(this.hostUri);
return new Promise<boolean>((resolve, _) => {
const get = https.request(options, res => {
resolve(res.statusCode === 200);
});
get.end();
get.on('error', err => {
resolve(false);
});
});
}
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', 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(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);
});
});
}
}