From e0dc8947742e616294994cb6ddb786d42ca30a43 Mon Sep 17 00:00:00 2001 From: Oscar Dominguez Date: Sun, 1 Aug 2021 22:41:55 +0200 Subject: [PATCH] feat(get-app-authentication): improve error message when privateKey is incomplete (#312) --- src/get-app-authentication.ts | 32 +++++++++++++++++++++----------- test/index.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/get-app-authentication.ts b/src/get-app-authentication.ts index 81274ffe8..3fad21b65 100644 --- a/src/get-app-authentication.ts +++ b/src/get-app-authentication.ts @@ -7,16 +7,26 @@ export async function getAppAuthentication({ privateKey, timeDifference, }: State & { timeDifference?: number }): Promise { - const appAuthentication = await githubAppJwt({ - id: +appId, - privateKey, - now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference, - }); + try { + const appAuthentication = await githubAppJwt({ + id: +appId, + privateKey, + now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference, + }); - return { - type: "app", - token: appAuthentication.token, - appId: appAuthentication.appId, - expiresAt: new Date(appAuthentication.expiration * 1000).toISOString(), - }; + return { + type: "app", + token: appAuthentication.token, + appId: appAuthentication.appId, + expiresAt: new Date(appAuthentication.expiration * 1000).toISOString(), + }; + } catch (error) { + if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { + throw new Error( + "The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'" + ); + } else { + throw error; + } + } } diff --git a/test/index.test.ts b/test/index.test.ts index 240e39266..8fe46b1cf 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -93,6 +93,28 @@ test("throws if invalid 'type' is provided", async () => { ); }); +test("throws if invalid Private Key is provided", async () => { + const auth = createAppAuth({ + appId: APP_ID, + privateKey: "INVALID_PRIVATE_KEY", + }); + + await expect(auth({ type: "app" })).rejects.toEqual(expect.anything()); +}); + +test("throws if incomplete Private Key is provided", async () => { + const auth = createAppAuth({ + appId: APP_ID, + privateKey: "-----BEGIN RSA PRIVATE KEY-----", + }); + + await expect(auth({ type: "app" })).rejects.toEqual( + new Error( + "The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'" + ) + ); +}); + test("README example for installation auth", async () => { const matchCreateInstallationAccessToken: MockMatcherFunction = ( url,