Skip to content

Commit b139c9a

Browse files
authored
Fix username/password auth
1 parent 5ad9206 commit b139c9a

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

sources/httpUtils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ async function fetch(input: string | URL, init?: RequestInit) {
2020
const username: string | undefined = input.username || process.env.COREPACK_NPM_USERNAME;
2121
const password: string | undefined = input.password || process.env.COREPACK_NPM_PASSWORD;
2222

23-
if (username && password) {
24-
const encodedCreds = Buffer.from(`${username}:${password}`, `utf8`).toString(`base64`);
23+
if (username || password) {
24+
const encodedCreds = Buffer.from(`${username ?? ''}:${password ?? ''}`, `utf8`).toString(`base64`);
2525
headers = {
2626
...headers,
2727
authorization: `Basic ${encodedCreds}`,

tests/npmRegistryUtils.test.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,36 @@ describe(`npm registry utils fetchAsJson`, () => {
9090
}));
9191
});
9292

93-
it(`does not add authorization header if COREPACK_NPM_USERNAME is set and COREPACK_NPM_PASSWORD is not.`, async () => {
93+
it(`adds authorization header if COREPACK_NPM_USERNAME is set and COREPACK_NPM_PASSWORD is not.`, async () => {
9494
// `process.env` is reset after each tests in setupTests.js.
9595
process.env.COREPACK_NPM_USERNAME = `foo`;
9696

97+
const encodedCreds = Buffer.from(`${process.env.COREPACK_NPM_USERNAME}:`, `utf8`).toString(`base64`);
98+
9799
await fetchAsJson(`package-name`);
98100

99101
expect(fetchMock).toBeCalled();
100-
expect(fetchMock).lastCalledWith(new URL(`${DEFAULT_NPM_REGISTRY_URL}/package-name`), expect.objectContaining({headers: DEFAULT_HEADERS}));
102+
expect(fetchMock).lastCalledWith(new URL(`${DEFAULT_NPM_REGISTRY_URL}/package-name`), expect.objectContaining({
103+
headers: {
104+
...DEFAULT_HEADERS,
105+
authorization: `Basic ${encodedCreds}`
106+
}));
107+
});
108+
109+
it(`adds authorization header if COREPACK_NPM_PASSWORD is set and COREPACK_NPM_USERNAME is not.`, async () => {
110+
// `process.env` is reset after each tests in setupTests.js.
111+
process.env.COREPACK_NPM_PASSWORD = `foo`;
112+
113+
const encodedCreds = Buffer.from(`:${process.env.COREPACK_NPM_PASSWORD}`, `utf8`).toString(`base64`);
114+
115+
await fetchAsJson(`package-name`);
116+
117+
expect(fetchMock).toBeCalled();
118+
expect(fetchMock).lastCalledWith(new URL(`${DEFAULT_NPM_REGISTRY_URL}/package-name`), expect.objectContaining({
119+
headers: {
120+
...DEFAULT_HEADERS,
121+
authorization: `Basic ${encodedCreds}`
122+
}));
101123
});
102124

103125
it(`does add authorization header if registry url contains a path`, async () => {

0 commit comments

Comments
 (0)