-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
78 lines (66 loc) · 1.99 KB
/
index.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
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
// @ts-check
import { createVerify } from "node:crypto";
import { request as defaultRequest } from "@octokit/request";
import { RequestError } from "@octokit/request-error";
/** @type {import('.').VerifyRequestByKeyIdInterface} */
export async function verifyRequest(rawBody, signature, key) {
// verify arguments
assertValidString(rawBody, "Invalid payload");
assertValidString(signature, "Invalid signature");
assertValidString(key, "Invalid key");
// verify signature
try {
return createVerify("SHA256")
.update(rawBody)
.verify(key, signature, "base64");
} catch {
return false;
}
}
/** @type {import('.').FetchVerificationKeysInterface} */
export async function fetchVerificationKeys(
{ token = "", request = defaultRequest } = { request: defaultRequest }
) {
const { data } = await request("GET /meta/public_keys/copilot_api", {
headers: token
? {
Authorization: `token ${token}`,
}
: {},
});
return data.public_keys;
}
/** @type {import('.').VerifyRequestByKeyIdInterface} */
export async function verifyRequestByKeyId(
rawBody,
signature,
keyId,
requestOptions
) {
// verify arguments
assertValidString(rawBody, "Invalid payload");
assertValidString(signature, "Invalid signature");
assertValidString(keyId, "Invalid keyId");
// receive valid public keys from GitHub
const keys = await fetchVerificationKeys(requestOptions);
// verify provided key Id
const publicKey = keys.find((key) => key.key_identifier === keyId);
if (!publicKey) {
const keyNotFoundError = Object.assign(
new Error(
"[@copilot-extensions/preview-sdk] No public key found matching key identifier"
),
{
keyId,
keys,
}
);
throw keyNotFoundError;
}
return verifyRequest(rawBody, signature, publicKey.key);
}
function assertValidString(value, message) {
if (typeof value !== "string" || value.length === 0) {
throw new Error(`[@copilot-extensions/preview-sdk] ${message}`);
}
}