mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-10 07:12:42 +00:00
fix: harden port listener detection
This commit is contained in:
@@ -50,22 +50,28 @@ export function pickProbeHostForBind(
|
|||||||
return "127.0.0.1";
|
return "127.0.0.1";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function safeDaemonEnv(env: Record<string, string> | undefined): string[] {
|
const SAFE_DAEMON_ENV_KEYS = [
|
||||||
if (!env) return [];
|
"CLAWDBOT_PROFILE",
|
||||||
const allow = [
|
"CLAWDBOT_STATE_DIR",
|
||||||
"CLAWDBOT_PROFILE",
|
"CLAWDBOT_CONFIG_PATH",
|
||||||
"CLAWDBOT_STATE_DIR",
|
"CLAWDBOT_GATEWAY_PORT",
|
||||||
"CLAWDBOT_CONFIG_PATH",
|
"CLAWDBOT_NIX_MODE",
|
||||||
"CLAWDBOT_GATEWAY_PORT",
|
];
|
||||||
"CLAWDBOT_NIX_MODE",
|
|
||||||
];
|
export function filterDaemonEnv(env: Record<string, string> | undefined): Record<string, string> {
|
||||||
const lines: string[] = [];
|
if (!env) return {};
|
||||||
for (const key of allow) {
|
const filtered: Record<string, string> = {};
|
||||||
|
for (const key of SAFE_DAEMON_ENV_KEYS) {
|
||||||
const value = env[key];
|
const value = env[key];
|
||||||
if (!value?.trim()) continue;
|
if (!value?.trim()) continue;
|
||||||
lines.push(`${key}=${value.trim()}`);
|
filtered[key] = value.trim();
|
||||||
}
|
}
|
||||||
return lines;
|
return filtered;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function safeDaemonEnv(env: Record<string, string> | undefined): string[] {
|
||||||
|
const filtered = filterDaemonEnv(env);
|
||||||
|
return Object.entries(filtered).map(([key, value]) => `${key}=${value}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeListenerAddress(raw: string): string {
|
export function normalizeListenerAddress(raw: string): string {
|
||||||
|
|||||||
@@ -14,16 +14,39 @@ import { getResolvedLoggerSettings } from "../../logging.js";
|
|||||||
import { defaultRuntime } from "../../runtime.js";
|
import { defaultRuntime } from "../../runtime.js";
|
||||||
import { colorize, isRich, theme } from "../../terminal/theme.js";
|
import { colorize, isRich, theme } from "../../terminal/theme.js";
|
||||||
import { formatCliCommand } from "../command-format.js";
|
import { formatCliCommand } from "../command-format.js";
|
||||||
import { formatRuntimeStatus, renderRuntimeHints, safeDaemonEnv } from "./shared.js";
|
import {
|
||||||
|
filterDaemonEnv,
|
||||||
|
formatRuntimeStatus,
|
||||||
|
renderRuntimeHints,
|
||||||
|
safeDaemonEnv,
|
||||||
|
} from "./shared.js";
|
||||||
import {
|
import {
|
||||||
type DaemonStatus,
|
type DaemonStatus,
|
||||||
renderPortDiagnosticsForCli,
|
renderPortDiagnosticsForCli,
|
||||||
resolvePortListeningAddresses,
|
resolvePortListeningAddresses,
|
||||||
} from "./status.gather.js";
|
} from "./status.gather.js";
|
||||||
|
|
||||||
|
function sanitizeDaemonStatusForJson(status: DaemonStatus): DaemonStatus {
|
||||||
|
const command = status.service.command;
|
||||||
|
if (!command?.environment) return status;
|
||||||
|
const safeEnv = filterDaemonEnv(command.environment);
|
||||||
|
const nextCommand = {
|
||||||
|
...command,
|
||||||
|
environment: Object.keys(safeEnv).length > 0 ? safeEnv : undefined,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
...status,
|
||||||
|
service: {
|
||||||
|
...status.service,
|
||||||
|
command: nextCommand,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function printDaemonStatus(status: DaemonStatus, opts: { json: boolean }) {
|
export function printDaemonStatus(status: DaemonStatus, opts: { json: boolean }) {
|
||||||
if (opts.json) {
|
if (opts.json) {
|
||||||
defaultRuntime.log(JSON.stringify(status, null, 2));
|
const sanitized = sanitizeDaemonStatusForJson(status);
|
||||||
|
defaultRuntime.log(JSON.stringify(sanitized, null, 2));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
|
import { resolveLsofCommandSync } from "../infra/ports-lsof.js";
|
||||||
|
|
||||||
export type PortProcess = { pid: number; command?: string };
|
export type PortProcess = { pid: number; command?: string };
|
||||||
|
|
||||||
@@ -30,7 +31,8 @@ export function parseLsofOutput(output: string): PortProcess[] {
|
|||||||
|
|
||||||
export function listPortListeners(port: number): PortProcess[] {
|
export function listPortListeners(port: number): PortProcess[] {
|
||||||
try {
|
try {
|
||||||
const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-FpFc"], {
|
const lsof = resolveLsofCommandSync();
|
||||||
|
const out = execFileSync(lsof, ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-FpFc"], {
|
||||||
encoding: "utf-8",
|
encoding: "utf-8",
|
||||||
});
|
});
|
||||||
return parseLsofOutput(out);
|
return parseLsofOutput(out);
|
||||||
|
|||||||
35
src/infra/ports-inspect.test.ts
Normal file
35
src/infra/ports-inspect.test.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import net from "node:net";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const runCommandWithTimeoutMock = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../process/exec.js", () => ({
|
||||||
|
runCommandWithTimeout: (...args: unknown[]) => runCommandWithTimeoutMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const describeUnix = process.platform === "win32" ? describe.skip : describe;
|
||||||
|
|
||||||
|
describeUnix("inspectPortUsage", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
runCommandWithTimeoutMock.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports busy when lsof is missing but loopback listener exists", async () => {
|
||||||
|
const server = net.createServer();
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||||
|
const port = (server.address() as net.AddressInfo).port;
|
||||||
|
|
||||||
|
runCommandWithTimeoutMock.mockRejectedValueOnce(
|
||||||
|
Object.assign(new Error("spawn lsof ENOENT"), { code: "ENOENT" }),
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { inspectPortUsage } = await import("./ports-inspect.js");
|
||||||
|
const result = await inspectPortUsage(port);
|
||||||
|
expect(result.status).toBe("busy");
|
||||||
|
expect(result.errors?.some((err) => err.includes("ENOENT"))).toBe(true);
|
||||||
|
} finally {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import net from "node:net";
|
import net from "node:net";
|
||||||
import { runCommandWithTimeout } from "../process/exec.js";
|
import { runCommandWithTimeout } from "../process/exec.js";
|
||||||
|
import { resolveLsofCommand } from "./ports-lsof.js";
|
||||||
import { buildPortHints } from "./ports-format.js";
|
import { buildPortHints } from "./ports-format.js";
|
||||||
import type { PortListener, PortUsage, PortUsageStatus } from "./ports-types.js";
|
import type { PortListener, PortUsage, PortUsageStatus } from "./ports-types.js";
|
||||||
|
|
||||||
@@ -71,7 +72,8 @@ async function readUnixListeners(
|
|||||||
port: number,
|
port: number,
|
||||||
): Promise<{ listeners: PortListener[]; detail?: string; errors: string[] }> {
|
): Promise<{ listeners: PortListener[]; detail?: string; errors: string[] }> {
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
const res = await runCommandSafe(["lsof", "-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-FpFcn"]);
|
const lsof = await resolveLsofCommand();
|
||||||
|
const res = await runCommandSafe([lsof, "-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-FpFcn"]);
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
const listeners = parseLsofFieldOutput(res.stdout);
|
const listeners = parseLsofFieldOutput(res.stdout);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
@@ -87,11 +89,12 @@ async function readUnixListeners(
|
|||||||
);
|
);
|
||||||
return { listeners, detail: res.stdout.trim() || undefined, errors };
|
return { listeners, detail: res.stdout.trim() || undefined, errors };
|
||||||
}
|
}
|
||||||
if (res.code === 1) {
|
const stderr = res.stderr.trim();
|
||||||
|
if (res.code === 1 && !res.error && !stderr) {
|
||||||
return { listeners: [], detail: undefined, errors };
|
return { listeners: [], detail: undefined, errors };
|
||||||
}
|
}
|
||||||
if (res.error) errors.push(res.error);
|
if (res.error) errors.push(res.error);
|
||||||
const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join("\n");
|
const detail = [stderr, res.stdout.trim()].filter(Boolean).join("\n");
|
||||||
if (detail) errors.push(detail);
|
if (detail) errors.push(detail);
|
||||||
return { listeners: [], detail: undefined, errors };
|
return { listeners: [], detail: undefined, errors };
|
||||||
}
|
}
|
||||||
@@ -175,7 +178,7 @@ async function readWindowsListeners(
|
|||||||
return { listeners, detail: res.stdout.trim() || undefined, errors };
|
return { listeners, detail: res.stdout.trim() || undefined, errors };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkPortInUse(port: number): Promise<PortUsageStatus> {
|
async function tryListenOnHost(port: number, host: string): Promise<PortUsageStatus | "skip"> {
|
||||||
try {
|
try {
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
const tester = net
|
const tester = net
|
||||||
@@ -184,15 +187,29 @@ async function checkPortInUse(port: number): Promise<PortUsageStatus> {
|
|||||||
.once("listening", () => {
|
.once("listening", () => {
|
||||||
tester.close(() => resolve());
|
tester.close(() => resolve());
|
||||||
})
|
})
|
||||||
.listen(port);
|
.listen({ port, host, exclusive: true });
|
||||||
});
|
});
|
||||||
return "free";
|
return "free";
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (isErrno(err) && err.code === "EADDRINUSE") return "busy";
|
if (isErrno(err) && err.code === "EADDRINUSE") return "busy";
|
||||||
|
if (isErrno(err) && (err.code === "EADDRNOTAVAIL" || err.code === "EAFNOSUPPORT")) {
|
||||||
|
return "skip";
|
||||||
|
}
|
||||||
return "unknown";
|
return "unknown";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function checkPortInUse(port: number): Promise<PortUsageStatus> {
|
||||||
|
const hosts = ["127.0.0.1", "0.0.0.0", "::1", "::"];
|
||||||
|
let sawUnknown = false;
|
||||||
|
for (const host of hosts) {
|
||||||
|
const result = await tryListenOnHost(port, host);
|
||||||
|
if (result === "busy") return "busy";
|
||||||
|
if (result === "unknown") sawUnknown = true;
|
||||||
|
}
|
||||||
|
return sawUnknown ? "unknown" : "free";
|
||||||
|
}
|
||||||
|
|
||||||
export async function inspectPortUsage(port: number): Promise<PortUsage> {
|
export async function inspectPortUsage(port: number): Promise<PortUsage> {
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
const result =
|
const result =
|
||||||
|
|||||||
35
src/infra/ports-lsof.ts
Normal file
35
src/infra/ports-lsof.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import fsPromises from "node:fs/promises";
|
||||||
|
|
||||||
|
const LSOF_CANDIDATES =
|
||||||
|
process.platform === "darwin"
|
||||||
|
? ["/usr/sbin/lsof", "/usr/bin/lsof"]
|
||||||
|
: ["/usr/bin/lsof", "/usr/sbin/lsof"];
|
||||||
|
|
||||||
|
async function canExecute(path: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await fsPromises.access(path, fs.constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveLsofCommand(): Promise<string> {
|
||||||
|
for (const candidate of LSOF_CANDIDATES) {
|
||||||
|
if (await canExecute(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
return "lsof";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveLsofCommandSync(): string {
|
||||||
|
for (const candidate of LSOF_CANDIDATES) {
|
||||||
|
try {
|
||||||
|
fs.accessSync(candidate, fs.constants.X_OK);
|
||||||
|
return candidate;
|
||||||
|
} catch {
|
||||||
|
// keep trying
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "lsof";
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user