Skip to content

Commit 36c440a

Browse files
authored
fix(cli): sanitize stored strings in directory, cron show, agents, channels, and sessions output (#123797)
* fix(cli): sanitize stored strings in table surfaces * fix(cli): use resolved identity agent id * test(cli): keep cron delivery status typed * test(cli): assert agent JSON non-sanitization without path equality
1 parent 13fee42 commit 36c440a

15 files changed

Lines changed: 318 additions & 42 deletions

‎src/cli/cron-cli/cron-pagination.gateway.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,23 @@ describe("cron CLI with the real Gateway pagination contract", () => {
472472
);
473473
});
474474

475+
it("preserves hostile stored values in cron show JSON", async () => {
476+
const name = "job\u001B]0;cron-json\u0007🦞\r\nname";
477+
const model = "model\u001B[31m\tvariant";
478+
const lastError = "failed\u001B]0;cron-error\u0007\nreason";
479+
const job = createJob(123, {
480+
name,
481+
payload: { kind: "agentTurn", message: "test", model },
482+
state: { lastError },
483+
});
484+
installRealCronGateway([job]);
485+
486+
await runCron(["show", job.id, "--json"]);
487+
488+
const result = mocks.runtime.writeJson.mock.calls.at(-1)?.[0] as CronJob;
489+
expect(result).toMatchObject({ id: job.id, name, payload: { model }, state: { lastError } });
490+
});
491+
475492
it("finds an exact cron job name beyond the first real Gateway page", async () => {
476493
const jobs = Array.from({ length: 201 }, (_, index) => createJob(index));
477494
jobs[200] = createJob(200, { name: "Last page exact job" });

‎src/cli/cron-cli/shared.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,38 @@ describe("printCronList", () => {
245245
expectLogsToInclude(show.logs, "last delivery error: offline");
246246
});
247247

248+
it("sanitizes every stored cron show value at the terminal boundary", () => {
249+
const control = "\u001B]0;cron-show-injection\u0007";
250+
const injected = (value: string) => `${control}${value}\r\nforged-row\tfield`;
251+
const job = createBaseJob({
252+
id: injected("job-id"),
253+
declarationKey: injected("declaration"),
254+
name: injected("name 🦞"),
255+
displayName: injected("display"),
256+
owner: { agentId: injected("owner"), sessionKey: injected("owner-session") },
257+
agentId: injected("agent"),
258+
sessionTarget: injected("session") as CronJob["sessionTarget"],
259+
payload: { kind: "agentTurn", message: "test", model: injected("model") },
260+
state: {
261+
lastError: injected("last-error"),
262+
lastDeliveryStatus: "not-delivered",
263+
lastDeliveryError: injected("delivery-error"),
264+
lastDiagnosticSummary: injected("diagnostic"),
265+
},
266+
});
267+
const { logs, runtime } = createRuntimeLogCapture();
268+
269+
printCronShow(job, runtime, {
270+
deliveryPreview: { label: injected("delivery"), detail: injected("detail") },
271+
});
272+
273+
const output = logs.join("\n");
274+
expect(output).not.toContain("\u001B");
275+
expect(output).not.toContain("\nforged-row");
276+
expect(output).toContain("\\r\\nforged-row\\tfield");
277+
expect(output).toContain("name 🦞");
278+
});
279+
248280
it("tolerates malformed rows in human-readable output", () => {
249281
const { logs, runtime } = createRuntimeLogCapture();
250282
const malformedJob = {

‎src/cli/cron-cli/shared.ts‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -540,28 +540,31 @@ export function printCronShow(
540540
opts?: { deliveryPreview?: CronDeliveryPreview },
541541
) {
542542
const preview = opts?.deliveryPreview ?? { label: "-", detail: "unavailable" };
543-
runtime.log(`id: ${job.id}`);
544-
runtime.log(`declaration: ${job.declarationKey ?? "-"}`);
545-
runtime.log(`name: ${job.name}`);
546-
runtime.log(`display name: ${job.displayName ?? "-"}`);
547-
runtime.log(`owner agent: ${job.owner?.agentId ?? "-"}`);
548-
runtime.log(`owner session: ${job.owner?.sessionKey ?? "-"}`);
543+
const showValue = (value: unknown) => sanitizeTerminalText(stringifyCell(value));
544+
runtime.log(`id: ${showValue(job.id)}`);
545+
runtime.log(`declaration: ${showValue(job.declarationKey)}`);
546+
runtime.log(`name: ${showValue(job.name)}`);
547+
runtime.log(`display name: ${showValue(job.displayName)}`);
548+
runtime.log(`owner agent: ${showValue(job.owner?.agentId)}`);
549+
runtime.log(`owner session: ${showValue(job.owner?.sessionKey)}`);
549550
runtime.log(`enabled: ${job.enabled ? "yes" : "no"}`);
550-
runtime.log(`schedule: ${formatSchedule(job.schedule, job.trigger !== undefined)}`);
551+
runtime.log(`schedule: ${showValue(formatSchedule(job.schedule, job.trigger !== undefined))}`);
551552
runtime.log(
552553
`trigger: ${job.trigger ? `once=${job.trigger.once === true ? "yes" : "no"}; evals=${job.state.triggerEvalCount ?? 0}; last eval=${formatRelative(job.state.lastTriggerEvalAtMs, Date.now())}; last fire=${formatRelative(job.state.lastTriggerFireAtMs, Date.now())}` : "-"}`,
553554
);
554-
runtime.log(`session: ${job.sessionTarget ?? "-"}`);
555-
runtime.log(`agent: ${job.agentId ?? "-"}`);
556-
runtime.log(`model: ${job.payload.kind === "agentTurn" ? (job.payload.model ?? "-") : "-"}`);
557-
runtime.log(`delivery: ${preview.label} (${preview.detail})`);
555+
runtime.log(`session: ${showValue(job.sessionTarget)}`);
556+
runtime.log(`agent: ${showValue(job.agentId)}`);
557+
runtime.log(
558+
`model: ${showValue(job.payload.kind === "agentTurn" ? job.payload.model : undefined)}`,
559+
);
560+
runtime.log(`delivery: ${showValue(preview.label)} (${showValue(preview.detail)})`);
558561
runtime.log(`next: ${formatRelative(job.state.nextRunAtMs, Date.now())}`);
559562
runtime.log(`last: ${formatRelative(job.state.lastRunAtMs, Date.now())}`);
560-
runtime.log(`status: ${formatCronStatusForDisplay(job)}`);
563+
runtime.log(`status: ${showValue(formatCronStatusForDisplay(job))}`);
561564
// lastError is the run/schedule failure message; the diagnostic line below is
562565
// the run-diagnostics summary and can be empty when only lastError is set.
563-
runtime.log(`last error: ${job.state.lastError ?? "-"}`);
564-
runtime.log(`last delivery: ${job.state.lastDeliveryStatus ?? "-"}`);
565-
runtime.log(`last delivery error: ${job.state.lastDeliveryError ?? "-"}`);
566-
runtime.log(`diagnostic: ${job.state.lastDiagnosticSummary ?? "-"}`);
566+
runtime.log(`last error: ${showValue(job.state.lastError)}`);
567+
runtime.log(`last delivery: ${showValue(job.state.lastDeliveryStatus)}`);
568+
runtime.log(`last delivery error: ${showValue(job.state.lastDeliveryError)}`);
569+
runtime.log(`diagnostic: ${showValue(job.state.lastDiagnosticSummary)}`);
567570
}

‎src/cli/directory-cli.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,42 @@ describe("registerDirectoryCli", () => {
244244
);
245245
});
246246

247+
it("sanitizes plugin directory entries only for terminal output", async () => {
248+
const entry = {
249+
id: "user:\u001B]0;directory-id\u0007🦞\nforged-row",
250+
name: "Alice\u001B[31m\r\nadmin\tbadge",
251+
};
252+
const listPeers = vi.fn().mockResolvedValue([entry]);
253+
mocks.resolveInstallableChannelPlugin.mockResolvedValue({
254+
cfg: { channels: { slack: {} } },
255+
channelId: "slack",
256+
plugin: { id: "slack", directory: { listPeers } },
257+
configChanged: false,
258+
});
259+
260+
const textProgram = new Command().name("openclaw");
261+
registerDirectoryCli(textProgram);
262+
await textProgram.parseAsync(["directory", "peers", "list", "--channel", "slack"], {
263+
from: "user",
264+
});
265+
266+
const textOutput = runtimeState.defaultRuntime.log.mock.calls.flat().join("\n");
267+
expect(textOutput).not.toContain("\u001B");
268+
expect(textOutput).not.toContain("\nforged-row");
269+
expect(textOutput).toContain("\\nforged-row");
270+
expect(textOutput).toContain("\\r\\nadmin\\tbadge");
271+
expect(textOutput).toContain("🦞");
272+
273+
runtimeState.defaultRuntime.writeJson.mockClear();
274+
const jsonProgram = new Command().name("openclaw");
275+
registerDirectoryCli(jsonProgram);
276+
await jsonProgram.parseAsync(["directory", "peers", "list", "--channel", "slack", "--json"], {
277+
from: "user",
278+
});
279+
280+
expect(runtimeState.defaultRuntime.writeJson).toHaveBeenCalledWith([entry]);
281+
});
282+
247283
it("reports unsupported directory capability instead of continuing setup for installed plugins", async () => {
248284
mocks.resolveInstallableChannelPlugin.mockResolvedValue({
249285
cfg: { channels: { "openclaw-weixin": {} } },

‎src/cli/directory-cli.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import {
66
} from "@openclaw/normalization-core/string-coerce";
77
import type { Command } from "commander";
88
import { formatDocsLink } from "../../packages/terminal-core/src/links.js";
9-
import { getTerminalTableWidth, renderTable } from "../../packages/terminal-core/src/table.js";
9+
import {
10+
getTerminalTableWidth,
11+
renderTerminalSafeTable,
12+
} from "../../packages/terminal-core/src/table.js";
1013
import { theme } from "../../packages/terminal-core/src/theme.js";
1114
import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
1215
import { resolveInstallableChannelPlugin } from "../commands/channel-setup/channel-plugin-resolution.js";
@@ -49,7 +52,7 @@ function printDirectoryList(params: {
4952
const tableWidth = getTerminalTableWidth();
5053
defaultRuntime.log(`${theme.heading(params.title)} ${theme.muted(`(${params.entries.length})`)}`);
5154
defaultRuntime.log(
52-
renderTable({
55+
renderTerminalSafeTable({
5356
width: tableWidth,
5457
columns: [
5558
{ key: "ID", header: "ID", minWidth: 16, flex: true },
@@ -221,7 +224,7 @@ export function registerDirectoryCli(program: Command) {
221224
const tableWidth = getTerminalTableWidth();
222225
defaultRuntime.log(theme.heading("Self"));
223226
defaultRuntime.log(
224-
renderTable({
227+
renderTerminalSafeTable({
225228
width: tableWidth,
226229
columns: [
227230
{ key: "ID", header: "ID", minWidth: 16, flex: true },

‎src/commands/agents.commands.identity.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import path from "node:path";
33
import { expectDefined } from "@openclaw/normalization-core";
44
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
5+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
56
import {
67
listAgentIds,
78
resolveAgentWorkspaceDir,
@@ -225,20 +226,20 @@ export async function agentsSetIdentityCommand(
225226
}
226227

227228
logConfigUpdated(runtime);
228-
runtime.log(`Agent: ${agentId}`);
229+
runtime.log(`Agent: ${sanitizeTerminalText(resolvedAgentId)}`);
229230
if (nextIdentity.name) {
230-
runtime.log(`Name: ${nextIdentity.name}`);
231+
runtime.log(`Name: ${sanitizeTerminalText(nextIdentity.name)}`);
231232
}
232233
if (nextIdentity.theme) {
233-
runtime.log(`Theme: ${nextIdentity.theme}`);
234+
runtime.log(`Theme: ${sanitizeTerminalText(nextIdentity.theme)}`);
234235
}
235236
if (nextIdentity.emoji) {
236-
runtime.log(`Emoji: ${nextIdentity.emoji}`);
237+
runtime.log(`Emoji: ${sanitizeTerminalText(nextIdentity.emoji)}`);
237238
}
238239
if (nextIdentity.avatar) {
239-
runtime.log(`Avatar: ${nextIdentity.avatar}`);
240+
runtime.log(`Avatar: ${sanitizeTerminalText(nextIdentity.avatar)}`);
240241
}
241242
if (workspaceDir) {
242-
runtime.log(`Workspace: ${shortenHomePath(workspaceDir)}`);
243+
runtime.log(`Workspace: ${sanitizeTerminalText(shortenHomePath(workspaceDir))}`);
243244
}
244245
}

‎src/commands/agents.commands.list.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,48 @@ describe("agentsListCommand", () => {
144144
]);
145145
});
146146

147+
it("sanitizes configured agent text without changing JSON summaries", async () => {
148+
const control = "\u001B]0;agents-list-injection\u0007";
149+
const identityName = `${control}Operator 🦞\r\nforged-row`;
150+
const workspace = `/tmp/workspace-${control}\tpath`;
151+
const model = `${control}provider/model\nvariant`;
152+
const cfg = {
153+
agents: {
154+
entries: {
155+
main: {
156+
name: `${control}Main\nAlias`,
157+
workspace,
158+
agentDir: `/tmp/agent-${control}\npath`,
159+
model,
160+
identity: { name: identityName },
161+
},
162+
},
163+
},
164+
bindings: [{ agentId: "main", match: { channel: "telegram" } }],
165+
} satisfies OpenClawConfig;
166+
requireValidConfigMock.mockResolvedValue(cfg);
167+
summarizeBindingsMock.mockReturnValue([`${control}Telegram\nroute`]);
168+
listProvidersForAgentMock.mockReturnValue([`${control}Telegram\tconfigured`]);
169+
170+
const textRuntime = createRuntime();
171+
await agentsListCommand({ bindings: true }, textRuntime);
172+
173+
const textOutput = vi.mocked(textRuntime.log).mock.calls.flat().join("\n");
174+
expect(textOutput).not.toContain("\u001B");
175+
expect(textOutput).not.toContain("\nforged-row");
176+
expect(textOutput).toContain("Operator 🦞\\r\\nforged-row");
177+
expect(textOutput).toContain("provider/model\\nvariant");
178+
expect(textOutput).toContain("Telegram\\nroute");
179+
180+
const jsonRuntime = createRuntime();
181+
await agentsListCommand({ json: true }, jsonRuntime);
182+
183+
// Workspace paths are platform-normalized before JSON, so assert the
184+
// non-sanitization invariant on it rather than byte equality.
185+
expect(jsonRuntime.json[0]).toEqual([expect.objectContaining({ identityName, model })]);
186+
expect((jsonRuntime.json[0] as Array<{ workspace: string }>)[0]?.workspace).toContain(control);
187+
});
188+
147189
it.skipIf(process.platform !== "win32")(
148190
"shortens real Windows home casing aliases in human output",
149191
async () => {

‎src/commands/agents.commands.list.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Implements `openclaw agents list` text and JSON summaries.
2+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
23
import { formatCliCommand } from "../cli/command-format.js";
34
import { listRouteBindings } from "../config/bindings.js";
45
import type { AgentRouteBinding } from "../config/types.js";
@@ -23,18 +24,19 @@ type AgentsListOptions = {
2324
};
2425

2526
function formatSummary(summary: AgentSummary) {
27+
const safe = sanitizeTerminalText;
2628
const defaultTag = summary.isDefault ? " (default)" : "";
2729
const header =
2830
summary.name && summary.name !== summary.id
29-
? `${summary.id}${defaultTag} (${summary.name})`
30-
: `${summary.id}${defaultTag}`;
31+
? `${safe(summary.id)}${defaultTag} (${safe(summary.name)})`
32+
: `${safe(summary.id)}${defaultTag}`;
3133

3234
const identityParts = [];
3335
if (summary.identityEmoji) {
34-
identityParts.push(summary.identityEmoji);
36+
identityParts.push(safe(summary.identityEmoji));
3537
}
3638
if (summary.identityName) {
37-
identityParts.push(summary.identityName);
39+
identityParts.push(safe(summary.identityName));
3840
}
3941
const identityLine = identityParts.length > 0 ? identityParts.join(" ") : null;
4042
const identitySource =
@@ -48,27 +50,27 @@ function formatSummary(summary: AgentSummary) {
4850
if (identityLine) {
4951
lines.push(` Identity: ${identityLine}${identitySource ? ` (${identitySource})` : ""}`);
5052
}
51-
lines.push(` Workspace: ${shortenHomePath(summary.workspace)}`);
52-
lines.push(` Agent dir: ${shortenHomePath(summary.agentDir)}`);
53+
lines.push(` Workspace: ${safe(shortenHomePath(summary.workspace))}`);
54+
lines.push(` Agent dir: ${safe(shortenHomePath(summary.agentDir))}`);
5355
if (summary.model) {
54-
lines.push(` Model: ${summary.model}`);
56+
lines.push(` Model: ${safe(summary.model)}`);
5557
}
5658
lines.push(` Routing rules: ${summary.bindings}`);
5759

5860
if (summary.routes?.length) {
59-
lines.push(` Routing: ${summary.routes.join(", ")}`);
61+
lines.push(` Routing: ${summary.routes.map(safe).join(", ")}`);
6062
}
6163
if (summary.providers?.length) {
6264
lines.push(" Providers:");
6365
for (const provider of summary.providers) {
64-
lines.push(` - ${provider}`);
66+
lines.push(` - ${safe(provider)}`);
6567
}
6668
}
6769

6870
if (summary.bindingDetails?.length) {
6971
lines.push(" Routing rules:");
7072
for (const binding of summary.bindingDetails) {
71-
lines.push(` - ${binding}`);
73+
lines.push(` - ${safe(binding)}`);
7274
}
7375
}
7476
return lines.join("\n");

‎src/commands/agents.identity.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import fs from "node:fs/promises";
33
import path from "node:path";
44
import { beforeEach, describe, expect, it, vi } from "vitest";
55
import { makeTempWorkspace } from "../test-helpers/workspace.js";
6-
import { baseConfigSnapshot, createTestRuntime } from "./test-runtime-config-helpers.js";
6+
import {
7+
baseConfigSnapshot,
8+
createCapturingTestRuntime,
9+
createTestRuntime,
10+
} from "./test-runtime-config-helpers.js";
711

812
const TEST_MAX_IDENTITY_FILE_BYTES = 4 * 1024 * 1024;
913

@@ -180,6 +184,31 @@ describe("agents set-identity command", () => {
180184
});
181185
});
182186

187+
it("sanitizes identity echoes while preserving stored and JSON values", async () => {
188+
const name = "Operator\u001B]0;identity-injection\u0007🦞\r\nforged-row\tbadge";
189+
configMocks.readConfigFileSnapshot.mockResolvedValue({
190+
...baseConfigSnapshot,
191+
config: { agents: { entries: { main: {} } } },
192+
});
193+
194+
await agentsSetIdentityCommand({ agent: "main", name }, runtime);
195+
196+
const textOutput = runtime.log.mock.calls.flat().join("\n");
197+
expect(textOutput).not.toContain("\u001B");
198+
expect(textOutput).not.toContain("\nforged-row");
199+
expect(textOutput).toContain("Operator🦞\\r\\nforged-row\\tbadge");
200+
expect(getWrittenMainIdentity()).toEqual({ name });
201+
202+
const jsonRuntime = createCapturingTestRuntime();
203+
await agentsSetIdentityCommand({ agent: "main", name, json: true }, jsonRuntime.runtime);
204+
expect(JSON.parse(jsonRuntime.logs.at(-1) ?? "{}")).toStrictEqual({
205+
agentId: "main",
206+
identity: { name },
207+
workspace: null,
208+
identityFile: null,
209+
});
210+
});
211+
183212
it("reads identity from an explicit IDENTITY.md path", async () => {
184213
const { workspace } = await createIdentityWorkspace();
185214
const identityPath = await writeIdentityFile(workspace, [

0 commit comments

Comments
 (0)