-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.js
More file actions
267 lines (226 loc) ยท 5.57 KB
/
Copy pathgithub.js
File metadata and controls
267 lines (226 loc) ยท 5.57 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
/**
* GitHub App ์ธ์ฆ ๋ฐ API ์ ํธ๋ฆฌํฐ
*/
import { GITHUB_USER_AGENT, GITHUB_ACCEPT_HEADER } from "./constants.js";
function encodeDerLength(length) {
if (length < 0x80) {
return Uint8Array.of(length);
}
const octets = [];
let value = length;
while (value > 0) {
octets.unshift(value & 0xff);
value >>= 8;
}
return Uint8Array.of(0x80 | octets.length, ...octets);
}
function encodeDer(tag, value) {
return Uint8Array.of(tag, ...encodeDerLength(value.length), ...value);
}
function concatUint8Arrays(...arrays) {
const totalLength = arrays.reduce((sum, array) => sum + array.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const array of arrays) {
result.set(array, offset);
offset += array.length;
}
return result;
}
function wrapPkcs1PrivateKey(pkcs1Der) {
const version = Uint8Array.of(0x02, 0x01, 0x00);
const algorithmIdentifier = Uint8Array.of(
0x30,
0x0d,
0x06,
0x09,
0x2a,
0x86,
0x48,
0x86,
0xf7,
0x0d,
0x01,
0x01,
0x01,
0x05,
0x00
);
const privateKey = encodeDer(0x04, pkcs1Der);
return encodeDer(
0x30,
concatUint8Arrays(version, algorithmIdentifier, privateKey)
);
}
/**
* GitHub API ์์ฒญ ํค๋ ์์ฑ
*/
export function getGitHubHeaders(token) {
return {
Authorization: `Bearer ${token}`,
Accept: GITHUB_ACCEPT_HEADER,
"User-Agent": GITHUB_USER_AGENT,
};
}
/**
* content_node_id๋ก๋ถํฐ PR ์ ๋ณด ์กฐํ (GraphQL)
*/
export async function getPRInfoFromNodeId(nodeId, token) {
const query = `
query($nodeId: ID!) {
node(id: $nodeId) {
... on PullRequest {
number
repository {
owner {
login
}
name
}
}
}
}
`;
const response = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: getGitHubHeaders(token),
body: JSON.stringify({
query,
variables: { nodeId },
}),
});
const result = await response.json();
if (result.errors) {
throw new Error(`GraphQL error: ${JSON.stringify(result.errors)}`);
}
const prData = result.data?.node;
if (!prData) {
return null;
}
return {
number: prData.number,
owner: prData.repository.owner.login,
repo: prData.repository.name,
};
}
/**
* GitHub App Installation Token ๋ฐ๊ธ
*/
export async function generateGitHubAppToken(env) {
// JWT ์์ฑ
const jwt = await createJWT(env.APP_ID, env.PRIVATE_KEY);
// Installation ID ์กฐํ
const installationsResponse = await fetch(
"https://api.github.com/app/installations",
{
headers: {
Authorization: `Bearer ${jwt}`,
Accept: "application/vnd.github+json",
"User-Agent": "DaleStudy-GitHub-App",
},
}
);
const installations = await installationsResponse.json();
const installation = installations.find(
(inst) => inst.account.login === "DaleStudy"
);
if (!installation) {
throw new Error("DaleStudy installation not found");
}
// Installation Token ์์ฑ
const tokenResponse = await fetch(
`https://api.github.com/app/installations/${installation.id}/access_tokens`,
{
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
Accept: "application/vnd.github+json",
"User-Agent": "DaleStudy-GitHub-App",
},
}
);
const tokenData = await tokenResponse.json();
if (!tokenData.token) {
throw new Error(`Failed to get token: ${JSON.stringify(tokenData)}`);
}
return tokenData.token;
}
/**
* JWT ์์ฑ (RS256)
*/
export async function createJWT(appId, privateKeyPem) {
const now = Math.floor(Date.now() / 1000);
const header = {
alg: "RS256",
typ: "JWT",
};
const payload = {
iat: now - 60,
exp: now + 10 * 60, // 10๋ถ
iss: appId,
};
const encodedHeader = base64UrlEncode(JSON.stringify(header));
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
const privateKey = await importPrivateKey(privateKeyPem);
const signature = await sign(
`${encodedHeader}.${encodedPayload}`,
privateKey
);
return `${encodedHeader}.${encodedPayload}.${signature}`;
}
/**
* Private Key import
*/
export async function importPrivateKey(pem) {
// PKCS8 ๋๋ PKCS1 ํ์ ์ง์
const isPKCS8 = pem.includes("BEGIN PRIVATE KEY");
const pemHeader = isPKCS8
? "-----BEGIN PRIVATE KEY-----"
: "-----BEGIN RSA PRIVATE KEY-----";
const pemFooter = isPKCS8
? "-----END PRIVATE KEY-----"
: "-----END RSA PRIVATE KEY-----";
const pemContents = pem
.replace(pemHeader, "")
.replace(pemFooter, "")
.replace(/\s/g, "");
let binaryDer = Uint8Array.from(atob(pemContents), (c) => c.charCodeAt(0));
if (!isPKCS8) {
binaryDer = wrapPkcs1PrivateKey(binaryDer);
}
return await crypto.subtle.importKey(
"pkcs8",
binaryDer,
{
name: "RSASSA-PKCS1-v1_5",
hash: "SHA-256",
},
false,
["sign"]
);
}
/**
* Sign with RS256
*/
export async function sign(data, key) {
const signature = await crypto.subtle.sign(
"RSASSA-PKCS1-v1_5",
key,
new TextEncoder().encode(data)
);
return base64UrlEncode(new Uint8Array(signature));
}
/**
* Base64 URL encode
*/
export function base64UrlEncode(data) {
if (typeof data === "string") {
data = new TextEncoder().encode(data);
}
let binary = "";
const bytes = new Uint8Array(data);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}