Skip to content

Commit

Permalink
feat: initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Aug 26, 2024
1 parent 6f7653d commit f8c4724
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { request } from "@octokit/request";

type RequestInterface = typeof request;
type RequestOptions = {
request?: RequestInterface;
token?: string;
};

interface VerifyInterface {
(
rawBody: string,
signature: string,
keyId: string,
requestOptions?: RequestOptions,
): Promise<boolean>;
}

export declare const verify: VerifyInterface;
56 changes: 56 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// @ts-check

import { createVerify } from "node:crypto";

import { request as defaultRequest } from "@octokit/request";
import { RequestError } from "@octokit/request-error";

/** @type {import('.').VerifyInterface} */
export async function verify(
rawBody,
signature,
keyId,
{ token = "", request = defaultRequest } = { request: defaultRequest },
) {
// verify arguments
assertValidString(rawBody, "Invalid payload");
assertValidString(signature, "Invalid signature");
assertValidString(keyId, "Invalid keyId");

// receive valid public keys from GitHub
const requestOptions = request.endpoint("GET /meta/public_keys/copilot_api", {
headers: token
? {
Authorization: `token ${token}`,
}
: {},
});
const response = await request(requestOptions);
const { data: keys } = response;

// verify provided key Id
const publicKey = keys.public_keys.find(
(key) => key.key_identifier === keyId,
);
if (!publicKey) {
throw new RequestError(
"[@copilot-extensions/preview-sdk] No public key found matching key identifier",
404,
{
request: requestOptions,
response,
},
);
}

const verify = createVerify("SHA256").update(rawBody);

// verify signature
return verify.verify(publicKey.key, signature, "base64");
}

function assertValidString(value, message) {
if (typeof value !== "string" || value.length === 0) {
throw new Error(`[@copilot-extensions/preview-sdk] ${message}`);
}
}

0 comments on commit f8c4724

Please sign in to comment.