Skip to content

Commit db3ac52

Browse files
committed
refactor(daemon): consolidate system ownership formatting
1 parent c943f1c commit db3ac52

5 files changed

Lines changed: 37 additions & 49 deletions

File tree

‎src/daemon/inspect.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { parseLaunchdPlistLabel } from "./launchd-plist.js";
1414
import { readLaunchDaemonPlistLabel } from "./launchd-system.js";
1515
import { resolveDaemonHomeDir } from "./paths.js";
1616
import { execSchtasks } from "./schtasks-exec.js";
17+
import { quotePosixShellArgument } from "./system-ownership-format.js";
1718
import { parseSystemdExecStart } from "./systemd-unit.js";
1819

1920
export type ExtraGatewayService = {
@@ -44,10 +45,6 @@ const SYSTEMD_REFERENCE_ONLY_KEYS = new Set([
4445
"wants",
4546
]);
4647

47-
function quotePosixCleanupArgument(value: string): string {
48-
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
49-
}
50-
5148
export function renderGatewayServiceCleanupHints(
5249
services: readonly ExtraGatewayService[] = [],
5350
): string[] {
@@ -67,24 +64,24 @@ export function renderGatewayServiceCleanupHints(
6764
: "gui/$UID";
6865
const launchctlCommand = domain === "system" ? "sudo launchctl" : "launchctl";
6966
hints.push(
70-
`${launchctlCommand} bootout ${domain}/${quotePosixCleanupArgument(service.label)}`,
67+
`${launchctlCommand} bootout ${domain}/${quotePosixShellArgument(service.label)}`,
7168
);
7269
if (plistPath) {
7370
const removeCommand = service.scope === "system" ? "sudo rm" : "rm";
74-
hints.push(`${removeCommand} ${quotePosixCleanupArgument(plistPath)}`);
71+
hints.push(`${removeCommand} ${quotePosixShellArgument(plistPath)}`);
7572
}
7673
break;
7774
}
7875
case "linux": {
7976
const systemctlCommand = service.scope === "user" ? "systemctl --user" : "sudo systemctl";
8077
hints.push(
81-
`${systemctlCommand} disable --now -- ${quotePosixCleanupArgument(service.label)}`,
78+
`${systemctlCommand} disable --now -- ${quotePosixShellArgument(service.label)}`,
8279
);
8380
if (service.detail.startsWith("unit:")) {
8481
const unitPath = service.detail.slice("unit:".length).trim();
8582
if (unitPath) {
8683
const removeCommand = service.scope === "system" ? "sudo rm" : "rm";
87-
hints.push(`${removeCommand} ${quotePosixCleanupArgument(unitPath)}`);
84+
hints.push(`${removeCommand} ${quotePosixShellArgument(unitPath)}`);
8885
}
8986
}
9087
break;

‎src/daemon/launchd-system.ts‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
/** Detects system-domain launchd ownership before mutating a user LaunchAgent. */
22
import fs from "node:fs/promises";
33
import path from "node:path";
4-
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
5-
import { sanitizeForLog } from "../../packages/terminal-core/src/ansi.js";
64
import { isMissingPathError } from "../infra/errors.js";
75
import { execFileUtf8 } from "./exec-file.js";
86
import {
@@ -11,6 +9,10 @@ import {
119
isLaunchctlNotLoaded,
1210
type LaunchctlResult,
1311
} from "./launchd-exec.js";
12+
import {
13+
formatSystemOwnershipFailureDetail,
14+
quotePosixShellArgument,
15+
} from "./system-ownership-format.js";
1416

1517
const SYSTEM_LAUNCH_DAEMON_DIR = "/Library/LaunchDaemons";
1618
const PLUTIL_PATH = "/usr/bin/plutil";
@@ -28,15 +30,6 @@ type SystemLaunchDaemonOwnership =
2830

2931
type SystemLaunchDaemonConflict = Exclude<SystemLaunchDaemonOwnership, { status: "absent" }>;
3032

31-
function formatUnknownError(error: unknown): string {
32-
const raw = error instanceof Error ? error.message : String(error);
33-
return truncateUtf16Safe(sanitizeForLog(raw), 500);
34-
}
35-
36-
function quotePosixArgument(value: string): string {
37-
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
38-
}
39-
4033
/**
4134
* Renders the package-independent ownership probe used by detached restart helpers.
4235
* The caller must refuse activation when `openclaw_system_launchd_conflict` is non-empty.
@@ -45,9 +38,9 @@ export function renderSystemLaunchDaemonOwnershipShellProbe(label: string): stri
4538
const serviceTarget = `system/${label}`;
4639
return `openclaw_system_launchd_conflict=""
4740
openclaw_system_launchd_detail=""
48-
openclaw_system_launchd_target=${quotePosixArgument(serviceTarget)}
49-
openclaw_system_launchd_dir=${quotePosixArgument(SYSTEM_LAUNCH_DAEMON_DIR)}
50-
openclaw_system_launchd_label=${quotePosixArgument(label)}
41+
openclaw_system_launchd_target=${quotePosixShellArgument(serviceTarget)}
42+
openclaw_system_launchd_dir=${quotePosixShellArgument(SYSTEM_LAUNCH_DAEMON_DIR)}
43+
openclaw_system_launchd_label=${quotePosixShellArgument(label)}
5144
openclaw_query_system_launchd() {
5245
openclaw_system_launchd_probe=$(launchctl print "$openclaw_system_launchd_target" 2>&1)
5346
openclaw_system_launchd_probe_status=$?
@@ -138,7 +131,7 @@ export async function readLaunchDaemonPlistLabel(
138131
? { status: "ok", label }
139132
: { status: "unlabeled" };
140133
} catch (error) {
141-
return { status: "unverifiable", detail: formatUnknownError(error) };
134+
return { status: "unverifiable", detail: formatSystemOwnershipFailureDetail(error) };
142135
}
143136
}
144137
try {
@@ -151,7 +144,7 @@ export async function readLaunchDaemonPlistLabel(
151144
if (code === "EACCES" || code === "EPERM") {
152145
return { status: "unreadable" };
153146
}
154-
return { status: "unverifiable", detail: formatUnknownError(error) };
147+
return { status: "unverifiable", detail: formatSystemOwnershipFailureDetail(error) };
155148
}
156149
return {
157150
status: "unverifiable",
@@ -174,7 +167,7 @@ async function findInstalledSystemLaunchDaemon(
174167
if (isMissingPathError(error)) {
175168
return { status: "absent" };
176169
}
177-
return { status: "unverifiable", detail: formatUnknownError(error) };
170+
return { status: "unverifiable", detail: formatSystemOwnershipFailureDetail(error) };
178171
}
179172

180173
for (const entry of entries.filter((candidate) => candidate.endsWith(".plist")).toSorted()) {
@@ -275,7 +268,7 @@ function formatSystemLaunchDaemonOwnershipError(ownership: SystemLaunchDaemonCon
275268
ownership.status === "loaded"
276269
? `Keep it as the sole gateway manager, or unload it with \`sudo launchctl bootout ${ownership.serviceTarget}\` and remove its plist before retrying.`
277270
: ownership.status === "installed"
278-
? `Keep it as the sole gateway manager, or remove or relocate ${quotePosixArgument(ownership.plistPath)} before retrying.`
271+
? `Keep it as the sole gateway manager, or remove or relocate ${quotePosixShellArgument(ownership.plistPath)} before retrying.`
279272
: "Fix the reported launchctl or filesystem access error, then retry.";
280273
return [
281274
formatSystemLaunchDaemonOwnershipSummary(ownership),

‎src/daemon/service-layout.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "node:path";
44
import { pathExists } from "../infra/fs-safe.js";
55
import { readPackageName, readPackageVersion } from "../infra/package-json.js";
66
import type { GatewayServiceCommandConfig } from "./service-types.js";
7+
import { quotePosixShellArgument } from "./system-ownership-format.js";
78

89
/** Summary of the installed gateway service command and package layout. */
910
export type GatewayServiceLayoutSummary = {
@@ -19,15 +20,8 @@ export type GatewayServiceLayoutSummary = {
1920
entrypointSourceCheckout?: boolean;
2021
};
2122

22-
function shellQuoteArg(value: string): string {
23-
if (/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)) {
24-
return value;
25-
}
26-
return `'${value.replaceAll("'", "'\\''")}'`;
27-
}
28-
2923
function formatExecStart(programArguments: readonly string[]): string {
30-
return programArguments.map(shellQuoteArg).join(" ");
24+
return programArguments.map(quotePosixShellArgument).join(" ");
3125
}
3226

3327
function resolveSystemdScopeFromServicePath(
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
2+
import { sanitizeForLog } from "../../packages/terminal-core/src/ansi.js";
3+
4+
export function quotePosixShellArgument(value: string): string {
5+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
6+
}
7+
8+
export function formatSystemOwnershipFailureDetail(error: unknown): string {
9+
const raw = error instanceof Error ? error.message : String(error);
10+
return truncateUtf16Safe(sanitizeForLog(raw), 500);
11+
}

‎src/daemon/systemd-system.ts‎

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
/** Detects system-scope systemd ownership before mutating a user gateway unit. */
22
import fs from "node:fs/promises";
33
import path from "node:path";
4-
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
5-
import { sanitizeForLog } from "../../packages/terminal-core/src/ansi.js";
64
import { isMissingPathError } from "../infra/errors.js";
5+
import {
6+
formatSystemOwnershipFailureDetail,
7+
quotePosixShellArgument,
8+
} from "./system-ownership-format.js";
79
import { execSystemctl, readSystemctlDetail } from "./systemd-exec.js";
810

911
type SystemSystemdOwnership =
@@ -19,15 +21,6 @@ type SystemSystemdOwnership =
1921

2022
type SystemSystemdConflict = Exclude<SystemSystemdOwnership, { status: "absent" }>;
2123

22-
function formatUnknownError(error: unknown): string {
23-
const raw = error instanceof Error ? error.message : String(error);
24-
return truncateUtf16Safe(sanitizeForLog(raw), 500);
25-
}
26-
27-
function quotePosixArgument(value: string): string {
28-
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
29-
}
30-
3124
function unverifiableSystemOwnership(
3225
unitName: string,
3326
detail: string,
@@ -88,7 +81,7 @@ async function findInstalledSystemUnit(
8881
if (isMissingPathError(error)) {
8982
continue;
9083
}
91-
const detail = `${unitPath}: ${formatUnknownError(error)}`;
84+
const detail = `${unitPath}: ${formatSystemOwnershipFailureDetail(error)}`;
9285
return unverifiableSystemOwnership(unitName, detail, "filesystem");
9386
}
9487
}
@@ -132,7 +125,7 @@ function isRunningAsRoot(): boolean {
132125

133126
function formatSystemSystemdOwnershipError(ownership: SystemSystemdConflict): string {
134127
const privilegePrefix = isRunningAsRoot() ? "" : "sudo ";
135-
const unitName = quotePosixArgument(ownership.unitName);
128+
const unitName = quotePosixShellArgument(ownership.unitName);
136129
const summary =
137130
ownership.status === "loaded"
138131
? `System systemd unit ${ownership.unitName} already owns this gateway unit name.`
@@ -147,9 +140,9 @@ function formatSystemSystemdOwnershipError(ownership: SystemSystemdConflict): st
147140
ownership.status === "loaded"
148141
? `Keep it as the sole gateway manager, or inspect it with \`${privilegePrefix}systemctl cat ${unitName}\`, then disable it and uninstall or reconfigure the package, generator, or administrator unit that owns it before retrying.`
149142
: installedInAdministratorPath
150-
? `Keep it as the sole gateway manager, or run \`${privilegePrefix}systemctl disable --now ${unitName}\`, \`${privilegePrefix}rm ${quotePosixArgument(ownership.unitPath)}\`, and \`${privilegePrefix}systemctl daemon-reload\` before retrying.`
143+
? `Keep it as the sole gateway manager, or run \`${privilegePrefix}systemctl disable --now ${unitName}\`, \`${privilegePrefix}rm ${quotePosixShellArgument(ownership.unitPath)}\`, and \`${privilegePrefix}systemctl daemon-reload\` before retrying.`
151144
: ownership.status === "installed"
152-
? `Keep it as the sole gateway manager, or inspect it with \`${privilegePrefix}systemctl cat ${unitName}\`, then uninstall or reconfigure the package, generator, or runtime owner of ${quotePosixArgument(ownership.unitPath)} before retrying.`
145+
? `Keep it as the sole gateway manager, or inspect it with \`${privilegePrefix}systemctl cat ${unitName}\`, then uninstall or reconfigure the package, generator, or runtime owner of ${quotePosixShellArgument(ownership.unitPath)} before retrying.`
153146
: "Fix the reported systemctl or filesystem access error, then retry.";
154147
return [
155148
summary,

0 commit comments

Comments
 (0)