Giter VIP home page Giter VIP logo

js-green-licenses's Introduction

JavaScript package.json License Checker

npm Version CI Dependency Status Known Vulnerabilities Code Style: Google

This is not an official Google product.

This is a tool for checking the license of JavaScript projects. It scans the package.json file to check its license and recursively checks all of its dependencies.

DISCLAIMER: This tool is NOT a replacement for legal advice or due diligence for your project's license validity. We recommend you consult a lawyer if you want legal advice.

Installation

npm install [--save-dev] js-green-licenses

If you want to install globally,

npm install -g js-green-licenses

CLI

usage: jsgl [-h] [-v] [--local <directory>] [--pr <github PR>]
            [--dev] [--verbose] [<package or package@version>]

License checker for npm modules

Positional arguments:
  <package or package@version>
                        Package name to check license for. Can include
                        version spec after @. E.g. foo@^1.2.3. Otherwise
                        latest.

Optional arguments:
  -h, --help            Show this help message and exit.
  -v, --version         Show program's version number and exit.
  --local <directory>, -l <directory>
                        Check a local directory instead of public npm.
  --pr <github PR>      Check a github pull request. Must be
                        <owner>/<repo>/pull/<id>
  --dev                 Also check devDependencies.
  --verbose             Verbose error outputs.

This tool checks licenses for 1) an already published npm package, 2) a local directory, or 3) a GitHub pull request. For checking an npm package, you can just pass the package name (optionally together with the version) as the argument. To check a local directory, you should pass the --local path/to/repo argument. To check for a GitHub PR, you should pass the --pr <owner>/<repo>/pull/<id> argument.

If the tool finds any non-green licenses in the given package or in its dependencies, they will be printed out together with the detailed information.

If you pass --dev, the devDependencies will be checked as well as the dependencies.

jsgl also checks sub-packages for --local and --pr flags when it detects that the repository is a monorepo. It assumes a certain directory structure for detecting whether a repository is a monorepo: the top-level directory should have the packages directory in it and sub-packages must exist under that directory. In that case, all the package.json files are found from sub-packages and jsgl checks all of them.

For example, when a directory foo is like this:

foo
 |
 +-- packages
 |    |
 |    +-- bar
 |    |    |
 |    |    +-- package.json
 |    |    |
 |    |    +-- ...
 |    |
 |    +-- baz
 |         |
 |         +-- package.json
 |         |
 |         +-- ...
 |
 +-- package.json
 |
 +-- ...

, jsgl checks all of foo/package.json, foo/packages/bar/package.json, and foo/packages/baz/package.json.

Configurations

You can customize how jsgl works with the configuration file, named js-green-licenses.json. For example, you can specify the license list that you would like to consider green. The license IDs must be listed in the greenLicenses section of the configuration file. In that case, jsgl will use that custom list instead of its default list.

The default green license list is:

const DEFAULT_GREEN_LICENSES = [
  '0BSD',         'AFL-2.1',      'AFL-3.0',      'APSL-2.0',     'Apache-1.1',
  'Apache-2.0',   'Artistic-1.0', 'Artistic-2.0', 'BSD-2-Clause', 'BSD-3-Clause',
  'BSL-1.0',      'CC-BY-1.0',    'CC-BY-2.0',    'CC-BY-2.5',    'CC-BY-3.0',
  'CC-BY-4.0',    'CC0-1.0',      'CDDL-1.0',     'CDDL-1.1',     'CPL-1.0',
  'EPL-1.0',      'FTL',          'IPL-1.0',      'ISC',          'LGPL-2.0',
  'LGPL-2.1',     'LGPL-3.0',     'LPL-1.02',     'MIT',          'MPL-1.0',
  'MPL-1.1',      'MPL-2.0',      'MS-PL',        'NCSA',         'OpenSSL',
  'PHP-3.0',      'Ruby',         'Unlicense',    'W3C',          'Xnet',
  'ZPL-2.0',      'Zend-2.0',     'Zlib',         'libtiff',
];

You can also allowlist some npm packages and they will be considered "green" even when they have non-green licenses or no licenses. It's useful when jsgl is unable to verify the validness of a certain package's license for some reason. For example, when a package doesn't specify its license in its package.json but has a separate LICENSE file, jsgl can't verify that. You can allowlist that package to make jsgl not complain about that package.

A typical configuration file looks like this:

{
  "greenLicenses": [
    // Custom green licenses.
    "Apache-2.0",
    "MIT",
    "BSD-3-Clause",
    ...
  ],
  "packageAllowlist": [
    /* packages considered ok */
    "foo",
    "bar",  // inline comment
    "package-with-no-license",
    "package-with-okish-license",
    ...
  ]
}

The greenLicenses section is for the custom license list and the packageAllowlist section is for the package allowlist.

Note that comments are allowed in js-green-licenses.json.

The configuration file must be located in the top-level directory of a repository for --local and --pr. When checking remote npm packages, jsgl tries to locate the configuration file in the current local directory from which jsgl is invoked.

It is desirable that the license names in the greenLicenses section be valid license IDs defined in https://spdx.org/licenses/ whenever possible.

Interface as a Library

You can also use js-green-licenses as a library as well as a command-line utility. Usually the LicenseChecker class is the only one you would have to use.

Instantiation

const opts = {
  dev: false,
  verbose: true,
};
const checker = new LicenseChecker(opts);

Both the dev and the verbose fields are optional and default to false. When dev is true, the devDependencies section is checked as well as the dependencies section of package.json. When verbose is true, jsgl generates more verbose output.

Use in Gulp

const jsgl = require('js-green-licenses');

gulp.task('check_licenses', function() {
  const checker = new jsgl.LicenseChecker({
    dev: true,
    verbose: false,
  });
  checker.setDefaultHandlers();
  return checker.checkLocalDirectory('.');
});

Methods

  • LicenseChecker#setDefaultHandler()

    setDefaultHandlers(): void;

    Sets the default event handlers that are used by the CLI. For events emitted by LicenseChecker, see the Events subsection.

  • LicenseChecker#checkLocalDirectory()

    checkLocalDirectory(directory: string): Promise<void>;

    This provides the functionality of the CLI when the --local flag is passed. It finds and checks the package.json file in the directory and recursively checks its dependencies. This method also detects monorepos and checks sub-packages as well, as explained in the CLI section above.

    This method reads in the configuration from the js-green-licenses.json file in the directory, if it exists.

  • LicenseChecker#checkRemotePackage()

    checkRemotePackage(pkg: string): Promise<void>;

    This provides the functionality of the CLI when neither --local or --pr is passed. It retrieves and checks the package.json for the remote npm package and recursively checks its dependencies.

    This method reads in the configuration from the js-green-licenses.json file in the current directory of the Node.js process.

  • LicenseChecker#checkGitHubPR()

    checkGitHubPR(repo: GitHubRepository, mergeCommitSha): Promise<void>;

    This provides the functionality of the CLI when the --pr flag is passed. It retrieves the package.json file from the GitHub repository at the given commit SHA and checks its license and recursively checks its dependencies. This method also detects monorepos and checks sub-packages as well, as explained in the CLI section above.

    This method reads in the configuration from the js-green-licenses.json file in the repository, if it exists.

    GitHubRepository is a helper class for interacting with the GitHub API. You can create its instance by calling LicenseChecker#prPathToGitHubRepoAndId().

  • LicenseChecker#prPathToGitHubRepoAndId()

    prPathToGitHubRepoAndId(prPath: string): {
        repo: GitHubRepository;
        prId: string;
    };

    prPath must be in the form, <owner>/<repo>/pull/<id>. This method will return the GitHubRepository instance and the PR id for the prPath.

Events

A LicenseChecker object emits following events during its processing.

  • non-green-license Emitted when a package with a non-green license is detected. The argument is

    interface NonGreenLicense {
      packageName: string;
      version: string;
      licenseName: string|null;
      parentPackages: string[];
    }
  • package.json Emitted for each package.json file being checked. This is emitted only when checking local repositories or GitHub repositories, but not when checking remote packages.

    The argument is a file path string of the corresponding package.json file.

  • end Emitted when the processing is done. No argument is given.

  • error Emitted when an error occurrs while processing. The argument is

    interface CheckError {
      err: Error;
      packageName: string;
      versionSpec: string;
      parentPackages: string[];
    }

js-green-licenses's People

Contributors

bcoe avatar dependabot[bot] avatar github-actions[bot] avatar greenkeeper[bot] avatar jinwoo avatar justinbeckwith avatar mat-sz avatar ofrobots avatar release-please[bot] avatar renovate-bot avatar renovate[bot] avatar royschut avatar rspier avatar splix avatar syedsaadqamar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

js-green-licenses's Issues

Support local-path versions

The version field can support local paths.

Currently when such a version is encountered an error results:

Error while checking arcs@file:../:
  [email protected] -> arcs@file:../

{ VersionNotFoundError: Version `file:../` for package `arcs` could not be found
    at Object.packageJson [as default] (/Users/plindner/arcs/storage-pouchdb/server/node_modules/package-json/index.js:87:23)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'VersionNotFoundError' }

semver parsing issue with leading zeros

I believe that the following library is failing to be found due to leading zeros in the version. This may be a semver issue.

Here's the error that I am seeing:

Error while checking esprima-fb@~3001.0001.0000-dev-harmony-fb:
  [email protected] -> [email protected] -> [email protected] -> [email protected] -> esprima-fb@~3001.0001.0000-dev-harmony-fb

{ VersionNotFoundError: Version `~3001.0001.0000-dev-harmony-fb` for package `esprima-fb` could not be found
    at Object.packageJson [as default] (/Users/plindner/arcs/storage-pouchdb/server/node_modules/package-json/index.js:87:23)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'VersionNotFoundError' }

Seeking workaround for git url

I have a problem about PackageNotFoundError.

If using github url for package.json (e.g. dependencies: { "package-a": "git+ssh://[email protected]/...." }), above error occurs after execute jsgl --local ..

The reason is package-json does not support git url and the issue is here.

As described above, I understand the unnecessity of fetching package from git url (because the aim of js-green-licenses is also for the open source library's license).

However, for some reasons (e.g. there are no private registries in the organization), it is not possible to remove those git url packages.

So I have 3 proposals.

  1. remove package directed to git url before iterating
  2. if package is allow-listed and is directed to git url, do not fetch from npm registry
  3. using git-package-json

At last I have a question.

Do you think which workaround is the best?

Encountered `Cannot read property <package version> of undefined`

When running the unit tests on @google-cloud/error-reporting on Node 4, the following error occurred when running jsgl:

> @google-cloud/[email protected] license-check /root/project
> jsgl --local .

Checking package.json...

Error while checking @google-cloud/common@^0.17.0:
  @google-cloud/[email protected] -> @google-cloud/common@^0.17.0

[TypeError: Cannot read property '^0.17.0' of undefined]

1 errors found.

npm ERR! Linux 4.4.0-116-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "license-check"
npm ERR! node v4.8.7
npm ERR! npm  v2.15.11
npm ERR! code ELIFECYCLE
npm ERR! @google-cloud/[email protected] license-check: `jsgl --local .`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @google-cloud/[email protected] license-check script 'jsgl --local .'.
npm ERR! This is most likely a problem with the @google-cloud/error-reporting package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     jsgl --local .
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs @google-cloud/error-reporting
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! 
npm ERR!     npm owner ls @google-cloud/error-reporting
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /root/project/npm-debug.log
npm ERR! Test failed.  See above for more details.
Exited with code 1

Whitelist specific versions

Is it possible to add a feature to whitelist only certain versions of a package?
Whitelisting only the package name doesn't really help when the license is changed by the package owner (especially when it's not reflected in the package.json of that package). I can only verify (manually) the current version in use and whitelist that if it has a "green license". But if the owner later decides to change the license, I still have the package excluded...

Ideally the packageAllowList would allow entries like "[email protected]" to lock a version.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dealing with unpublished packages

We have 2 independent projects one depend on another. Say ProjectApp which uses ProjetLib. During the development we publish each commit to the ProjectLib as a tarbal accessible by an URL. And we want to use that development/snapshot version in ProjectApp. Which works fine by itself, we are able to reference it by URL.

But the problem that js-green-license doesn't work in that situation because it tries to download package.json of ProjectLib from NPM, which doesn't exist:

VersionNotFoundError: Version `^0.9.0-dev` for package `@emeraldpay/emerald-vault-core` could not be found

I see a couple of ways how js-green-license can deal with it, and I can submit a PR with one of the solution, but I'd like to hear js-green-license authors opinion on this.

I think that the most straightforward solution would be using packageAllowlist and ignoring unpublished dependencies which are in this list. I mean just skip VersionNotFoundError for such packages, but check them if they exist. Is that ok?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/strip-json-comments Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency make-dir to v5
  • fix(deps): update dependency meow to v13
  • fix(deps): update dependency package-json to v10
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/ci.yaml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/checkout v3
  • actions/setup-node v3
  • actions/checkout v3
  • actions/setup-node v3
  • actions/checkout v3
  • actions/setup-node v3
.github/workflows/release.yaml
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • gaxios ^5.0.0
  • meow ^9.0.0
  • npm-package-arg ^8.0.0
  • package-json ^7.0.0
  • semver ^7.3.2
  • spdx-correct ^3.0.0
  • spdx-satisfies ^5.0.0
  • strip-json-comments ^3.0.0
  • @types/mocha ^10.0.0
  • @types/node ^18.0.0
  • @types/npm-package-arg ^6.0.0
  • @types/proxyquire ^1.3.28
  • @types/semver ^7.2.0
  • @types/spdx-correct ^3.0.0
  • @types/spdx-satisfies ^0.1.0
  • @types/strip-json-comments 0.0.30
  • c8 ^7.12.0
  • gts ^3.0.0
  • inline-fixtures ^1.1.0
  • make-dir ^3.0.0
  • mocha ^10.0.0
  • mock-fs ^5.0.0
  • nock ^13.0.0
  • proxyquire ^2.0.1
  • typescript ~4.9.0
  • node ^12.20.0 || ^14.13.1 || >=16.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

VersionNotFoundError: Version `https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz` for package `xlsx` could not be found

In my package.json I have following dependency:

"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz"

xlsx is published under Apache 2.0 license.

I included xlsx in packageAllowlist. Nevertheless I get

Error while checking xlsx@https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz:
  [email protected] -> xlsx@https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz

VersionNotFoundError: Version `https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz` for package `xlsx` could not be found
    at packageJson (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\node_modules\package-json\index.js:83:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async LicenseChecker.checkLicenses (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\checker.js:237:26)
    at async LicenseChecker.checkLicensesForDeps (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\checker.js:256:13)
    at async LicenseChecker.checkPackageJson (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\checker.js:290:9)
    at async LicenseChecker.checkPackageJsonContent (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\checker.js:300:13)
    at async LicenseChecker.checkLocalDirectory (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\checker.js:360:13)
    at async main (C:\python_env\App\WinPython\n\node_modules\js-green-licenses\build\src\cli.js:65:9)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.