Skip to content

Commit df70014

Browse files
shanselmanCopilot
andcommitted
feat: add browser proxy password auth retry
Co-authored-by: Copilot <[email protected]>
1 parent ad323b8 commit df70014

4 files changed

Lines changed: 110 additions & 27 deletions

File tree

‎docs/MISSION_CONTROL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ Keep StatusDetailWindow as the first Command Center, but plan for tabs/sections:
318318

319319
Recommended: investigate option 1 first, with `browser.proxy` gated to local/tunnel topologies and disabled for remote public gateways unless the upstream browser host contract says otherwise.
320320

321-
Current Windows implementation status: Windows node now advertises `browser.proxy` and forwards it to the local browser control host at `127.0.0.1:{gateway port + 2}` using the gateway bearer token. Command Center still performs the read-only feasibility probe and warns when no compatible local browser host is listening, because the command depends on that local service being available.
321+
Current Windows implementation status: Windows node now advertises `browser.proxy` and forwards it to the local browser control host at `127.0.0.1:{gateway port + 2}`. It uses the gateway bearer token first and retries with the same shared secret as browser-host password/basic auth if bearer auth is rejected. Command Center still performs the read-only feasibility probe and warns when no compatible local browser host is listening, because the command depends on that local service being available.
322322

323323
## 7. Security and privacy requirements
324324

‎docs/gateway-node-integration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ PR #159 originally explored session-based start/stop recording commands, but the
177177

178178
| Command | macOS | Windows | Notes |
179179
|---------|-------|---------|-------|
180-
| `browser.proxy` | ✅ | ✅ | Local browser-control bridge; requires browser control host on gateway port + 2 |
180+
| `browser.proxy` | ✅ | ✅ | Local browser-control bridge; requires browser control host on gateway port + 2 and retries with password/basic auth if bearer auth is rejected |
181181

182182
### 2.6 Safe Gateway-Policy Gaps to Consider
183183

‎src/OpenClaw.Shared/Capabilities/BrowserProxyCapability.cs‎

Lines changed: 56 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -54,37 +54,22 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest re
5454
using var timeoutCts = new System.Threading.CancellationTokenSource(TimeSpan.FromMilliseconds(timeoutMs));
5555

5656
var uri = BuildUri(controlPort, path, request.Args);
57-
using var httpRequest = new HttpRequestMessage(new HttpMethod(method), uri);
58-
if (!string.IsNullOrWhiteSpace(_bearerToken))
59-
{
60-
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _bearerToken);
61-
}
62-
63-
if (method is "POST" or "DELETE" &&
64-
request.Args.ValueKind == JsonValueKind.Object &&
65-
request.Args.TryGetProperty("body", out var body))
66-
{
67-
httpRequest.Content = new StringContent(body.GetRawText(), Encoding.UTF8, "application/json");
68-
}
69-
7057
try
7158
{
59+
using var httpRequest = CreateHttpRequest(method, uri, request.Args, usePasswordAuth: false);
7260
using var response = await _httpClient.SendAsync(httpRequest, timeoutCts.Token);
7361
var responseText = await response.Content.ReadAsStringAsync(timeoutCts.Token);
74-
if (response.StatusCode == HttpStatusCode.Unauthorized)
75-
return Error("Browser control host rejected authentication.");
76-
if (!response.IsSuccessStatusCode)
77-
return Error(string.IsNullOrWhiteSpace(responseText) ? $"Browser control host returned HTTP {(int)response.StatusCode}" : responseText);
7862

79-
using var doc = string.IsNullOrWhiteSpace(responseText)
80-
? JsonDocument.Parse("{}")
81-
: JsonDocument.Parse(responseText);
82-
var result = doc.RootElement.Clone();
83-
var files = TryCollectFiles(result);
63+
if (response.StatusCode == HttpStatusCode.Unauthorized &&
64+
!string.IsNullOrWhiteSpace(_bearerToken))
65+
{
66+
using var passwordRequest = CreateHttpRequest(method, uri, request.Args, usePasswordAuth: true);
67+
using var passwordResponse = await _httpClient.SendAsync(passwordRequest, timeoutCts.Token);
68+
var passwordResponseText = await passwordResponse.Content.ReadAsStringAsync(timeoutCts.Token);
69+
return BuildProxyResponse(passwordResponse, passwordResponseText);
70+
}
8471

85-
return files.Count == 0
86-
? Success(new { result })
87-
: Success(new { result, files });
72+
return BuildProxyResponse(response, responseText);
8873
}
8974
catch (TaskCanceledException)
9075
{
@@ -108,6 +93,52 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest re
10893
}
10994
}
11095

96+
private HttpRequestMessage CreateHttpRequest(string method, Uri uri, JsonElement args, bool usePasswordAuth)
97+
{
98+
var httpRequest = new HttpRequestMessage(new HttpMethod(method), uri);
99+
if (!string.IsNullOrWhiteSpace(_bearerToken))
100+
{
101+
if (usePasswordAuth)
102+
{
103+
httpRequest.Headers.TryAddWithoutValidation("x-openclaw-password", _bearerToken);
104+
httpRequest.Headers.Authorization = new AuthenticationHeaderValue(
105+
"Basic",
106+
Convert.ToBase64String(Encoding.UTF8.GetBytes($":{_bearerToken}")));
107+
}
108+
else
109+
{
110+
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _bearerToken);
111+
}
112+
}
113+
114+
if (method is "POST" or "DELETE" &&
115+
args.ValueKind == JsonValueKind.Object &&
116+
args.TryGetProperty("body", out var body))
117+
{
118+
httpRequest.Content = new StringContent(body.GetRawText(), Encoding.UTF8, "application/json");
119+
}
120+
121+
return httpRequest;
122+
}
123+
124+
private NodeInvokeResponse BuildProxyResponse(HttpResponseMessage response, string responseText)
125+
{
126+
if (response.StatusCode == HttpStatusCode.Unauthorized)
127+
return Error("Browser control host rejected authentication.");
128+
if (!response.IsSuccessStatusCode)
129+
return Error(string.IsNullOrWhiteSpace(responseText) ? $"Browser control host returned HTTP {(int)response.StatusCode}" : responseText);
130+
131+
using var doc = string.IsNullOrWhiteSpace(responseText)
132+
? JsonDocument.Parse("{}")
133+
: JsonDocument.Parse(responseText);
134+
var result = doc.RootElement.Clone();
135+
var files = TryCollectFiles(result);
136+
137+
return files.Count == 0
138+
? Success(new { result })
139+
: Success(new { result, files });
140+
}
141+
111142
private static bool TryResolveControlEndpoint(string gatewayUrl, out int controlPort, out string error)
112143
{
113144
controlPort = 0;

‎tests/OpenClaw.Shared.Tests/CapabilityTests.cs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.IO;
22
using System.Net;
33
using System.Net.Http;
4+
using System.Text;
45
using System.Text.Json;
56
using Xunit;
67
using OpenClaw.Shared;
@@ -712,6 +713,34 @@ public async Task BrowserProxy_ReturnsUnauthorizedAsAuthError()
712713
Assert.Contains("authentication", res.Error);
713714
}
714715

716+
[Fact]
717+
public async Task BrowserProxy_RetriesUnauthorizedWithPasswordAuth()
718+
{
719+
var handler = new BrowserProxyAuthFallbackHandler();
720+
var cap = new BrowserProxyCapability(
721+
NullLogger.Instance,
722+
"ws://127.0.0.1:18789",
723+
"browser-secret",
724+
handler);
725+
726+
var res = await cap.ExecuteAsync(new NodeInvokeRequest
727+
{
728+
Id = "browser-4",
729+
Command = "browser.proxy",
730+
Args = Parse("""{"method":"DELETE","path":"/tabs/1","body":{"reason":"test"}}""")
731+
});
732+
733+
Assert.True(res.Ok);
734+
Assert.Equal(2, handler.Requests.Count);
735+
Assert.Equal("Bearer", handler.Requests[0].Headers.Authorization?.Scheme);
736+
Assert.Equal("Basic", handler.Requests[1].Headers.Authorization?.Scheme);
737+
Assert.Equal(
738+
Convert.ToBase64String(Encoding.UTF8.GetBytes(":browser-secret")),
739+
handler.Requests[1].Headers.Authorization?.Parameter);
740+
Assert.True(handler.Requests[1].Headers.TryGetValues("x-openclaw-password", out var passwordValues));
741+
Assert.Contains("browser-secret", passwordValues);
742+
}
743+
715744
private sealed class CapturingHandler : HttpMessageHandler
716745
{
717746
private readonly string _response;
@@ -736,6 +765,29 @@ protected override Task<HttpResponseMessage> SendAsync(
736765
});
737766
}
738767
}
768+
769+
private sealed class BrowserProxyAuthFallbackHandler : HttpMessageHandler
770+
{
771+
public List<HttpRequestMessage> Requests { get; } = new();
772+
773+
protected override Task<HttpResponseMessage> SendAsync(
774+
HttpRequestMessage request,
775+
CancellationToken cancellationToken)
776+
{
777+
Requests.Add(request);
778+
var hasPasswordHeader =
779+
request.Headers.TryGetValues("x-openclaw-password", out var passwordValues) &&
780+
passwordValues.Contains("browser-secret");
781+
var isBasic = request.Headers.Authorization?.Scheme == "Basic";
782+
var status = hasPasswordHeader && isBasic ? HttpStatusCode.OK : HttpStatusCode.Unauthorized;
783+
var response = status == HttpStatusCode.OK ? """{"ok":true}""" : "Unauthorized";
784+
785+
return Task.FromResult(new HttpResponseMessage(status)
786+
{
787+
Content = new StringContent(response)
788+
});
789+
}
790+
}
739791
}
740792

741793
public class CanvasCapabilityTests

0 commit comments

Comments
 (0)