@kaynooo/cli-proc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-proc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "pid, ports, procs: one process inspected, who listens on a port, and leftover or heavy dev processes cleaned, read straight from /proc (Linux).",
6
+ "author": "Kaynooo <contact@kaynooo.fr>",
7
+ "license": "MIT",
8
+ "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/proc#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
12
+ "directory": "packages/proc"
13
+ },
14
+ "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
15
+ "keywords": ["process", "port", "proc", "kill", "cli", "bun"],
16
+ "os": ["linux"],
17
+ "bin": {
18
+ "pid": "./dist/pid-cli.js",
19
+ "ports": "./dist/ports-cli.js",
20
+ "procs": "./dist/procs-cli.js"
21
+ },
22
+ "files": ["dist", "src"],
23
+ "engines": {
24
+ "bun": ">=1.4.3"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
28
+ },
29
+ "scripts": {
30
+ "build": "$npm_execpath build src/pid-cli.ts src/ports-cli.ts src/procs-cli.ts --target bun --outdir dist",
31
+ "pid": "$npm_execpath src/pid-cli.ts",
32
+ "ports": "$npm_execpath src/ports-cli.ts",
33
+ "procs": "$npm_execpath src/procs-cli.ts"
34
+ },
35
+ "devDependencies": {
36
+ "@kaynooo/cli-kit": "0.20.0"
37
+ }
38
+ }
package/src/docker.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { Container } from './parse'
2
+ import { runCommand } from '@kaynooo/cli-kit'
3
+ import { parseDockerPs } from './parse'
4
+
5
+ const FORMAT = '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}'
6
+
7
+ // The running containers with their published ports and compose labels; none, quietly, when docker is missing or its daemon unreachable.
8
+ export async function dockerContainers(): Promise<Container[]> {
9
+ if (Bun.which('docker') === null)
10
+ return []
11
+
12
+ try {
13
+ const ran = await runCommand(['docker', 'ps', '--format', FORMAT], { timeoutMs: 4000 })
14
+
15
+ return ran.code === 0 ? parseDockerPs(ran.text) : []
16
+ }
17
+ catch {
18
+ return []
19
+ }
20
+ }
package/src/kill.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { ProcInfo } from './read'
2
+ import { readText } from './read'
3
+
4
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'fish', 'dash', 'ash', 'nu', 'tcsh', 'ksh', 'elvish', 'xonsh'])
5
+ const TERMINALS = new Set(['kitty', 'alacritty', 'konsole', 'wezterm-gui', 'foot', 'footclient', 'xterm', 'gnome-terminal-', 'ghostty', 'tmux: server', 'tmux', 'screen', 'terminator', 'tilix', 'urxvt', 'st', 'yakuake', 'ptyxis'])
6
+
7
+ export interface Guard {
8
+ uid: number
9
+ // The calling process and each of its ancestors.
10
+ mine: ReadonlySet<number>
11
+ }
12
+
13
+ // Why a process must not be signalled, undefined when it may be.
14
+ export function protectionOf(proc: ProcInfo, { uid, mine }: Guard): string | undefined {
15
+ if (proc.pid === 1)
16
+ return 'pid 1'
17
+
18
+ if (proc.uid !== uid)
19
+ return 'another user\'s process'
20
+
21
+ if (mine.has(proc.pid))
22
+ return 'this command or one of its ancestors'
23
+
24
+ if (SHELLS.has(proc.comm))
25
+ return 'a shell'
26
+
27
+ return TERMINALS.has(proc.comm) ? 'a terminal' : undefined
28
+ }
29
+
30
+ export interface Signaller {
31
+ send: (pid: number, signal: NodeJS.Signals) => boolean
32
+ alive: (pid: number) => Promise<boolean>
33
+ sleep: (ms: number) => Promise<void>
34
+ }
35
+
36
+ export const realSignaller: Signaller = {
37
+ send(pid, signal) {
38
+ try {
39
+ process.kill(pid, signal)
40
+
41
+ return true
42
+ }
43
+ catch {
44
+ return false
45
+ }
46
+ },
47
+ // A zombie is dead for our purposes: its parent has yet to reap it.
48
+ async alive(pid) {
49
+ const stat = await readText(`/proc/${pid}/stat`)
50
+
51
+ return stat !== undefined && !stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z')
52
+ },
53
+ sleep: async ms => Bun.sleep(ms),
54
+ }
55
+
56
+ export interface Outcome {
57
+ // Gone after SIGTERM.
58
+ terminated: number[]
59
+ // Needed SIGKILL.
60
+ killed: number[]
61
+ // Still there at the end, or refused the signal.
62
+ survived: number[]
63
+ }
64
+
65
+ const POLL_MS = 100
66
+
67
+ async function waitGone(pids: number[], graceMs: number, signaller: Signaller): Promise<number[]> {
68
+ let alive = pids
69
+ let waited = 0
70
+
71
+ while (alive.length > 0 && waited < graceMs) {
72
+ await signaller.sleep(POLL_MS)
73
+ waited += POLL_MS
74
+ alive = await filterAlive(alive, signaller)
75
+ }
76
+
77
+ return alive
78
+ }
79
+
80
+ async function filterAlive(pids: number[], signaller: Signaller): Promise<number[]> {
81
+ const alive: number[] = []
82
+
83
+ for (const pid of pids) {
84
+ if (await signaller.alive(pid))
85
+ alive.push(pid)
86
+ }
87
+
88
+ return alive
89
+ }
90
+
91
+ // SIGTERM to each pid, then with `escalate` SIGKILL to those still there after `graceMs`.
92
+ export async function terminate(pids: number[], { escalate, graceMs, signaller = realSignaller }: { escalate: boolean, graceMs: number, signaller?: Signaller }): Promise<Outcome> {
93
+ const refused = pids.filter(pid => !signaller.send(pid, 'SIGTERM'))
94
+ const sent = pids.filter(pid => !refused.includes(pid))
95
+ const remaining = await waitGone(sent, graceMs, signaller)
96
+ const terminated = sent.filter(pid => !remaining.includes(pid))
97
+
98
+ if (!escalate || remaining.length === 0)
99
+ return { terminated, killed: [], survived: [...refused, ...remaining] }
100
+
101
+ for (const pid of remaining)
102
+ signaller.send(pid, 'SIGKILL')
103
+
104
+ const stuck = await waitGone(remaining, 2000, signaller)
105
+
106
+ return { terminated, killed: remaining.filter(pid => !stuck.includes(pid)), survived: [...refused, ...stuck] }
107
+ }
package/src/mask.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { isSecretName } from '@kaynooo/cli-kit'
2
+
3
+ export const MASK = '***'
4
+
5
+ // Shapes of a secret that give themselves away whatever the name holding them: a URL password, a well known token format, a long opaque token.
6
+ const URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi
7
+ const TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g
8
+ const OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi
9
+ const PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/
10
+
11
+ // A value with whatever looks like a secret inside it replaced.
12
+ export function maskText(value: string): string {
13
+ return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK)
14
+ }
15
+
16
+ // A value under its variable name: all of it when the name says secret, else the secrets inside it.
17
+ export function maskValue(name: string, value: string): string {
18
+ if (value === '')
19
+ return value
20
+
21
+ return isSecretName(name) ? MASK : maskText(value)
22
+ }
23
+
24
+ export function maskEnviron(entries: [name: string, value: string][]): [name: string, value: string][] {
25
+ return entries.map(([name, value]) => [name, maskValue(name, value)])
26
+ }
27
+
28
+ const FLAG = /^-{1,2}([\w.-]+)(=|$)/
29
+ const ASSIGNMENT_NAME = /^[\w.-]+$/
30
+
31
+ // A command line with secrets masked: `--password=x`, `--token x` and `API_KEY=x` words, and secret shapes in any other.
32
+ export function maskArgs(args: string[]): string[] {
33
+ let hidden = false
34
+
35
+ return args.map((arg) => {
36
+ if (hidden) {
37
+ hidden = false
38
+
39
+ return arg.startsWith('-') ? maskText(arg) : MASK
40
+ }
41
+
42
+ const flag = FLAG.exec(arg)
43
+
44
+ if (flag !== null) {
45
+ if (flag[2] === '=')
46
+ return isSecretName(flag[1]!) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg)
47
+
48
+ hidden = isSecretName(flag[1]!)
49
+
50
+ return arg
51
+ }
52
+
53
+ const equals = arg.indexOf('=')
54
+
55
+ return equals > 0 && ASSIGNMENT_NAME.test(arg.slice(0, equals)) ? `${arg.slice(0, equals + 1)}${maskValue(arg.slice(0, equals), arg.slice(equals + 1))}` : maskText(arg)
56
+ })
57
+ }
package/src/parse.ts ADDED
@@ -0,0 +1,284 @@
1
+ export type Protocol = 'tcp' | 'udp'
2
+
3
+ export interface Socket {
4
+ protocol: Protocol
5
+ family: 4 | 6
6
+ address: string
7
+ port: number
8
+ inode: number
9
+ uid: number
10
+ }
11
+
12
+ // A TCP socket in LISTEN, or a UDP one bound and not connected.
13
+ const LISTENING: Record<Protocol, string> = { tcp: '0A', udp: '07' }
14
+ const WHITESPACE = /\s+/
15
+ const HEX_PAIR = /../g
16
+ const SOCKET_LINK = /^socket:\[(\d+)\]$/
17
+ const UNIT_SCOPE = /\.(?:service|scope)$/
18
+ const CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/
19
+ const DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/
20
+
21
+ // One 32-bit word of an address, which /proc prints in the host's byte order (little endian), as its two hextets.
22
+ function word(hex: string): [number, number] {
23
+ const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map(byte => Number.parseInt(byte, 16))
24
+
25
+ return [(bytes[0]! << 8) | bytes[1]!, (bytes[2]! << 8) | bytes[3]!]
26
+ }
27
+
28
+ // An address as /proc/net/tcp and /proc/net/tcp6 write it: eight hex digits for IPv4, thirty-two for IPv6.
29
+ export function parseAddress(hex: string): string {
30
+ if (hex.length === 8) {
31
+ const [high, low] = word(hex)
32
+
33
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`
34
+ }
35
+
36
+ const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word)
37
+
38
+ if (hextets.length !== 8)
39
+ return hex
40
+
41
+ if (hextets.slice(0, 5).every(part => part === 0) && hextets[5] === 0xFFFF)
42
+ return `::ffff:${hextets[6]! >> 8}.${hextets[6]! & 255}.${hextets[7]! >> 8}.${hextets[7]! & 255}`
43
+
44
+ return compress(hextets)
45
+ }
46
+
47
+ // The textual form of eight hextets, the longest run of zeros (two or more) written `::`.
48
+ function compress(hextets: number[]): string {
49
+ let best = { start: -1, length: 0 }
50
+ let run = { start: 0, length: 0 }
51
+
52
+ for (const [at, part] of hextets.entries()) {
53
+ run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 }
54
+
55
+ if (run.length > best.length)
56
+ best = run
57
+ }
58
+
59
+ const text = (parts: number[]) => parts.map(part => part.toString(16)).join(':')
60
+
61
+ if (best.length < 2)
62
+ return text(hextets)
63
+
64
+ return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`
65
+ }
66
+
67
+ // The listening sockets of one /proc/net table, `family` telling its address width.
68
+ export function parseNetTable(text: string, protocol: Protocol, family: 4 | 6): Socket[] {
69
+ const sockets: Socket[] = []
70
+
71
+ for (const line of text.split('\n').slice(1)) {
72
+ const columns = line.trim().split(WHITESPACE)
73
+ const [address = '', port = ''] = (columns[1] ?? '').split(':')
74
+
75
+ if (columns.length < 10 || columns[3] !== LISTENING[protocol])
76
+ continue
77
+
78
+ const number = Number.parseInt(port, 16)
79
+
80
+ if (number === 0 || Number.isNaN(number))
81
+ continue
82
+
83
+ sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) })
84
+ }
85
+
86
+ return sockets
87
+ }
88
+
89
+ // The inode of a `socket:[12345]` fd link, undefined for any other.
90
+ export function socketInode(link: string): number | undefined {
91
+ const match = SOCKET_LINK.exec(link)
92
+
93
+ return match === null ? undefined : Number(match[1])
94
+ }
95
+
96
+ export interface Stat {
97
+ comm: string
98
+ state: string
99
+ ppid: number
100
+ pgrp: number
101
+ session: number
102
+ tty: number
103
+ // Clock ticks after boot at which the process started.
104
+ startTicks: number
105
+ threads: number
106
+ }
107
+
108
+ // /proc/<pid>/stat. The command sits in parentheses and may hold spaces and parentheses itself, so the fields are counted from its last one.
109
+ export function parseStat(text: string): Stat | undefined {
110
+ const open = text.indexOf('(')
111
+ const close = text.lastIndexOf(')')
112
+
113
+ if (open === -1 || close < open)
114
+ return undefined
115
+
116
+ const rest = text.slice(close + 2).trim().split(WHITESPACE)
117
+ const field = (number: number) => Number(rest[number - 3])
118
+
119
+ if (rest.length < 20)
120
+ return undefined
121
+
122
+ return { comm: text.slice(open + 1, close), state: rest[0]!, ppid: field(4), pgrp: field(5), session: field(6), tty: field(7), threads: field(20), startTicks: field(22) }
123
+ }
124
+
125
+ // The `Key:\tvalue` lines of /proc/<pid>/status.
126
+ export function parseStatus(text: string): Map<string, string> {
127
+ const fields = new Map<string, string>()
128
+
129
+ for (const line of text.split('\n')) {
130
+ const colon = line.indexOf(':')
131
+
132
+ if (colon > 0)
133
+ fields.set(line.slice(0, colon), line.slice(colon + 1).trim())
134
+ }
135
+
136
+ return fields
137
+ }
138
+
139
+ // A status value in kB (`VmRSS: 1234 kB`) in bytes.
140
+ export function statusBytes(fields: Map<string, string>, key: string): number | undefined {
141
+ const value = Number.parseInt(fields.get(key) ?? '', 10)
142
+
143
+ return Number.isNaN(value) ? undefined : value * 1024
144
+ }
145
+
146
+ // The real user id of `Uid:\t1000\t1000\t1000\t1000`.
147
+ export function statusUid(fields: Map<string, string>): number | undefined {
148
+ const value = Number.parseInt(fields.get('Uid') ?? '', 10)
149
+
150
+ return Number.isNaN(value) ? undefined : value
151
+ }
152
+
153
+ export interface Limit {
154
+ name: string
155
+ soft: string
156
+ hard: string
157
+ units: string
158
+ }
159
+
160
+ const LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/
161
+
162
+ // /proc/<pid>/limits, whose columns are padded with spaces and whose names hold single ones.
163
+ export function parseLimits(text: string): Limit[] {
164
+ const limits: Limit[] = []
165
+
166
+ for (const line of text.split('\n').slice(1)) {
167
+ const match = LIMIT_LINE.exec(line)
168
+
169
+ if (match !== null)
170
+ limits.push({ name: match[1]!, soft: match[2]!, hard: match[3]!, units: match[4] ?? '' })
171
+ }
172
+
173
+ return limits
174
+ }
175
+
176
+ // /proc/<pid>/cmdline: arguments joined by NUL, empty for a kernel thread.
177
+ export function parseCmdline(text: string): string[] {
178
+ return text.split('\0').filter((_, at, parts) => at < parts.length - 1 || parts[at] !== '')
179
+ }
180
+
181
+ export function parseEnviron(text: string): [name: string, value: string][] {
182
+ return parseCmdline(text).map((entry) => {
183
+ const equals = entry.indexOf('=')
184
+
185
+ return equals === -1 ? [entry, ''] : [entry.slice(0, equals), entry.slice(equals + 1)]
186
+ })
187
+ }
188
+
189
+ export interface CgroupEntry {
190
+ hierarchy: string
191
+ controllers: string
192
+ path: string
193
+ }
194
+
195
+ export function parseCgroup(text: string): CgroupEntry[] {
196
+ return text.split('\n').filter(line => line !== '').map((line) => {
197
+ const [hierarchy = '', controllers = '', ...path] = line.split(':')
198
+
199
+ return { hierarchy, controllers, path: path.join(':') }
200
+ })
201
+ }
202
+
203
+ // The innermost systemd unit or scope of a cgroup v2 path: `app-kitty-123.scope`, `docker-<id>.scope`, `foo.service`.
204
+ export function cgroupUnit(entries: CgroupEntry[]): string | undefined {
205
+ const path = (entries.find(entry => entry.hierarchy === '0') ?? entries[0])?.path ?? ''
206
+
207
+ return path.split('/').reverse().find(part => UNIT_SCOPE.test(part))
208
+ }
209
+
210
+ // The container id a cgroup path names, for Docker (`docker-<id>.scope` or `/docker/<id>`) and Podman (`libpod-<id>.scope`).
211
+ export function cgroupContainer(entries: CgroupEntry[]): string | undefined {
212
+ for (const { path } of entries) {
213
+ const match = CONTAINER_ID.exec(path)
214
+
215
+ if (match !== null)
216
+ return match[1]
217
+ }
218
+
219
+ return undefined
220
+ }
221
+
222
+ const SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i
223
+ const SIZE_UNITS: Record<string, number> = { '': 1024 ** 2, 'k': 1024, 'm': 1024 ** 2, 'g': 1024 ** 3, 't': 1024 ** 4 }
224
+
225
+ // A size such as `500M`, `1.5G` or `800k` in bytes, a bare number counting megabytes; undefined when it is none.
226
+ export function parseSize(text: string): number | undefined {
227
+ const match = SIZE.exec(text.trim())
228
+
229
+ return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2]!.toLowerCase()]!)
230
+ }
231
+
232
+ // The name behind a uid in /etc/passwd text.
233
+ export function userNameOf(passwd: string, uid: number): string | undefined {
234
+ for (const line of passwd.split('\n')) {
235
+ const [name, , id] = line.split(':')
236
+
237
+ if (id === String(uid) && name !== undefined && name !== '')
238
+ return name
239
+ }
240
+
241
+ return undefined
242
+ }
243
+
244
+ export interface Published {
245
+ host: number
246
+ protocol: Protocol
247
+ }
248
+
249
+ export interface Container {
250
+ name: string
251
+ project: string | undefined
252
+ service: string | undefined
253
+ published: Published[]
254
+ }
255
+
256
+ // The tab separated rows of `docker ps --format '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}'`; a published range (`8000-8002->80-82/tcp`) counts each of its host ports.
257
+ export function parseDockerPs(text: string): Container[] {
258
+ const containers: Container[] = []
259
+
260
+ for (const line of text.split('\n')) {
261
+ const [name = '', ports = '', project = '', service = ''] = line.split('\t')
262
+
263
+ if (name === '')
264
+ continue
265
+
266
+ const published: Published[] = []
267
+
268
+ for (const entry of ports.split(',')) {
269
+ const match = DOCKER_PORT.exec(entry)
270
+
271
+ if (match === null)
272
+ continue
273
+
274
+ const first = Number(match[1])
275
+
276
+ for (let host = first; host <= Number(match[2] ?? first); host++)
277
+ published.push({ host, protocol: match[3] as Protocol })
278
+ }
279
+
280
+ containers.push({ name, project: project === '' ? undefined : project, service: service === '' ? undefined : service, published })
281
+ }
282
+
283
+ return containers
284
+ }
package/src/pid-cli.ts ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import process from 'node:process'
4
+ import { runMain } from '@kaynooo/cli-kit'
5
+ import { version } from '../package.json'
6
+ import { pid } from './pid'
7
+
8
+ process.exitCode = await runMain({ name: 'pid', version, run: pid })