From e2eb3a4e4815b69c107f03ed912a0ee2e34baa2f Mon Sep 17 00:00:00 2001 From: Kanad Gupta Date: Mon, 5 Jun 2023 10:19:11 -0500 Subject: [PATCH] fix(fetch): stricter source URL type-checking --- __tests__/lib/fetch.test.ts | 24 ++++++++++++++++++++++++ src/lib/readmeAPIFetch.ts | 12 +++++++----- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/__tests__/lib/fetch.test.ts b/__tests__/lib/fetch.test.ts index 3d794fa15..1538da720 100644 --- a/__tests__/lib/fetch.test.ts +++ b/__tests__/lib/fetch.test.ts @@ -89,6 +89,30 @@ describe('#fetch()', () => { mock.done(); }); + it('should omit source URL header if URL is invalid', async () => { + const key = 'API_KEY'; + delete process.env.GITHUB_SERVER_URL; + + const mock = getAPIMock() + .get('/api/v1') + .basicAuth({ user: key }) + .reply(200, function () { + return this.req.headers; + }); + + const headers = await readmeAPIFetch( + '/api/v1', + { + method: 'get', + headers: cleanHeaders(key), + }, + { filePath: './📈 Dashboard & Metrics/openapi.json', fileType: 'path' } + ).then(handleRes); + + expect(headers['x-readme-source-url']).toBeUndefined(); + mock.done(); + }); + it('should include source URL header with relative path', async () => { const key = 'API_KEY'; diff --git a/src/lib/readmeAPIFetch.ts b/src/lib/readmeAPIFetch.ts index e26101a72..beebf4278 100644 --- a/src/lib/readmeAPIFetch.ts +++ b/src/lib/readmeAPIFetch.ts @@ -162,12 +162,14 @@ export default async function readmeAPIFetch( * @see {@link https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables} * @example https://github.com/readmeio/rdme/blob/cb4129d5c7b51ff3b50f933a9c7d0c3d0d33d62c/documentation/rdme.md */ - headers.set( - 'x-readme-source-url', - encodeURI( + try { + const sourceUrl = new URL( `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${filePath}` - ) - ); + ).href; + headers.set('x-readme-source-url', sourceUrl); + } catch (e) { + debug(`error constructing github source url: ${e.message}`); + } } }