diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cb96925..6db9feb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing & Maintaining -Maintainer notes for [port-kill-cli](README.md) (`pk` / `kp`): repository protection, releasing, development and branding. This file is not part of the npm package. See also [TESTING.md](TESTING.md) and [SECURITY.md](SECURITY.md). +Maintainer notes for [cross-port-kill](README.md) (`pk` / `kp`): repository protection, releasing, development and branding. This file is not part of the npm package. See also [TESTING.md](TESTING.md) and [SECURITY.md](SECURITY.md). ## Branch protection @@ -27,6 +27,20 @@ npm version patch # bumps package.json and creates the vX.Y.Z tag git push --follow-tags # triggers the publish workflow ``` +### The rename to `cross-port-kill` (2.0.0) + +The package was published as `@majidev-org/port-kill-cli` up to 1.2.0. npm cannot rename a package, so `cross-port-kill` is a new package that continues at 2.0.0. A token limited to the old package cannot create a new one, so the first release needs a token that can: + +1. On npmjs.com (*Access Tokens → Generate New Token → Granular Access Token*), create a token with **read and write** on **all packages** and a **1-day expiry**. Store it as the `NPM_TOKEN` repository secret. +2. Push the 2.0.0 commit to `main`, wait for CI to pass, then push the tag: `git tag v2.0.0 && git push origin v2.0.0`. The workflow publishes `cross-port-kill` with provenance. +3. Replace `NPM_TOKEN` with a token limited to `cross-port-kill` (read and write), and delete the 1-day token and the old package's token. +4. Deprecate the old package so its users are told where to go: + ```bash + npm deprecate @majidev-org/port-kill-cli "Renamed to cross-port-kill: npm i -g cross-port-kill (or npx cross-port-kill)" + ``` + +From 2.0.1 on, releases go through the workflow as above. + ## Development ```bash @@ -38,3 +52,5 @@ See [TESTING.md](TESTING.md) for linking the CLI locally and manual test scenari ## Branding Logo and icons live in [assets/](assets/): [logo.svg](assets/logo.svg), [icon.svg](assets/icon.svg) (plus [icon-512.png](assets/icon-512.png) and [logo.png](assets/logo.png)) and [social-preview.png](assets/social-preview.png) (1280×640, for the GitHub social card). They are not part of the npm package. The SVGs are hand-drawn shapes with no font dependency; regenerate the PNGs with headless Chrome, e.g. `google-chrome --headless --window-size=512,512 --default-background-color=00000000 --screenshot=assets/icon-512.png assets/icon.svg`. + +The animated terminal demo at the top of the README, [demo.svg](assets/demo.svg), is generated by [scripts/make-demo.mjs](scripts/make-demo.mjs) from the CLI's own table and color code, so it matches the real output. Run `node scripts/make-demo.mjs` after changing how the picker, `--info` or the result lines look. The picker layout is copied from `pickCheckboxes()` in [src/interactive.js](src/interactive.js), so update the script if that changes. The static screenshots (`screenshot-*.png`) are real terminal captures and need retaking by hand. diff --git a/PRIVACY.md b/PRIVACY.md index a4b8f69..0b9a4fb 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy Policy -`pk` (`@majidev-org/port-kill-cli`) is a local command-line tool. **It collects no data.** +`pk` (`cross-port-kill`) is a local command-line tool. **It collects no data.** ## What it does and does not do diff --git a/README.md b/README.md index 7030aa1..071e224 100644 --- a/README.md +++ b/README.md @@ -1,168 +1,180 @@

- pk – port-kill-cli logo + pk – cross-port-kill logo

-# port-kill-cli (`pk` / `kp` / `kill-port`) +# cross-port-kill (`pk` / `cpk` / `kill-port`) -[![npm version](https://img.shields.io/npm/v/@majidev-org/port-kill-cli)](https://www.npmjs.com/package/@majidev-org/port-kill-cli) +[![npm version](https://img.shields.io/npm/v/cross-port-kill)](https://www.npmjs.com/package/cross-port-kill) [![Publish](https://github.com/majidev-org/port-kill-cli/actions/workflows/publish.yml/badge.svg)](https://github.com/majidev-org/port-kill-cli/actions/workflows/publish.yml) -[![node](https://img.shields.io/node/v/@majidev-org/port-kill-cli)](https://nodejs.org) -[![license: MIT](https://img.shields.io/npm/l/@majidev-org/port-kill-cli)](LICENSE) +[![node](https://img.shields.io/node/v/cross-port-kill)](https://nodejs.org) +[![license: MIT](https://img.shields.io/npm/l/cross-port-kill)](LICENSE) -A fast, zero-dependency, cross-platform CLI to find and kill processes occupying ports on **Linux**, **macOS**, and **Windows**. +Free a port without breaking Docker or killing the wrong process. `pk 3000` works the same on **Linux**, **macOS** and **Windows** and so do [seven other names](#commands) for the same command, such as `cpk` and `kill-port`. -Stop Googling `lsof` vs `netstat`—just run `pk 3000` (`kp`, `kill-port` and `port-kill` are the same command). +- **Docker-aware:** a port published by a container is freed with `docker stop`, not by killing Docker's proxy and breaking its networking. +- **Graceful and safe:** `SIGTERM` first, `SIGKILL` only if the process won't exit, and the PID is re-checked before every signal so a recycled PID is never hit. +- **Interactive picker:** run `pk` alone to tick the ports to free from a list. +- **Type it your way:** `pk kill 3000`, `pk port 3000`, `pk what is on 3000`, `pk localhost:3000` or a pasted URL all work, and typos get a *did you mean*. +- **TCP and UDP:** TCP by default, UDP with `--udp`, `5353/udp` or `pk-udp`. +- **Zero dependencies:** nothing to download beyond the package itself, so `npx` starts instantly.

- Terminal running pk: a checklist of four listening ports with columns for port, process, PID, user, access and command. Two ports are ticked, the last row is highlighted, and a footer lists the keys: arrows move, space toggles, a selects all, enter frees the selected ports, q quits. + A terminal runs pk. A checklist of four ports appears; port 3000 (node) and port 8080 (a Docker container running nginx) are ticked and Enter is pressed. pk reports port 3000 freed by killing node via SIGTERM (graceful) and port 8080 freed by stopping the Docker container via docker stop, then 'Freed 2 of 2 ports'. Next, pk --info lists the two ports still in use, 5173 and 8000.

-[npm package](https://www.npmjs.com/package/@majidev-org/port-kill-cli) · [Source](https://github.com/majidev-org/port-kill-cli) · [Report an issue](https://github.com/majidev-org/port-kill-cli/issues) · [Security policy](SECURITY.md) · [Privacy](PRIVACY.md) · [Terms](TERMS.md) +**[Usage guide](USAGE.md)**: every command with an animation · [npm package](https://www.npmjs.com/package/cross-port-kill) · [Source](https://github.com/majidev-org/port-kill-cli) · [Report an issue](https://github.com/majidev-org/port-kill-cli/issues) · [Security policy](SECURITY.md) · [Privacy](PRIVACY.md) · [Terms](TERMS.md) -## Features -- **Zero Dependencies:** Instant startup with `npx`—no bloated `node_modules` tree. -- **Cross-Platform:** Works seamlessly on Linux (`ss`, falling back to `lsof`), macOS (`lsof`), and Windows (`netstat` / `taskkill`). -- **Safe & Graceful:** On Linux/macOS sends `SIGTERM` first so servers clean up properly, escalating to `SIGKILL` only if needed. Before every signal it re-checks that the PID still holds the port, so a recycled PID is never killed by mistake. By default only the process holding the port is stopped; `--children` adds everything running under it and `--tree` its parent too. Windows has no graceful signal for server processes, so `taskkill /T /F` (the holder and everything under it) is always used there. -- **Process Info:** Shows the process name and PID, who can reach the port (`all interfaces` or `localhost only`), and on Linux/macOS the owning user and full command line. Docker containers show their image. -- **Clear Results:** Every freed port says how it was stopped (`SIGTERM (graceful)`, `SIGTERM, then SIGKILL`, `SIGKILL (forced)`, `taskkill /T /F`, `docker stop`) and multi-port runs end with a `Freed 3 of 4 ports` summary. -- **Multi-Port & Ranges:** Kill single ports, multiple ports, or port ranges in one command. Ports are freed concurrently, so five servers take about half a second, not five times as long. Large ranges print one summary line for the free ports instead of one line each. -- **Docker-Aware:** Ports published by a Docker container are freed with `docker stop` instead of killing Docker's proxy (which would break Docker networking). Remote Docker contexts (`DOCKER_HOST=tcp://…`, `ssh://…`) are ignored, so a container on another machine is never stopped because its port number matches. -- **Interactive Mode:** Run `pk` with no arguments to see every port in use and tick the ones to free. +## Quick Start -## Requirements -- [Node.js](https://nodejs.org) 18 or newer. -- Linux: [`ss`](https://man7.org/linux/man-pages/man8/ss.8.html) (falls back to [`lsof`](https://man7.org/linux/man-pages/man8/lsof.8.html) when `ss` is missing). macOS: `lsof`. Both also use `ps` for the owner and command. -- Windows: `netstat`, `tasklist` and `taskkill`, which ship with the OS. -- Optional: [Docker](https://docs.docker.com/get-docker/) to detect and stop containers that publish ports. +Run it once without installing: -## Installation & Quick Start - -### Run without installing (`npx`) ```bash -npx @majidev-org/port-kill-cli 3000 +npx cross-port-kill 3000 ``` -### Install globally for the shortcuts +Or install it for the short commands: + ```bash -npm install -g @majidev-org/port-kill-cli -pk 3000 # or: kp 3000 (also available as `port-kill` and `kill-port`) -``` +npm install -g cross-port-kill -### Update +pk 3000 # the shortest name +cpk 3000 # same thing +kill-port 3000 # same thing, if that's the name you remember +``` -npm does not notify you about new versions of a global package, so check from time to time: +Needs [Node.js](https://nodejs.org) 18 or newer. Everything else ships with your OS (see [Requirements](#requirements)). -```bash -pk --version # what you have -npm view @majidev-org/port-kill-cli version # latest published -npm outdated -g @majidev-org/port-kill-cli # shows current vs latest (no output = up to date) +## Usage & Examples -npm install -g @majidev-org/port-kill-cli@latest # update -``` +The animations below show what each command prints. Every example works with any of the [command names](#commands). For everything in one place, with a cheat sheet, see the **[usage guide](USAGE.md)**. -With `npx`, add `@latest` (`npx @majidev-org/port-kill-cli@latest 3000`) to be sure you are not running a cached older copy. To hear about releases, use **Watch → Custom → Releases** on the [GitHub repository](https://github.com/majidev-org/port-kill-cli). +### Free ports -### Uninstall +

+ A terminal frees ports. pk 3000 frees port 3000 by killing node via SIGTERM (graceful). pk 3000 5173 8000 says port 3000 is already free and frees 5173 and 8000, then 'Freed 2 of 2 ports'. pk 4000-4003 says ports 4001 and 4003 are already free and frees 4000 and 4002. +

```bash -npm uninstall -g @majidev-org/port-kill-cli +pk 3000 # one port +pk 3000 5173 8080 # several at once (freed in parallel) +pk 3000-3005 # a range; free ports in it are just reported ``` -This removes all four commands (`pk`, `kp`, `kill-port`, `port-kill`). Use the package name, not a command name. `pk` stores no config or data, so nothing else is left behind. If you only ever used `npx`, nothing is installed; `npm cache clean --force` clears the cached download. +### Just say it -## Usage & Examples +Type what you mean in plain words. Questions only ever look, they never kill. -```bash -# Kill a single port -pk 3000 # or: kp 3000 +

+ A terminal uses plain words. pk port 3000 shows node holding port 3000 and ends with 'To free it: pk 3000'. pk kill 3000 frees it. pk what is on 8080 shows the Docker container api and how to free it; a question only ever looks. pk kil 5173 is a typo and pk answers: Unknown word 'kil'. Did you mean 'kill'? +

-# Kill multiple ports at once -pk 3000 5173 8080 # or: kp 3000 5173 8080 +```bash +pk kill 3000 # frees it (also: free, stop, close) +pk port 3000 # shows what holds it and the command to free it (also: show, check, list) +pk what is on 3000 # a question: shows, never kills (also: who uses 3000, is 3000 free) +pk kill -9 3000 # forced (also: pk force 3000) +pk kill the port on 3000 # filler words like the, on, at, using are fine +``` -# Kill a range of ports -pk 3000-3005 # or: kp 3000-3005 +A mistyped word gets a suggestion: `pk kil 3000` answers *Did you mean "kill"?*. -# Inspect what is running on a port without killing it -pk 3000 --info # or: kp 3000 --info +### Write it however you remember -# Force kill immediately (skips graceful SIGTERM) -pk 3000 --force # or: kp 3000 --force +`pk` accepts a port the way you saw it, so you can paste straight from an error message, a browser or another tool: -# Also stop everything running under it (Linux/macOS; Windows always does) -pk 3000 --children # or: kp 3000 --children +

+ A terminal frees ports written in different ways, as pasted from an error message or a browser. pk localhost:3000 frees node on 3000. pk http://localhost:5173/ frees the vite server. pk :::8000, the address from an EADDRINUSE error, frees python3 on 8000. pk udp:5353 frees UDP port 5353. pk --forse 9000 is a typo and pk answers: Did you mean '--force'? +

-# Stop its parent and everything under that, e.g. a helper's app (Linux/macOS). Asks first -pk 3000 --tree # or: kp 3000 --tree -pk 3000 --tree --yes # same, without the question (scripts) +```bash +pk :3000 # as shown by pk --info or fkill +pk localhost:3000 # any host:port; [::1]:3000 and :::3000 (EADDRINUSE) work too +pk http://localhost:5173/ # a URL from your browser or dev server +pk 3000,5173 # a comma list +pk 3000..3005 # another range style +pk udp:5353 # the protocol before or after: 5353/udp, udp/5353, 5353:udp +pk -ui 5353 # short flags combine +kill-port --port 3000 --method udp # kill-port's own syntax +``` -# Pick ports to free from an interactive list -pk # or: kp +The host part is ignored: `pk` frees the port whatever address it's bound to. A mistyped option gets a suggestion (`--forse` → *Did you mean "--force"?*). -# List every port in use (processes and Docker containers) -pk --info # or: kp --info +### See what's using a port, without killing it -# Show the installed version -pk --version # or: kp --version +

+ A terminal inspects ports without killing anything. pk 3000 --info shows node on port 3000, localhost only, with its PID, user and command, then '1 in use'. pk --info lists every port in use: two node servers, a python3 server reachable on all interfaces, and a Docker container running nginx. +

-# Show help menu -pk --help # or: kp --help +```bash +pk 3000 --info # what holds port 3000 +pk --info # every port in use, processes and Docker containers ``` -Every example works with any of the command names below. +### Docker containers -## Commands - -| Command | Notes | -| :--- | :--- | -| `pk` | Shortest alias | -| `kp` | Alias | -| `kill-port` | Alias. Clashes with the separate `kill-port` npm package if both are installed globally | -| `port-kill` | Full name, never collides with other tools | +A port published by a container is freed by stopping the container, not by killing Docker's proxy process (which would break Docker networking). -## Arguments +

+ A terminal frees a port published by Docker. pk 8080 --info shows the container api running nginx:1.27 on port 8080, listed as a container rather than as the Docker proxy process. pk 8080 then frees the port by stopping the container via docker stop. +

-| Argument | Example | Meaning | -| :--- | :--- | :--- | -| `` | `pk 3000` | A single port, 1–65535 | -| `-` | `pk 3000-3005` | An inclusive range | -| several | `pk 3000 5173 3000-3005` | Any mix of ports and ranges. Duplicates are ignored | -| none | `pk` | Interactive picker (see below) | +```bash +pk 8080 # docker stop +pk 8080 --force # docker kill +``` -## Output +### Processes that won't stop -Inspect what holds your ports without killing anything: +`pk` sends `SIGTERM` first so the server can shut down cleanly. If it's still holding the port after 300 ms, `pk` follows up with `SIGKILL`. `--force` skips straight to it.

- Terminal running pk 3000 5173 8000 8080 --info: a table of four python3 processes showing port, PID, user, whether each port is reachable on localhost only or all interfaces, and the full command line, followed by '4 in use'. + A terminal frees ports held by processes that ignore SIGTERM. pk 9000 sends SIGTERM, waits, and escalates: 'Freed port 9000 — killed node via SIGTERM, then SIGKILL'. pk 9001 --force kills immediately: 'via SIGKILL (forced)'.

-Free several ports at once. Each result says how the process was stopped, and a summary closes the run: +```bash +pk 9000 # SIGTERM, then SIGKILL only if needed +pk 9000 --force # SIGKILL immediately +``` + +### Child processes and whole apps + +By default only the process holding the port is stopped, not what runs under it and not the app that started it. Many apps hold their port in a helper (VS Code's extension host, pgAdmin's server), so the app can stay open after its port is freed. `--children` also stops what runs under the holder, such as workers behind a server. `--tree` stops its parent too, which can close the whole app and lose unsaved work, so it lists the parents and asks first. Both are Linux/macOS only.

- Terminal running pk 3000 8000: two lines reading 'Freed port … killed python3 via SIGTERM (graceful)' and the summary 'Freed 2 of 2 ports'. + A terminal stops more than the port holder. pk 3000 --children frees port 3000 and also stops the 4 worker processes under it. pk 5050 --tree lists the parent it would stop, pgadmin4, warns that unsaved work is lost and asks 'Stop them? [y/N]'. After answering y, port 5050 is freed and the parent pgadmin4 is stopped too.

-- The table fits your terminal: the command column shrinks (and is cut with `…`) to the available width, and colors follow `NO_COLOR` and are off when output is piped. **`ACCESS`** is green for `localhost only` and yellow for `all interfaces`. Containers show their id, `container` and their image. -- **`localhost only`** means the port is bound to `127.0.0.1` / `::1`. **`all interfaces`** (`0.0.0.0`, `::`, `*`) means other machines on the network can reach it. Any other bind address is printed as is. -- **`user` and `cmd`** come from `ps`, so they appear on Linux and macOS only. Windows shows the process name, PID and bind address. Commands longer than 100 characters are shortened. -- Command lines can contain secrets such as tokens passed as arguments. `ps` shows them to any local user already, but keep it in mind before pasting `pk --info` output into a bug report. -- The `Freed N of M ports` summary appears when more than one port was handled. A failure sets exit code `1`. +```bash +pk 3000 --children # the holder and everything under it +pk 5050 --tree # its parent too, after asking [y/N] +pk 5050 --tree --yes # same, without the question (scripts) +``` -## Options +### UDP ports -| Flag | Alias | Description | -| :--- | :--- | :--- | -| `--info` | `-i` | Show the process, bind address, owner and command using the port without killing it | -| `--force` | `-f` | Immediately force-kill the process (`SIGKILL` / `taskkill /F` / `docker kill`) | -| `--children` | `-c` | Also stop everything running under the process, such as workers behind a server. Linux/macOS only, because `taskkill /T` already does this on Windows | -| `--tree` | | Stop the process's parent and everything under that (which includes `--children`), for when the port is held by a helper of a larger app. Linux/macOS only. Never stops `pk`'s own terminal, `init`, a shell or a session manager. Docker containers are unaffected. It lists the parents it would stop and asks `[y/N]` first (without a terminal it refuses unless you pass `--yes`) | -| `--yes` | `-y` | Skip the `--tree` question | -| `--version` | `-v` | Print the installed version | -| `--help` | `-h` | Display usage instructions and options | +Ports are TCP unless you ask for UDP, so a plain port number never stops a UDP socket by accident. + +

+ A terminal frees a UDP port. pk 5353 says port 5353 is already free, because ports are TCP by default. pk udp ports lists the UDP ports in use: node bound to 5353 on all interfaces, and suggests 'To free one: pk 5353/udp' or picking from a list with pk --udp. pk 5353/udp frees it: 'Freed port 5353/udp — killed node via SIGTERM (graceful)'. +

+ +```bash +pk udp ports # list UDP ports in use, with commands to free them (also: pk udp) +pk tcp udp ports # list both (also: pk both) +pk 5353 --udp # UDP port 5353 +pk 5353/udp # the same, as a suffix +pk-udp 5353 # the same, as its own command +pk 5353/udp 3000 # UDP 5353 and TCP 3000 in one go +pk 53 --tcp --udp # both protocols +pk --udp --info # every UDP port in use (or: pk-udp --info) +pk --udp # pick UDP ports from the interactive list (or: pk-udp) +``` -Flags can go before or after the ports and can be combined: `pk 3000 -i`, `pk -f 3000-3005`. +### Pick from a list -By default `pk` stops only the process that holds the port, not what runs under it and not the app that started it. Many apps hold their port in a helper (VS Code's extension host, pgAdmin's server), so the window or app can stay open after its port is freed. `--children` also stops what runs under the holder. `--tree` stops the parent as well, which can close the whole app and lose unsaved work, so it lists the parents and asks before doing it. +```bash +pk # tick ports to free, see Interactive Mode below +``` ## Interactive Mode @@ -182,10 +194,6 @@ Running `pk` with no ports lists every port in use as a checkbox list, so you ti ↑↓ move · space toggle · a all · c children · t app · enter free selected · q quit ``` -The two options under the list work like the ports: move onto one with `↑`/`↓` and press `Space`, or press its key from anywhere. Ticking the app also shows the children as included. Closing the app still lists the parents and asks `[y/N]` first, and the flags `--children` / `--tree` just start with the boxes ticked. The options are hidden on Windows, where children are always stopped and `--tree` is not supported. The typed prompt has no checkboxes, so there you need the flags. - -The highlighted row is drawn as a selection bar, the line under the list shows the full owner and command of that row, and a `↑ n more` / `↓ n more` marker appears in the rule when the list is taller than your terminal. - | Key | Action | | :--- | :--- | | `↑` / `↓` (or `k` / `j`) | Move the cursor | @@ -196,9 +204,13 @@ The highlighted row is drawn as a selection bar, the line under the list shows t | `Enter` | Free the ticked ports (nothing ticked = cancel) | | `q`, `Esc` or `Ctrl+C` | Cancel without killing anything | -Long lists scroll to fit your terminal. `--force`, `--children` and `--tree` also apply here (`pk -f`, `pk --tree`). `pk --info` prints the same list without prompting. With no terminal attached (for example in a script or CI), `pk` prints the help instead of waiting for input. +The two options under the list work like the ports: move onto one with `↑`/`↓` and press `Space`, or press its key from anywhere. Ticking the app also shows the children as included. Closing the app still lists the parents and asks `[y/N]` first, and the flags `--children` / `--tree` just start with the boxes ticked. The options are hidden on Windows, where children are always stopped and `--tree` is not supported. -**Typed prompt:** when raw keypresses are not available (for example output is piped, as in `pk | tee out.txt`), the list is numbered instead and you type your choice: +The highlighted row is drawn as a selection bar, the line under the list shows the full owner and command of that row, and a `↑ n more` / `↓ n more` marker appears in the rule when the list is taller than your terminal. + +Long lists scroll to fit your terminal. `--force`, `--children` and `--tree` also apply here (`pk -f`, `pk --tree`), and `--udp` lists UDP ports instead (`pk --udp`). `pk --info` prints the same list without prompting. With no terminal attached (for example in a script or CI), `pk` prints the help instead of waiting for input. + +**Typed prompt:** when raw keypresses are not available (for example output is piped, as in `pk | tee out.txt`), the list is numbered instead and you type your choice. It has no checkboxes, so use the flags for children or the app. | Input | Frees | | :--- | :--- | @@ -208,37 +220,172 @@ Long lists scroll to fit your terminal. `--force`, `--children` and `--tree` als | `a` or `all` | Every listed entry | | Enter (empty) | Nothing, cancels | -## Exit Codes & Environment +## Options -| | | +| Flag | Alias | Description | +| :--- | :--- | :--- | +| `--info` | `-i` | Show the process, bind address, owner and command using the port without killing it | +| `--force` | `-f` | Immediately force-kill the process (`SIGKILL` / `taskkill /F` / `docker kill`) | +| `--children` | `-c` | Also stop everything running under the process, such as workers behind a server. Linux/macOS only, because `taskkill /T` already does this on Windows | +| `--tree` | | Stop the process's parent and everything under that (which includes `--children`), for when the port is held by a helper of a larger app. Linux/macOS only. Never stops `pk`'s own terminal, `init`, a shell or a session manager. Docker containers are unaffected. It lists the parents it would stop and asks `[y/N]` first (without a terminal it refuses unless you pass `--yes`) | +| `--yes` | `-y` | Skip the `--tree` question | +| `--udp` | `-u` | Use UDP ports instead of TCP. Also what `pk` and `pk --info` list. The `pk-udp` command has it built in | +| `--tcp` | `-t` | Use TCP ports (the default). With `--udp`, check both | +| `--port ` | `-p` | Ports given as an option, as `kill-port` does: `-p 3000`, `--port=3000,3001` | +| `--method ` | `-m` | The protocol, as `kill-port` does: `--method udp`. Same as `--udp` | +| `--version` | `-v` | Print the installed version | +| `--help` | `-h` | Display usage instructions and options | + +Flags can go before or after the ports, are not case-sensitive, and short ones can be combined: `pk 3000 -i`, `pk -f 3000-3005`, `pk -ui 5353`, `pk --UDP 5353`, `pk -udp 5353`. + +## Arguments + +| Argument | Examples | Meaning | +| :--- | :--- | :--- | +| port | `3000`, `:3000` | A single port, 1–65535 | +| host and port | `localhost:3000`, `127.0.0.1:3000`, `[::1]:3000`, `:::3000`, `*:3000` | The port; the host is ignored | +| URL | `http://localhost:5173/app` | Its port, or 80 / 443 when the URL has none | +| range | `3000-3005`, `3000..3005`, `3000–3005` | An inclusive range | +| list | `3000,5173,8080` | Same as separate arguments | +| with a protocol | `5353/udp`, `5353:udp`, `udp/5353`, `udp:5353`, `4000-4005/udp` | That port over UDP (or TCP), whatever the flags say | +| several | `pk 3000 5173 3000-3005 5353/udp` | Any mix of the above. Duplicates are ignored | +| none | `pk` | [Interactive picker](#interactive-mode) | + +Words work too, anywhere in the command: + +| Words | Mean | | :--- | :--- | -| Exit `0` | Success, including when a port was already free | -| Exit `1` | Bad arguments, no tool available to list ports, or a process or container could not be stopped (for example permission denied) | -| `NO_COLOR` | Set to any non-empty value to disable colored output | +| `kill`, `free`, `stop`, `close`, `end`, `release`, `terminate` | Free the ports (the default anyway) | +| `port`, `ports`, `show`, `check`, `find`, `status`, `inspect`, `list`, `ls`, `info` | `--info`, unless a kill word is also there (`pk kill port 3000` frees it) | +| `what`, `who`, `which`, `is` | A question: always `--info`, even with a kill word (`pk is 3000 free` never kills) | +| `force`, `-9` | `--force` | +| `tcp`, `udp`, `both` | The protocol. On their own they list those ports: `pk udp`, `pk tcp udp ports`, `pk both` | +| `children`, `tree`, `help`, `version` | The option of the same name | +| `on`, `at`, `the`, `and`, `all`, `only`, `open`, `using`, `uses`, `by`, `in`, `of`, `for`, `my`, `please`, … | Ignored | + +An explicit flag always wins: `pk kill 3000 --info` only looks. + +## Commands + +Installing the package adds ten commands. The first eight are the same program, so pick the one you remember or type fastest. + +| Command | Example | Why it's there | +| :--- | :--- | :--- | +| `pk` | `pk 3000` | Shortest: **p**ort **k**ill | +| `kp` | `kp 3000` | Same letters reversed: **k**ill **p**ort | +| `cpk` | `cpk 3000` | **C**ross **p**ort **k**ill, the package name shortened | +| `ckp` | `ckp 3000` | **C**ross **k**ill **p**ort | +| `port-kill` | `port-kill 3000` | Spelled out | +| `kill-port` | `kill-port 3000` | Spelled out the other way round | +| `cross-port-kill` | `cross-port-kill 3000` | Matches the package name, so it's the same in `npx` and after installing | +| `cross-kill-port` | `cross-kill-port 3000` | Package name the other way round | + +Two more commands start with a protocol chosen, for when you work with UDP often: + +| Command | Example | Same as | +| :--- | :--- | :--- | +| `pk-udp` | `pk-udp 5353` | `pk 5353 --udp` | +| `pk-tcp` | `pk-tcp 3000` | `pk 3000 --tcp`, which is also plain `pk 3000` | + +Every option works with them (`pk-udp --info`, `pk-udp` alone opens the picker with UDP ports). A suffix still wins (`pk-udp 3000/tcp` is TCP), and adding the other flag checks both (`pk-udp 53 --tcp`). + +If another globally installed tool also provides `pk`, `port-kill` or `kill-port`, whichever was installed last takes that name. `cross-port-kill` and `cross-kill-port` are unlikely to be taken by anything else, so use them in scripts and shared docs. ## Using in `package.json` Scripts -Ensure your dev port is always free before starting your server: + +Make sure your dev port is free before your server starts: ```json { "scripts": { - "predev": "npx @majidev-org/port-kill-cli 3000", + "predev": "npx cross-port-kill 3000", "dev": "next dev" } } ``` +For a team project, add it as a dev dependency so everyone gets the same version and the script needs no download: + +```bash +npm install --save-dev cross-port-kill +``` + +```json +{ + "scripts": { + "predev": "cross-port-kill 3000 5173", + "dev": "next dev", + "ports": "cross-port-kill --info" + } +} +``` + +Use `cross-port-kill` (not `pk`) in scripts: it is the name least likely to clash with another tool on a teammate's machine. + +## Reading the Output + +- Every freed port says how it was stopped: `SIGTERM (graceful)`, `SIGTERM, then SIGKILL`, `SIGKILL (forced)`, `taskkill /T /F` or `docker stop`. When more than one port was handled, a `Freed N of M ports` summary closes the run. +- The table fits your terminal: the command column shrinks (and is cut with `…`) to the available width, and colors follow `NO_COLOR` and are off when output is piped. Containers show their id, `container` and their image. +- **`ACCESS`** is green for `localhost only` (bound to `127.0.0.1` / `::1`) and yellow for `all interfaces` (`0.0.0.0`, `::`, `*`), which means other machines on the network can reach the port. Any other bind address is printed as is. +- UDP ports show as `:5353/udp` in the table and in results. TCP ports have no suffix. +- `--info` ends with the command that frees what it showed (`To free it: pk 3000`), using the command name you typed. +- **`user` and `cmd`** come from `ps`, so they appear on Linux and macOS only. Windows shows the process name, PID and bind address. Commands longer than 100 characters are shortened. +- Command lines can contain secrets such as tokens passed as arguments. `ps` shows them to any local user already, but keep it in mind before pasting `pk --info` output into a bug report. + +## How It Works + +- **Finding ports:** Linux uses `ss` (falling back to `lsof`), macOS uses `lsof`, and Windows uses `netstat`, each in a single call. A TCP port counts when something listens on it; a UDP port when a socket is bound to it. Connected UDP client sockets (a DNS lookup, a QUIC connection) are ignored. +- **Stopping processes:** on Linux/macOS, `SIGTERM` first and `SIGKILL` only if the process is still there after 300 ms. Before every signal `pk` re-checks that the PID still holds the port, so a recycled PID is never killed by mistake. Windows has no graceful signal for server processes, so `taskkill /T /F` (the holder and everything under it) is always used there. +- **Docker:** ports published by a running container are matched to that container (by port and protocol) and freed with `docker stop`, never by killing Docker's proxy. Remote Docker contexts (`DOCKER_HOST=tcp://…`, `ssh://…`) are ignored, so a container on another machine is never stopped because its port number matches. +- **Speed:** ports are freed concurrently, so five servers take about half a second, not five times as long. Large ranges print one summary line for the free ports instead of one line each. + +## Requirements + +- [Node.js](https://nodejs.org) 18 or newer. +- Linux: [`ss`](https://man7.org/linux/man-pages/man8/ss.8.html) (falls back to [`lsof`](https://man7.org/linux/man-pages/man8/lsof.8.html) when `ss` is missing). macOS: `lsof`. Both also use `ps` for the owner and command. +- Windows: `netstat`, `tasklist` and `taskkill`, which ship with the OS. +- Optional: [Docker](https://docs.docker.com/get-docker/) to detect and stop containers that publish ports. + +## Exit Codes & Environment + +| | | +| :--- | :--- | +| Exit `0` | Success, including when a port was already free | +| Exit `1` | Bad arguments, no tool available to list ports, or a process or container could not be stopped (for example permission denied) | +| `NO_COLOR` | Set to any non-empty value to disable colored output | + ## Security `pk` runs every system tool without a shell, validates ports as integers in 1–65535, and strips control, bidi and zero-width characters from process names before printing them (a process can name itself anything, including terminal escape codes). If no tool can list ports it fails with an error instead of claiming a port is free. On Windows, commands are resolved from `System32` so a stray `netstat.exe` in the current folder is never run. Killing another user's process needs `sudo` or Administrator rights. See [SECURITY.md](SECURITY.md) for the full list and how to report a vulnerability. -## Contributing +## Update -Bug reports and ideas are welcome in the [issue tracker](https://github.com/majidev-org/port-kill-cli/issues). To work on the code, see [CONTRIBUTING.md](CONTRIBUTING.md) and [TESTING.md](TESTING.md). +npm does not notify you about new versions of a global package, so check from time to time: -## Terms, Privacy & License +```bash +pk --version # what you have +npm view cross-port-kill version # latest published +npm outdated -g cross-port-kill # shows current vs latest (no output = up to date) -`pk` terminates processes, so read the [Terms of Use](TERMS.md) before using it on systems you don't own. It collects no data; see the [Privacy Policy](PRIVACY.md). Vulnerabilities go through the [Security Policy](SECURITY.md). +npm install -g cross-port-kill@latest # update +``` + +With `npx`, add `@latest` (`npx cross-port-kill@latest 3000`) to be sure you are not running a cached older copy. To hear about releases, use **Watch → Custom → Releases** on the [GitHub repository](https://github.com/majidev-org/port-kill-cli). + +## Uninstall + +```bash +npm uninstall -g cross-port-kill +``` + +This removes all ten commands (`pk`, `kp`, `cpk`, `ckp`, `port-kill`, `kill-port`, `cross-port-kill`, `cross-kill-port`, `pk-udp`, `pk-tcp`). Use the package name, not a command name. `pk` stores no config or data, so nothing else is left behind. If you only ever used `npx`, nothing is installed; `npm cache clean --force` clears the cached download. + +## Contributing + +The full [usage guide](USAGE.md) covers every command. Bug reports and ideas are welcome in the [issue tracker](https://github.com/majidev-org/port-kill-cli/issues). To work on the code, see [CONTRIBUTING.md](CONTRIBUTING.md) and [TESTING.md](TESTING.md). + +## License, Terms & Privacy -## License [MIT](LICENSE) © [Majid Ali](https://majidev.netlify.app) + +`pk` terminates processes, so read the [Terms of Use](TERMS.md) before using it on systems you don't own. It collects no data; see the [Privacy Policy](PRIVACY.md). Vulnerabilities go through the [Security Policy](SECURITY.md). diff --git a/SECURITY.md b/SECURITY.md index 0f0ccff..49add63 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -10,7 +10,7 @@ Please do **not** open a public issue for security problems. Use GitHub's privat [majidev.netlify.app](https://majidev.netlify.app) and ask for a private channel. Only the latest published version is supported; fixes ship as a new patch release on -[npm](https://www.npmjs.com/package/@majidev-org/port-kill-cli). +[npm](https://www.npmjs.com/package/cross-port-kill). ## What `pk` does to stay safe diff --git a/TERMS.md b/TERMS.md index 48b5d26..0729d60 100644 --- a/TERMS.md +++ b/TERMS.md @@ -1,6 +1,6 @@ # Terms of Use -By installing or running `pk` / `port-kill` (`@majidev-org/port-kill-cli`) you agree to these terms. They sit alongside the [MIT License](LICENSE), which governs copying and modification of the code; if the two conflict, the license wins. +By installing or running `cross-port-kill` under any of its command names (`pk`, `kp`, `cpk`, `ckp`, `port-kill`, `kill-port`, `cross-port-kill`, `cross-kill-port`, `pk-udp`, `pk-tcp`) you agree to these terms. They sit alongside the [MIT License](LICENSE), which governs copying and modification of the code; if the two conflict, the license wins. ## 1. What the tool does diff --git a/TESTING.md b/TESTING.md index 685e105..927133b 100644 --- a/TESTING.md +++ b/TESTING.md @@ -1,6 +1,6 @@ # Local Development & Testing Guide -Follow these steps to link, run, and test `port-kill-cli` (`pk` / `kp`) locally before publishing to npm. See the [README](README.md) for usage and [SECURITY.md](SECURITY.md) for the safety checks these tests exercise. +Follow these steps to link, run, and test `cross-port-kill` (`pk` / `kp`) locally before publishing to npm. See the [README](README.md) for usage and [SECURITY.md](SECURITY.md) for the safety checks these tests exercise. **Requirements:** [Node.js](https://nodejs.org) 18+; `lsof` (or `ss` on Linux); optionally [Docker](https://docs.docker.com/get-docker/) for Test E. @@ -14,11 +14,19 @@ chmod +x bin/cli.js npm link ``` -This creates a global symlink so you can run `pk`, `kp` and `port-kill` from any directory. Verify it works: +This creates a global symlink so you can run all ten commands (`pk`, `kp`, `cpk`, `ckp`, `port-kill`, `kill-port`, `cross-port-kill`, `cross-kill-port`, `pk-udp`, `pk-tcp`) from any directory. Verify it works: ```bash pk --help kp --version +cpk --version +ckp --version +port-kill --version +kill-port --version +cross-port-kill --version +cross-kill-port --version +pk-udp --version +pk-tcp --version # all ten print the same version ``` --- @@ -80,13 +88,33 @@ Each scenario starts a throwaway server with `node -e "require('http').createSer ### Test D: Invalid Input & Edge Cases ```bash -pk 99999 # (or kp 99999) ✖ Invalid port or range: "99999" (expected 1–65535, e.g. 3000 or 3000-3005) -pk abc # (or kp abc) ✖ Invalid port or range: "abc" (expected 1–65535, e.g. 3000 or 3000-3005) +pk 99999 # (or kp 99999) ✖ Invalid port or range: "99999" (expected 1–65535, e.g. 3000, 3000-3005, :3000, localhost:3000 or 5353/udp) +pk abc # (or kp abc) ✖ Invalid port or range: "abc" (expected 1–65535, e.g. 3000, 3000-3005, :3000, localhost:3000 or 5353/udp) pk 3005-3000 # (or kp 3005-3000) ✖ Invalid port or range … (end before start) -pk --nope # (or kp --nope) ✖ Unknown option: "--nope" +pk --nope # (or kp --nope) ✖ Unknown option: "--nope". Run pk --help to see the options. +pk --forse # (or kp --forse) ✖ Unknown option: "--forse". Did you mean "--force"? pk < /dev/null # (or kp < /dev/null) prints the help menu (no interactive prompt without a TTY) +pk 3000/sctp # (or kp 3000/sctp) ✖ Invalid port or range: "3000/sctp" (only /tcp and /udp) ``` +### Test D1: Words +Start a dummy server on `4001` (as in Test A), then: +1. `pk port 4001`, `pk what is on 4001` and `pk is 4001 free`. *Expected:* each shows the server and ends with `To free it: pk 4001`. The server keeps running. +2. `pk kil 4001`. *Expected:* `✖ Unknown word: "kil". Did you mean "kill"?`, nothing is stopped. +3. `pk kill 4001`. *Expected:* `✔ Freed port 4001 …`. +4. `pk localhost:4001` and `pk http://localhost:4001/` work the same as `pk 4001` (restart the server between runs). + +### Test D2: UDP Ports +1. Bind a UDP socket in a separate terminal: + ```bash + node -e "require('dgram').createSocket('udp4').bind(5454, () => console.log('bound 5454/udp'))" + ``` +2. Run `pk 5454`. *Expected:* `• Port 5454 is already free.` and the socket keeps running (TCP is the default). +3. Run `pk 5454 --udp --info` (or `pk 5454/udp --info`). *Expected:* a row for `:5454/udp` with the node PID. +4. Run `pk 5454/udp`. *Expected:* `✔ Freed port 5454/udp … via SIGTERM (graceful)` and the first terminal returns to the prompt. +5. Run `pk --udp`. *Expected:* the picker lists UDP ports only, each shown as `:/udp`. +6. Docker: `docker run -d --rm --name pk-udp -p 5455:53/udp alpine sleep 600`, then `pk 5455` says already free and `pk 5455/udp` stops the container via `docker stop`. + ### Test E: Docker Containers 1. Start a container that publishes a port: ```bash @@ -131,5 +159,5 @@ pk 4002 --info # or: kp 4002 --info To test the published package instead of your local checkout: ```bash -npm unlink -g @majidev-org/port-kill-cli +npm unlink -g cross-port-kill ``` diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000..b5a95ab --- /dev/null +++ b/USAGE.md @@ -0,0 +1,281 @@ +# cross-port-kill usage guide + +Every way to use `pk`, with an animation for each. For installation and an overview, see the [README](README.md). + +All examples use `pk`, but every [command name](#every-command-name) works the same: `cpk 3000`, `kill-port 3000` and `cross-port-kill 3000` are identical. + +## Contents + +- [Cheat sheet](#cheat-sheet) +- [Free ports](#free-ports) +- [Just say it](#just-say-it) +- [Write a port any way](#write-a-port-any-way) +- [Look before you kill](#look-before-you-kill) +- [TCP and UDP](#tcp-and-udp) +- [Pick from a list](#pick-from-a-list) +- [Docker containers](#docker-containers) +- [Processes that won't stop](#processes-that-wont-stop) +- [Child processes and whole apps](#child-processes-and-whole-apps) +- [Every command name](#every-command-name) +- [Scripts and CI](#scripts-and-ci) + +## Cheat sheet + +| I want to… | Type | +| :--- | :--- | +| Free port 3000 | `pk 3000` or `pk kill 3000` | +| Free several ports | `pk 3000 5173 8080` or `pk 3000,5173,8080` | +| Free a range | `pk 3000-3005` or `pk 3000..3005` | +| See what's on port 3000, without killing it | `pk port 3000` or `pk 3000 --info` or `pk what is on 3000` | +| See every port in use | `pk ports` or `pk --info` or `pk list` | +| See UDP ports in use | `pk udp` or `pk udp ports` | +| See TCP and UDP ports in use | `pk both` or `pk tcp udp ports` | +| Pick ports to free from a list | `pk` (TCP), `pk --udp` or `pk-udp` (UDP), `pk --tcp --udp` (both) | +| Free a UDP port | `pk 5353/udp` or `pk udp 5353` or `pk-udp 5353` | +| Free a port from an error message | `pk :::3000` or `pk 127.0.0.1:3000` (paste it as is) | +| Free the port in a URL | `pk http://localhost:5173/` | +| Free a port held by Docker | `pk 8080` (stops the container) | +| Kill right away, no grace period | `pk 3000 --force` or `pk kill -9 3000` or `pk force 3000` | +| Also stop the workers under it | `pk 3000 --children` | +| Close the whole app holding the port | `pk 3000 --tree` (asks first) | +| Do it in a script without questions | `cross-port-kill 3000 --tree --yes` | +| Check the version | `pk --version` or `pk version` | +| See all options | `pk --help` or `pk help` | + +## Free ports + +

+ A terminal frees ports. pk 3000 frees port 3000 by killing node via SIGTERM (graceful). pk 3000 5173 8000 says port 3000 is already free and frees 5173 and 8000, then 'Freed 2 of 2 ports'. pk 4000-4003 says ports 4001 and 4003 are already free and frees 4000 and 4002. +

+ +```bash +pk 3000 # one port +pk 3000 5173 8080 # several, freed in parallel +pk 3000-3005 # an inclusive range; ports in it that are free are just reported +pk 3000,5173 8000-8002 # any mix +``` + +Each line says how the process was stopped (`SIGTERM (graceful)`, `SIGTERM, then SIGKILL`, `SIGKILL (forced)`, `taskkill /T /F` or `docker stop`). With more than one port, a `Freed N of M ports` summary closes the run. A port that is already free is not an error. + +## Just say it + +Type what you mean. Words can go anywhere in the command, and a mistyped word gets a *did you mean*. + +

+ A terminal uses plain words. pk port 3000 shows node holding port 3000 and ends with 'To free it: pk 3000'. pk kill 3000 frees it. pk what is on 8080 shows the Docker container api and how to free it; a question only ever looks. pk kil 5173 is a typo and pk answers: Unknown word 'kil'. Did you mean 'kill'? +

+ +```bash +pk kill 3000 # frees it +pk free 3000 # same (also: stop, close, end, release, terminate) +pk port 3000 # shows what holds it and the command to free it +pk show 3000 # same (also: check, find, status, inspect, list, ls, info) +pk what is on 3000 # a question: shows, never kills +pk who uses 3000 # same +pk is 3000 free? # same, even with "free" in it +pk kill the port on 3000 # filler words are ignored +pk kill -9 3000 # forced +pk force 3000 # same +pk kil 3000 # ✖ Unknown word: "kil". Did you mean "kill"? +``` + +| Words | Mean | +| :--- | :--- | +| `kill`, `free`, `stop`, `close`, `end`, `release`, `terminate` | Free the ports (the default anyway) | +| `port`, `ports`, `show`, `check`, `find`, `status`, `inspect`, `list`, `ls`, `info` | Show info, unless a kill word is also there (`pk kill port 3000` frees it) | +| `what`, `who`, `which`, `is` | A question: always shows info, even with a kill word | +| `tcp`, `udp`, `both` | The protocol. On their own they list those ports ([TCP and UDP](#tcp-and-udp)) | +| `force`, `-9` | `--force` | +| `children`, `tree`, `help`, `version` | The option of the same name | +| `on`, `at`, `the`, `and`, `all`, `only`, `open`, `using`, `uses`, `by`, `in`, `of`, `for`, `my`, `please`, … | Ignored | + +When in doubt, `pk` looks instead of killing. An explicit flag always wins: `pk kill 3000 --info` only looks. + +## Write a port any way + +Paste a port the way you saw it, from an error message, a browser or another tool. + +

+ A terminal frees ports written in different ways, as pasted from an error message or a browser. pk localhost:3000 frees node on 3000. pk http://localhost:5173/ frees the vite server. pk :::8000, the address from an EADDRINUSE error, frees python3 on 8000. pk udp:5353 frees UDP port 5353. pk --forse 9000 is a typo and pk answers: Did you mean '--force'? +

+ +| Form | Examples | +| :--- | :--- | +| Port | `3000`, `:3000` | +| Host and port (host ignored) | `localhost:3000`, `127.0.0.1:3000`, `0.0.0.0:3000`, `[::1]:3000`, `:::3000`, `*:3000` | +| URL | `http://localhost:5173/app` (no port in the URL means 80 or 443) | +| Range | `3000-3005`, `3000..3005`, `3000–3005` | +| List | `3000,5173,8080` | +| With a protocol | `5353/udp`, `5353:udp`, `udp/5353`, `udp:5353`, `4000-4005/udp` | +| kill-port's syntax | `--port 3000`, `-p 3000,3001`, `--port=3000`, `--method udp`, `-m udp` | + +Options are forgiving too: they are not case-sensitive (`--UDP`), long ones work with one dash (`-udp`), short ones combine (`-ui` = `-u -i`), and a mistyped one gets a suggestion (`--forse` → *Did you mean "--force"?*). + +## Look before you kill + +`--info` shows what holds a port without touching it, and ends with the command that frees it. + +

+ A terminal inspects ports without killing anything. pk 3000 --info shows node on port 3000, localhost only, with its PID, user and command, then '1 in use'. pk --info lists every port in use: two node servers, a python3 server reachable on all interfaces, and a Docker container running nginx. +

+ +```bash +pk 3000 --info # one port; ends with "To free it: pk 3000" +pk port 3000 # same, in words +pk 3000 5173 --info # several; ends with "To free them: pk 3000 5173" +pk --info # every port in use; ends with example commands and how to pick +pk ports # same, in words +``` + +The table shows the port, process, PID (or container id), owner, who can reach the port and the full command line: + +- **`localhost only`** (green) means bound to `127.0.0.1` / `::1`. **`all interfaces`** (yellow) means `0.0.0.0`, `::` or `*`, reachable from other machines on the network. Any other address is printed as is. +- **User and command** come from `ps`, so they show on Linux and macOS. Windows shows the process name, PID and address. +- Command lines can contain secrets passed as arguments. Check before pasting `pk --info` output into a bug report. + +## TCP and UDP + +Ports are TCP unless you say otherwise, so `pk 5353` never stops a UDP socket by accident. + +

+ A terminal frees a UDP port. pk 5353 says port 5353 is already free, because ports are TCP by default. pk udp ports lists the UDP ports in use: node bound to 5353 on all interfaces, and suggests 'To free one: pk 5353/udp' or picking from a list with pk --udp. pk 5353/udp frees it: 'Freed port 5353/udp — killed node via SIGTERM (graceful)'. +

+ +```bash +# List +pk udp # UDP ports in use, with commands to free them +pk udp ports # same +pk tcp # TCP ports in use (same as pk ports) +pk tcp udp ports # both (also: pk both, pk tcp and udp) +pk --udp --info # the flag form + +# Free +pk 5353/udp # UDP port 5353 +pk udp 5353 # same +pk 5353 --udp # same +pk-udp 5353 # same, as its own command +pk 5353/udp 3000 # UDP 5353 and TCP 3000 together +pk 53 --tcp --udp # port 53 over both protocols + +# Pick from a list +pk --udp # UDP ports +pk-udp # same +pk kill udp # same +pk --tcp --udp # both +``` + +A protocol written on a port (`5353/udp`) wins over the flags for that port: `pk-udp 3000/tcp` is TCP. + +## Pick from a list + +Run `pk` with no ports to tick the ones to free. + +

+ A terminal runs pk. A checklist of four ports appears; port 3000 (node) and port 8080 (a Docker container running nginx) are ticked and Enter is pressed. pk reports port 3000 freed by killing node via SIGTERM (graceful) and port 8080 freed by stopping the Docker container via docker stop, then 'Freed 2 of 2 ports'. Next, pk --info lists the two ports still in use, 5173 and 8000. +

+ +| Key | Action | +| :--- | :--- | +| `↑` / `↓` (or `k` / `j`) | Move | +| `Space` | Tick or untick | +| `a` | Tick all, or untick all | +| `c` | Also stop what it started (`--children`) | +| `t` | Also close the app that started it (`--tree`) | +| `Enter` | Free the ticked ports (nothing ticked = cancel) | +| `q`, `Esc`, `Ctrl+C` | Cancel | + +```bash +pk # TCP ports +pk --udp # UDP ports (or: pk-udp) +pk -f # force-kill what you tick +pk --children # start with "also stop what it started" ticked +``` + +Without a terminal (a script, CI), `pk` prints the help instead of waiting. When output is piped, the list is numbered and you type `1 3`, `2-4` or `all`. See [Interactive Mode](README.md#interactive-mode) in the README for details. + +## Docker containers + +A port published by a container is freed by stopping the container, not by killing Docker's proxy (which would break Docker networking). + +

+ A terminal frees a port published by Docker. pk 8080 --info shows the container api running nginx:1.27 on port 8080, listed as a container rather than as the Docker proxy process. pk 8080 then frees the port by stopping the container via docker stop. +

+ +```bash +pk 8080 --info # shows the container, its id and image +pk 8080 # docker stop +pk 8080 --force # docker kill +pk 5353/udp # a container publishing UDP 5353 +``` + +Only a Docker daemon on this machine counts. Remote contexts (`DOCKER_HOST=tcp://…`, `ssh://…`) are ignored, so a container on another machine is never stopped because its port number matches. + +## Processes that won't stop + +`pk` sends `SIGTERM` first so the server can shut down cleanly, and follows up with `SIGKILL` only if it still holds the port after 300 ms. + +

+ A terminal frees ports held by processes that ignore SIGTERM. pk 9000 sends SIGTERM, waits, and escalates: 'Freed port 9000 — killed node via SIGTERM, then SIGKILL'. pk 9001 --force kills immediately: 'via SIGKILL (forced)'. +

+ +```bash +pk 9000 # SIGTERM, then SIGKILL only if needed +pk 9000 --force # SIGKILL right away (also: -f, pk kill -9 9000, pk force 9000) +``` + +Before every signal, `pk` re-checks that the PID still holds the port, so a recycled PID is never hit. On Windows there is no graceful signal for servers, so `taskkill /T /F` is always used. + +## Child processes and whole apps + +By default only the process holding the port is stopped. Linux and macOS only: + +

+ A terminal stops more than the port holder. pk 3000 --children frees port 3000 and also stops the 4 worker processes under it. pk 5050 --tree lists the parent it would stop, pgadmin4, warns that unsaved work is lost and asks 'Stop them? [y/N]'. After answering y, port 5050 is freed and the parent pgadmin4 is stopped too. +

+ +```bash +pk 3000 --children # also stop what runs under it, such as workers (also: -c, pk kill 3000 children) +pk 5050 --tree # also stop its parent app, after asking [y/N] +pk 5050 --tree --yes # same, without the question +``` + +`--tree` never stops `pk`'s own terminal, `init`, a shell or a session manager. On Windows, `taskkill /T` always stops the children and `--tree` is not supported. + +## Every command name + +One install adds ten commands: + +| Command | Same as | +| :--- | :--- | +| `pk`, `kp`, `cpk`, `ckp` | Short names | +| `port-kill`, `kill-port` | Spelled out | +| `cross-port-kill`, `cross-kill-port` | The package name; least likely to clash with other tools | +| `pk-udp` | `pk --udp` | +| `pk-tcp` | `pk --tcp` (the default) | + +```bash +npx cross-port-kill 3000 # without installing +npm install -g cross-port-kill +pk 3000 +cpk 3000 +kill-port 3000 +cross-port-kill 3000 +pk-udp 5353 +``` + +## Scripts and CI + +```json +{ + "scripts": { + "predev": "cross-port-kill 3000 5173", + "dev": "next dev", + "ports": "cross-port-kill --info" + } +} +``` + +- Use `cross-port-kill` in scripts: it is the name least likely to clash on a teammate's machine. Add it with `npm install --save-dev cross-port-kill`, or use `npx cross-port-kill` without installing. +- `--tree` asks before closing an app; in a script, pass `--yes` or it refuses. +- Exit code `0` means success (including "already free"); `1` means bad arguments, no tool to list ports, or something could not be stopped. +- Set `NO_COLOR=1` to turn colors off. They are also off when output is piped. diff --git a/assets/demo-docker.svg b/assets/demo-docker.svg new file mode 100644 index 0000000..4e5aaa8 --- /dev/null +++ b/assets/demo-docker.svg @@ -0,0 +1,95 @@ + +cross-port-kill: pk 8080 +A terminal frees a port published by Docker. pk 8080 --info shows the container api running nginx:1.27 on port 8080, listed as a container rather than as the Docker proxy process. pk 8080 then frees the port by stopping the container via docker stop. + + + + +pk 8080 +$ +$ p +$ pk +$ pk +$ pk 8 +$ pk 80 +$ pk 808 +$ pk 8080 +$ pk 8080 +$ pk 8080 - +$ pk 8080 -- +$ pk 8080 --i +$ pk 8080 --in +$ pk 8080 --inf +$ pk 8080 --info +$ pk 8080 --info +PORT PROCESS PID/ID USER ACCESS COMMAND +─────────────────────────────────────────────────────────────────────────────────────── +:8080 api a1b2c3d4e5f6containerall interfacesnginx:1.27 +─────────────────────────────────────────────────────────────────────────────────────── + 1 in use + To free it: pk 8080 +$ +$ p +$ pk +$ pk +$ pk 8 +$ pk 80 +$ pk 808 +$ pk 8080 +$ pk 8080 + Freeing port… +✔ Freed port 8080— stopped Docker container api(a1b2c3d4e5f6)via docker stop +$ +$ p +$ pk +$ pk +$ pk 8 +$ pk 80 +$ pk 808 +$ pk 8080 +$ pk 8080 +• Port 8080 is already free. +$ + diff --git a/assets/demo-force.svg b/assets/demo-force.svg new file mode 100644 index 0000000..5637489 --- /dev/null +++ b/assets/demo-force.svg @@ -0,0 +1,76 @@ + +cross-port-kill: pk 9000 +A terminal frees ports held by processes that ignore SIGTERM. pk 9000 sends SIGTERM, waits, and escalates: "Freed port 9000 — killed node via SIGTERM, then SIGKILL". pk 9001 --force kills immediately: "via SIGKILL (forced)". + + + + +pk 9000 +$ +$ p +$ pk +$ pk +$ pk 9 +$ pk 90 +$ pk 900 +$ pk 9000 +$ pk 9000 + Freeing port… +✔ Freed port 9000— killednode(PID 42100)via SIGTERM, then SIGKILL +$ +$ p +$ pk +$ pk +$ pk 9 +$ pk 90 +$ pk 900 +$ pk 9001 +$ pk 9001 +$ pk 9001 - +$ pk 9001 -- +$ pk 9001 --f +$ pk 9001 --fo +$ pk 9001 --for +$ pk 9001 --forc +$ pk 9001 --force +$ pk 9001 --force + Freeing port… +✔ Freed port 9001— killednode(PID 42101)via SIGKILL (forced) +$ + diff --git a/assets/demo-formats.svg b/assets/demo-formats.svg new file mode 100644 index 0000000..887d456 --- /dev/null +++ b/assets/demo-formats.svg @@ -0,0 +1,209 @@ + +cross-port-kill: pk localhost:3000 +A terminal frees ports written in different ways, as pasted from an error message or a browser. pk localhost:3000 frees node on 3000. pk http://localhost:5173/ frees the vite server. pk :::8000, the address from an EADDRINUSE error, frees python3 on 8000. pk udp:5353 frees UDP port 5353. pk --forse 9000 is a typo and pk answers: Did you mean '--force'? + + + + +pk localhost:3000 +$ +$ p +$ pk +$ pk +$ pk l +$ pk lo +$ pk loc +$ pk loca +$ pk local +$ pk localh +$ pk localho +$ pk localhos +$ pk localhost +$ pk localhost: +$ pk localhost:3 +$ pk localhost:30 +$ pk localhost:300 +$ pk localhost:3000 +$ pk localhost:3000 + Freeing port… +✔ Freed port 3000— killednode(PID 41210)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk h +$ pk ht +$ pk htt +$ pk http +$ pk http: +$ pk http:/ +$ pk http:// +$ pk http://l +$ pk http://lo +$ pk http://loc +$ pk http://loca +$ pk http://local +$ pk http://localh +$ pk http://localho +$ pk http://localhos +$ pk http://localhost +$ pk http://localhost: +$ pk http://localhost:5 +$ pk http://localhost:51 +$ pk http://localhost:517 +$ pk http://localhost:5173 +$ pk http://localhost:5173/ +$ pk http://localhost:5173/ + Freeing port… +✔ Freed port 5173— killednode(PID 41288)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk : +$ pk :: +$ pk ::: +$ pk :::8 +$ pk :::80 +$ pk :::800 +$ pk :::8000 +$ pk :::8000 + Freeing port… +✔ Freed port 8000— killedpython3(PID 41302)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk u +$ pk ud +$ pk udp +$ pk udp: +$ pk udp:5 +$ pk udp:53 +$ pk udp:535 +$ pk udp:5353 +$ pk udp:5353 + Freeing port… +✔ Freed port 5353/udp— killednode(PID 41500)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk - +$ pk -- +$ pk --f +$ pk --fo +$ pk --for +$ pk --fors +$ pk --forse +$ pk --forse +$ pk --forse 9 +$ pk --forse 90 +$ pk --forse 900 +$ pk --forse 9000 +$ pk --forse 9000 +✖ Unknown option: "--forse". Did you mean "--force"? +$ + diff --git a/assets/demo-free.svg b/assets/demo-free.svg new file mode 100644 index 0000000..23dd62f --- /dev/null +++ b/assets/demo-free.svg @@ -0,0 +1,119 @@ + +cross-port-kill: pk 3000 +A terminal frees ports. pk 3000 frees port 3000 by killing node via SIGTERM (graceful). pk 3000 5173 8000 says port 3000 is already free and frees 5173 and 8000, then "Freed 2 of 2 ports". pk 4000-4003 says ports 4001 and 4003 are already free and frees 4000 and 4002. + + + + +pk 3000 +$ +$ p +$ pk +$ pk +$ pk 3 +$ pk 30 +$ pk 300 +$ pk 3000 +$ pk 3000 + Freeing port… +✔ Freed port 3000— killednode(PID 41210)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk 3 +$ pk 30 +$ pk 300 +$ pk 3000 +$ pk 3000 +$ pk 3000 5 +$ pk 3000 51 +$ pk 3000 517 +$ pk 3000 5173 +$ pk 3000 5173 +$ pk 3000 5173 8 +$ pk 3000 5173 80 +$ pk 3000 5173 800 +$ pk 3000 5173 8000 +$ pk 3000 5173 8000 +• Port 3000 is already free. + Freeing 2 ports… +✔ Freed port 5173— killednode(PID 41288)via SIGTERM (graceful) +✔ Freed port 8000— killedpython3(PID 41302)via SIGTERM (graceful) +✔ Freed 2 of 2 ports +$ +$ p +$ pk +$ pk +$ pk 4 +$ pk 40 +$ pk 400 +$ pk 4000 +$ pk 4000- +$ pk 4000-4 +$ pk 4000-40 +$ pk 4000-400 +$ pk 4000-4003 +$ pk 4000-4003 +• Port 4001 is already free. +• Port 4003 is already free. + Freeing 2 ports… +✔ Freed port 4000— killednode(PID 41400)via SIGTERM (graceful) +✔ Freed port 4002— killednode(PID 41402)via SIGTERM (graceful) +✔ Freed 2 of 2 ports +$ + diff --git a/assets/demo-info.svg b/assets/demo-info.svg new file mode 100644 index 0000000..43a96cb --- /dev/null +++ b/assets/demo-info.svg @@ -0,0 +1,84 @@ + +cross-port-kill: pk --info +A terminal inspects ports without killing anything. pk 3000 --info shows node on port 3000, localhost only, with its PID, user and command, then "1 in use". pk --info lists every port in use: two node servers, a python3 server reachable on all interfaces, and a Docker container running nginx. + + + + +pk --info +$ +$ p +$ pk +$ pk +$ pk 3 +$ pk 30 +$ pk 300 +$ pk 3000 +$ pk 3000 +$ pk 3000 - +$ pk 3000 -- +$ pk 3000 --i +$ pk 3000 --in +$ pk 3000 --inf +$ pk 3000 --info +$ pk 3000 --info +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────────── +:3000 node 41210 dev localhost onlynode server.js +───────────────────────────────────────────────────────────────────────────────────────────── + 1 in use + To free it: pk 3000 +$ +$ p +$ pk +$ pk +$ pk - +$ pk -- +$ pk --i +$ pk --in +$ pk --inf +$ pk --info +$ pk --info +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────────── +:3000 node 41210 dev localhost onlynode server.js +:5173 node 41288 dev localhost onlynode node_modules/.bin/vite +:8000 python3 41302 dev all interfacespython3 -m http.server 8000 +:8080 api a1b2c3d4e5f6containerall interfacesnginx:1.27 +───────────────────────────────────────────────────────────────────────────────────────────── + To free one: pk 3000 · several: pk 3000 5173 · or pick from a list: pk +$ + diff --git a/assets/demo-tree.svg b/assets/demo-tree.svg new file mode 100644 index 0000000..c58d15a --- /dev/null +++ b/assets/demo-tree.svg @@ -0,0 +1,105 @@ + +cross-port-kill: pk --tree +A terminal stops more than the port holder. pk 3000 --children frees port 3000 and also stops the 4 worker processes under it. pk 5050 --tree lists the parent it would stop, pgadmin4, warns that unsaved work is lost and asks "Stop them? [y/N]". After answering y, port 5050 is freed and the parent pgadmin4 is stopped too. + + + + +pk --tree +$ +$ p +$ pk +$ pk +$ pk 3 +$ pk 30 +$ pk 300 +$ pk 3000 +$ pk 3000 +$ pk 3000 - +$ pk 3000 -- +$ pk 3000 --c +$ pk 3000 --ch +$ pk 3000 --chi +$ pk 3000 --chil +$ pk 3000 --child +$ pk 3000 --childr +$ pk 3000 --childre +$ pk 3000 --children +$ pk 3000 --children + Freeing port… +✔ Freed port 3000— killednode(PID 41210)via SIGTERM (graceful) + 4 other processes +$ +$ p +$ pk +$ pk +$ pk 5 +$ pk 50 +$ pk 505 +$ pk 5050 +$ pk 5050 +$ pk 5050 - +$ pk 5050 -- +$ pk 5050 --t +$ pk 5050 --tr +$ pk 5050 --tre +$ pk 5050 --tree +$ pk 5050 --tree +! --tree will also stop these parents, and everything running under them: +:5050 python3 (PID 4180)→pgadmin4(PID 4100) + Unsaved work in those programs is lost. +? Stop them? [y/N] +? Stop them? [y/N] y +? Stop them? [y/N] y + Freeing port… +✔ Freed port 5050— killedpython3(PID 4180)via SIGTERM (graceful) + parent pgadmin4 (PID 4100) +$ + diff --git a/assets/demo-udp.svg b/assets/demo-udp.svg new file mode 100644 index 0000000..e65204b --- /dev/null +++ b/assets/demo-udp.svg @@ -0,0 +1,98 @@ + +cross-port-kill: pk udp ports +A terminal frees a UDP port. pk 5353 says port 5353 is already free, because ports are TCP by default. pk udp ports lists the UDP ports in use: node bound to 5353 on all interfaces, and suggests 'To free one: pk 5353/udp' or picking from a list with pk --udp. pk 5353/udp frees it: 'Freed port 5353/udp — killed node via SIGTERM (graceful)'. + + + + +pk udp ports +$ +$ p +$ pk +$ pk +$ pk 5 +$ pk 53 +$ pk 535 +$ pk 5353 +$ pk 5353 +• Port 5353 is already free. +$ +$ p +$ pk +$ pk +$ pk u +$ pk ud +$ pk udp +$ pk udp +$ pk udp p +$ pk udp po +$ pk udp por +$ pk udp port +$ pk udp ports +$ pk udp ports +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────── +:5353/udp node 41500 dev all interfacesnode discovery.js +───────────────────────────────────────────────────────────────────────────────── + To free one: pk 5353/udp · or pick from a list: pk --udp +$ +$ p +$ pk +$ pk +$ pk 5 +$ pk 53 +$ pk 535 +$ pk 5353 +$ pk 5353/ +$ pk 5353/u +$ pk 5353/ud +$ pk 5353/udp +$ pk 5353/udp + Freeing port… +✔ Freed port 5353/udp— killednode(PID 41500)via SIGTERM (graceful) +$ + diff --git a/assets/demo-words.svg b/assets/demo-words.svg new file mode 100644 index 0000000..50c687f --- /dev/null +++ b/assets/demo-words.svg @@ -0,0 +1,155 @@ + +cross-port-kill: pk port 3000 +A terminal uses plain words. pk port 3000 shows node holding port 3000 and ends with 'To free it: pk 3000'. pk kill 3000 frees it. pk what is on 8080 shows the Docker container api and how to free it; a question only ever looks. pk kil 5173 is a typo and pk answers: Unknown word 'kil'. Did you mean 'kill'? + + + + +pk port 3000 +$ +$ p +$ pk +$ pk +$ pk p +$ pk po +$ pk por +$ pk port +$ pk port +$ pk port 3 +$ pk port 30 +$ pk port 300 +$ pk port 3000 +$ pk port 3000 +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────── +:3000 node 41210 dev localhost onlynode server.js +───────────────────────────────────────────────────────────────────────────────────────── + 1 in use + To free it: pk 3000 +$ +$ p +$ pk +$ pk +$ pk k +$ pk ki +$ pk kil +$ pk kill +$ pk kill +$ pk kill 3 +$ pk kill 30 +$ pk kill 300 +$ pk kill 3000 +$ pk kill 3000 + Freeing port… +✔ Freed port 3000— killednode(PID 41210)via SIGTERM (graceful) +$ +$ p +$ pk +$ pk +$ pk w +$ pk wh +$ pk wha +$ pk what +$ pk what +$ pk what i +$ pk what is +$ pk what is +$ pk what is o +$ pk what is on +$ pk what is on +$ pk what is on 8 +$ pk what is on 80 +$ pk what is on 808 +$ pk what is on 8080 +$ pk what is on 8080 +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────── +:8080 api a1b2c3d4e5f6containerall interfacesnginx:1.27 +───────────────────────────────────────────────────────────────────────────────────────── + 1 in use + To free it: pk 8080 +$ +$ p +$ pk +$ pk +$ pk k +$ pk ki +$ pk kil +$ pk kil +$ pk kil 5 +$ pk kil 51 +$ pk kil 517 +$ pk kil 5173 +$ pk kil 5173 +✖ Unknown word: "kil". Did you mean "kill"? +$ + diff --git a/assets/demo.svg b/assets/demo.svg new file mode 100644 index 0000000..1cf713d --- /dev/null +++ b/assets/demo.svg @@ -0,0 +1,88 @@ + +cross-port-kill: pk +A terminal runs pk. A checklist of four ports appears; port 3000 (node) and port 8080 (a Docker container running nginx) are ticked and Enter is pressed. pk reports port 3000 freed by killing node via SIGTERM (graceful) and port 8080 freed by stopping the Docker container via docker stop, then "Freed 2 of 2 ports". Next, pk --info lists the two ports still in use, 5173 and 8000. + + + + +pk +$ +$ p +$ pk +$ pk +pkSelect ports to free0 of 4 selected +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────────── +❯ [ ] :3000 node 41210 dev localhost only node server.js +[ ]:5173 node 41288 dev localhost onlynode node_modules/.bin/vite +[ ]:8000 python3 41302 dev all interfacespython3 -m http.server 8000 +[ ]:8080 api a1b2c3d4e5f6containerall interfacesnginx:1.27 +───────────────────────────────────────────────────────────────────────────────────────────── +[ ] Also stop what it started --children +[ ] Also close the app that started it --tree + user dev · cmd node server.js +↑↓move · spacetoggle · aall · cchildren · tapp · enterfree selected · qquit +pkSelect ports to free1 of 4 selected +❯ [x] :3000 node 41210 dev localhost only node server.js +[x]:3000 node 41210 dev localhost onlynode server.js +❯ [ ] :5173 node 41288 dev localhost only node node_modules/.bin/vite + user dev · cmd node node_modules/.bin/vite +❯ [ ] :8000 python3 41302 dev all interfaces python3 -m http.server 8000 + user dev · cmd python3 -m http.server 8000 +❯ [ ] :8080 api a1b2c3d4e5f6 container all interfaces nginx:1.27 + image nginx:1.27 +pkSelect ports to free2 of 4 selected +❯ [x] :8080 api a1b2c3d4e5f6 container all interfaces nginx:1.27 + Freeing 2 ports… +✔ Freed port 3000— killednode(PID 41210)via SIGTERM (graceful) +✔ Freed port 8080— stopped Docker container api(a1b2c3d4e5f6)via docker stop +✔ Freed 2 of 2 ports +$ pk +$ pk - +$ pk -- +$ pk --i +$ pk --in +$ pk --inf +$ pk --info +$ pk --info +PORT PROCESS PID/ID USER ACCESS COMMAND +───────────────────────────────────────────────────────────────────────────────────────────── +:5173 node 41288 dev localhost onlynode node_modules/.bin/vite +:8000 python3 41302 dev all interfacespython3 -m http.server 8000 +───────────────────────────────────────────────────────────────────────────────────────────── + To free one: pk 5173 · several: pk 5173 8000 · or pick from a list: pk +$ + diff --git a/bin/cli.js b/bin/cli.js index d6c884f..9e1c199 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -2,14 +2,26 @@ import { createRequire } from 'node:module'; import process from 'node:process'; -import { parseArgs } from '../src/args.js'; +import { basename } from 'node:path'; +import { parseArgs, portLabel } from '../src/args.js'; import { c } from '../src/colors.js'; import { confirmParents, pickTargets, printTargets } from '../src/interactive.js'; import { scopeOf } from '../src/tree.js'; +import { freeHint } from '../src/ui.js'; import { describe, findTargets, freeTarget, printable, targetKey } from '../src/targets.js'; const { version } = createRequire(import.meta.url)('../package.json'); +/** + * The name to suggest in hints: the one the user typed, `npx cross-port-kill` under npx, and `pk` when + * the name is lost (Windows shims run cli.js directly). pk-udp/pk-tcp hints carry /udp already, so plain pk. + */ +function commandName() { + if (process.env.npm_command === 'exec') return 'npx cross-port-kill'; + const name = basename(process.argv[1] ?? '').replace(/\.(js|cmd|ps1)$/i, ''); + return ['pk', 'kp', 'cpk', 'ckp', 'port-kill', 'kill-port', 'cross-port-kill', 'cross-kill-port'].includes(name) ? name : 'pk'; +} + function printHelp() { const section = (title) => c.bold(c.cyan(title)); const row = (usage, text) => ` ${c.bold(usage.padEnd(24))}${text}`; @@ -26,18 +38,34 @@ ${row('pk 3000', 'Free port 3000')} ${row('pk 3000 5173 8080', 'Free several ports')} ${row('pk 3000-3005', 'Free a range of ports')} ${row('pk 3000 --info', 'Show what holds port 3000, without killing')} +${row('pk 5353 --udp', 'Free UDP port 5353 (or: pk 5353/udp, pk-udp 5353)')} ${row('pk --info', 'List every port in use')} + ${section('OR JUST SAY IT')} +${row('pk kill 3000', 'Free it (also: free, stop, close)')} +${row('pk port 3000', 'Show what holds it, and the command to free it (also: show, check, list)')} +${row('pk what is on 3000', 'Questions only ever look, never kill (also: who uses 3000, is 3000 free)')} +${row('pk kill -9 3000', 'Force it (also: pk force 3000)')} + + ${section('PORTS CAN BE WRITTEN AS')} +${row('3000 :3000', 'A port, with or without the colon')} +${row('localhost:3000', 'Any host:port or URL, e.g. [::1]:3000 or http://localhost:5173')} +${row('3000-3005 3000,5173', 'A range, or a list (also 3000..3005)')} +${row('5353/udp udp:5353', 'With a protocol (also: pk udp 5353)')} + ${section('OPTIONS')} ${flag('-i, --info', 'Inspect only (do not kill)')} ${flag('-f, --force', 'Force kill immediately (SIGKILL / taskkill /F / docker kill)')} ${flag('-c, --children', 'Also stop everything running under it (always so on Windows)')} ${flag(' --tree', 'Stop its parent and everything under that, after asking (not on Windows)')} ${flag('-y, --yes', 'Do not ask before --tree stops a parent')} +${flag('-u, --udp', 'Use UDP ports instead of TCP (with --tcp: both)')} +${flag('-t, --tcp', 'Use TCP ports (the default)')} +${flag('-p, --port ', 'Ports as an option, kill-port style (with -m, --method tcp|udp)')} ${flag('-v, --version', 'Show version')} ${flag('-h, --help', 'Show this help message')} - ${c.dim('Also available as kp, kill-port and port-kill. Ports published by Docker are freed by stopping the container.')} + ${c.dim('Also available as kp, cpk, ckp, port-kill, kill-port, cross-port-kill and cross-kill-port; pk-udp and pk-tcp are pk --udp and pk --tcp. Ports published by Docker are freed by stopping the container.')} `); } @@ -58,7 +86,7 @@ async function freeAll(targets, { force, children, tree, yes }) { for (const t of targets) { const key = targetKey(t); if (!groups.has(key)) groups.set(key, { target: t, ports: [] }); - groups.get(key).ports.push(t.port); + groups.get(key).ports.push(portLabel(t.port, t.protocol)); } const scope = scopeOf({ children, tree }); @@ -117,18 +145,23 @@ async function main() { // No ports: list everything (--info) or pick interactively; scripts without a TTY get help if (opts.ports.length === 0) { if (!opts.info && !process.stdin.isTTY) return printHelp(); - const targets = await findTargets(); - if (targets.length === 0) return console.log(c.dim('• No ports in use.')); - if (opts.info) return printTargets(targets); + const targets = await findTargets([], opts.protocols); + const which = opts.protocols.length === 1 ? `${opts.protocols[0].toUpperCase()} ` : ''; + if (targets.length === 0) return console.log(c.dim(`• No ${which}ports in use.`)); + if (opts.info) { + printTargets(targets); + const labels = [...new Set(targets.map((t) => portLabel(t.port, t.protocol)))]; + return console.log(freeHint(labels, { command: commandName(), all: true, protocols: opts.protocols })); + } const picked = await pickTargets(targets, opts); return freeAll(picked.targets, { ...opts, ...picked }); } const targets = await findTargets(opts.ports); - const busy = new Set(targets.map((t) => t.port)); - const free = opts.ports.filter((port) => !busy.has(port)); + const busy = new Set(targets.map((t) => portLabel(t.port, t.protocol))); + const free = opts.ports.map(({ port, protocol }) => portLabel(port, protocol)).filter((label) => !busy.has(label)); if (free.length <= 10) { - for (const port of free) console.log(c.dim(`• Port ${port} is already free.`)); + for (const label of free) console.log(c.dim(`• Port ${label} is already free.`)); } else { console.log(c.dim(`• ${free.length} of ${opts.ports.length} ports are already free.`)); // pk 1-65535 must not print 65k lines } @@ -137,6 +170,8 @@ async function main() { if (targets.length > 0) { printTargets(targets); console.log(c.dim(` ${targets.length} in use`)); + const labels = [...new Set(targets.map((t) => portLabel(t.port, t.protocol)))]; + console.log(freeHint(labels, { command: commandName() })); } return; } diff --git a/bin/pk-tcp.js b/bin/pk-tcp.js new file mode 100755 index 0000000..b67feaa --- /dev/null +++ b/bin/pk-tcp.js @@ -0,0 +1,9 @@ +#!/usr/bin/env node +// `pk-tcp`: pk with --tcp already given. A separate file rather than a check of the command name, +// because npm's Windows shims run bin/cli.js directly and the typed name is lost. +// The flag only sets the default: a suffix (`3000/tcp`, `5353/udp`) still wins, and adding +// --udp checks both protocols. +import process from 'node:process'; + +process.argv.splice(2, 0, '--tcp'); +await import('./cli.js'); diff --git a/bin/pk-udp.js b/bin/pk-udp.js new file mode 100755 index 0000000..916ad38 --- /dev/null +++ b/bin/pk-udp.js @@ -0,0 +1,9 @@ +#!/usr/bin/env node +// `pk-udp`: pk with --udp already given. A separate file rather than a check of the command name, +// because npm's Windows shims run bin/cli.js directly and the typed name is lost. +// The flag only sets the default: a suffix (`3000/tcp`, `5353/udp`) still wins, and adding +// --tcp checks both protocols. +import process from 'node:process'; + +process.argv.splice(2, 0, '--udp'); +await import('./cli.js'); diff --git a/package.json b/package.json index 1a6ab3a..e43dbd0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { - "name": "@majidev-org/port-kill-cli", - "version": "1.2.0", + "name": "cross-port-kill", + "version": "2.0.0", "description": "A fast, zero-dependency, cross-platform CLI to find and kill processes occupying ports on Linux, macOS, and Windows (pk 3000)", "repository": { "type": "git", @@ -12,10 +12,16 @@ }, "type": "module", "bin": { - "port-kill": "./bin/cli.js", "pk": "./bin/cli.js", "kp": "./bin/cli.js", - "kill-port": "./bin/cli.js" + "cpk": "./bin/cli.js", + "ckp": "./bin/cli.js", + "port-kill": "./bin/cli.js", + "kill-port": "./bin/cli.js", + "cross-port-kill": "./bin/cli.js", + "cross-kill-port": "./bin/cli.js", + "pk-udp": "./bin/pk-udp.js", + "pk-tcp": "./bin/pk-tcp.js" }, "files": [ "bin/", @@ -33,6 +39,10 @@ "port-killer", "free-port", "pk", + "cpk", + "cross-port-kill", + "udp", + "tcp", "cli", "process", "cross-platform", diff --git a/scripts/make-demo.mjs b/scripts/make-demo.mjs new file mode 100644 index 0000000..bf9c77e --- /dev/null +++ b/scripts/make-demo.mjs @@ -0,0 +1,412 @@ +#!/usr/bin/env node +// Builds the animated terminal demos in assets/ (demo.svg and demo-*.svg), one per use case. +// +// node scripts/make-demo.mjs +// +// Tables, colors and result lines come from the CLI's own helpers (src/ui.js, src/targets.js), so the +// demos stay in step with the real output. A few layouts are copied instead because they are not +// exported: the picker (pickCheckboxes in src/interactive.js), the --tree question (confirmParents) +// and the "how" strings of src/kill.js. Update them here if those change. Not part of the npm package. + +import { writeFileSync } from 'node:fs'; +import process from 'node:process'; + +process.stdout.isTTY = true; // colors.js only emits ANSI codes for a terminal +delete process.env.NO_COLOR; + +const { c } = await import('../src/colors.js'); +const { parseArgs, portLabel } = await import('../src/args.js'); +const { cellsOf, describe, extra } = await import('../src/targets.js'); +const { columnWidths, dataRow, freeHint, headerRow, keyHints, labelledRule, plainRow, rule, tableWidth } = await import('../src/ui.js'); + +// ---------------------------------------------------------------- sample data + +const proc = (port, name, pid, address, command, protocol = 'tcp') => + ({ kind: 'process', port, protocol, name, pid, user: 'dev', address, command }); +const NODE = proc(3000, 'node', 41210, '127.0.0.1', 'node server.js'); +const VITE = proc(5173, 'node', 41288, '127.0.0.1', 'node node_modules/.bin/vite'); +const PY = proc(8000, 'python3', 41302, '0.0.0.0', 'python3 -m http.server 8000'); +const API = { kind: 'container', port: 8080, protocol: 'tcp', name: 'api', id: 'a1b2c3d4e5f6', address: '0.0.0.0', image: 'nginx:1.27' }; +const MDNS = proc(5353, 'node', 41500, '0.0.0.0', 'node discovery.js', 'udp'); +const PGADMIN = proc(5050, 'python3', 4180, '127.0.0.1', '/usr/pgadmin4/venv/bin/python3 pgAdmin4.py'); + +const GRACEFUL = 'SIGTERM (graceful)'; + +// ---------------------------------------------------------------- output, as the CLI prints it + +const prompt = (typed, caret = false) => `${c.green('$')} ${typed}${caret ? '▋' : ''}`; + +/** + * What --info prints: printTargets() from src/interactive.js, then for named ports the "N in use" line + * and the command to free them, or for a full listing how to pick one (see bin/cli.js). + */ +function table(targets, { named = false, protocols = ['tcp'] } = {}) { + const rows = targets.map(cellsOf); + const widths = columnWidths(rows, 2); + const line = rule(tableWidth(widths, 2) - 2); + const labels = [...new Set(targets.map((t) => portLabel(t.port, t.protocol)))]; + return [ + ` ${headerRow(widths)}`, + ` ${line}`, + ...rows.map((r) => ` ${dataRow(r, widths)}`), + ` ${line}`, + ...(named ? [c.dim(` ${targets.length} in use`), freeHint(labels)] : [freeHint(labels, { all: true, protocols })]), + ]; +} + +/** The error the real parser gives for these arguments, as bin/cli.js prints it. */ +function parseError(args) { + try { + parseArgs(args); + } catch (err) { + return c.red(`✖ ${err.message}`); + } + throw new Error(`expected "${args.join(' ')}" to be rejected`); +} + +const freed = (t, how = GRACEFUL) => + `${c.green('✔')} Freed port ${c.bold(portLabel(t.port, t.protocol))} ${c.dim(`— ${t.kind === 'container' ? 'stopped' : 'killed'}`)} ${describe(t)} ${c.dim(`via ${how}`)}`; +const summary = (n, of = n) => (n === of ? c.green : c.yellow)(`${n === of ? '✔' : '!'} Freed ${n} of ${of} ports`); +const alreadyFree = (label) => c.dim(`• Port ${label} is already free.`); +const freeing = (n) => c.dim(` Freeing ${n === 1 ? 'port' : `${n} ports`}…`); + +const PICKER_KEYS = [['↑↓', 'move'], ['space', 'toggle'], ['a', 'all'], ['c', 'children'], ['t', 'app'], ['enter', 'free selected'], ['q', 'quit']]; +const OPTIONS = [ + { label: 'Also stop what it started', flag: '--children' }, + { label: 'Also close the app that started it', flag: '--tree' }, +]; + +/** The checkbox picker as pickCheckboxes() draws it. */ +function picker(targets, checked, cursor) { + const cells = targets.map(cellsOf); + const widths = columnWidths(cells, 6); + const length = tableWidth(widths, 6) - 2; + const left = ' pk Select ports to free'; + const right = `${checked.size} of ${targets.length} selected`; + const pad = ' '.repeat(Math.max(2, length + 2 - left.length - right.length)); + const rows = cells.map((row, i) => { + const box = checked.has(i) ? '[x]' : '[ ]'; + if (i === cursor) return c.inverse(`❯ ${box} ${plainRow(row, widths)}`.padEnd(length + 2)); + return ` ${checked.has(i) ? c.green(box) : c.dim(box)} ${dataRow(row, widths)}`; + }); + return [ + ` ${c.bold('pk')} ${c.dim('Select ports to free')}${pad}${checked.size ? c.green(right) : c.dim(right)}`, + ` ${headerRow(widths)}`, + ` ${rule(length)}`, + ...rows, + ` ${labelledRule('', length)}`, + ...OPTIONS.map((o) => ` ${c.dim('[ ]')} ${o.label} ${c.dim(o.flag)}`), + c.dim(` ${extra(targets[cursor])}`), + ` ${keyHints(PICKER_KEYS)}`, + ]; +} + +// ---------------------------------------------------------------- sessions + +/** A terminal session recorded as frames: [seconds on screen, terminal lines]. */ +class Session { + constructor({ cols = 96 } = {}) { + this.cols = cols; + process.stdout.columns = cols; // tables fill the terminal width, as in a real terminal + this.lines = []; + this.frames = []; + this.poster = 0; + } + + show(seconds, extra = []) { + this.frames.push([seconds, [...this.lines, ...extra]]); + } + + /** Type a command at the prompt, then press Enter. */ + type(command, { before = 0.5, perChar = 0.07, after = 0.35 } = {}) { + this.show(before, [prompt('', true)]); + for (let i = 1; i <= command.length; i++) this.show(i === command.length ? after : perChar, [prompt(command.slice(0, i), true)]); + this.lines.push(prompt(command)); + return this; + } + + print(lines, seconds = 1.8) { + this.lines.push(...lines); + this.show(seconds); + return this; + } + + /** Show `lines` under the output for a moment without keeping them (the "Freeing…" status line). */ + flash(lines, seconds = 0.6) { + this.show(seconds, lines); + return this; + } + + /** Mark the latest frame as the still image for prefers-reduced-motion. */ + still() { + this.poster = this.frames.length - 1; + return this; + } + + clear() { + this.lines = []; + return this; + } + + end(seconds = 2.6) { + this.show(seconds, [prompt('', true)]); + return this; + } +} + +const scenes = []; +const scene = (file, title, desc, build) => scenes.push({ file, title, desc, session: build() }); + +scene('demo.svg', 'pk', + 'A terminal runs pk. A checklist of four ports appears; port 3000 (node) and port 8080 (a Docker container running nginx) are ticked and Enter is pressed. pk reports port 3000 freed by killing node via SIGTERM (graceful) and port 8080 freed by stopping the Docker container via docker stop, then "Freed 2 of 2 ports". Next, pk --info lists the two ports still in use, 5173 and 8000.', + () => { + const s = new Session(); + const targets = [NODE, VITE, PY, API]; + s.type('pk'); + const checked = new Set(); + let cursor = 0; + const pick = (seconds) => s.show(seconds, picker(targets, checked, cursor)); + pick(1.1); + checked.add(0); pick(0.8); + cursor = 1; pick(0.4); + cursor = 2; pick(0.4); + cursor = 3; pick(0.7); + checked.add(3); pick(1.1); + s.still(); + s.lines.push(...picker(targets, checked, cursor)); + s.flash([freeing(2)], 1.0).print([freed(NODE), freed(API, 'docker stop'), summary(2)], 2.6); + s.clear().type('pk --info').print(table([VITE, PY]), 0.1).end(3.2); + return s; + }); + +scene('demo-free.svg', 'pk 3000', + 'A terminal frees ports. pk 3000 frees port 3000 by killing node via SIGTERM (graceful). pk 3000 5173 8000 says port 3000 is already free and frees 5173 and 8000, then "Freed 2 of 2 ports". pk 4000-4003 says ports 4001 and 4003 are already free and frees 4000 and 4002.', + () => { + const s = new Session({ cols: 84 }); + const r0 = proc(4000, 'node', 41400, '127.0.0.1', 'node worker.js'); + const r2 = proc(4002, 'node', 41402, '127.0.0.1', 'node worker.js'); + s.type('pk 3000').flash([freeing(1)], 0.5).print([freed(NODE)], 1.4); + s.type('pk 3000 5173 8000').print([alreadyFree(3000)], 0.1).flash([freeing(2)], 0.6).print([freed(VITE), freed(PY), summary(2)], 1.6).still(); + s.type('pk 4000-4003').print([alreadyFree(4001), alreadyFree(4003)], 0.1).flash([freeing(2)], 0.6).print([freed(r0), freed(r2), summary(2)], 0.1); + return s.end(3.2); + }); + +scene('demo-info.svg', 'pk --info', + 'A terminal inspects ports without killing anything. pk 3000 --info shows node on port 3000, localhost only, with its PID, user and command, then "1 in use". pk --info lists every port in use: two node servers, a python3 server reachable on all interfaces, and a Docker container running nginx.', + () => { + const s = new Session(); + s.type('pk 3000 --info').print(table([NODE], { named: true }), 2.0); + s.type('pk --info').print(table([NODE, VITE, PY, API]), 0.1).still(); + return s.end(3.6); + }); + +scene('demo-docker.svg', 'pk 8080', + 'A terminal frees a port published by Docker. pk 8080 --info shows the container api running nginx:1.27 on port 8080, listed as a container rather than as the Docker proxy process. pk 8080 then frees the port by stopping the container via docker stop.', + () => { + const s = new Session({ cols: 90 }); + s.type('pk 8080 --info').print(table([API], { named: true }), 2.0); + s.type('pk 8080').flash([freeing(1)], 1.3).print([freed(API, 'docker stop')], 0.1).still(); + s.type('pk 8080').print([alreadyFree(8080)], 0.1); + return s.end(3.2); + }); + +scene('demo-force.svg', 'pk 9000', + 'A terminal frees ports held by processes that ignore SIGTERM. pk 9000 sends SIGTERM, waits, and escalates: "Freed port 9000 — killed node via SIGTERM, then SIGKILL". pk 9001 --force kills immediately: "via SIGKILL (forced)".', + () => { + const s = new Session({ cols: 84 }); + const stubborn = proc(9000, 'node', 42100, '127.0.0.1', 'node stubborn.js'); + const stuck = proc(9001, 'node', 42101, '127.0.0.1', 'node stuck.js'); + s.type('pk 9000').flash([freeing(1)], 0.8).print([freed(stubborn, 'SIGTERM, then SIGKILL')], 1.8).still(); + s.type('pk 9001 --force').flash([freeing(1)], 0.3).print([freed(stuck, 'SIGKILL (forced)')], 0.1); + return s.end(3.2); + }); + +scene('demo-tree.svg', 'pk --tree', + 'A terminal stops more than the port holder. pk 3000 --children frees port 3000 and also stops the 4 worker processes under it. pk 5050 --tree lists the parent it would stop, pgadmin4, warns that unsaved work is lost and asks "Stop them? [y/N]". After answering y, port 5050 is freed and the parent pgadmin4 is stopped too.', + () => { + const s = new Session({ cols: 100 }); + s.type('pk 3000 --children').flash([freeing(1)], 0.6).print([freed(NODE, `${GRACEFUL} + 4 other processes`)], 1.8); + s.type('pk 5050 --tree').print([ + '', + c.yellow('! --tree will also stop these parents, and everything running under them:'), + '', + ` ${c.bold(':5050')} python3 ${c.dim('(PID 4180)')} ${c.dim('→')} ${c.bold('pgadmin4')} ${c.dim('(PID 4100)')}`, + c.dim(''), + c.dim(' Unsaved work in those programs is lost.'), + '', + ], 0.1); + const ask = `${c.cyan('?')} Stop them? ${c.dim('[y/N]')} `; + s.show(1.4, [`${ask}▋`]); + s.show(0.5, [`${ask}y▋`]); + s.lines.push(`${ask}y`); + s.flash([freeing(1)], 0.6).print([freed(PGADMIN, `${GRACEFUL} + parent pgadmin4 (PID 4100)`)], 0.1).still(); + return s.end(3.4); + }); + +scene('demo-udp.svg', 'pk udp ports', + "A terminal frees a UDP port. pk 5353 says port 5353 is already free, because ports are TCP by default. pk udp ports lists the UDP ports in use: node bound to 5353 on all interfaces, and suggests 'To free one: pk 5353/udp' or picking from a list with pk --udp. pk 5353/udp frees it: 'Freed port 5353/udp — killed node via SIGTERM (graceful)'.", + () => { + const s = new Session({ cols: 84 }); + s.type('pk 5353').print([alreadyFree(5353)], 1.4); + s.type('pk udp ports').print(table([MDNS], { protocols: ['udp'] }), 2.2); + s.type('pk 5353/udp').flash([freeing(1)], 0.5).print([freed(MDNS)], 0.1).still(); + return s.end(3.2); + }); + +scene('demo-words.svg', 'pk port 3000', + "A terminal uses plain words. pk port 3000 shows node holding port 3000 and ends with 'To free it: pk 3000'. pk kill 3000 frees it. pk what is on 8080 shows the Docker container api and how to free it; a question only ever looks. pk kil 5173 is a typo and pk answers: Unknown word 'kil'. Did you mean 'kill'?", + () => { + const s = new Session({ cols: 92 }); + s.type('pk port 3000').print(table([NODE], { named: true }), 1.8); + s.type('pk kill 3000').flash([freeing(1)], 0.5).print([freed(NODE)], 1.2); + s.type('pk what is on 8080').print(table([API], { named: true }), 0.1).still(); + s.show(1.6); + s.type('pk kil 5173').print([parseError(['kil', '5173'])], 0.1); + return s.end(3.2); + }); + +scene('demo-formats.svg', 'pk localhost:3000', + "A terminal frees ports written in different ways, as pasted from an error message or a browser. pk localhost:3000 frees node on 3000. pk http://localhost:5173/ frees the vite server. pk :::8000, the address from an EADDRINUSE error, frees python3 on 8000. pk udp:5353 frees UDP port 5353. pk --forse 9000 is a typo and pk answers: Did you mean '--force'?", + () => { + const s = new Session({ cols: 86 }); + s.type('pk localhost:3000').flash([freeing(1)], 0.4).print([freed(NODE)], 0.9); + s.type('pk http://localhost:5173/').flash([freeing(1)], 0.4).print([freed(VITE)], 0.9); + s.type('pk :::8000').flash([freeing(1)], 0.4).print([freed(PY)], 0.9); + s.type('pk udp:5353').flash([freeing(1)], 0.4).print([freed(MDNS)], 0.1).still(); + s.show(0.9); + s.type('pk --forse 9000').print([parseError(['--forse', '9000'])], 0.1); + return s.end(3.2); + }); + +// ---------------------------------------------------------------- ANSI → SVG + +const FONT = 15; +const CW = 9; // character cell width +const LH = 22; // line height +const PAD_X = 22; +const BAR = 40; // title bar height + +const PALETTE = { + fg: '#cdd6f4', dim: '#9399b2', bg: '#1e1e2e', bar: '#181825', border: '#313244', + 31: '#f38ba8', 32: '#a6e3a1', 33: '#f9e2af', 34: '#89b4fa', 36: '#89dceb', +}; + +const esc = (s) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +/** Split one ANSI line into styled runs with their starting column. */ +function runs(line) { + const out = []; + let state = {}; + let col = 0; + for (const part of line.split(/(\x1b\[[0-9;]*m)/)) { + const m = /^\x1b\[([0-9;]*)m$/.exec(part); + if (m) { + for (const code of m[1].split(';').map(Number)) { + if (code === 0) state = {}; + else if (code === 1) state = { ...state, bold: true }; + else if (code === 2) state = { ...state, dim: true }; + else if (code === 7) state = { ...state, inverse: true }; + else if (PALETTE[code]) state = { ...state, color: PALETTE[code] }; + } + } else if (part) { + // the caret is drawn as a block of its own + for (const [i, piece] of part.split('▋').entries()) { + if (i > 0) out.push({ caret: true, col: col++ }); + if (!piece) continue; + const len = [...piece].length; + out.push({ text: piece, col, len, ...state }); + col += len; + } + } + } + return out; +} + +function lineSvg(line, row) { + const y = BAR + 18 + row * LH; + const base = y + FONT - 1; + let svg = ''; + for (const r of runs(line)) { + const x = PAD_X + r.col * CW; + if (r.caret) { + svg += ``; + continue; + } + let fill = r.color ?? (r.dim ? PALETTE.dim : PALETTE.fg); + if (r.inverse) { + svg += ``; + fill = PALETTE.bg; + } + if (!r.text.trim()) continue; + // textLength pins every run to the character grid, whatever monospace font the viewer has + const weight = r.bold ? ' font-weight="700"' : ''; + svg += `${esc(r.text)}`; + } + return svg; +} + +function render({ title, desc, session }) { + const { frames, poster, cols } = session; + const rows = Math.max(...frames.map(([, lines]) => lines.length)); + const W = PAD_X * 2 + cols * CW; + const H = BAR + 18 + rows * LH + 14; + const total = frames.reduce((sum, [s]) => sum + s, 0); + const starts = []; + frames.reduce((t, [s]) => (starts.push(t), t + s), 0); + + // Each distinct (row, content) is drawn once and shown only during the frames that contain it. + const pieces = new Map(); + frames.forEach(([, lines], i) => + lines.forEach((line, row) => { + const key = `${row}:${line}`; + if (!pieces.has(key)) pieces.set(key, { svg: lineSvg(line, row), shown: new Set() }); + pieces.get(key).shown.add(i); + }), + ); + + const pct = (t) => `${+((t / total) * 100).toFixed(3)}%`; + const keyframes = new Map(); // signature -> animation name + let body = ''; + for (const { svg, shown } of pieces.values()) { + if (!svg) continue; // blank line + const stops = []; + let prev; + frames.forEach((_f, i) => { + const v = shown.has(i) ? 1 : 0; + if (v !== prev) stops.push(`${pct(starts[i])}{opacity:${v}}`); + prev = v; + }); + stops.push(`100%{opacity:${prev}}`); + const sig = stops.join(''); + if (!keyframes.has(sig)) keyframes.set(sig, `k${keyframes.size}`); + body += `${svg}\n`; + } + + const css = [ + `text{font-family:'JetBrains Mono','SF Mono',Menlo,'DejaVu Sans Mono',Consolas,monospace;font-size:${FONT}px;white-space:pre}`, + `g{opacity:0;animation-duration:${total.toFixed(2)}s;animation-iteration-count:infinite;animation-timing-function:step-end}`, + ...[...keyframes].map(([sig, name]) => `.${name}{animation-name:${name}}@keyframes ${name}{${sig}}`), + '.caret{animation:blink 1s step-end infinite}@keyframes blink{50%{opacity:0}}', + '@media (prefers-reduced-motion:reduce){*{animation:none!important}g.p{opacity:1}}', + ].join('\n'); + + const svg = ` +cross-port-kill: ${esc(title)} +${esc(desc)} + + + + +${esc(title)} +${body} +`; + return { svg, total, W, H, count: frames.length }; +} + +for (const s of scenes) { + const { svg, total, W, H, count } = render(s); + writeFileSync(new URL(`../assets/${s.file}`, import.meta.url), svg); + console.error(`assets/${s.file}: ${W}×${H}, ${count} frames, ${total.toFixed(1)} s, ${(svg.length / 1024).toFixed(1)} KB`); +} diff --git a/src/args.js b/src/args.js index dc2b65b..b525e5d 100644 --- a/src/args.js +++ b/src/args.js @@ -1,46 +1,209 @@ -const FLAGS = { - '-i': 'info', - '--info': 'info', - '-f': 'force', - '--force': 'force', - '-c': 'children', - '--children': 'children', - '--tree': 'tree', - '-y': 'yes', - '--yes': 'yes', - '-h': 'help', - '--help': 'help', - '-v': 'version', - '--version': 'version', +// Argument parsing is deliberately forgiving: people type what they remember, paste what an error +// message or a browser showed them, or use another tool's syntax (pk also answers to `kill-port`). +// Anything that clearly names a port is accepted; anything else fails with a hint. + +/** Long option name -> option key. Matched case-insensitively, with one or two leading dashes. */ +const LONG = { + info: 'info', + force: 'force', + children: 'children', + tree: 'tree', + tcp: 'tcp', + udp: 'udp', + yes: 'yes', + help: 'help', + version: 'version', }; +/** Short flags; they can be combined (`-ui` = `-u -i`). `-9` is `kill -9` habit for --force. */ +const SHORT = { i: 'info', f: 'force', c: 'children', t: 'tcp', u: 'udp', y: 'yes', h: 'help', v: 'version', 9: 'force' }; + +/** Options that take a value: `--port 3000`, `-p 3000`, `--port=3000` (kill-port's syntax). */ +const VALUED = { port: 'port', p: 'port', method: 'method', m: 'method', protocol: 'method' }; + +/** + * Plain words, so people can type what they mean: `pk kill 3000`, `pk port 3000`, `pk what is on 3000`. + * Ports are numbers, so no word clashes with one. When in doubt the answer is to look, not to kill: + * a question (`is`, `what`, `who`, `which`) only ever shows info, even next to a kill word. + */ +const KILL_WORDS = ['kill', 'free', 'stop', 'close', 'end', 'release', 'terminate', 'kill-port', 'killport', 'port-kill']; +const INFO_WORDS = ['port', 'ports', 'info', 'list', 'ls', 'show', 'check', 'find', 'status', 'inspect']; +const QUESTION_WORDS = ['is', 'what', 'whats', "what's", 'who', 'whos', "who's", 'which']; +const FILLER_WORDS = ['on', 'at', 'the', 'using', 'uses', 'used', 'by', 'in', 'of', 'for', 'please', 'up', 'and', 'all', 'only', 'open', 'busy', 'listening', 'active', 'running', 'my', 'me']; +const OPTION_WORDS = { force: 'force', children: 'children', tree: 'tree', help: 'help', version: 'version' }; +const PROTOCOL_WORDS = { tcp: ['tcp'], udp: ['udp'], both: ['tcp', 'udp'] }; +const ALL_WORDS = [...KILL_WORDS, ...INFO_WORDS, ...QUESTION_WORDS, ...FILLER_WORDS, ...Object.keys(OPTION_WORDS), ...Object.keys(PROTOCOL_WORDS)]; + +const DEFAULT_PORT = { 'http:': 80, 'ws:': 80, 'https:': 443, 'wss:': 443 }; + export const isValidPort = (p) => Number.isInteger(p) && p > 0 && p <= 65535; +export const PROTOCOLS = ['tcp', 'udp']; + +/** "3000" for TCP (the default everyone means), "5353/udp" otherwise. */ +export const portLabel = (port, protocol = 'tcp') => (protocol === 'tcp' ? String(port) : `${port}/${protocol}`); + +const EXAMPLES = 'e.g. 3000, 3000-3005, :3000, localhost:3000 or 5353/udp'; + +/** Edit distance, for "did you mean" on mistyped options and words. */ +function distance(a, b) { + const row = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + let prev = row[0]; + row[0] = i; + for (let j = 1; j <= b.length; j++) { + const next = row[j]; + row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = next; + } + } + return row[b.length]; +} + +const closest = (name, names) => { + const [best] = names.map((n) => [n, distance(name, n)]).sort((a, b) => a[1] - b[1]); + return best && best[1] <= Math.min(2, Math.floor(name.length / 2)) ? best[0] : null; +}; + +function unknownOption(arg) { + const name = arg.replace(/^-+/, '').split('=')[0].toLowerCase(); + const best = closest(name, [...Object.keys(LONG), 'port', 'method']); + const hint = best ? ` Did you mean "--${best}"?` : ' Run pk --help to see the options.'; + return new Error(`Unknown option: "${arg}".${hint}`); +} + +/** + * Turn one port argument into a range and an optional protocol. Accepts: + * 3000 3000-3005 3000..3005 3000–3005 a port or an inclusive range + * :3000 localhost:3000 127.0.0.1:3000 [::1]:3000 :::3000 *:3000 a bind address (host ignored) + * http://localhost:5173/path a URL (its port, or 80/443 by default) + * 5353/udp 5353:udp udp/5353 udp:5353 3000-3005/tcp a protocol before or after + * @returns {{ start: number, end: number, protocol?: string }} + */ +export function parsePortSpec(arg) { + const fail = () => new Error(`Invalid port or range: "${arg}" (expected 1–65535, ${EXAMPLES})`); + let text = arg.trim().toLowerCase(); + let protocol; + + const url = text.match(/^([a-z][a-z0-9+.-]*:)\/\//); + if (url) { + let parsed; + try { + parsed = new URL(text); + } catch { + throw fail(); + } + const port = parsed.port ? Number(parsed.port) : DEFAULT_PORT[parsed.protocol]; + if (!port) throw fail(); + return { start: port, end: port }; + } + + const before = text.match(/^(tcp|udp)[:/](.+)$/); + const after = text.match(/^(.+?)[:/](tcp|udp)$/); + if (before) [, protocol, text] = before; + else if (after) [, text, protocol] = after; + + // host:port, [v6]:port, :::port, :port. The port is after the last colon. + if (text.includes(':')) text = text.slice(text.lastIndexOf(':') + 1); + + const m = text.match(/^(\d+)(?:\s*(?:-|\.\.|–|—)\s*(\d+))?$/); + const start = Number(m?.[1]); + const end = Number(m?.[2] ?? m?.[1]); + if (!m || !isValidPort(start) || !isValidPort(end) || end < start) throw fail(); + return { start, end, protocol }; +} + +function parseMethod(value) { + const protocol = String(value ?? '').toLowerCase(); + if (!PROTOCOLS.includes(protocol)) throw new Error(`Invalid protocol: "${value ?? ''}" (expected tcp or udp)`); + return protocol; +} + /** * Parse CLI arguments into options. Throws an Error with a user-facing message on bad input. - * @returns {{ info: boolean, force: boolean, children: boolean, tree: boolean, yes: boolean, help: boolean, version: boolean, ports: number[] }} + * + * Ports are TCP unless chosen otherwise: `--udp` switches every port to UDP, `--tcp --udp` checks + * both, and a protocol written on a port (`5353/udp`, `udp:5353`) sets it for that one argument. + * `protocols` is what the flags select; it also decides what `pk` and `pk --info` list. + * @returns {{ info: boolean, force: boolean, children: boolean, tree: boolean, yes: boolean, help: boolean, + * version: boolean, tcp: boolean, udp: boolean, protocols: string[], ports: { port: number, protocol: string }[] }} */ export function parseArgs(argv) { - const opts = { info: false, force: false, children: false, tree: false, yes: false, help: false, version: false, ports: [] }; - const ports = new Set(); - - for (const arg of argv) { - if (arg.startsWith('-')) { - const key = FLAGS[arg]; - if (!key) throw new Error(`Unknown option: "${arg}"`); - opts[key] = true; + const opts = { info: false, force: false, children: false, tree: false, yes: false, help: false, version: false, tcp: false, udp: false, ports: [] }; + const specs = []; + const said = { kill: false, info: false, question: false, protocol: false }; + const addPorts = (value) => { + for (const part of String(value).split(',').filter((p) => p.trim())) specs.push(parsePortSpec(part)); + }; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + + if (arg === '-9') { + opts.force = true; // kill -9 + continue; + } + if (/^-\d/.test(arg) || !arg.startsWith('-')) { + const word = arg.toLowerCase().replace(/[?!.]+$/, ''); // "what's on 3000?" works too + if (KILL_WORDS.includes(word)) said.kill = true; + else if (INFO_WORDS.includes(word)) said.info = true; + else if (QUESTION_WORDS.includes(word)) said.question = true; + else if (FILLER_WORDS.includes(word)) continue; + else if (PROTOCOL_WORDS[word]) { + for (const proto of PROTOCOL_WORDS[word]) opts[proto] = true; // `pk udp`, `pk tcp udp`, `pk both` + said.protocol = true; + } + else if (OPTION_WORDS[word]) opts[OPTION_WORDS[word]] = true; + else if (/^[a-z'-]+$/.test(word) && !/^(tcp|udp)$/.test(word)) { + const best = closest(word, ALL_WORDS); + throw new Error(`Unknown word: "${arg}".${best ? ` Did you mean "${best}"?` : ' Run pk --help to see what pk understands.'}`); + } else addPorts(arg.replace(/[?!]+$/, '')); // ports: "3000", "3000,5173", ":3000", "3000?" continue; } - const match = arg.match(/^(\d+)(?:-(\d+))?$/); - const start = Number(match?.[1]); - const end = Number(match?.[2] ?? match?.[1]); - if (!match || !isValidPort(start) || !isValidPort(end) || end < start) { - throw new Error(`Invalid port or range: "${arg}" (expected 1–65535, e.g. 3000 or 3000-3005)`); + const [rawName, inline] = arg.replace(/^-+/, '').split(/=(.*)/s); + const name = rawName.toLowerCase(); + const valued = VALUED[name]; + if (valued) { + const value = inline ?? argv[++i]; + if (value === undefined) throw new Error(`Option "${arg}" needs a value, e.g. ${arg} ${valued === 'port' ? '3000' : 'udp'}`); + if (valued === 'port') addPorts(value); + else opts[parseMethod(value)] = true; + continue; + } + if (inline !== undefined) throw unknownOption(arg); + + if (LONG[name]) { + opts[LONG[name]] = true; // --udp, --UDP, -udp + continue; } - for (let p = start; p <= end; p++) ports.add(p); + // -ui = -u -i. Short flags keep their case sensitivity loose too: -U works. + const letters = arg.startsWith('--') ? null : [...name]; + if (letters?.length && letters.every((ch) => SHORT[ch])) { + for (const ch of letters) opts[SHORT[ch]] = true; + continue; + } + throw unknownOption(arg); } - opts.ports = [...ports]; + // A question only looks. Otherwise a kill word frees, and an info word without one looks. + // A protocol named on its own (`pk udp`, `pk tcp udp ports`) means "show me those": a listing, + // not the picker. The flags (--udp, pk-udp) keep opening the picker, and `pk kill udp` picks too. + const protocolOnly = said.protocol && specs.length === 0; + if (said.question || ((said.info || protocolOnly) && !said.kill)) opts.info = true; + opts.protocols = opts.udp ? (opts.tcp ? ['tcp', 'udp'] : ['udp']) : ['tcp']; + + // A protocol written on the port wins over the flags for that argument. Duplicates collapse. + const seen = new Set(); + for (const { start, end, protocol } of specs) { + for (const proto of protocol ? [protocol] : opts.protocols) { + for (let port = start; port <= end; port++) { + const key = `${port}/${proto}`; + if (seen.has(key)) continue; + seen.add(key); + opts.ports.push({ port, protocol: proto }); + } + } + } return opts; } diff --git a/src/docker.js b/src/docker.js index cf37163..16e0032 100644 --- a/src/docker.js +++ b/src/docker.js @@ -18,9 +18,9 @@ export function isLocalEndpoint(endpoint) { } /** - * List host ports published by running Docker containers. + * List host ports published by running Docker containers, with their protocol (tcp, udp, or sctp). * Returns [] when Docker is not installed, the daemon is not reachable, or it is not on this machine. - * @returns {Promise<{ port: number, id: string, name: string, image: string, address: string }[]>} + * @returns {Promise<{ port: number, protocol: string, id: string, name: string, image: string, address: string }[]>} */ export async function listContainerPorts() { try { @@ -32,7 +32,7 @@ export async function listContainerPorts() { } } -/** Parse `docker ps` rows like: `a1b2c3\tweb\tnginx:1.27\t0.0.0.0:8080->80/tcp, :::8080->80/tcp` */ +/** Parse `docker ps` rows like: `a1b2c3\tweb\tnginx:1.27\t0.0.0.0:8080->80/tcp, :::8080->80/tcp, 0.0.0.0:5353->53/udp` */ export function parseDockerPs(out) { const results = []; for (const line of out.split(/\r?\n/)) { @@ -41,14 +41,16 @@ export function parseDockerPs(out) { if (!/^[0-9a-f]+$/i.test(id) || !name) continue; const seen = new Set(); for (const mapping of ports.split(', ')) { - const m = mapping.match(/^(.*):(\d+)(?:-(\d+))?->/); // greedy: ":::8080->" gives address "::" + // greedy: ":::8080->" gives address "::". The container side ends in /tcp, /udp or /sctp. + const m = mapping.match(/^(.*):(\d+)(?:-(\d+))?->[\d-]+\/(\w+)$/); if (!m) continue; const start = Number(m[2]); const end = Number(m[3] ?? m[2]); + const protocol = m[4].toLowerCase(); for (let port = start; port <= end; port++) { - if (seen.has(port)) continue; - seen.add(port); - results.push({ port, id, name, image, address: m[1] }); + if (seen.has(`${port}/${protocol}`)) continue; + seen.add(`${port}/${protocol}`); + results.push({ port, protocol, id, name, image, address: m[1] }); } } } diff --git a/src/interactive.js b/src/interactive.js index e07103d..9714b42 100644 --- a/src/interactive.js +++ b/src/interactive.js @@ -1,5 +1,6 @@ import process from 'node:process'; import { createInterface, emitKeypressEvents } from 'node:readline'; +import { portLabel } from './args.js'; import { c } from './colors.js'; import { cellsOf, extra, printable } from './targets.js'; import { planKill, readProcessTable } from './tree.js'; @@ -231,7 +232,7 @@ export async function confirmParents(targets) { for (const { t, plan } of plans) { const others = plan.pids.length - 2; const more = others > 0 ? c.dim(` + ${others} other process${others === 1 ? '' : 'es'}`) : ''; - console.log(` ${c.bold(`:${t.port}`)} ${printable(t.name)} ${c.dim(`(PID ${t.pid})`)} ${c.dim('→')} ${c.bold(printable(plan.parent.name))} ${c.dim(`(PID ${plan.parent.pid})`)}${more}`); + console.log(` ${c.bold(`:${portLabel(t.port, t.protocol)}`)} ${printable(t.name)} ${c.dim(`(PID ${t.pid})`)} ${c.dim('→')} ${c.bold(printable(plan.parent.name))} ${c.dim(`(PID ${plan.parent.pid})`)}${more}`); } for (const note of spared) console.log(c.dim(`\n Not stopped: ${printable(note)}`)); console.log(c.dim('\n Unsaved work in those programs is lost.')); diff --git a/src/listeners.js b/src/listeners.js index d081068..a4697e6 100644 --- a/src/listeners.js +++ b/src/listeners.js @@ -22,19 +22,22 @@ export const reach = (address = '') => WILDCARD.has(address) ? 'all interfaces' : isLoopback(address) ? 'localhost only' : address; /** - * List every process listening on a TCP port, in a single system call. - * @returns {{ port: number, pid: number, name: string, address: string }[]} sorted by port + * List every process listening on a TCP port or bound to a UDP port, in a single system call. + * UDP has no "listening": a bound, unconnected socket is what receives on a port, so that is what + * counts. Connected UDP sockets are clients (a DNS lookup, a QUIC connection) and are skipped. + * @param {string[]} [protocols] 'tcp' and/or 'udp' + * @returns {{ port: number, protocol: string, pid: number, name: string, address: string }[]} sorted by port */ -export function listListeners() { - const raw = process.platform === 'win32' ? listWindows() : listUnix(); +export function listListeners(protocols = ['tcp']) { + const raw = (process.platform === 'win32' ? listWindows() : listUnix(protocols)).filter((l) => protocols.includes(l.protocol)); const merged = new Map(); for (const l of raw) { - const key = `${l.port}:${l.pid}`; // IPv4 + IPv6 sockets of the same process collapse to one entry + const key = `${l.port}/${l.protocol}:${l.pid}`; // IPv4 + IPv6 sockets of the same process collapse to one entry const prev = merged.get(key); // keep the widest exposure, so *:3000 plus [::1]:3000 reports "all interfaces" if (!prev || breadth(l.address) > breadth(prev.address)) merged.set(key, l); } - return [...merged.values()].sort((a, b) => a.port - b.port || a.pid - b.pid); + return [...merged.values()].sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol) || a.pid - b.pid); } /** @@ -64,15 +67,31 @@ export function addProcessDetails(targets) { // wrong, so when no tool could look, listing fails loudly instead of returning []. const couldNotLook = (err) => ['ENOENT', 'ETIMEDOUT', 'ENOBUFS'].includes(err.code); -const listLsof = () => parseLsof(run('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'])); -const listSs = () => parseSs(run('ss', ['-tlnp'])); +// One lsof call per protocol: combined with a TCP state filter (-sTCP:LISTEN), lsof drops -iUDP files. +// lsof exits 1 when it finds nothing; that is an answer, unlike a missing or timed-out lsof. +const LSOF_SELECT = { tcp: ['-iTCP', '-sTCP:LISTEN'], udp: ['-iUDP'] }; +function listLsof(protocols) { + return protocols.flatMap((protocol) => { + let out; + try { + out = run('lsof', ['-nP', ...LSOF_SELECT[protocol], '-F', 'pcPn']); + } catch (err) { + if (couldNotLook(err) || err.status !== 1) throw err; + out = String(err.stdout ?? ''); + } + return parseLsof(out); + }); +} +// -l lists listening TCP sockets and unconnected (bound) UDP sockets +const listSs = (protocols) => + parseSs(run('ss', [`-${protocols.includes('tcp') ? 't' : ''}${protocols.includes('udp') ? 'u' : ''}lnp`]), protocols[0]); // ss is about twice as fast as lsof, so Linux tries it first; lsof is the fallback (and the macOS tool). -function listUnix() { +function listUnix(protocols) { const errors = []; for (const list of process.platform === 'linux' ? [listSs, listLsof] : [listLsof]) { try { - return list(); + return list(protocols); } catch (err) { errors.push(err); // missing, or lsof's exit 1 for "nothing listens": try the next tool } @@ -92,52 +111,71 @@ function listWindows() { } } catch {} // No catch: if netstat fails we have not seen the ports, and "port is free" would be a lie. + // -ano lists TCP and UDP in one call; listListeners keeps the protocols asked for. return parseNetstat(run('netstat', ['-ano'])).map((l) => ({ ...l, name: names.get(l.pid) ?? 'unknown' })); } -/** Parse `lsof -F pcn` output: p, c, n
lines. */ +/** + * Parse `lsof -F pcPn` output: p, c, then per socket P and n
. + * Without P lines (older callers) every socket is TCP. A UDP name with "->" is a connected client + * socket (local->remote), not something serving the port, so it is skipped. + */ export function parseLsof(out) { const results = []; let pid; let name = 'unknown'; + let protocol = 'tcp'; for (const line of out.split(/\r?\n/)) { const value = line.slice(1); if (line[0] === 'p') pid = Number(value); else if (line[0] === 'c') name = value; + else if (line[0] === 'P') protocol = value.toLowerCase(); else if (line[0] === 'n') { + if (value.includes('->') || !['tcp', 'udp'].includes(protocol)) continue; const port = portOf(value); - if (port && pid) results.push({ port, pid, name, address: addressOf(value) }); + if (port && pid) results.push({ port, protocol, pid, name, address: addressOf(value) }); } } return results; } -/** Parse `ss -tlnp` output. Rows without pid info (other users' processes) are skipped. */ -export function parseSs(out) { +/** + * Parse `ss -tlnp` / `-ulnp` / `-tulnp` output. With both -t and -u, ss adds a Netid column (tcp/udp) + * first; with one of them there is none and every row is `protocol`. + * Rows without pid info (other users' processes) are skipped. + */ +export function parseSs(out, protocol = 'tcp') { const results = []; for (const line of out.split(/\r?\n/)) { - const local = line.trim().split(/\s+/)[3]; + const cols = line.trim().split(/\s+/); + const netid = ['tcp', 'udp'].includes(cols[0]) ? cols[0] : null; + const local = cols[netid ? 4 : 3]; const port = portOf(local); if (!port) continue; for (const m of line.matchAll(/\("([^"]+)",pid=(\d+)/g)) { - results.push({ port, pid: Number(m[2]), name: m[1], address: addressOf(local) }); + results.push({ port, protocol: netid ?? protocol, pid: Number(m[2]), name: m[1], address: addressOf(local) }); } } return results; } /** - * Parse `netstat -ano` TCP rows. A listening socket has a foreign port of 0; checking that - * instead of the "LISTENING" state keeps this working on non-English Windows. + * Parse `netstat -ano` TCP and UDP rows. A listening TCP socket has a foreign port of 0; checking + * that instead of the "LISTENING" state keeps this working on non-English Windows. UDP rows have no + * state column (`UDP 0.0.0.0:5353 *:* 77`) and every one is a bound socket. */ export function parseNetstat(out) { const results = []; for (const line of out.split(/\r?\n/)) { - const [proto, local, foreign, , pidStr] = line.trim().split(/\s+/); - if (proto !== 'TCP' || !foreign?.endsWith(':0')) continue; + const cols = line.trim().split(/\s+/); + const [proto, local, foreign] = cols; + let pidStr; + if (proto === 'TCP' && foreign?.endsWith(':0')) pidStr = cols[4]; + else if (proto === 'UDP' && foreign === '*:*') pidStr = cols[3]; + else continue; const port = portOf(local); const pid = Number(pidStr); - if (port && pid > 0) results.push({ port, pid, address: addressOf(local) }); + if (port && pid > 0) results.push({ port, protocol: proto.toLowerCase(), pid, address: addressOf(local) }); } return results; } diff --git a/src/targets.js b/src/targets.js index da38aeb..b62524a 100644 --- a/src/targets.js +++ b/src/targets.js @@ -1,35 +1,42 @@ import { c } from './colors.js'; import { isDockerProxy, listContainerPorts, stopContainer } from './docker.js'; import { killPid } from './kill.js'; +import { portLabel } from './args.js'; import { addProcessDetails, listListeners, reach } from './listeners.js'; /** * A target is something occupying a port that pk can free: a host process or a Docker container. - * `address` is the bind address; `user` and `command` come from `ps` and may be absent (Windows, no ps). - * @typedef {{ kind: 'process', port: number, pid: number, name: string, address: string, user?: string, command?: string } - * | { kind: 'container', port: number, id: string, name: string, image: string, address: string }} Target + * `protocol` is 'tcp' or 'udp'; `address` is the bind address; `user` and `command` come from `ps` + * and may be absent (Windows, no ps). + * @typedef {{ kind: 'process', port: number, protocol: string, pid: number, name: string, address: string, user?: string, command?: string } + * | { kind: 'container', port: number, protocol: string, id: string, name: string, image: string, address: string }} Target */ +const slot = (t) => `${t.port}/${t.protocol}`; + /** - * Find everything occupying the given ports (or all listening ports when none are given). + * Find everything occupying the given ports, or every port in use over `protocols` when none are given. * Ports published by a container map to the container, not to Docker's proxy process. - * @param {number[]} [ports] + * @param {{ port: number, protocol: string }[]} [ports] + * @param {string[]} [protocols] what to list when no ports are given * @returns {Promise} */ -export async function findTargets(ports) { +export async function findTargets(ports = [], protocols = ['tcp']) { + const wanted = ports.length ? new Set(ports.map(slot)) : null; + const scope = wanted ? [...new Set(ports.map((p) => p.protocol))] : protocols; + const pendingContainers = listContainerPorts(); // docker runs in the background while the sync port listing below blocks - const listeners = listListeners(); - const containers = await pendingContainers; - const dockerPorts = new Set(containers.map((t) => t.port)); - const processes = listeners.filter((l) => !(dockerPorts.has(l.port) && isDockerProxy(l.name))); + const listeners = listListeners(scope); + const containers = (await pendingContainers).filter((t) => scope.includes(t.protocol)); + const dockerPorts = new Set(containers.map(slot)); + const processes = listeners.filter((l) => !(dockerPorts.has(slot(l)) && isDockerProxy(l.name))); - const wanted = ports?.length ? new Set(ports) : null; const found = [ ...containers.map((t) => ({ kind: 'container', ...t })), ...processes.map((t) => ({ kind: 'process', ...t })), ] - .filter((t) => !wanted || wanted.has(t.port)) - .sort((a, b) => a.port - b.port); + .filter((t) => !wanted || wanted.has(slot(t))) + .sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol)); return addProcessDetails(found); } @@ -49,9 +56,9 @@ export const describe = (t) => ? `Docker container ${c.bold(printable(t.name))} ${c.dim(`(${t.id})`)}` : `${c.bold(printable(t.name))} ${c.dim(`(PID ${t.pid})`)}`; -/** Plain, sanitized text for each table column of a target (see ui.js). */ +/** Plain, sanitized text for each table column of a target (see ui.js). UDP ports read ":5353/udp". */ export const cellsOf = (t) => ({ - port: `:${t.port}`, + port: `:${portLabel(t.port, t.protocol)}`, name: printable(t.name), id: t.kind === 'container' ? t.id.slice(0, 12) : String(t.pid), user: t.kind === 'container' ? 'container' : printable(t.user ?? ''), @@ -78,11 +85,11 @@ export function extra(t) { // 300 ms graceful wait, so the escalation check always sees fresh data. let scan = { at: 0, listeners: [] }; function recentListeners() { - if (Date.now() - scan.at > 100) scan = { listeners: listListeners(), at: Date.now() }; + if (Date.now() - scan.at > 100) scan = { listeners: listListeners(['tcp', 'udp']), at: Date.now() }; return scan.listeners; } -const holdsPort = (t) => recentListeners().some((l) => l.pid === t.pid && l.port === t.port); +const holdsPort = (t) => recentListeners().some((l) => l.pid === t.pid && l.port === t.port && l.protocol === t.protocol); /** @returns {Promise} how the target was stopped, for reporting. Async so a sync throw becomes a rejection. */ export async function freeTarget(t, force, scope = 'holder') { diff --git a/src/ui.js b/src/ui.js index ac04277..4e3a4c4 100644 --- a/src/ui.js +++ b/src/ui.js @@ -8,7 +8,7 @@ import { c } from './colors.js'; const GAP = ' '; /** [cell key, header title, max width]; the last column takes whatever width is left. */ const COLUMNS = [ - ['port', 'PORT', 7], + ['port', 'PORT', 10], // ":65535/udp" ['name', 'PROCESS', 26], ['id', 'PID/ID', 12], ['user', 'USER', 14], @@ -70,5 +70,24 @@ export const rule = (length) => c.dim('─'.repeat(Math.max(0, length))); export const labelledRule = (label, length) => label ? c.dim(`─ ${label} ${'─'.repeat(Math.max(0, length - label.length - 3))}`) : rule(length); +/** + * The command that frees what --info just showed, so nobody has to work it out. For named ports: + * "To free it: pk 3000" / "To free them: pk 3000 5353/udp". For a full listing, real examples from it + * and how to open the picker for the same protocols: "To free one: pk 3000 · several: pk 3000 5173 · + * or pick from a list: pk". + * @param {string[]} labels port labels as typed back to pk ("3000", "5353/udp"), in display order + * @param {{ command?: string, all?: boolean, protocols?: string[] }} [options] + */ +export function freeHint(labels, { command = 'pk', all = false, protocols = ['tcp'] } = {}) { + const cmd = (args) => c.bold(`${command} ${args}`.trim()); + if (!all) return c.dim(` To free ${labels.length === 1 ? 'it' : 'them'}: ${cmd(labels.join(' '))}`); + const pick = protocols.includes('udp') ? (protocols.includes('tcp') ? '--tcp --udp' : '--udp') : ''; + const parts = []; + if (labels.length > 0) parts.push(`To free one: ${cmd(labels[0])}`); + if (labels.length > 1) parts.push(`several: ${cmd(labels.slice(0, 2).join(' '))}`); + parts.push(`${parts.length ? 'or ' : ''}pick from a list: ${cmd(pick)}`); + return c.dim(` ${parts.join(c.dim(' · '))}`); +} + /** Key hints like "↑↓ move · space toggle", key names bold. */ export const keyHints = (pairs) => pairs.map(([key, label]) => `${c.bold(key)} ${c.dim(label)}`).join(c.dim(' · ')); diff --git a/test/e2e.test.js b/test/e2e.test.js index c69bfa0..9177354 100644 --- a/test/e2e.test.js +++ b/test/e2e.test.js @@ -11,9 +11,14 @@ const cli = fileURLToPath(new URL('../bin/cli.js', import.meta.url)); const pk = (...args) => spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8', timeout: 20_000, env: { ...process.env, NO_COLOR: '1' } }); -test('e2e: package.json exposes pk, kp, kill-port and port-kill as the same CLI', async () => { +test('e2e: package.json exposes every command name as the same CLI', async () => { const { bin } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')); - assert.deepEqual(bin, { 'port-kill': './bin/cli.js', pk: './bin/cli.js', kp: './bin/cli.js', 'kill-port': './bin/cli.js' }); + const names = ['pk', 'kp', 'cpk', 'ckp', 'port-kill', 'kill-port', 'cross-port-kill', 'cross-kill-port']; + assert.deepEqual(bin, { + ...Object.fromEntries(names.map((n) => [n, './bin/cli.js'])), + 'pk-udp': './bin/pk-udp.js', + 'pk-tcp': './bin/pk-tcp.js', + }); }); // PATH='' makes lsof/ss unfindable on Unix. Windows resolves tools from System32 regardless of PATH. @@ -55,6 +60,79 @@ test('e2e: --info reports, pk frees the port, second run says already free', asy assert.match(pk(String(port)).stdout, new RegExp(`Port ${port} is already free`)); }); +test('e2e: a pasted URL or host:port frees the port', async (t) => { + const { child, port } = await startServer(); + t.after(() => child.kill('SIGKILL')); + + const info = pk(`localhost:${port}`, 'list'); // "list" is --info + assert.match(info.stdout, new RegExp(`:${port}\\b.*\\b${child.pid}\\b`), info.stdout + info.stderr); + assert.equal(child.exitCode, null, 'list must not kill'); + + const kill = pk(`http://localhost:${port}/`); + assert.equal(kill.status, 0, kill.stdout + kill.stderr); + assert.match(kill.stdout, new RegExp(`Freed port ${port}`)); + await exited(child); +}); + +test('e2e: "pk port N" shows the holder and how to free it, "pk kill N" frees it', async (t) => { + const { child, port } = await startServer(); + t.after(() => child.kill('SIGKILL')); + + for (const words of [['port', String(port)], ['what', 'is', 'on', String(port)], ['is', String(port), 'free']]) { + const r = pk(...words); + assert.match(r.stdout, new RegExp(`:${port}\\b.*\\b${child.pid}\\b`), words.join(' ') + '\n' + r.stdout + r.stderr); + assert.match(r.stdout, new RegExp(`To free it: \\S+ ${port}\\b`)); + assert.equal(child.exitCode, null, `"${words.join(' ')}" must not kill`); + } + + const kill = pk('kill', String(port)); + assert.equal(kill.status, 0, kill.stdout + kill.stderr); + assert.match(kill.stdout, new RegExp(`Freed port ${port}`)); + await exited(child); +}); + +/** Bind a UDP socket on a free port and resolve once it is bound. */ +async function startUdp() { + const code = `const s=require('dgram').createSocket('udp4');s.bind(0,'127.0.0.1',()=>console.log(s.address().port));setInterval(()=>{},1e6);`; + const child = spawn(process.execPath, ['-e', code], { stdio: ['ignore', 'pipe', 'inherit'] }); + const [chunk] = await once(child.stdout, 'data'); + return { child, port: Number(String(chunk).trim()) }; +} + +test('e2e: UDP ports are only touched when asked for, with --udp or a /udp suffix', async (t) => { + const { child, port } = await startUdp(); + t.after(() => child.kill('SIGKILL')); + + const tcpOnly = pk(String(port)); // TCP is the default: the UDP holder must survive + assert.match(tcpOnly.stdout, new RegExp(`Port ${port} is already free`), tcpOnly.stdout + tcpOnly.stderr); + assert.equal(child.exitCode, null, 'a plain port must not stop a UDP socket'); + + const info = pk(String(port), '--udp', '--info'); + assert.match(info.stdout, new RegExp(`:${port}/udp\\b.*\\b${child.pid}\\b`), info.stdout + info.stderr); + + const kill = pk(`${port}/udp`); + assert.equal(kill.status, 0, kill.stdout + kill.stderr); + assert.match(kill.stdout, new RegExp(`Freed port ${port}/udp`)); + await exited(child); +}); + +test('e2e: pk-udp is pk --udp, pk-tcp is pk --tcp', async (t) => { + const run = (file, ...args) => + spawnSync(process.execPath, [fileURLToPath(new URL(`../bin/${file}`, import.meta.url)), ...args], { + encoding: 'utf8', timeout: 20_000, env: { ...process.env, NO_COLOR: '1' }, + }); + const { child, port } = await startUdp(); + t.after(() => child.kill('SIGKILL')); + + assert.match(run('pk-tcp.js', String(port)).stdout, new RegExp(`Port ${port} is already free`)); + assert.equal(child.exitCode, null, 'pk-tcp must not stop a UDP socket'); + + const kill = run('pk-udp.js', String(port)); + assert.equal(kill.status, 0, kill.stdout + kill.stderr); + assert.match(kill.stdout, new RegExp(`Freed port ${port}/udp`)); + await exited(child); +}); + test('e2e: --force kills a process that ignores SIGTERM', { skip: process.platform === 'win32' && 'no SIGTERM on Windows' }, async (t) => { const { child, port } = await startServer({ ignoreSigterm: true }); t.after(() => child.kill('SIGKILL')); diff --git a/test/parsers.test.js b/test/parsers.test.js index 95e0648..c7f751d 100644 --- a/test/parsers.test.js +++ b/test/parsers.test.js @@ -9,15 +9,118 @@ import { cellsOf, printable } from '../src/targets.js'; import { parseProcessTable, planKill, scopeOf } from '../src/tree.js'; import { columnWidths, fit } from '../src/ui.js'; +const tcp = (...ports) => ports.map((port) => ({ port, protocol: 'tcp' })); +const udp = (...ports) => ports.map((port) => ({ port, protocol: 'udp' })); + test('parseArgs: ports, ranges, flags', () => { const opts = parseArgs(['3000', '3000-3002', '-f', '--info']); - assert.deepEqual(opts.ports, [3000, 3001, 3002]); + assert.deepEqual(opts.ports, tcp(3000, 3001, 3002)); + assert.deepEqual(opts.protocols, ['tcp']); assert.equal(opts.force, true); assert.equal(opts.info, true); }); +test('parseArgs: --udp switches every port to UDP, --tcp --udp checks both', () => { + assert.deepEqual(parseArgs(['5353', '-u']).ports, udp(5353)); + assert.deepEqual(parseArgs(['--udp']).protocols, ['udp']); + assert.deepEqual(parseArgs(['53', '--tcp', '--udp']).ports, [...tcp(53), ...udp(53)]); + assert.deepEqual(parseArgs(['-t']).protocols, ['tcp']); +}); + +test('parseArgs: a /tcp or /udp suffix sets the protocol of that argument only', () => { + assert.deepEqual(parseArgs(['5353/udp', '3000']).ports, [...udp(5353), ...tcp(3000)]); + assert.deepEqual(parseArgs(['3000/tcp', '--udp']).ports, tcp(3000)); + assert.deepEqual(parseArgs(['4000-4001/UDP']).ports, udp(4000, 4001)); + assert.deepEqual(parseArgs(['53/udp', '53/udp', '53']).ports, [...udp(53), ...tcp(53)]); // duplicates collapse +}); + +test('parseArgs: forgiving port formats', () => { + const ports = (...args) => parseArgs(args).ports; + for (const same of [':3000', 'localhost:3000', '127.0.0.1:3000', '0.0.0.0:3000', '[::1]:3000', ':::3000', '*:3000', 'http://localhost:3000/', 'HTTP://LOCALHOST:3000/app?x=1']) { + assert.deepEqual(ports(same), tcp(3000), same); + } + assert.deepEqual(ports('http://localhost'), tcp(80)); + assert.deepEqual(ports('https://example.test/'), tcp(443)); + assert.deepEqual(ports('3000,5173'), tcp(3000, 5173)); + assert.deepEqual(ports('3000,', '5173'), tcp(3000, 5173)); // "pk 3000, 5173" + for (const range of ['3000..3002', '3000–3002', '3000-3002', 'localhost:3000-3002']) assert.deepEqual(ports(range), tcp(3000, 3001, 3002), range); + for (const same of ['5353/udp', '5353:udp', 'udp/5353', 'udp:5353', 'UDP:5353', 'localhost:5353/udp']) assert.deepEqual(ports(same), udp(5353), same); +}); + +test('parseArgs: forgiving options', () => { + assert.deepEqual(parseArgs(['udp', '5353']).ports, udp(5353)); + assert.deepEqual(parseArgs(['5353', 'UDP']).ports, udp(5353)); + for (const word of ['list', 'ls', 'info']) assert.equal(parseArgs([word]).info, true, word); + assert.equal(parseArgs(['help']).help, true); + assert.equal(parseArgs(['--UDP']).udp, true); + assert.equal(parseArgs(['-udp']).udp, true); + assert.equal(parseArgs(['-tree']).tree, true); + const combined = parseArgs(['-ui', '5353']); + assert.equal(combined.info, true); + assert.deepEqual(combined.ports, udp(5353)); + // kill-port's syntax + assert.deepEqual(parseArgs(['--port', '3000']).ports, tcp(3000)); + assert.deepEqual(parseArgs(['-p', '3000,3001']).ports, tcp(3000, 3001)); + assert.deepEqual(parseArgs(['--port=3000', '--method', 'udp']).ports, udp(3000)); + assert.deepEqual(parseArgs(['-p', '53', '-m', 'UDP']).ports, udp(53)); +}); + +test('parseArgs: words say what to do', () => { + const run = (...args) => parseArgs(args); + for (const verb of ['kill', 'free', 'stop', 'close', 'KILL', 'kill-port']) { + const o = run(verb, '3000'); + assert.deepEqual([o.info, o.ports], [false, tcp(3000)], verb); + } + for (const look of ['port', 'show', 'check', 'find', 'status', 'list']) { + const o = run(look, '3000'); + assert.deepEqual([o.info, o.ports], [true, tcp(3000)], look); + } + assert.equal(run('kill', 'port', '3000').info, false); // "kill port 3000": the verb wins over "port" + assert.equal(run('kill', 'the', 'port', 'on', '3000').info, false); + assert.equal(run('what', 'is', 'on', '3000?').info, true); + assert.equal(run('who', 'uses', '3000').info, true); + assert.equal(run("what's", 'on', ':3000').info, true); + assert.equal(run('is', '3000', 'free?').info, true); // a question never kills, even with "free" in it + assert.equal(run('kill', '3000', '--info').info, true); // an explicit flag wins + assert.equal(run('kill', '-9', '3000').force, true); + assert.equal(run('force', 'kill', '3000').force, true); + assert.deepEqual(run('kill', 'udp', '5353').ports, udp(5353)); + assert.equal(run('kill', '3000', 'children').children, true); +}); + +test('parseArgs: a protocol named on its own lists those ports', () => { + const run = (...args) => parseArgs(args); + const look = (o) => [o.info, o.protocols, o.ports.length]; + assert.deepEqual(look(run('udp')), [true, ['udp'], 0]); + assert.deepEqual(look(run('tcp')), [true, ['tcp'], 0]); + assert.deepEqual(look(run('udp', 'ports')), [true, ['udp'], 0]); + assert.deepEqual(look(run('tcp', 'udp', 'ports')), [true, ['tcp', 'udp'], 0]); + assert.deepEqual(look(run('tcp', 'and', 'udp')), [true, ['tcp', 'udp'], 0]); + assert.deepEqual(look(run('both')), [true, ['tcp', 'udp'], 0]); + assert.deepEqual(look(run('all', 'udp', 'ports')), [true, ['udp'], 0]); + assert.deepEqual(look(run('show', 'me', 'open', 'udp', 'ports')), [true, ['udp'], 0]); + // Not a listing: a kill word picks, a port frees, and the flags keep opening the picker + assert.equal(run('kill', 'udp').info, false); + assert.equal(run('udp', '5353').info, false); + assert.equal(run('--udp').info, false); +}); + +test('parseArgs: mistyped words suggest the closest one', () => { + assert.throws(() => parseArgs(['kil', '3000']), /Unknown word: "kil". Did you mean "kill"\?/); + assert.throws(() => parseArgs(['prot', '3000']), /Did you mean "port"\?/); + assert.throws(() => parseArgs(['banana']), /pk --help/); +}); + +test('parseArgs: unknown options suggest the closest one', () => { + assert.throws(() => parseArgs(['--forse']), /Did you mean "--force"/); + assert.throws(() => parseArgs(['--udpp']), /Did you mean "--udp"/); + assert.throws(() => parseArgs(['--zzzzzz']), /pk --help/); + assert.throws(() => parseArgs(['--port']), /needs a value/); + assert.throws(() => parseArgs(['--method', 'sctp']), /Invalid protocol/); +}); + test('parseArgs: rejects bad input', () => { - for (const bad of ['abc', '0', '70000', '3005-3000', '3000-abc', '--nope']) { + for (const bad of ['abc', '0', '70000', '3005-3000', '3000-abc', '--nope', '3000/sctp', '3000/', '/udp', 'localhost', 'ftp://host', 'http://', '-x', '--info=1', 'kil', 'localhost']) { assert.throws(() => parseArgs([bad]), undefined, bad); } }); @@ -25,9 +128,17 @@ test('parseArgs: rejects bad input', () => { test('parseLsof', () => { const out = 'p123\ncnode\nf20\nn*:3000\nf21\nn[::1]:3000\np456\ncpython3\nf3\nn127.0.0.1:8000\n'; assert.deepEqual(parseLsof(out), [ - { port: 3000, pid: 123, name: 'node', address: '*' }, - { port: 3000, pid: 123, name: 'node', address: '[::1]' }, - { port: 8000, pid: 456, name: 'python3', address: '127.0.0.1' }, + { port: 3000, protocol: 'tcp', pid: 123, name: 'node', address: '*' }, + { port: 3000, protocol: 'tcp', pid: 123, name: 'node', address: '[::1]' }, + { port: 8000, protocol: 'tcp', pid: 456, name: 'python3', address: '127.0.0.1' }, + ]); +}); + +test('parseLsof: protocol per socket, connected UDP client sockets skipped', () => { + const out = 'p123\ncnode\nPTCP\nn*:3000\nPUDP\nn*:5353\nPUDP\nn10.0.0.2:51000->8.8.8.8:53\n'; + assert.deepEqual(parseLsof(out), [ + { port: 3000, protocol: 'tcp', pid: 123, name: 'node', address: '*' }, + { port: 5353, protocol: 'udp', pid: 123, name: 'node', address: '*' }, ]); }); @@ -37,20 +148,41 @@ test('parseSs', () => { 'LISTEN 0 511 *:3000 *:* users:(("node",pid=123,fd=20))', 'LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:*', ].join('\n'); - assert.deepEqual(parseSs(out), [{ port: 3000, pid: 123, name: 'node', address: '*' }]); + assert.deepEqual(parseSs(out), [{ port: 3000, protocol: 'tcp', pid: 123, name: 'node', address: '*' }]); +}); + +test('parseSs: UDP alone, and the Netid column of -tulnp', () => { + const udpOnly = [ + 'State Recv-Q Send-Q Local Address:Port Peer Address:Port Process', + 'UNCONN 0 0 0.0.0.0:5353 0.0.0.0:* users:(("avahi",pid=7,fd=12))', + ].join('\n'); + assert.deepEqual(parseSs(udpOnly, 'udp'), [{ port: 5353, protocol: 'udp', pid: 7, name: 'avahi', address: '0.0.0.0' }]); + + const both = [ + 'Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process', + 'udp UNCONN 0 0 0.0.0.0:5353 0.0.0.0:* users:(("avahi",pid=7,fd=12))', + 'tcp LISTEN 0 511 *:3000 *:* users:(("node",pid=123,fd=20))', + ].join('\n'); + assert.deepEqual(parseSs(both), [ + { port: 5353, protocol: 'udp', pid: 7, name: 'avahi', address: '0.0.0.0' }, + { port: 3000, protocol: 'tcp', pid: 123, name: 'node', address: '*' }, + ]); }); -test('parseNetstat: listening sockets only, IPv4 and IPv6', () => { +test('parseNetstat: listening TCP and bound UDP sockets, IPv4 and IPv6', () => { const out = [ ' Proto Local Address Foreign Address State PID', ' TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 1234', ' TCP [::]:5173 [::]:0 ABHÖREN 99', ' TCP 127.0.0.1:3000 127.0.0.1:51234 ESTABLISHED 1234', ' UDP 0.0.0.0:5353 *:* 77', + ' UDP [::]:5353 *:* 77', ].join('\r\n'); assert.deepEqual(parseNetstat(out), [ - { port: 3000, pid: 1234, address: '0.0.0.0' }, - { port: 5173, pid: 99, address: '[::]' }, + { port: 3000, protocol: 'tcp', pid: 1234, address: '0.0.0.0' }, + { port: 5173, protocol: 'tcp', pid: 99, address: '[::]' }, + { port: 5353, protocol: 'udp', pid: 77, address: '0.0.0.0' }, + { port: 5353, protocol: 'udp', pid: 77, address: '[::]' }, ]); }); @@ -60,12 +192,16 @@ test('parseDockerPs: published ports, ranges, IPv6 duplicates', () => { '--rm\tevil\talpine\t0.0.0.0:7000->80/tcp', // not a hex id: must never reach `docker stop` 'c3d4\tdb\tpostgres\t5432/tcp', 'e5f6\tmulti\tapp\t127.0.0.1:5000-5001->5000-5001/tcp, [::]:9229->9229/tcp', + 'f7a8\tdns\tcoredns\t0.0.0.0:53->53/udp, 0.0.0.0:53->53/tcp, :::53->53/udp', ].join('\n'); + const box = (port, protocol, id, name, image, address) => ({ port, protocol, id, name, image, address }); assert.deepEqual(parseDockerPs(out), [ - { port: 8080, id: 'a1b2', name: 'web', image: 'nginx:1.27', address: '0.0.0.0' }, - { port: 5000, id: 'e5f6', name: 'multi', image: 'app', address: '127.0.0.1' }, - { port: 5001, id: 'e5f6', name: 'multi', image: 'app', address: '127.0.0.1' }, - { port: 9229, id: 'e5f6', name: 'multi', image: 'app', address: '[::]' }, + box(8080, 'tcp', 'a1b2', 'web', 'nginx:1.27', '0.0.0.0'), + box(5000, 'tcp', 'e5f6', 'multi', 'app', '127.0.0.1'), + box(5001, 'tcp', 'e5f6', 'multi', 'app', '127.0.0.1'), + box(9229, 'tcp', 'e5f6', 'multi', 'app', '[::]'), + box(53, 'udp', 'f7a8', 'dns', 'coredns', '0.0.0.0'), // the same number over TCP is a separate port + box(53, 'tcp', 'f7a8', 'dns', 'coredns', '0.0.0.0'), ]); }); @@ -120,6 +256,8 @@ test('cellsOf: sanitized cells for processes and containers', () => { assert.deepEqual(cellsOf(proc), { port: ':3000', name: 'no de', id: '42', user: 'me', access: 'all interfaces', command: 'node a b' }); const box = { kind: 'container', port: 80, id: 'a1b2c3d4e5f6a7b8', name: 'web', image: 'nginx', address: '127.0.0.1' }; assert.deepEqual(cellsOf(box), { port: ':80', name: 'web', id: 'a1b2c3d4e5f6', user: 'container', access: 'localhost only', command: 'nginx' }); + assert.equal(cellsOf({ ...proc, protocol: 'tcp' }).port, ':3000'); + assert.equal(cellsOf({ ...proc, port: 5353, protocol: 'udp' }).port, ':5353/udp'); }); test('columnWidths: the command column takes the remaining terminal width', () => {