diff --git a/.changeset/guard-process-group-pgids.md b/.changeset/guard-process-group-pgids.md new file mode 100644 index 0000000..ead557c --- /dev/null +++ b/.changeset/guard-process-group-pgids.md @@ -0,0 +1,5 @@ +--- +"@aliou/pi-processes": patch +--- + +Guard process-group helpers against non-positive pgids. `isProcessGroupAlive` now returns `false` and `killProcessGroup` now throws a `RangeError` when given a `0` or negative process-group ID, instead of probing or signaling the caller's own process group. diff --git a/src/utils/process-group.test.ts b/src/utils/process-group.test.ts new file mode 100644 index 0000000..a090941 --- /dev/null +++ b/src/utils/process-group.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { isProcessGroupAlive, killProcessGroup } from "./process-group"; + +describe("process-group helpers with non-positive pgids", () => { + it("isProcessGroupAlive(0) returns false", () => { + expect(isProcessGroupAlive(0)).toBe(false); + }); + + it("isProcessGroupAlive(-1) returns false", () => { + expect(isProcessGroupAlive(-1)).toBe(false); + }); + + it("killProcessGroup(0, ...) throws RangeError", () => { + expect(() => killProcessGroup(0, "SIGTERM")).toThrow(RangeError); + }); + + it("killProcessGroup(-1, ...) throws RangeError", () => { + expect(() => killProcessGroup(-1, "SIGTERM")).toThrow(RangeError); + }); +}); diff --git a/src/utils/process-group.ts b/src/utils/process-group.ts index 728c65c..8decb49 100644 --- a/src/utils/process-group.ts +++ b/src/utils/process-group.ts @@ -3,6 +3,7 @@ * Uses signal 0 to test existence without actually sending a signal. */ export function isProcessGroupAlive(pgid: number): boolean { + if (!Number.isInteger(pgid) || pgid <= 0) return false; try { process.kill(-pgid, 0); return true; @@ -18,5 +19,8 @@ export function isProcessGroupAlive(pgid: number): boolean { * Negative PID targets the process group. */ export function killProcessGroup(pgid: number, signal: NodeJS.Signals): void { + if (!Number.isInteger(pgid) || pgid <= 0) { + throw new RangeError("Process group ID must be a positive integer"); + } process.kill(-pgid, signal); }