Skip to content

fix(agents): escape terminal controls in routing binding reports - #176763

Closed
Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:alix/fix-binding-report-controls-20261019
Closed

Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:alix/fix-binding-report-controls-20261019

Conversation

@Alix-007

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: routing binding reports can clear terminal output or insert extra report lines when configured match fields contain control characters.

User Impact

User impact: operators can read routing reports safely without changing routing keys, stored configuration, JSON output, or ordinary Unicode text.

Why This Change Was Made

Apply the existing terminal sanitizer at the binding command's human-readable output boundaries, including mutation summaries and conflicts. Keep the shared binding description formatter raw for JSON consumers. No config/default, protocol/schema, permission/security-policy, dependency, compatibility, or migration changes.

Evidence

Normal-built CLI, Node 26.1.0 on Linux, isolated HOME/config/state, no external services or production credentials:

  • Base: e63269c28a22a6eec7c0758d54dc6dbe674e2886 (RED run 2026-10-19T01:09:29.616Z).
  • Product head: 40e10c66f3701718c422c8e2ed929065e8230cc1 (GREEN run 2026-10-19T01:30:02.623Z).
  • Production entry: node <checkout>/openclaw.mjs agents bindings [--agent main|--json]; canonical owner: src/commands/agents.commands.bind.ts.
  • Recorder/readback: captured child stdout/stderr/exit plus config-file byte/hash readback. Every child process exited 0 on both versions.
Actual CLI BASE controls / injected lines HEAD controls / injected lines
agents bindings 10 / 5 0 / 0
agents bindings --agent main 10 / 5 0 / 0

The schema-accepted fixture places café\x1b[2J\x07\nFORGED in account, peer, guild, team and role strings. HEAD prints café\nFORGED (a visible backslash+n) in each field, with no injected line. This is a display-hardening claim, not a claim that control-bearing IDs are valid remote service IDs.

Controls: 0 unsafe controls and 0 injected lines in two text modes; five visible escaped newlines per mode; raw JSON match fields/description preserved; exact ordinary Unicode report unchanged; config bytes unchanged.

Focused regressions: OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/agents.bind.commands.test.ts --maxWorkers=1 — 14/14 pass, exit 0; 3.47 s selected shard, 7.68 s including wrapper. Core and canonical commands-test type checks, explicit type-aware lint (including the modified test), format, line-cap ratchet, and independent adversarial review passed. The host's older glibc cannot load tsrs, so type checks used the documented OPENCLAW_TYPECHECKER=tsgo fallback.

Generated proof receipt
  • Scenario: routing binding reports safely render configured match fields while JSON retains original values; ordinary Unicode, JSON values and stored config are preserved
  • Entry: node /openclaw.mjs agents bindings [--agent main|--json]; disputed owner ran unmocked: src/commands/agents.commands.bind.ts
  • Same command on base e63269c and head 40e10c6: node proof-bindings.mjs <checkout> <red|green>
    • Before (base): RED both text list variants emit 10 unsafe controls and five injected lines each
    • After (head): GREEN both text variants emit 0 unsafe controls and 0 injected lines; all four real CLI processes exit 0
  • Readback (subprocess,config-file): captured child stdout/stderr/exit plus config-file byte/hash readback
  • Proof harness: complete collector and shared fixture source published in PR body; portable helper import path is the only local-layout adjustment
  • Control: 0 unsafe controls and 0 injected lines in two text modes; five visible escaped newlines per mode; raw JSON match fields/description preserved; exact ordinary Unicode report unchanged; config bytes unchanged
  • Other callers checked: list, bind/unbind description sections and conflict text share this owner; shared raw formatter and JSON bypass preserved; agents list already safe; interactive add wizard outside scope
  • Tests: OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/agents.bind.commands.test.ts --maxWorkers=1: 14 pass, exit 0; core and canonical commands-test types, explicit type-aware lint, format, ratchet and independent P0-P3 adversarial review pass (measured cost: 3.47 s selected shard; 7.68 s including wrapper; cold preparation reported separately in local task log)
  • Not tested: real channel delivery, rich PTY colors, Windows/macOS terminals, interactive add wizard, full CI suite locally; mutation text/JSON covered by focused unit tests, real CLI proof covers read-only list variants
Reproduce the real CLI proof

Install the pinned dependencies in clean checkouts at the SHAs above, then build normally with pnpm build qaRuntime (used on BASE) or pnpm build cliStartup (used on HEAD; core CLI only). Save the two files below together outside the checkout. The same collector and scenario run on both versions:

node proof-bindings.mjs <base-checkout> red
node proof-bindings.mjs <head-checkout> green

Invocation form: node proof-bindings.mjs <checkout> <red|green>. Only the helper import path is flattened for copying. The collector checks clean Git HEAD against the build stamp and records stdout, stderr, exit status, and readback in its printed temporary receipt directory.

proof-bindings.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import {fixture} from './proof-cli-common.mjs';

const f = fixture('bindings-terminal', process.argv[2], process.argv[3]);
const value = 'café\x1b[2J\x07\nFORGED';
const match = {channel:'telegram', accountId:value, peer:{kind:'direct',id:value}, guildId:value, teamId:value, roles:[value]};
f.config.bindings = [{type:'route',agentId:'main',match}];
f.writeConfig();
const before = fs.readFileSync(f.configPath);
for (const args of [['agents','bindings'],['agents','bindings','--agent','main']]) {
  const row = f.run(args.join('-'), args);
  assert.equal(row.code,0,row.stderr);
  const controls = (row.stdout.match(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g) ?? []).length;
  const forged = (row.stdout.match(/\nFORGED/g) ?? []).length;
  if (f.phase === 'red') {assert.ok(controls>0);assert.equal(forged,5);}
  else {assert.equal(controls,0);assert.equal(forged,0);assert.equal((row.stdout.match(/café\\nFORGED/g) ?? []).length,5);}
  f.receipt.observations.push({args,controls,forged,stdout:row.stdout});
}
const json = f.run('json-raw-value-control',['agents','bindings','--json']);
assert.equal(json.code,0,json.stderr);
const payload = JSON.parse(json.stdout);
assert.deepEqual(payload[0].match,match);
assert.ok(payload[0].description.includes(value));
assert.ok(fs.readFileSync(f.configPath).equals(before));

// A clean report remains an exact, readable compatibility control.
f.config.bindings = [{type:'route',agentId:'main',match:{channel:'telegram',peer:{kind:'direct',id:'café-123'}}}];
f.writeConfig();
const normal = f.run('legal-unicode-control',['agents','bindings']);
assert.equal(normal.code,0,normal.stderr);
assert.equal(normal.stdout,'Routing bindings:\n- main <- telegram peer=direct:café-123\n');
f.receipt.observations.push({jsonRawValuesPreserved:true,readOnlyConfigHash:f.hash(before),configBytesUnchanged:true,legalUnicodeControl:true});
f.finish();

proof-cli-common.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {execFileSync, spawnSync} from 'node:child_process';

export function fixture(name, checkoutArg, phase) {
  assert.ok(['red', 'green'].includes(phase));
  const checkout = path.resolve(checkoutArg);
  const root = fs.mkdtempSync(path.join(os.tmpdir(), `alix-${name}-`));
  for (const leaf of ['home', 'state', 'workspace', 'tmp']) fs.mkdirSync(path.join(root, leaf));
  const hash = bytes => createHash('sha256').update(bytes).digest('hex');
  // Read-only containers receive a host Git attestation before the bind mount.
  const head = process.env.PROOF_CHECKED_HEAD ?? execFileSync('git', ['rev-parse', 'HEAD'], {cwd: checkout, encoding: 'utf8'}).trim();
  const status = process.env.PROOF_CHECKED_STATUS ?? execFileSync('git', ['status', '--porcelain'], {cwd: checkout, encoding: 'utf8'}).trim();
  assert.match(head, /^[a-f0-9]{40}$/);
  const stamp = JSON.parse(fs.readFileSync(path.join(checkout, 'dist/.buildstamp')));
  assert.equal(status, ''); assert.equal(stamp.head, head); assert.equal(stamp.inputsClean, true);
  const configPath = path.join(root, 'openclaw.json');
  const config = {agents: {ownership: 'explicit', defaults: {systemAgent: {agentId: 'main'}}, entries: {main: {workspace: path.join(root, 'workspace')}}}, tools: {profile: 'minimal'}, plugins: {allow: [], slots: {memory: 'none'}}, logging: {level: 'warn', consoleLevel: 'warn', file: path.join(root, 'runtime.log')}};
  const receipt = {name, phase, head, time: new Date().toISOString(), root, runs: [], observations: []};
  const save = () => fs.writeFileSync(path.join(root, 'receipt.json'), JSON.stringify(receipt, null, 2));
  const writeConfig = () => fs.writeFileSync(configPath, JSON.stringify(config), {mode: 0o600});
  writeConfig();
  const env = {PATH: `${path.dirname(process.execPath)}:/usr/bin:/bin`, HOME: path.join(root, 'home'), TMPDIR: path.join(root, 'tmp'), LANG: 'C.UTF-8', TZ: 'UTC', CI: '1', OPENCLAW_CONFIG_PATH: configPath, OPENCLAW_STATE_DIR: path.join(root, 'state'), OPENCLAW_NO_RESPAWN: '1', OPENCLAW_DISABLE_BONJOUR: '1'};
  function run(label, args) {
    const result = spawnSync(process.execPath, [path.join(checkout, 'openclaw.mjs'), ...args], {cwd: path.join(root, 'workspace'), env, encoding: 'utf8', timeout: 90000, maxBuffer: 4 * 1024 * 1024});
    const row = {label, args, code: result.status, stdout: result.stdout, stderr: result.stderr};
    receipt.runs.push(row); save();
    console.log(JSON.stringify({label, code: row.code}));
    assert.equal(result.error, undefined, 'Timeout/spawn errors are not product RED');
    assert.equal(result.signal, null);
    return row;
  }
  function finish() {receipt.result = 'PASS'; save(); console.log(JSON.stringify({result: 'PASS', receipt: path.join(root, 'receipt.json')}));}
  return {root, config, configPath, writeConfig, receipt, run, finish, hash, phase};
}
Scope and limitations

Two files; production/test LOC (added, removed):

49	0	src/commands/agents.bind.commands.test.ts
5	3	src/commands/agents.commands.bind.ts

Existing-solutions preflight: reused the canonical terminal-core sanitizer; no new abstraction. Sibling coverage: list, bind/unbind description sections and conflict text share this owner; shared raw formatter and JSON bypass preserved; agents list already safe; interactive add wizard outside scope.

Not tested: real channel delivery, rich PTY colors, Windows/macOS terminals, interactive add wizard, full CI suite locally; mutation text/JSON covered by focused unit tests, real CLI proof covers read-only list variants. Fixtures remain in their printed temporary directories for inspection; remove only those generated directories after inspecting them. No production data, existing sessions, channels or service configuration were loaded or changed.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@Alix-007
Alix-007 marked this pull request as ready for review October 19, 2026 01:35
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: S labels Oct 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sanitizes human-readable routing-binding reports while preserving raw JSON values and stored configuration.

Example: A stored Telegram account ID contains café followed by ESC[2J, BEL, and a newline before FORGED.

  • Before: Listing bindings emits terminal controls and places FORGED on an extra report line.
  • After: The report displays café\nFORGED without terminal controls or an injected line, while JSON retains the original value.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, useful boundary repair with supplied shipped-CLI before/after evidence, distinct regression tests, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied built-CLI Linux results exercise the changed binding-list owner on pinned base and head in isolated state, showing controls and injected lines eliminated in both listing modes while Unicode, raw JSON, and config bytes remain intact; mutation rendering has supporting command tests.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Configured binding fields can clear terminal output or forge extra lines when operators inspect routing reports.
Reason: The patch closes a concrete rendering gap and follows the established terminal-only sanitation contract without new settings or behavior restrictions.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current terminal-rendering defect with a focused patch, relevant regression coverage, and supplied CLI evidence; no actionable introduced defect was found.

Priority: P2
Reviewed head: 40e10c66f3701718c422c8e2ed929065e8230cc1

Before merge

None.

Findings

None.

Agent review details

How this fits together

The agents CLI reads configured routing bindings, formats their descriptions, and sends them either to human-readable terminal output or machine-readable JSON.

flowchart LR
  A[Stored routing bindings] --> B[Agents binding commands]
  B --> C[Raw binding descriptions]
  C --> D[Terminal sanitizer]
  D --> E[Human report]
  C --> F[JSON output]
Loading

Technical review

Best possible solution:

Apply the existing sanitizer only at the binding commands’ terminal-output boundaries and preserve raw routing and JSON values.

Do we have a high-confidence way to reproduce the issue?

Current-main schema and output code establish the path from control-bearing stored match fields to raw terminal output, supported by the contributor’s pinned base/head CLI results; this review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete repair for the stated command boundary: it reuses the canonical sanitizer without changing the shared raw formatter or introducing another rendering owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against ff26768c39d6.

Provenance checked

  • Binding report projections keeps the original intent (refactor(commands): deslop commands sixth pass #161202: The prior cleanup reused shared descriptions and result projections to remove formatter plumbing while preserving existing command contracts.)
  • Raw JSON descriptions keeps the original intent (4ee41cc: The existing command separates machine-readable JSON output from human logging; this PR retains that separation and leaves the shared descriptions raw.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main defect: Current main still interpolates raw binding descriptions into listing, mutation-summary, and conflict output; the production module is unchanged between the pinned merge base and fetched main. (src/commands/agents.commands.bind.ts:105, ff26768c39d6)
  • Minimal boundary repair: The introduced production hunks apply the existing sanitizer at three text-output boundaries, leaving describeBinding, JSON branches, routing decisions, and config writes unchanged. (src/commands/agents.commands.bind.ts:107, 40e10c66f370)
  • Existing sanitizer contract: sanitizeTerminalText strips ANSI sequences and removes control characters while rendering carriage returns, newlines, and tabs as visible escapes. (packages/terminal-core/src/safe-text.ts:11, 40e10c66f370)
  • Reachable input and regression coverage: The binding schema accepts string match fields; added command tests exercise unsafe stored descriptions in listing and removal output and independently require unchanged JSON values. (src/commands/agents.bind.commands.test.ts:93, 40e10c66f370)
  • Supplied shipped-CLI evidence: The PR body records built-CLI base/head results in isolated Linux state: both listing modes change from ten unsafe controls and five injected lines to zero, with Unicode, raw JSON, and config-byte controls preserved; the complete collector is supplied. (40e10c66f370)
  • Exact-head CI: Live REST reads show a successful openclaw/ci-gate check and successful dependency, security-sensitive-review, and CI commit statuses for the reviewed head; an older PR-context job was cancelled rather than reporting a code failure. (40e10c66f370)

PR surface

Source +2, Tests +49. Total +51 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 3 +2
Tests 1 49 0 +49
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 54 3 +51

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Stored control characters can manipulate an operator’s routing report; the focused display repair has limited scope and preserves routing behavior.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 18, 2026, 9:53 PM ET / October 19, 2026, 01:53 UTC.

@roboclaw-bot roboclaw-bot added the clawtributor-review Clawtributor pull request awaiting prioritized maintainer review label Oct 22, 2026
obviyus added a commit that referenced this pull request Oct 27, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs #184685, #184666, #184324, #184303, #176763, #176773 and #172873 by @Alix-007 and #184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: #185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

@shakkernerd: #185927 (2d2b465) landed a root-cause fix that routes the covered CLI report values through one terminalText owner, and it covers this PR's output sites. @Alix-007's commit from this PR is kept there with co-author credit. Leaving the close to you since it's assigned to you.

Rechecked against current main 7b31ab208c80123884bb3d67842331122e48d3d6: Routing-binding list, change-section and conflict descriptions use terminalText at the human-output boundary; JSON descriptions remain raw. The site is fixed on main. This PR remains open for its assignee.

@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 28, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs openclaw#184685, openclaw#184666, openclaw#184324, openclaw#184303, openclaw#176763, openclaw#176773 and openclaw#172873 by @Alix-007 and openclaw#184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: openclaw#185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@Alix-007

Copy link
Copy Markdown
Contributor Author

Thanks @obviyus for the detailed follow-up on the routing reports and the shared fix. Much appreciated.

@Alix-007

Alix-007 commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Hi @shakkernerd, could you take a look at the final disposition here when you have a chance? It's been open for over a week; #185927 already includes the fix with co-author credit. Thanks!

@Alix-007 Alix-007 closed this Nov 2, 2026
@Alix-007

Alix-007 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Closing this as absorbed by the merged #185927, with contributor credit retained. Thanks @obviyus for integrating the fix, and @shakkernerd for taking a look!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributor-review Clawtributor pull request awaiting prioritized maintainer review clawtributors PR from a clawtributor commands Command implementations P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants