forked from refined-github/refined-github
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub-token.ts
More file actions
46 lines (37 loc) · 1.37 KB
/
github-token.ts
File metadata and controls
46 lines (37 loc) · 1.37 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
import {v3} from './api.js';
import optionsStorage from '../options-storage.js';
const settings = optionsStorage.getAll();
export async function getToken(): Promise<string | undefined> {
const {personalToken} = await settings;
return personalToken;
}
export async function expectToken(): Promise<string> {
const personalToken = await getToken();
if (!personalToken) {
throw new Error('Personal token required for this feature');
}
return personalToken;
}
export async function parseTokenScopes(headers: Headers): Promise<string[]> {
// If `X-OAuth-Scopes` is not present, the token may be not a classic token.
const scopesHeader = headers.get('X-OAuth-Scopes');
if (!scopesHeader) {
return [];
}
const scopes = scopesHeader.split(', ');
scopes.push('valid_token');
if (scopes.includes('repo')) {
scopes.push('public_repo');
}
if (scopes.includes('project')) {
scopes.push('read:project');
}
return scopes;
}
export async function expectTokenScope(scope: string): Promise<void> {
const {headers} = await v3('/');
const tokenScopes = await parseTokenScopes(headers);
if (!tokenScopes.includes(scope)) {
throw new Error('The token you provided does not have ' + (tokenScopes.length > 0 ? `the \`${scope}\` scope. It only includes \`${tokenScopes.join(', ')}\`.` : 'any scope. You can change the scope of your token at https://github.com/settings/tokens'));
}
}