-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathgithubToken.ts
More file actions
44 lines (34 loc) · 1.07 KB
/
githubToken.ts
File metadata and controls
44 lines (34 loc) · 1.07 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
import axios from 'axios'
import * as jwt from 'jsonwebtoken'
import { GITHUB_TOKEN_CONFIG } from '@/conf'
let token: string | undefined
let expiration: Date | undefined
export const getGithubInstallationToken = async (): Promise<string> => {
if (token && expiration && expiration.getTime() > Date.now()) {
return token
}
// refresh token
const config = GITHUB_TOKEN_CONFIG
const now = Math.floor(Date.now() / 1000)
const payload = {
iat: now - 60,
exp: now + 10 * 60,
iss: config.clientId,
}
const privateKey = Buffer.from(config.privateKey, 'base64').toString('ascii')
const jwtToken = jwt.sign(payload, privateKey, { algorithm: 'RS256' })
const response = await axios.post(
`https://api.github.com/app/installations/${config.installationId}/access_tokens`,
{},
{
headers: {
Authorization: `Bearer ${jwtToken}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
},
},
)
token = response.data.token
expiration = new Date(response.data.expires_at)
return token
}