Skip to content

Commit 76f4d52

Browse files
AlexAlves87AlexAlves87claude
authored
feat: add exec approval prompt dialog for system.run on the Windows node (#1045)
* feat: add display sanitizer for exec approval command text Command text shown in an approval prompt can carry invisible or direction-changing code points (BiDi overrides, zero-width characters, fake line breaks, non-ASCII spaces) that let an agent make the approved text look like a different command. Add a rune-based sanitizer that escapes those code points as \u{HEX} before any UI binding, leaving legitimate text untouched. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * feat: add exec approval prompt handler core Add the UI-free core behind the approval prompt: a handler that sanitizes the command, working directory, and resolved path, builds a display-ready view, and resolves the outcome behind two injected delegates (dispatcher enqueue + show dialog) so its full behavior is testable without WinUI. It is fail-closed: never throws, never returns a plain allow, and denies on cancellation, enqueue failure, window close, or any internal error. Also flag mixed-script confusables (Latin intermixed with Cyrillic or Greek, the homoglyph-spoofing signal from Unicode UTS #39) so the dialog can warn the user. Confusables are not escaped — that would mangle legitimate non-ASCII text — only reported. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * feat: add exec approval prompt dialog Add the WindowEx approval window built in code like the existing pairing and recording-consent dialogs (the tray has no reliable XamlRoot for ContentDialog). It shows the sanitized command in a monospaced, selectable card plus optional context rows, and offers Deny / Allow Once / Allow Always. Security posture: the allow buttons are never default-focused and arm only once a short delay has elapsed AND the whole command has been scrolled into view, so a long command cannot be approved with its dangerous tail off-screen. Escape, the close button, and Alt+F4 all resolve to Deny. A caution row appears when the command trips the mixed-script confusable check. Strings added to all five locales. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * feat: wire the real approval dialog behind the prompt-handler seam Replace the null prompt handler in the coordinator construction with a thin WinUI adapter that supplies the real dispatcher hop and dialog window to the shared handler core. The coordinator keeps the always-cannot-present evaluator, so the dialog stays dormant until a real presentation gate lands: the new path remains inert (opt-in flag off and presentation gated off). Update the log message to reflect that the prompt dialog is wired. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: AlexAlves87 <[email protected]> Co-authored-by: Claude Sonnet 4.6 <[email protected]>
1 parent e157ceb commit 76f4d52

15 files changed

Lines changed: 1561 additions & 5 deletions
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System.Globalization;
2+
using System.Text;
3+
4+
namespace OpenClaw.Shared.ExecApprovals;
5+
6+
/// <summary>
7+
/// Escapes invisible and direction-changing Unicode code points before command text is
8+
/// rendered in an approval prompt, so an agent cannot make the approved text look like
9+
/// a different command (BiDi overrides, zero-width characters, fake line breaks,
10+
/// non-ASCII spaces that spoof token boundaries).
11+
/// </summary>
12+
public static class ExecApprovalCommandDisplaySanitizer
13+
{
14+
public static string Sanitize(string text)
15+
{
16+
if (string.IsNullOrEmpty(text))
17+
return text;
18+
19+
var sanitized = new StringBuilder(text.Length);
20+
// Iterate by runes, not chars: Format-category code points exist outside the
21+
// BMP and a per-char loop would misclassify surrogate pairs.
22+
foreach (var rune in text.EnumerateRunes())
23+
{
24+
if (ShouldEscape(rune))
25+
sanitized.Append("\\u{").Append(rune.Value.ToString("X")).Append('}');
26+
else
27+
sanitized.Append(rune.ToString());
28+
}
29+
return sanitized.ToString();
30+
}
31+
32+
private static bool ShouldEscape(Rune rune)
33+
{
34+
var category = Rune.GetUnicodeCategory(rune);
35+
if (category is UnicodeCategory.Control
36+
or UnicodeCategory.Format
37+
or UnicodeCategory.LineSeparator
38+
or UnicodeCategory.ParagraphSeparator)
39+
{
40+
return true;
41+
}
42+
43+
// Non-ASCII space separators (NBSP, narrow NBSP, ideographic space, …) render
44+
// like a plain space but are handled differently by shells/parsers.
45+
if (category == UnicodeCategory.SpaceSeparator && rune.Value != 0x20)
46+
return true;
47+
48+
// Hangul filler characters render as blank but are not classified as spaces.
49+
return rune.Value is 0x115F or 0x1160 or 0x3164 or 0xFFA0;
50+
}
51+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
using System.Text;
2+
3+
namespace OpenClaw.Shared.ExecApprovals;
4+
5+
/// <summary>
6+
/// Flags command text that mixes scripts which are visually confusable with Latin
7+
/// (Cyrillic or Greek letters intermixed with Latin ones inside a single token), the
8+
/// classic homoglyph-spoofing signal from Unicode UTS #39 mixed-script detection.
9+
/// It does not escape or alter the text — escaping confusables would mangle legitimate
10+
/// non-ASCII commands. It only reports whether a warning should be shown next to the
11+
/// rendered command so the user is told the text may not read the way it looks.
12+
///
13+
/// Single-script text (all Latin, all Greek, all Cyrillic, all Han, …) is never flagged;
14+
/// only a token drawing letters from two or more of the Latin-confusable scripts is.
15+
/// </summary>
16+
public static class ExecApprovalConfusableDetector
17+
{
18+
private enum ConfusableScript { None, Latin, Cyrillic, Greek }
19+
20+
public static bool HasMixedScriptConfusable(string? text)
21+
{
22+
if (string.IsNullOrEmpty(text))
23+
return false;
24+
25+
// Whitespace separates command tokens; a homoglyph attack lives inside one
26+
// token (a spoofed executable name or argument), so scripts are only compared
27+
// within a token, never across the whole string.
28+
var scriptsInToken = ConfusableScript.None;
29+
var seenSecond = false;
30+
31+
foreach (var rune in text.EnumerateRunes())
32+
{
33+
if (Rune.IsWhiteSpace(rune))
34+
{
35+
scriptsInToken = ConfusableScript.None;
36+
continue;
37+
}
38+
39+
var script = Classify(rune.Value);
40+
if (script == ConfusableScript.None)
41+
continue;
42+
43+
if (scriptsInToken == ConfusableScript.None)
44+
{
45+
scriptsInToken = script;
46+
}
47+
else if (scriptsInToken != script)
48+
{
49+
seenSecond = true;
50+
break;
51+
}
52+
}
53+
54+
return seenSecond;
55+
}
56+
57+
private static ConfusableScript Classify(int cp)
58+
{
59+
// Latin letters that carry ASCII-lookalikes (basic + accented ranges).
60+
if ((cp >= 0x0041 && cp <= 0x005A) || (cp >= 0x0061 && cp <= 0x007A)
61+
|| (cp >= 0x00C0 && cp <= 0x024F)
62+
|| (cp >= 0x1E00 && cp <= 0x1EFF))
63+
return ConfusableScript.Latin;
64+
65+
// Greek and Coptic + Greek Extended.
66+
if ((cp >= 0x0370 && cp <= 0x03FF) || (cp >= 0x1F00 && cp <= 0x1FFF))
67+
return ConfusableScript.Greek;
68+
69+
// Cyrillic + Cyrillic Supplement.
70+
if (cp >= 0x0400 && cp <= 0x052F)
71+
return ConfusableScript.Cyrillic;
72+
73+
// Digits, punctuation, symbols, and every other script (Han, Hiragana, Arabic,
74+
// …) are script-neutral for this check: they carry no Latin homoglyph risk.
75+
return ConfusableScript.None;
76+
}
77+
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
4+
5+
namespace OpenClaw.Shared.ExecApprovals;
6+
7+
/// <summary>
8+
/// Display-ready strings for the exec approval prompt window. All values are already
9+
/// sanitized for rendering; the dialog never sees the raw request.
10+
/// </summary>
11+
public sealed record ExecApprovalPromptView(
12+
string CommandText,
13+
string AgentLabel,
14+
string? CwdText,
15+
string? ExecutablePathText,
16+
bool HasConfusableWarning);
17+
18+
/// <summary>
19+
/// Prompt-handler core behind the approval dialog. UI-free: the dispatcher hop and the
20+
/// window are injected as delegates so the full decision behavior is testable without
21+
/// WinUI. Fail-closed contract: never throws, never returns plain Allow, and resolves
22+
/// Deny on cancellation, enqueue failure, window close, or any internal error.
23+
/// </summary>
24+
public sealed class ExecApprovalV2UiPromptHandler : IExecApprovalV2PromptHandler
25+
{
26+
private readonly Func<Action, bool> _tryEnqueue;
27+
private readonly Func<ExecApprovalPromptView, CancellationToken, Task<ExecApprovalPromptOutcome>> _showDialog;
28+
private readonly IOpenClawLogger _logger;
29+
30+
public ExecApprovalV2UiPromptHandler(
31+
Func<Action, bool> tryEnqueue,
32+
Func<ExecApprovalPromptView, CancellationToken, Task<ExecApprovalPromptOutcome>> showDialog,
33+
IOpenClawLogger logger)
34+
{
35+
_tryEnqueue = tryEnqueue ?? throw new ArgumentNullException(nameof(tryEnqueue));
36+
_showDialog = showDialog ?? throw new ArgumentNullException(nameof(showDialog));
37+
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
38+
}
39+
40+
public async Task<ExecApprovalPromptOutcome> PromptAsync(
41+
ExecApprovalV2PromptRequest request, CancellationToken cancellationToken = default)
42+
{
43+
try
44+
{
45+
if (cancellationToken.IsCancellationRequested)
46+
return ExecApprovalPromptOutcome.Deny;
47+
48+
// Every field shown in the dialog originates from agent-controlled input,
49+
// including the agent label, so all of them go through the display sanitizer
50+
// before any UI binding to neutralize BiDi and control-character spoofing.
51+
var commandText = ExecApprovalCommandDisplaySanitizer.Sanitize(request.DisplayCommand);
52+
var agentLabel = ExecApprovalCommandDisplaySanitizer.Sanitize(request.AgentId);
53+
var cwdText = request.Cwd is null ? null : ExecApprovalCommandDisplaySanitizer.Sanitize(request.Cwd);
54+
var pathText = request.ResolvedPath is null ? null : ExecApprovalCommandDisplaySanitizer.Sanitize(request.ResolvedPath);
55+
56+
// Homoglyphs and mixed scripts survive sanitization by design (escaping them
57+
// would break legitimate non-ASCII text); surface them as a visible warning
58+
// instead so the user knows the command may not read the way it looks.
59+
var hasConfusable =
60+
ExecApprovalConfusableDetector.HasMixedScriptConfusable(commandText)
61+
|| ExecApprovalConfusableDetector.HasMixedScriptConfusable(cwdText)
62+
|| ExecApprovalConfusableDetector.HasMixedScriptConfusable(pathText);
63+
64+
var view = new ExecApprovalPromptView(commandText, agentLabel, cwdText, pathText, hasConfusable);
65+
66+
var tcs = new TaskCompletionSource<ExecApprovalPromptOutcome>(
67+
TaskCreationOptions.RunContinuationsAsynchronously);
68+
69+
// This TCS is the single authority for the outcome; first result wins.
70+
// Cancellation resolves it directly — no dispatcher hop — so a hung or
71+
// slow dialog can never delay the deny. Window teardown on cancel is
72+
// visual cleanup only, owned by the dialog delegate.
73+
using var registration = cancellationToken.Register(
74+
() => tcs.TrySetResult(ExecApprovalPromptOutcome.Deny));
75+
76+
// Cancellation may have resolved the TCS already (inline during Register).
77+
// A request that is already denied must never surface a window.
78+
if (tcs.Task.IsCompleted)
79+
return await tcs.Task.ConfigureAwait(false);
80+
81+
if (!_tryEnqueue(() => _ = RunDialogAsync(view, tcs, cancellationToken)))
82+
{
83+
_logger.Warn("[EXEC-APPROVALS] prompt: dispatcher enqueue failed; denying");
84+
tcs.TrySetResult(ExecApprovalPromptOutcome.Deny);
85+
}
86+
87+
var outcome = await tcs.Task.ConfigureAwait(false);
88+
if (outcome == ExecApprovalPromptOutcome.Allow)
89+
{
90+
_logger.Error("[EXEC-APPROVALS] prompt: dialog returned plain Allow; " +
91+
"only AllowOnce/AllowAlways are valid from UI — denying");
92+
return ExecApprovalPromptOutcome.Deny;
93+
}
94+
return outcome;
95+
}
96+
catch (Exception ex)
97+
{
98+
try { _logger.Warn($"[EXEC-APPROVALS] prompt failed; denying: {ex.Message}"); } catch { }
99+
return ExecApprovalPromptOutcome.Deny;
100+
}
101+
}
102+
103+
// Runs on the dispatcher. The try/catch wraps the entire async body so failures
104+
// after the first await (where the delegate is effectively fire-and-forget) still
105+
// resolve the outcome instead of escaping.
106+
private async Task RunDialogAsync(
107+
ExecApprovalPromptView view,
108+
TaskCompletionSource<ExecApprovalPromptOutcome> tcs,
109+
CancellationToken cancellationToken)
110+
{
111+
try
112+
{
113+
// The request may have been cancelled while this action sat in the
114+
// dispatcher queue; it is already denied, so never show the dialog.
115+
if (cancellationToken.IsCancellationRequested)
116+
{
117+
tcs.TrySetResult(ExecApprovalPromptOutcome.Deny);
118+
return;
119+
}
120+
121+
var outcome = await _showDialog(view, cancellationToken).ConfigureAwait(false);
122+
tcs.TrySetResult(outcome);
123+
}
124+
catch (Exception ex)
125+
{
126+
try { _logger.Warn($"[EXEC-APPROVALS] prompt dialog failed; denying: {ex.Message}"); } catch { }
127+
tcs.TrySetResult(ExecApprovalPromptOutcome.Deny);
128+
}
129+
}
130+
}

0 commit comments

Comments
 (0)