Skip to content

Commit

Permalink
feat: add support for configurable registries and applicable authenti…
Browse files Browse the repository at this point in the history
…cation options
  • Loading branch information
micsco committed Sep 28, 2022
1 parent 9a09dad commit 7e61a46
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 7 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,16 @@ This command will retrieve the given package manager from the specified archive

- `COREPACK_ROOT` has no functional impact on Corepack itself; it's automatically being set in your environment by Corepack when it shells out to the underlying package managers, so that they can feature-detect its presence (useful for commands like `yarn init`).

- `COREPACK_NPM_REGISTRY` sets the registry base url used when retrieving package managers from npm. Default value is `https://registry.npmjs.org`

- `COREPACK_NPM_TOKEN` sets a Bearer token authorization header when connecting to `npm` type registry.

- `COREPACK_NPM_USERNAME` and `COREPACK_NPM_PASSWORD` to set a Basic authorization header when connecting to NPM type registry. Note: both environment variables are required, if you want to send an empty password, explicitly set `COREPACK_NPM_PASSWORD` to an empty string.

- `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` are supported through [`node-proxy-agent`](https://github.com/TooTallNate/node-proxy-agent).

[`npm-registry-fetch`]: https://github.com/npm/npm-registry-fetch

## Contributing

If you want to build corepack yourself, you can build the project like this:
Expand Down
12 changes: 5 additions & 7 deletions sources/corepackUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import * as folderUtils from './folderUti
import * as fsUtils from './fsUtils';
import * as httpUtils from './httpUtils';
import * as nodeUtils from './nodeUtils';
import * as npmRegistryUtils from './npmRegistryUtils';
import {RegistrySpec, Descriptor, Locator, PackageManagerSpec} from './types';


export async function fetchLatestStableVersion(spec: RegistrySpec) {
switch (spec.type) {
case `npm`: {
const {[`dist-tags`]: {latest}, versions: {[latest]: {dist: {shasum}}}} =
await httpUtils.fetchAsJson(`https://registry.npmjs.org/${spec.package}`);
return `${latest}+sha1.${shasum}`;
return await npmRegistryUtils.fetchLatestStableVersion(spec.package);
}
case `url`: {
const data = await httpUtils.fetchAsJson(spec.url);
Expand All @@ -32,8 +32,7 @@ export async function fetchLatestStableVersion(spec: RegistrySpec) {
export async function fetchAvailableTags(spec: RegistrySpec): Promise<Record<string, string>> {
switch (spec.type) {
case `npm`: {
const data = await httpUtils.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, {headers: {[`Accept`]: `application/vnd.npm.install-v1+json`}});
return data[`dist-tags`];
return await npmRegistryUtils.fetchAvailableTags(spec.package);
}
case `url`: {
const data = await httpUtils.fetchAsJson(spec.url);
Expand All @@ -48,8 +47,7 @@ export async function fetchAvailableTags(spec: RegistrySpec): Promise<Record<str
export async function fetchAvailableVersions(spec: RegistrySpec): Promise<Array<string>> {
switch (spec.type) {
case `npm`: {
const data = await httpUtils.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, {headers: {[`Accept`]: `application/vnd.npm.install-v1+json`}});
return Object.keys(data.versions);
return await npmRegistryUtils.fetchAvailableVersions(spec.package);
}
case `url`: {
const data = await httpUtils.fetchAsJson(spec.url);
Expand Down
51 changes: 51 additions & 0 deletions sources/npmRegistryUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {UsageError} from 'clipanion';
import {OutgoingHttpHeaders} from 'http2';

import * as httpUtils from './httpUtils';

// load abbreviated metadata as that's all we need for these calls
// see: https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md
export const DEFAULT_HEADERS: OutgoingHttpHeaders = {
[`Accept`]: `application/vnd.npm.install-v1+json`,
};
export const DEFAULT_NPM_REGISTRY_URL = `https://registry.npmjs.org`;

export async function fetchAsJson(packageName: string) {
const npmRegistryUrl = process.env.COREPACK_NPM_REGISTRY || DEFAULT_NPM_REGISTRY_URL;

if (process.env.COREPACK_ENABLE_NETWORK === `0`)
throw new UsageError(`Network access disabled by the environment; can't reach npm repository ${npmRegistryUrl}`);

const headers = {...DEFAULT_HEADERS};

if (`COREPACK_NPM_TOKEN` in process.env) {
headers.authorization = `Bearer ${process.env.COREPACK_NPM_TOKEN}`;
} else if (`COREPACK_NPM_USERNAME` in process.env
&& `COREPACK_NPM_PASSWORD` in process.env) {
const encodedPassword = Buffer.from(`${process.env.COREPACK_NPM_PASSWORD}`, `base64`).toString(`utf8`);
const encodedCreds = Buffer.from(`${process.env.COREPACK_NPM_USERNAME}:${encodedPassword}`, `utf8`).toString(`base64`);
headers.authorization = `Basic ${encodedCreds}`;
}

return httpUtils.fetchAsJson(`${npmRegistryUrl}/${packageName}`, {headers});
}

export async function fetchLatestStableVersion(packageName: string) {
const metadata = await fetchAsJson(packageName);
const {latest} = metadata[`dist-tags`];
if (latest === undefined) throw new Error(`${packageName} does not have a "latest" tag.`);

const {shasum} = metadata.versions[latest].dist;

return `${latest}+sha1.${shasum}`;
}

export async function fetchAvailableTags(packageName: string) {
const metadata = await fetchAsJson(packageName);
return metadata[`dist-tags`];
}

export async function fetchAvailableVersions(packageName: string) {
const metadata = await fetchAsJson(packageName);
return Object.keys(metadata.versions);
}
92 changes: 92 additions & 0 deletions tests/npmRegistryUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {UsageError} from 'clipanion';

import {fetchAsJson as httpFetchAsJson} from '../sources/httpUtils';
import {DEFAULT_HEADERS, DEFAULT_NPM_REGISTRY_URL, fetchAsJson} from '../sources/npmRegistryUtils';

jest.mock(`../sources/httpUtils`);

describe(`npm registry utils fetchAsJson`, () => {
const OLD_ENV = process.env;

beforeEach(() => {
process.env = {...OLD_ENV}; // Make a copy
jest.resetAllMocks();
});

afterEach(() => {
process.env = OLD_ENV; // Restore old environment
});

it(`throw usage error if COREPACK_ENABLE_NETWORK env is set to 0`, async () => {
process.env.COREPACK_ENABLE_NETWORK = `0`;

expect(fetchAsJson(`package-name`)).rejects.toThrowError();
});

it(`loads from DEFAULT_NPM_REGISTRY_URL by default`, async () => {
await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${DEFAULT_NPM_REGISTRY_URL}/package-name`, {headers: DEFAULT_HEADERS});
});

it(`loads from custom COREPACK_NPM_REGISTRY if set`, async () => {
process.env.COREPACK_NPM_REGISTRY = `https://registry.example.org`;
await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${process.env.COREPACK_NPM_REGISTRY}/package-name`, {headers: DEFAULT_HEADERS});
});

it(`adds authorization header with bearer token if COREPACK_NPM_TOKEN is set`, async () => {
process.env.COREPACK_NPM_TOKEN = `kcaperoc`;

await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${DEFAULT_NPM_REGISTRY_URL}/package-name`, {headers: {
...DEFAULT_HEADERS,
authorization: `Bearer ${process.env.COREPACK_NPM_TOKEN}`,
}});
});

it(`only adds authorization header with bearer token if COREPACK_NPM_TOKEN and COREPACK_NPM_USERNAME are set`, async () => {
process.env.COREPACK_NPM_TOKEN = `kcaperoc`;
process.env.COREPACK_NPM_USERNAME = `john`;
process.env.COREPACK_NPM_PASSWORD = `easypass123`;

await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${DEFAULT_NPM_REGISTRY_URL}/package-name`, {headers: {
...DEFAULT_HEADERS,
authorization: `Bearer ${process.env.COREPACK_NPM_TOKEN}`,
}});
});


it(`adds authorization header with basic auth if COREPACK_NPM_USERNAME and COREPACK_NPM_PASSWORD are set`, async () => {
process.env.COREPACK_NPM_USERNAME = `john`;
process.env.COREPACK_NPM_PASSWORD = `easypass123`;

const encodedPassword = Buffer.from(`${process.env.COREPACK_NPM_PASSWORD}`, `base64`).toString(`utf8`);
const encodedCreds = Buffer.from(`${process.env.COREPACK_NPM_USERNAME}:${encodedPassword}`, `utf8`).toString(`base64`);

await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${DEFAULT_NPM_REGISTRY_URL}/package-name`, {headers: {
...DEFAULT_HEADERS,
authorization: `Basic ${encodedCreds}`,
}});
});

it(`does not add authorization header if COREPACK_NPM_USERNAME is set and COREPACK_NPM_PASSWORD is not.`, async () => {
process.env.COREPACK_NPM_USERNAME = `john`;

await fetchAsJson(`package-name`);

expect(httpFetchAsJson).toBeCalled();
expect(httpFetchAsJson).lastCalledWith(`${DEFAULT_NPM_REGISTRY_URL}/package-name`, {headers: DEFAULT_HEADERS});
});
});

0 comments on commit 7e61a46

Please sign in to comment.