Skip to content

Commit f51a861

Browse files
bkudiessCopilotshanselman
authored
Improve remote gateway setup and connection error recovery (#828)
* Improve remote gateway setup and connection error recovery Add RemoteGatewayClassifier + GatewayErrorClassifier in OpenClaw.Shared and wire ConnectionPage remote setup advice, scope/token-drift/TLS recovery, and localized strings. Co-authored-by: Copilot <[email protected]> * Clear stale SSH fields for setup-code flow Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent 37bdd38 commit f51a861

17 files changed

Lines changed: 1403 additions & 58 deletions

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,7 @@ public async Task SwitchGatewayAsync(string gatewayId)
518518
}
519519
}
520520

521-
public async Task<SetupCodeResult> ApplySetupCodeAsync(string setupCode)
521+
public async Task<SetupCodeResult> ApplySetupCodeAsync(string setupCode, SshTunnelConfig? sshTunnel = null)
522522
{
523523
ThrowIfDisposed();
524524

@@ -554,6 +554,7 @@ public async Task<SetupCodeResult> ApplySetupCodeAsync(string setupCode)
554554
Url = gatewayUrl,
555555
SharedGatewayToken = existing?.SharedGatewayToken, // preserve existing shared token if any
556556
BootstrapToken = decoded.Token ?? existing?.BootstrapToken,
557+
SshTunnel = sshTunnel ?? existing?.SshTunnel,
557558
};
558559
_registry.AddOrUpdate(record);
559560
_registry.SetActive(recordId);

‎src/OpenClaw.Connection/IGatewayConnectionManager.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public interface IGatewayConnectionManager : IDisposable, IAsyncDisposable
4646
Task EnsureNodeConnectedAsync(CancellationToken cancellationToken = default);
4747

4848
// ─── Setup ───
49-
Task<SetupCodeResult> ApplySetupCodeAsync(string setupCode);
49+
Task<SetupCodeResult> ApplySetupCodeAsync(string setupCode, SshTunnelConfig? sshTunnel = null);
5050
Task<SetupCodeResult> ConnectWithSharedTokenAsync(string gatewayUrl, string token, SshTunnelConfig? sshTunnel = null);
5151

5252
// ─── Operator Client Access ───
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
using System;
2+
3+
namespace OpenClaw.Shared;
4+
5+
/// <summary>
6+
/// Actionable classification of a gateway connection error. Lets the UI route a
7+
/// raw error string to a specific recovery path instead of a generic failure —
8+
/// distinguishing unauthorized, scope mismatch, token drift, pairing, TLS,
9+
/// tunnel, and server problems.
10+
/// </summary>
11+
public enum GatewayErrorKind
12+
{
13+
/// <summary>No error text, or nothing recognizable.</summary>
14+
Unknown,
15+
16+
/// <summary>Connection refused / unreachable / timed out.</summary>
17+
Network,
18+
19+
/// <summary>Generic unauthorized / invalid-token rejection.</summary>
20+
Auth,
21+
22+
/// <summary>
23+
/// The stored device token is no longer recognized by the gateway (rotated,
24+
/// revoked, or replaced) — the fix is to re-pair, not to retry.
25+
/// </summary>
26+
TokenDrift,
27+
28+
/// <summary>
29+
/// Authenticated but missing a required operator/node scope (e.g. cannot
30+
/// approve pairing or read config) — the fix is to re-pair for higher scopes.
31+
/// </summary>
32+
ScopeMismatch,
33+
34+
/// <summary>Device/node pairing approval is pending on the gateway host.</summary>
35+
PairingRequired,
36+
37+
/// <summary>Pairing was explicitly rejected on the gateway host.</summary>
38+
PairingRejected,
39+
40+
/// <summary>TLS/certificate/cleartext transport problem.</summary>
41+
Tls,
42+
43+
/// <summary>SSH tunnel could not be established or dropped.</summary>
44+
Tunnel,
45+
46+
/// <summary>Gateway returned a 5xx / internal error.</summary>
47+
Server,
48+
49+
/// <summary>Rate limited by the gateway.</summary>
50+
RateLimited,
51+
}
52+
53+
/// <summary>
54+
/// Pure heuristic classifier for gateway error strings. Order is significant:
55+
/// the more specific kinds (scope, token drift) are matched before the generic
56+
/// auth bucket so a "re-pair" path wins over a plain "retry" path.
57+
/// </summary>
58+
public static class GatewayErrorClassifier
59+
{
60+
public static GatewayErrorKind Classify(string? error)
61+
{
62+
if (string.IsNullOrWhiteSpace(error))
63+
return GatewayErrorKind.Unknown;
64+
65+
var e = error.ToLowerInvariant();
66+
67+
if ((Contains(e, "rate") && Contains(e, "limit")) ||
68+
Contains(e, "429") || Contains(e, "too many request"))
69+
return GatewayErrorKind.RateLimited;
70+
71+
// SSH/tunnel first: SSH failures often read "Permission denied
72+
// (publickey)" which would otherwise be mistaken for a scope problem.
73+
if (Contains(e, "ssh") || Contains(e, "tunnel"))
74+
return GatewayErrorKind.Tunnel;
75+
76+
// Transport security before pairing/auth: e.g. "certificate not
77+
// approved by CA" must not be read as a pairing approval.
78+
if (Contains(e, "tls") || Contains(e, "ssl") || Contains(e, "certificate") ||
79+
Contains(e, "cert ") || Contains(e, "handshake") ||
80+
Contains(e, "cleartext") || Contains(e, "insecure"))
81+
return GatewayErrorKind.Tls;
82+
83+
// Scope/permission problems — authenticated but under-privileged.
84+
if (Contains(e, "scope") ||
85+
Contains(e, "insufficient priv") ||
86+
Contains(e, "not permitted") ||
87+
Contains(e, "permission denied") ||
88+
(Contains(e, "forbidden") && Contains(e, "scope")))
89+
return GatewayErrorKind.ScopeMismatch;
90+
91+
// Token drift — the device token specifically is stale/unknown.
92+
if (Contains(e, "re-pair") || Contains(e, "repair token") ||
93+
Contains(e, "token rotat") || Contains(e, "token revoked") ||
94+
Contains(e, "token mismatch") || Contains(e, "token drift") ||
95+
(Contains(e, "device token") &&
96+
(Contains(e, "unknown") || Contains(e, "invalid") ||
97+
Contains(e, "expired") || Contains(e, "not recognized") ||
98+
Contains(e, "no longer"))))
99+
return GatewayErrorKind.TokenDrift;
100+
101+
// Pairing lifecycle. Use specific tokens ("pairing"/"approval") so we
102+
// don't match "repair" (contains "pair") or "approved by CA".
103+
if (Contains(e, "pairing") || Contains(e, "approval"))
104+
{
105+
if (Contains(e, "reject") || Contains(e, "denied") || Contains(e, "declin"))
106+
return GatewayErrorKind.PairingRejected;
107+
return GatewayErrorKind.PairingRequired;
108+
}
109+
110+
// Server (5xx) before the broad auth bucket: a transient
111+
// "500 internal error: token validation failed" must not route the
112+
// user to a re-pair flow.
113+
if (Contains(e, "500") || Contains(e, "502") || Contains(e, "503") ||
114+
Contains(e, "internal error") || Contains(e, "server error"))
115+
return GatewayErrorKind.Server;
116+
117+
// Generic auth — after the more specific auth-adjacent kinds above.
118+
if (Contains(e, "401") || Contains(e, "unauthor") || Contains(e, "forbid") ||
119+
Contains(e, "auth") || Contains(e, "token") || Contains(e, "credential"))
120+
return GatewayErrorKind.Auth;
121+
122+
// Network.
123+
if (Contains(e, "refused") || Contains(e, "unreachable") ||
124+
Contains(e, "timeout") || Contains(e, "timed out") ||
125+
Contains(e, "network") || Contains(e, "no route") ||
126+
Contains(e, "could not connect") || Contains(e, "connection closed"))
127+
return GatewayErrorKind.Network;
128+
129+
return GatewayErrorKind.Unknown;
130+
}
131+
132+
private static bool Contains(string haystack, string needle) =>
133+
haystack.Contains(needle, StringComparison.Ordinal);
134+
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
using System;
2+
3+
namespace OpenClaw.Shared;
4+
5+
/// <summary>
6+
/// How the tray reaches a configured gateway. Drives remote-setup guidance and
7+
/// the cleartext-token warning in Connection settings.
8+
/// </summary>
9+
public enum GatewayConnectionTopology
10+
{
11+
/// <summary>URL was empty or could not be parsed.</summary>
12+
Unknown,
13+
14+
/// <summary>localhost / 127.0.0.1 / ::1 — reached directly on this machine.</summary>
15+
Local,
16+
17+
/// <summary>
18+
/// A loopback URL that actually fronts a remote gateway through a managed
19+
/// SSH tunnel (the WebSocket talks to <c>ws://localhost:&lt;localPort&gt;</c>
20+
/// but the bytes are encrypted by SSH end-to-end).
21+
/// </summary>
22+
SshTunnel,
23+
24+
/// <summary>Remote host over TLS (<c>wss://</c> or <c>https://</c>).</summary>
25+
DirectSecure,
26+
27+
/// <summary>
28+
/// Remote host over cleartext (<c>ws://</c> or <c>http://</c>) — the token
29+
/// travels unencrypted across the network.
30+
/// </summary>
31+
DirectInsecure,
32+
}
33+
34+
/// <summary>Whether the credential is protected in transit.</summary>
35+
public enum GatewayTransportSecurity
36+
{
37+
/// <summary>Loopback only — no network exposure.</summary>
38+
LocalLoopback,
39+
40+
/// <summary>Encrypted (TLS) or tunnelled (SSH) — token protected on the wire.</summary>
41+
Encrypted,
42+
43+
/// <summary>Cleartext to a non-local host — token exposed on the wire.</summary>
44+
Cleartext,
45+
}
46+
47+
/// <summary>Immutable classification of a gateway endpoint for setup/repair UX.</summary>
48+
public sealed record RemoteGatewayProfile(
49+
GatewayConnectionTopology Topology,
50+
GatewayTransportSecurity Security,
51+
string Host,
52+
bool IsTls)
53+
{
54+
public bool IsLocal => Topology == GatewayConnectionTopology.Local;
55+
56+
public bool IsRemote =>
57+
Topology is GatewayConnectionTopology.DirectSecure
58+
or GatewayConnectionTopology.DirectInsecure
59+
or GatewayConnectionTopology.SshTunnel;
60+
61+
/// <summary>
62+
/// True when a token would travel in cleartext over a network. The UI should
63+
/// steer the user to TLS (<c>wss://</c>), an SSH tunnel, or a trusted proxy
64+
/// (e.g. Tailscale) before saving such a gateway.
65+
/// </summary>
66+
public bool RecommendsTransportHardening =>
67+
Security == GatewayTransportSecurity.Cleartext;
68+
}
69+
70+
/// <summary>
71+
/// Pure classifier that maps a gateway URL (plus whether a managed SSH tunnel is
72+
/// configured) to a <see cref="RemoteGatewayProfile"/>. No I/O, no UI types.
73+
/// </summary>
74+
public static class RemoteGatewayClassifier
75+
{
76+
public static RemoteGatewayProfile Classify(string? url, bool hasSshTunnel = false)
77+
{
78+
var trimmed = url?.Trim();
79+
if (string.IsNullOrEmpty(trimmed) ||
80+
!Uri.TryCreate(trimmed, UriKind.Absolute, out var uri) ||
81+
string.IsNullOrEmpty(uri.Host))
82+
{
83+
// Unparseable input is left to GatewayUrlHelper validation elsewhere;
84+
// we surface no transport warning so half-typed URLs don't flicker a
85+
// scary banner on every keystroke.
86+
return new RemoteGatewayProfile(
87+
GatewayConnectionTopology.Unknown,
88+
GatewayTransportSecurity.LocalLoopback,
89+
Host: string.Empty,
90+
IsTls: false);
91+
}
92+
93+
var host = uri.Host;
94+
var scheme = uri.Scheme;
95+
var isTls = scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ||
96+
scheme.Equals("https", StringComparison.OrdinalIgnoreCase);
97+
98+
// A managed SSH tunnel encrypts the hop even though the WebSocket URL is
99+
// loopback. Treat it as a remote-but-encrypted endpoint.
100+
if (hasSshTunnel)
101+
{
102+
return new RemoteGatewayProfile(
103+
GatewayConnectionTopology.SshTunnel,
104+
GatewayTransportSecurity.Encrypted,
105+
host,
106+
isTls);
107+
}
108+
109+
if (LocalGatewayUrlClassifier.IsLocalGatewayUrl(trimmed))
110+
{
111+
return new RemoteGatewayProfile(
112+
GatewayConnectionTopology.Local,
113+
GatewayTransportSecurity.LocalLoopback,
114+
host,
115+
isTls);
116+
}
117+
118+
return isTls
119+
? new RemoteGatewayProfile(
120+
GatewayConnectionTopology.DirectSecure,
121+
GatewayTransportSecurity.Encrypted,
122+
host,
123+
IsTls: true)
124+
: new RemoteGatewayProfile(
125+
GatewayConnectionTopology.DirectInsecure,
126+
GatewayTransportSecurity.Cleartext,
127+
host,
128+
IsTls: false);
129+
}
130+
}

0 commit comments

Comments
 (0)