Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ test/tools/trigger-appveyor-tests.sh
jsconfig.json
travis_after_all.py
/.nyc_output
/examples
9 changes: 9 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,12 @@ Some tests deliberately contain lines with only whitespace, to check how
multiline commit messages behave across operating systems. If your editor
strips trailing whitespace on save, turn that off for `test/` before editing
those files, or the tests will change in ways you didn't intend.

### A commitizen config in your home directory can change test results

Config loading comes from `@commitizen/config`, which falls back to `.czrc`,
`.cz.json` or `package.json` in your home directory when a project has none.
Unlike commitizen's old built-in loader, it doesn't skip that step while tests
run. If you have one of those files in your home directory, the `init` tests
may see an adapter as already configured. Rename the file while you run the
tests.
89 changes: 84 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ Simply use `git cz` or just `cz` instead of `git commit` when committing. You ca
_Alternatively_, if you are using **npm 5.2+** you can [use `npx`](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) instead of installing globally:

```sh
npx cz
npx --no -- cz
```

`--no` stops npx from downloading anything when commitizen isn't installed in the project. Without it, npx would fetch an unrelated npm package that is also named `cz`. With pnpm, use `pnpm exec cz`.

or as an npm script:

```json
Expand All @@ -44,7 +46,7 @@ When you're working in a Commitizen-friendly repository, you'll be prompted to f

### If your repo is NOT Commitizen friendly:

If you're **not** working in a Commitizen-friendly repository, then `git cz` will work just the same as `git commit`, but `npx cz` will use the [streamich/git-cz](https://github.com/streamich/git-cz) adapter. To fix this, you need to first [make your repo Commitizen friendly](#making-your-repo-commitizen-friendly)
If you're **not** working in a Commitizen-friendly repository, then `git cz` will work just the same as `git commit`. To fix this, you need to first [make your repo Commitizen friendly](#making-your-repo-commitizen-friendly)

## Making your repo Commitizen friendly

Expand Down Expand Up @@ -162,7 +164,7 @@ For `husky` users, add the following configuration to the project's `package.jso
```json
"husky": {
"hooks": {
"prepare-commit-msg": "exec < /dev/tty && npx cz --hook || true"
"prepare-commit-msg": "exec < /dev/tty && npx --no -- cz --hook || true"
}
}
```
Expand Down Expand Up @@ -283,7 +285,84 @@ We know that every project and build process has different requirements, so we'v
- [cz-vinyl](https://github.com/Exlint/cz-vinyl)
- [commit-jazzer](https://github.com/Zilero232/commit-jazzer)

To create an adapter, just fork one of these great adapters and modify it to suit your needs. We pass you an instance of [Inquirer.js](https://github.com/SBoudrias/Inquirer.js/), but you can capture input using whatever means necessary. Just call the `commit` callback with a string and we'll be happy. Publish it to npm, and you'll be all set!
### Writing an adapter

An adapter can work in one of two ways.

**As a program (adapter protocol).** Commitizen runs your adapter as its own
Node.js program, so you can use any prompt library, ES modules and top-level
`await`, and you don't need to depend on `commitizen`. Declare it in the
adapter's `package.json`:

```json
{
"main": "./bin.js",
"commitizenAdapter": {
"protocol": [1],
"bin": "./bin.js"
}
}
```

Commitizen runs `bin` with the same Node.js and your terminal, and sets:

| Variable | Meaning |
|---|---|
| `CZ_PROTOCOL` | The protocol version, currently `1`. |
| `CZ_MESSAGE_FILE` | An empty file. Write the commit message to it. |
| `CZ_CONFIG_FILE` | A JSON file with the project's commitizen config (`config.commitizen`, `.czrc` or `.cz.json`). |
| `CZ_GIT_ROOT` | The repository root. |

Exit with 0 after writing the message and commitizen commits it, including
`--hook` and `--retry` support. Exit with 0 without writing anything to cancel,
or exit non-zero to abort; commitizen exits with the same status. `main` must
point at a file that exists, because commitizen resolves the adapter path the
same way for every adapter. See [examples/protocol-adapter](examples/protocol-adapter)
for a complete adapter with no dependencies.

**As a module (original API).** Export a `prompter(cz, commit)` function.
Commitizen loads the module with `require()` and passes an instance of
[Inquirer.js](https://github.com/SBoudrias/Inquirer.js/) 8, though you can
capture input using whatever means necessary. Call the `commit` callback with a
string and we'll be happy. Existing adapters keep working this way.

Publish your adapter to npm, and you'll be all set!

## Security: risks and how to reduce them

Commitizen runs code from your project's dependencies, and sometimes from the repository itself. Plain `git commit` doesn't. This section explains the risks and what you can do about each.

### Risks

- **An adapter runs with your full permissions.** Commitizen runs the adapter named in `config.commitizen.path`, either inside its own process (a `prompter` adapter) or as a separate program (a protocol adapter). Either way it runs as you. It can read your files, SSH keys and environment variables (including tokens), change your working tree and staged files, and run git. Commitizen can't limit what an adapter does.
- **A repository can bring its own adapter.** `config.commitizen.path` can name a file inside the repository, such as `./tools/adapter.js`. Running `git cz` in a repository you've just cloned can then run that repository's code, just as `npm test` would.
- **An adapter can change what gets committed.** Commitizen commits whatever is staged when the adapter finishes.
- **Some adapters send data elsewhere.** Adapters that integrate with issue trackers or AI services may send your branch name, staged changes or message to that service.
- **Commit messages are kept for `--retry`.** Commitizen saves the last message for each repository in `commitizen.json` in your user cache directory (for example `~/Library/Caches/commitizen` on macOS or `~/.cache/commitizen` on Linux).
- **Installing runs code.** Depending on your package manager, installing an adapter can run install scripts from the adapter and any of its dependencies. A compromised release of any of them runs on your machine before you ever use commitizen.
- **`npx cz` can download an unrelated package.** If commitizen isn't installed in the project, `npx cz` looks for an npm package named `cz`, which isn't commitizen.

### Reducing the risk

- **Choose adapters as carefully as any dev dependency you run**, such as a test runner or linter. Prefer widely used, maintained adapters, and read what an adapter sends to other services before giving it tokens.
- **Check a repository before running `git cz` in it.** Look at `config.commitizen` in its `package.json`, `.czrc` or `.cz.json`. A path starting with `./` runs code from the repository.
- **Check your commit** with `git show --stat HEAD` when trying out an adapter you haven't reviewed.
- **Keep secrets out of commit messages.** They end up in git history anyway.
- **Run the commitizen installed in your project**, not one npx downloads: `npx --no -- cz`, `pnpm exec cz` or `node_modules/.bin/cz`. `--no` makes npx fail instead of downloading.
- **Commit your lockfile and install exact versions** (`--save-exact`, as in the examples above), so everyone runs the versions you reviewed.
- **Delay new releases.** Most attacks through npm are found and removed within days. A minimum release age makes your package manager ignore versions newer than that, and avoid install scripts where you can:

| Package manager | `commitizen init` | Install scripts from dependencies | Minimum release age |
|---|---|---|---|
| npm | default | Run by default. Use `--ignore-scripts` or `ignore-scripts=true` in `.npmrc`. | [`min-release-age`](https://docs.npmjs.com/cli/v11/using-npm/config#min-release-age) (days), npm 11.10+ |
| Yarn 1 | `--yarn` | Run by default. Use `--ignore-scripts`. | Not available |
| Yarn 2+ | `--yarn` | Run by default. Set `enableScripts: false` in `.yarnrc.yml`. | [`npmMinimalAgeGate`](https://yarnpkg.com/configuration/yarnrc#npmMinimalAgeGate), Yarn 4.10+ |
| pnpm | `--pnpm` | Not run: commitizen passes `--ignore-scripts`, and pnpm 10+ runs dependency scripts only for packages you allow. | [`minimumReleaseAge`](https://pnpm.io/settings#minimumreleaseage) (minutes); on by default (1 day) in pnpm 11 |
| Bun | Not supported; install the adapter yourself and set `config.commitizen.path` | Run only for packages in `trustedDependencies` (and Bun's built-in list). | [`minimumReleaseAge`](https://bun.com/docs/pm/cli/install) in `bunfig.toml` (seconds) |

Commitizen itself passes the commit message to git as a single argument, never through a shell, so a message can't run commands.

To report a security problem in commitizen itself, use [GitHub's private vulnerability reporting](https://github.com/commitizen/cz-cli/security/advisories/new) rather than a public issue.

## Retrying failed commits

Expand All @@ -294,7 +373,7 @@ Please note that the retry cache may be cleared when upgrading Commitizen versio
It is important to note that if you are running `cz` from an npm script (let's say it is called `commit`) you will need to do one of the following:

- Pass `-- --retry` as an argument for your script. i.e: `npm run commit -- --retry`
- Use [npx](https://www.npmjs.com/package/npx) to find and call the `cz` executable directly. i.e: `npx cz --retry`
- Use [npx](https://www.npmjs.com/package/npx) to find and call the `cz` executable directly. i.e: `npx --no -- cz --retry`

Note that the last two options **do not** require you to pass `--` before the args but the first **does**.

Expand Down
17 changes: 17 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Security policy

## Reporting a vulnerability

Please report security problems privately through [GitHub's private vulnerability reporting](https://github.com/commitizen/cz-cli/security/advisories/new), not in a public issue or pull request.

Include what you found, the commitizen version, and steps to reproduce it if you can. We'll reply in the advisory, and credit you when the fix is published unless you'd rather not be named.

## Supported versions

Fixes are released for the latest major version only. Please upgrade before reporting a problem in an older version.

## What counts as a vulnerability

Commitizen runs the adapter your project configures, with your permissions, so an adapter doing something harmful isn't a vulnerability in commitizen itself. Report those to the adapter's maintainers. See [Security: risks and how to reduce them](README.md#security-risks-and-how-to-reduce-them) for what commitizen does and doesn't protect against.

Problems in commitizen's own code, such as running code or commands it shouldn't, are in scope.
15 changes: 9 additions & 6 deletions bin/git-cz.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ process.on('uncaughtException', function (err) {
process.exit(1);
});

// catch SIGINT signal
process.stdin.on('data', function (key) {
if (key == '\u0003') {
process.exit(130); // 128 + SIGINT
}
});
// catch SIGINT signal. Only a terminal can send Ctrl-C as data; listening on a
// pipe would read input meant for the adapter.
if (process.stdin.isTTY) {
process.stdin.on('data', function (key) {
if (key == '\u0003') {
process.exit(130); // 128 + SIGINT
}
});
}

require('../dist/cli/git-cz.js').bootstrap({
cliPath: path.join(__dirname, '../')
Expand Down
24 changes: 24 additions & 0 deletions examples/protocol-adapter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Example protocol adapter

A complete commitizen adapter using the adapter protocol, with no dependencies.
It asks for a type and a subject and writes `type: subject` as the commit
message. If the project's commitizen config has a `types` array, it offers
those types instead of the defaults.

- [package.json](package.json) declares the protocol in `commitizenAdapter`.
- [bin.js](bin.js) is the whole adapter. Under commitizen it writes the message
to `CZ_MESSAGE_FILE`; run on its own (`node bin.js`) it prints it.

To try it in a repository, point the commitizen config at this directory:

```json
{
"config": {
"commitizen": {
"path": "/absolute/path/to/cz-cli/examples/protocol-adapter"
}
}
}
```

then stage a change and run `git cz`.
38 changes: 38 additions & 0 deletions examples/protocol-adapter/bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// A complete commitizen adapter using the adapter protocol, with no
// dependencies. commitizen runs this file and commits whatever it writes to
// CZ_MESSAGE_FILE. Run on its own, it prints the message instead.
import fs from 'node:fs';
import { createInterface } from 'node:readline/promises';

const config = process.env.CZ_CONFIG_FILE
? JSON.parse(fs.readFileSync(process.env.CZ_CONFIG_FILE, 'utf8'))
: {};
const types = config.types || ['feat', 'fix', 'docs', 'chore'];

const rl = createInterface({ input: process.stdin, output: process.stdout });
const lines = rl[Symbol.asyncIterator]();

async function ask(question) {
process.stdout.write(question);
const { value, done } = await lines.next();
// Ctrl-C or end of input: exit non-zero, so commitizen commits nothing.
if (done) process.exit(130);
return value.trim();
}

const type = await ask(`Type (${types.join(', ')}): `);
const subject = await ask('Subject: ');
rl.close();

if (!types.includes(type) || subject === '') {
console.error(`A type from ${types.join(', ')} and a subject are required.`);
process.exit(1);
}

const message = `${type}: ${subject}\n`;
if (process.env.CZ_MESSAGE_FILE) {
fs.writeFileSync(process.env.CZ_MESSAGE_FILE, message);
} else {
process.stdout.write(message);
}
13 changes: 13 additions & 0 deletions examples/protocol-adapter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "cz-example-protocol-adapter",
"version": "0.0.0",
"private": true,
"description": "Minimal commitizen adapter using the adapter protocol",
"type": "module",
"main": "./bin.js",
"bin": "./bin.js",
"commitizenAdapter": {
"protocol": [1],
"bin": "./bin.js"
}
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@
"yarn-cli": "npm:yarn@1.22.22"
},
"dependencies": {
"@commitizen/config": "1.0.1",
"cachedir": "2.4.0",
"cz-conventional-changelog": "3.3.0",
"dedent": "1.7.2",
"detect-indent": "7.0.2",
"inquirer": "8.2.7",
"minimist": "1.2.8",
"strip-json-comments": "5.1.0"
"minimist": "1.2.8"
},
"nyc": {
"extends": "@istanbuljs/nyc-config-babel",
Expand Down
14 changes: 11 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions renovate.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
{
"extends": [
"github>commitizen/commitizen-renovate-config"
],
"packageRules": [
{
"description": "Adapters receive commitizen's inquirer 8 instance and many rely on its API, so inquirer stays on major version 8.",
"matchPackageNames": [
"inquirer"
],
"matchUpdateTypes": [
"major"
],
"enabled": false
}
]
}
2 changes: 1 addition & 1 deletion src/cli/strategies/git-cz.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function gitCz (rawGitArgs, environment, adapterConfig) {

let resolvedAdapterConfigPath = resolveAdapterPath(adapterConfig.path);
let resolvedAdapterRootPath = findPackageRoot(resolvedAdapterConfigPath);
let prompter = getPrompter(adapterConfig.path);
let prompter = getPrompter(adapterConfig.path, adapterConfig);
let shouldStageAllFiles = rawGitArgs.includes('-a') || rawGitArgs.includes('--all');

isClean(process.cwd(), function (error, stagingIsClean) {
Expand Down
14 changes: 12 additions & 2 deletions src/commitizen/adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import fs from 'node:fs';
import detectIndent from 'detect-indent';

import { findNearestNodeModules, isFunction } from '../common/util';
import { createProtocolPrompter, getProtocolDeclaration } from './protocol';

export {
addPathToAdapterConfig,
Expand Down Expand Up @@ -147,12 +148,21 @@ function getInstallStringMappings({ save, dev, saveDev, exact, saveExact, force
}

/**
* Gets the prompter from an adapter given an adapter path
* Gets the prompter from an adapter given an adapter path.
*
* For an adapter that declares the adapter protocol in its package.json, the
* prompter runs the adapter's program and `config` (the commitizen config) is
* passed to it. Other adapters are loaded with require(), as always.
*/
function getPrompter (adapterPath) {
function getPrompter (adapterPath, config) {
// Resolve the adapter path
let resolvedAdapterPath = resolveAdapterPath(adapterPath);

let declaration = getProtocolDeclaration(resolvedAdapterPath);
if (declaration) {
return createProtocolPrompter(declaration, config, getGitRootPath());
}

// Load the adapter
let adapter = require(resolvedAdapterPath);

Expand Down
14 changes: 4 additions & 10 deletions src/commitizen/configLoader.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import { loader } from '../configLoader';

export { load };

// Configuration sources in priority order.
var configs = ['.czrc', '.cz.json', 'package.json'];

function load (config, cwd) {
return loader(configs, config, cwd);
}
// The config loader lives in @commitizen/config so adapters can use it without
// depending on commitizen. It stays exported here as
// require('commitizen').configLoader for the adapters that already use it.
export { load } from '@commitizen/config';
Loading
Loading