-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathutils.ts
More file actions
303 lines (258 loc) · 7.92 KB
/
utils.ts
File metadata and controls
303 lines (258 loc) · 7.92 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { ipcRenderer } from 'electron';
import { format } from 'date-fns';
import semver from 'semver';
import { APPLICATION } from '../../../shared/constants';
import { namespacedEvent } from '../../../shared/events';
import type {
Account,
AuthCode,
AuthState,
ClientID,
GitifyUser,
Hostname,
Link,
Token,
} from '../../types';
import type { UserDetails } from '../../typesGitHub';
import { getAuthenticatedUser } from '../api/client';
import { apiRequest } from '../api/request';
import { encryptValue, openExternalLink } from '../comms';
import { Constants } from '../constants';
import { getPlatformFromHostname } from '../helpers';
import { rendererLogError, rendererLogInfo, rendererLogWarn } from '../logger';
import type { AuthMethod, AuthResponse, AuthTokenResponse } from './types';
export function authGitHub(
authOptions = Constants.DEFAULT_AUTH_OPTIONS,
): Promise<AuthResponse> {
return new Promise((resolve, reject) => {
const authUrl = new URL(`https://${authOptions.hostname}`);
authUrl.pathname = '/login/oauth/authorize';
authUrl.searchParams.append('client_id', authOptions.clientId);
authUrl.searchParams.append(
'scope',
Constants.OAUTH_SCOPES.RECOMMENDED.toString(),
);
openExternalLink(authUrl.toString() as Link);
const handleCallback = (callbackUrl: string) => {
const url = new URL(callbackUrl);
const type = url.hostname;
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');
const errorDescription = url.searchParams.get('error_description');
const errorUri = url.searchParams.get('error_uri');
if (code && (type === 'auth' || type === 'oauth')) {
const authMethod: AuthMethod =
type === 'auth' ? 'GitHub App' : 'OAuth App';
resolve({
authMethod: authMethod,
authCode: code as AuthCode,
authOptions: authOptions,
});
} else if (error) {
reject(
new Error(
`Oops! Something went wrong and we couldn't log you in using GitHub. Please try again. Reason: ${errorDescription} Docs: ${errorUri}`,
),
);
}
};
ipcRenderer.on(
namespacedEvent('auth-callback'),
(_, callbackUrl: string) => {
rendererLogInfo(
'renderer:auth-callback',
`received authentication callback URL ${callbackUrl}`,
);
handleCallback(callbackUrl);
},
);
});
}
export async function getUserData(
token: Token,
hostname: Hostname,
): Promise<GitifyUser> {
const response: UserDetails = (await getAuthenticatedUser(hostname, token))
.data;
return {
id: response.id,
login: response.login,
name: response.name,
avatar: response.avatar_url,
};
}
export async function getToken(
authCode: AuthCode,
authOptions = Constants.DEFAULT_AUTH_OPTIONS,
): Promise<AuthTokenResponse> {
const url =
`https://${authOptions.hostname}/login/oauth/access_token` as Link;
const data = {
client_id: authOptions.clientId,
client_secret: authOptions.clientSecret,
code: authCode,
};
const response = await apiRequest(url, 'POST', data);
return {
hostname: authOptions.hostname,
token: response.data.access_token,
};
}
export async function addAccount(
auth: AuthState,
method: AuthMethod,
token: Token,
hostname: Hostname,
): Promise<AuthState> {
const accountList = auth.accounts;
const encryptedToken = await encryptValue(token);
let newAccount = {
hostname: hostname,
method: method,
platform: getPlatformFromHostname(hostname),
token: encryptedToken,
} as Account;
newAccount = await refreshAccount(newAccount);
const newAccountUUID = getAccountUUID(newAccount);
const accountAlreadyExists = accountList.some(
(a) => getAccountUUID(a) === newAccountUUID,
);
if (accountAlreadyExists) {
rendererLogWarn(
'addAccount',
`account for user ${newAccount.user.login} already exists`,
);
} else {
accountList.push(newAccount);
}
return {
accounts: accountList,
};
}
export function removeAccount(auth: AuthState, account: Account): AuthState {
const updatedAccounts = auth.accounts.filter(
(a) => a.token !== account.token,
);
return {
accounts: updatedAccounts,
};
}
export async function refreshAccount(account: Account): Promise<Account> {
try {
const res = await getAuthenticatedUser(account.hostname, account.token);
// Refresh user data
account.user = {
id: res.data.id,
login: res.data.login,
name: res.data.name,
avatar: res.data.avatar_url,
};
account.version = extractHostVersion(
res.headers['x-github-enterprise-version'],
);
const accountScopes = res.headers['x-oauth-scopes']
?.split(',')
.map((scope: string) => scope.trim());
account.hasRequiredScopes =
Constants.OAUTH_SCOPES.RECOMMENDED.every((scope) =>
accountScopes.includes(scope),
) ||
Constants.OAUTH_SCOPES.ALTERNATE.every((scope) =>
accountScopes.includes(scope),
);
if (!account.hasRequiredScopes) {
rendererLogWarn(
'refreshAccount',
`account for user ${account.user.login} is missing required scopes`,
);
}
} catch (err) {
rendererLogError(
'refreshAccount',
`failed to refresh account for user ${account.user.login}`,
err,
);
}
return account;
}
export function extractHostVersion(version: string | null): string {
if (version) {
return semver.valid(semver.coerce(version));
}
return 'latest';
}
export function getDeveloperSettingsURL(account: Account): Link {
const settingsURL = new URL(`https://${account.hostname}`);
switch (account.method) {
case 'GitHub App':
settingsURL.pathname =
'/settings/connections/applications/27a352516d3341cee376';
break;
case 'OAuth App':
settingsURL.pathname = '/settings/developers';
break;
case 'Personal Access Token':
settingsURL.pathname = '/settings/tokens';
break;
default:
settingsURL.pathname = '/settings';
break;
}
return settingsURL.toString() as Link;
}
export function getNewTokenURL(hostname: Hostname): Link {
const date = format(new Date(), 'PP p');
const newTokenURL = new URL(`https://${hostname}/settings/tokens/new`);
newTokenURL.searchParams.append(
'description',
`${APPLICATION.NAME} (Created on ${date})`,
);
newTokenURL.searchParams.append(
'scopes',
Constants.OAUTH_SCOPES.RECOMMENDED.join(','),
);
return newTokenURL.toString() as Link;
}
export function getNewOAuthAppURL(hostname: Hostname): Link {
const date = format(new Date(), 'PP p');
const newOAuthAppURL = new URL(
`https://${hostname}/settings/applications/new`,
);
newOAuthAppURL.searchParams.append(
'oauth_application[name]',
`${APPLICATION.NAME} (Created on ${date})`,
);
newOAuthAppURL.searchParams.append(
'oauth_application[url]',
'https://gitify.io',
);
newOAuthAppURL.searchParams.append(
'oauth_application[callback_url]',
'gitify://oauth',
);
return newOAuthAppURL.toString() as Link;
}
export function isValidHostname(hostname: Hostname) {
return /^([A-Z0-9]([A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}$/i.test(hostname);
}
export function isValidClientId(clientId: ClientID) {
return /^[A-Z0-9_]{20}$/i.test(clientId);
}
export function isValidToken(token: Token) {
return /^[A-Z0-9_]{40}$/i.test(token);
}
export function getAccountUUID(account: Account): string {
return btoa(`${account.hostname}-${account.user.id}-${account.method}`);
}
export function hasAccounts(auth: AuthState) {
return auth.accounts.length > 0;
}
export function hasMultipleAccounts(auth: AuthState) {
return auth.accounts.length > 1;
}
export function formatRecommendedOAuthScopes() {
return Constants.OAUTH_SCOPES.RECOMMENDED.join(', ');
}
export function formatAlternateOAuthScopes() {
return Constants.OAUTH_SCOPES.ALTERNATE.join(', ');
}