-
Notifications
You must be signed in to change notification settings - Fork 11
/
github-api-request-as-app.js
41 lines (35 loc) · 1.13 KB
/
github-api-request-as-app.js
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
module.exports = async (context, appId, privateKey, requestMethod, requestPath, body) => {
const header = {
"alg": "RS256",
"typ": "JWT"
}
const now = Math.floor(new Date().getTime() / 1000)
const payload = {
// issued at time, 60 seconds in the past to allow for clock drift
iat: now - 60,
// JWT expiration time (10 minute maximum)
exp: now + (10 * 60),
// GitHub App's identifier
iss: appId
}
const toBase64 = (obj) => Buffer.from(JSON.stringify(obj), "utf-8").toString("base64url")
const headerAndPayload = `${toBase64(header)}.${toBase64(payload)}`
const crypto = require('crypto')
const signer = crypto.createSign("RSA-SHA256")
signer.update(headerAndPayload)
const signature = signer.sign({
key: privateKey
}, "base64url")
const token = `${headerAndPayload}.${signature}`
const httpsRequest = require('./https-request')
return await httpsRequest(
context,
null,
requestMethod,
requestPath,
body,
{
Authorization: `Bearer ${token}`,
}
)
}