|
| 1 | +// @ts-check |
| 2 | + |
| 3 | +import { createVerify } from "node:crypto"; |
| 4 | + |
| 5 | +import { request as defaultRequest } from "@octokit/request"; |
| 6 | +import { RequestError } from "@octokit/request-error"; |
| 7 | + |
| 8 | +/** @type {import('.').VerifyInterface} */ |
| 9 | +export async function verify( |
| 10 | + rawBody, |
| 11 | + signature, |
| 12 | + keyId, |
| 13 | + { token = "", request = defaultRequest } = { request: defaultRequest }, |
| 14 | +) { |
| 15 | + // verify arguments |
| 16 | + assertValidString(rawBody, "Invalid payload"); |
| 17 | + assertValidString(signature, "Invalid signature"); |
| 18 | + assertValidString(keyId, "Invalid keyId"); |
| 19 | + |
| 20 | + // receive valid public keys from GitHub |
| 21 | + const requestOptions = request.endpoint("GET /meta/public_keys/copilot_api", { |
| 22 | + headers: token |
| 23 | + ? { |
| 24 | + Authorization: `token ${token}`, |
| 25 | + } |
| 26 | + : {}, |
| 27 | + }); |
| 28 | + const response = await request(requestOptions); |
| 29 | + const { data: keys } = response; |
| 30 | + |
| 31 | + // verify provided key Id |
| 32 | + const publicKey = keys.public_keys.find( |
| 33 | + (key) => key.key_identifier === keyId, |
| 34 | + ); |
| 35 | + if (!publicKey) { |
| 36 | + throw new RequestError( |
| 37 | + "[@copilot-extensions/preview-sdk] No public key found matching key identifier", |
| 38 | + 404, |
| 39 | + { |
| 40 | + request: requestOptions, |
| 41 | + response, |
| 42 | + }, |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + const verify = createVerify("SHA256").update(rawBody); |
| 47 | + |
| 48 | + // verify signature |
| 49 | + return verify.verify(publicKey.key, signature, "base64"); |
| 50 | +} |
| 51 | + |
| 52 | +function assertValidString(value, message) { |
| 53 | + if (typeof value !== "string" || value.length === 0) { |
| 54 | + throw new Error(`[@copilot-extensions/preview-sdk] ${message}`); |
| 55 | + } |
| 56 | +} |
0 commit comments