import { readFileSync, readlinkSync } from "node:fs"; import { execFileSync } from "node:child_process"; import { hostname, uptime } from "node:os"; import { win32 } from "node:path"; let machineIdRead: { platform: string; id: string | undefined } | undefined; /** This machine's own id where there is no /proc boot id, from the system's own tool at its fixed path. */ function machineId(): string | undefined { const read = (file: string, args: string[], pattern: RegExp) => { try { const out = execFileSync(file, args, { encoding: "utf-8", timeout: 2_000, windowsHide: true, }); return pattern.exec(out)?.[1]; } catch { return undefined; } }; if (machineIdRead?.platform === process.platform) return machineIdRead.id; const systemRoot = process.env.SystemRoot; machineIdRead = { platform: process.platform, id: process.platform === "darwin" ? read( "/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], /"IOPlatformUUID" = "([^"]+)"/, ) : process.platform === "win32" && systemRoot && /^[A-Za-z]:\\/.test(systemRoot) ? read( win32.join(systemRoot, "System32", "reg.exe"), ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"], /MachineGuid\s+REG_SZ\s+(\S+)/, ) : undefined, }; return machineIdRead.id; } /** * Where a pid means this process: host and boot, plus the Linux pid namespace. Containers and machines on a shared * folder can share a hostname, and every normal Linux host has the same root pid namespace id. */ function pidScope(): { host: string; boot?: string; pidns?: string; machine?: string } { const attempt = (read: () => string) => { try { return read(); } catch { return undefined; } }; const bootId = attempt(() => readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim()); return { host: hostname(), // Without /proc (macOS, Windows) the boot time in seconds stands in for the boot id, on this machine's own id. boot: bootId ?? attempt(() => `s:${Math.round(Date.now() / 1000 - uptime())}`), pidns: attempt(() => readlinkSync("/proc/self/ns/pid")), machine: bootId === undefined ? machineId() : undefined, }; } function alive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; } } export type OwnerRecord = { pid?: unknown; host?: unknown; boot?: unknown; pidns?: unknown; machine?: unknown; }; function knownPidScope(): ReturnType | undefined { const scope = pidScope(); const unknown = scope.boot === undefined || (process.platform === "linux" && scope.pidns === undefined) || (scope.boot.startsWith("s:") && scope.machine === undefined); return unknown ? undefined : scope; } /** A boot id matches exactly; a boot estimate in seconds moves with uptime's whole-second tick, so within 2 s. */ function sameBoot(stamped: unknown, current: string | undefined): boolean { if (stamped === current) return true; const seconds = (boot: unknown) => typeof boot === "string" ? /^s:(\d+)$/.exec(boot)?.[1] : undefined; const [a, b] = [seconds(stamped), seconds(current)]; return a !== undefined && b !== undefined && Math.abs(Number(a) - Number(b)) <= 2; } function inThisPidScope(owner: OwnerRecord): boolean { const scope = knownPidScope(); return ( scope !== undefined && owner.host === scope.host && sameBoot(owner.boot, scope.boot) && owner.pidns === scope.pidns && owner.machine === scope.machine ); } /** This process, stamped so a later reader can tell whether it still runs. */ export function processOwnerRecord(): OwnerRecord { return { pid: process.pid, ...pidScope() }; } /** "gone" only for an owner in this pid scope that has exited; "unknown" when the record cannot say. */ export function ownerRecordState(owner: OwnerRecord): "gone" | "live" | "unknown" { const { pid } = owner; if (!inThisPidScope(owner) || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) { return "unknown"; } return alive(pid) ? "live" : "gone"; }