diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b8415bdda9..6a340cb3f8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1305,6 +1305,7 @@ leading and trailing pipe. Columns, in order: | dashboard-browser-fixture-guard | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | handing a Dashboard URL straight to Windows even when the app runs under the gateway fixture | DashboardBrowser | App supplies the Windows launch and logger delegates | outside fixture mode the exact URL goes to Windows; under OPENCLAW_GATEWAY_FIXTURE the launch is suppressed and only the redacted target is logged; a one-shot dashboard-browser-failure.once marker simulates one browser failure; an invalid fixture context fails closed | DashboardBrowserTests.FixtureRun_NeverReachesWindowsAndLogsOnlyTheRedactedUrl | behavioral | - | | setup-session-captured-authority | authoritative | src/OpenClaw.SetupEngine/SetupGatewaySession.cs | deriving client authority from a later active registry record | SetupGatewaySessionBinding | session reloads registry only to validate captured identity at admission, handshake, reconnect and request boundaries | a socket opened for Gateway A cannot be reported as Gateway B; same-ID endpoint and SSH changes fail while connection timestamps remain valid | SetupGatewaySessionBindingTests.ChangedRegistryDuringConnect_CannotRelabelAlreadyCreatedClient | behavioral | - | | setup-dashboard-pending-proof | authoritative | src/OpenClaw.Tray.WinUI/Services/SetupDashboardHandoff.cs | accepting external serialized completion JSON as verified proof | SetupDashboardHandoffStore + SetupNativeHandoffLauncher | activation parser admits only an opaque native handle; WindowManager rechecks current observations with SetupDashboardLiveFacts | a short-lived local pending record is exclusively leased, consumed on successful native presentation and retained only for explicit failed-launch retry; unknown, expired, forged, consumed and in-flight replay fail visibly; old generation numbers are not live authority | SetupDashboardHandoffStoreTests.ForgedShapeAndUnknownHandle_AreNotVerificationAuthority | behavioral | - | +| saved-personal-dashboard-owner | authoritative | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | saved-row personal Dashboard browser and shared-token handoff | GatewayDashboardLauncher + WindowManager | page passes the requested Gateway through IAppCommands; App composes native admission and preserves that target on retry; shared rows retain their existing endpoint provenance path | a Personal row never exports saved credentials; missing or changed current lease refuses admission before a window effect, including after old-window retirement | AppRefactorContractTests.SavedPersonalDashboard_CarriesRequestedGatewayThroughAdmissionAndRetry | source-shape | when mounted saved-row Dashboard coverage proves requested-target admission and lease replacement during window retirement | ## Deferred test builders diff --git a/docs/CONNECTION_ARCHITECTURE.md b/docs/CONNECTION_ARCHITECTURE.md index f39fd721c9..c6e7209be0 100644 --- a/docs/CONNECTION_ARCHITECTURE.md +++ b/docs/CONNECTION_ARCHITECTURE.md @@ -895,7 +895,7 @@ the existing `SetupGatewaySession` reads credentials from the active registry. No browser-profile credentials are accepted by this port, and it does not change Node mode, local MCP, capability settings, or install WSL. -Credential resolution order is intentionally strict: +Credential resolution order for the default Gateway credential mode is intentionally strict: 1. **Stored device token** in the per-gateway identity directory. 2. **`GatewayRecord.SharedGatewayToken`** - shared token for HTTP/chat surfaces. @@ -922,6 +922,34 @@ URLs; remote HTTPS gateways retain proxy support. It accepts the original 200-399 response without following redirects, so a readiness check never contacts a `Location` destination. Browser navigation remains a separate step. +## Personal Tailscale operator identity + +The direct Gateway form offers **Personal Tailscale identity** as an explicit +operator authentication mode. It requires a credential-free `wss://` address +under `.ts.net`, without SSH forwarding. The hostname admits the route; it does +not prove the caller's identity. The Gateway must support personal Tailscale +authentication and a canonical `users.self` profile. + +`CredentialResolver` returns an empty personal credential without reading saved +operator tokens. The client signs an interactive `gateway-client` / `ui` connect +with empty `auth`. A current-socket hello must report `auth.method=tailscale` +and a nonempty `recoveryScope`. Application readiness follows a successful +`users.self` read on that same transport epoch. Node credential resolution and +saved shared credentials remain unchanged. Personal failures do not activate +shared-token or bootstrap recovery. + +The personal Dashboard opens in a native WebView. Each challenge rechecks +`users.self` and the exact current lease before returning a signed credentialless +response bound to the method and recovery scope. The shared Control UI must +support this native response contract. Navigation, reconnect, profile changes +and lease retirement prevent an old document from receiving a new proof. + +Each window uses its own named InPrivate browser profile. Closing or retiring +that window calls the browser's profile deletion API and closes the control. +WebView2 deletes the marked profile at browser-process exit and retries after +later starts if another process holds its files. This does not assert immediate +disk erasure. + ## Self-recovery and automatic local-gateway repair Two orthogonal self-healing behaviors keep the connection reliable without dead-ending the user: diff --git a/docs/OPERATOR_NODE_CONCEPTS.md b/docs/OPERATOR_NODE_CONCEPTS.md index 5e5054035e..0a1101a8cf 100644 --- a/docs/OPERATOR_NODE_CONCEPTS.md +++ b/docs/OPERATOR_NODE_CONCEPTS.md @@ -73,6 +73,13 @@ tokens can help the app connect for the first time, but a paired device token takes precedence after approval. This keeps long-lived operator and node identity scoped to the gateway record that issued it. +An existing Tailscale Gateway can instead use the explicit personal operator +mode. The Gateway verifies the Tailscale user, and Companion checks the current +personal profile before exposing the operator connection. This does not turn the +Windows node identity into a person or change node pairing. See +[personal Tailscale operator identity](CONNECTION_ARCHITECTURE.md#personal-tailscale-operator-identity) +for the connection and Dashboard requirements. + Some trust decisions are intentionally not automatic. Node command trust and capability reapproval stay pending until an operator explicitly approves them, so a new or changed node capability is visible before the gateway can use it. diff --git a/src/OpenClaw.Connection/BootstrapTokenLifecycle.cs b/src/OpenClaw.Connection/BootstrapTokenLifecycle.cs index 65b5cc0b3b..7ba3cab0ae 100644 --- a/src/OpenClaw.Connection/BootstrapTokenLifecycle.cs +++ b/src/OpenClaw.Connection/BootstrapTokenLifecycle.cs @@ -228,7 +228,8 @@ internal OperatorCredentialSelection SelectOperatorCredential( var selected = resolved; lock (_stateLock) { - if (_forceBootstrapForGatewayRecordId == record.Id && + if (record.OperatorAuthentication == OperatorAuthenticationMode.GatewayCredential && + _forceBootstrapForGatewayRecordId == record.Id && !string.IsNullOrWhiteSpace(record.BootstrapToken)) { var credential = new GatewayCredential( @@ -390,7 +391,7 @@ attempt.GatewayRecordId is null || } var record = _registry.GetById(attempt.GatewayRecordId); - if (record is null) + if (record is null || record.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale) return false; var hasSharedToken = !string.IsNullOrWhiteSpace(record.SharedGatewayToken); diff --git a/src/OpenClaw.Connection/CredentialResolver.cs b/src/OpenClaw.Connection/CredentialResolver.cs index 83585f4588..c026871575 100644 --- a/src/OpenClaw.Connection/CredentialResolver.cs +++ b/src/OpenClaw.Connection/CredentialResolver.cs @@ -35,6 +35,22 @@ public GatewayCredentialResolution ResolveOperatorDetailed(GatewayRecord record, { ArgumentNullException.ThrowIfNull(record); + if (record.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale) + { + if (record.SshTunnel is not null || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(record.Url, out _, out var error)) + return new(null, GatewayCredentialResolutionStatus.Missing, + Detail: "Personal authentication requires a direct credential-free wss:// host.ts.net route."); + return GatewayCredentialResolution.FromLegacy(new GatewayCredential( + string.Empty, false, GatewayPersonalAuthenticationPolicy.CredentialSource) + { + OperatorAuthentication = OperatorAuthenticationMode.PersonalTailscale + }); + } + if (record.OperatorAuthentication != OperatorAuthenticationMode.GatewayCredential) + return new(null, GatewayCredentialResolutionStatus.Corrupt, + Detail: "The saved operator authentication mode is unsupported."); + return ResolveRole( _identityReader.ReadStoredDeviceToken(identityPath), SourceDeviceToken, diff --git a/src/OpenClaw.Connection/GatewayClientFactory.cs b/src/OpenClaw.Connection/GatewayClientFactory.cs index f64362da68..5bca1b45a3 100644 --- a/src/OpenClaw.Connection/GatewayClientFactory.cs +++ b/src/OpenClaw.Connection/GatewayClientFactory.cs @@ -28,7 +28,8 @@ public IGatewayClientLifecycle Create( bootstrapPairAsNode: false, identityPath: identityPath, ignoreStoredDeviceToken: credential.IsBootstrapToken, - assistantMediaAuthToken: credential.InteractiveHttpToken) + assistantMediaAuthToken: credential.InteractiveHttpToken, + operatorAuthentication: credential.OperatorAuthentication) { SupportsExecApprovals = SupportsExecApprovals, ClientIdentity = ClientIdentity, diff --git a/src/OpenClaw.Connection/GatewayConnectionManager.PersonalIdentity.cs b/src/OpenClaw.Connection/GatewayConnectionManager.PersonalIdentity.cs new file mode 100644 index 0000000000..0c96e0cb9c --- /dev/null +++ b/src/OpenClaw.Connection/GatewayConnectionManager.PersonalIdentity.cs @@ -0,0 +1,139 @@ +using System.Text.Json; +using OpenClaw.Shared; + +namespace OpenClaw.Connection; + +public sealed partial class GatewayConnectionManager +{ + private enum PersonalVerification { NotRequired, Verified, Stale, Rejected } + private PersonalOperatorLease? _personalOperatorLease; + + public PersonalOperatorLease? CurrentPersonalOperatorLease + { + get + { + var lease = Volatile.Read(ref _personalOperatorLease); + var client = _activeLifecycle?.DataClient; + if (lease is null || client is not { IsPersonalTailscaleAuthentication: true } || + lease.Generation != Interlocked.Read(ref _generation) || + client.SessionMutationConnectionEpoch != lease.TransportEpoch || + client.AuthenticatedSigningDeviceId != lease.DeviceId || + client.PersonalRecoveryScope != lease.RecoveryScope || + _registry.ActiveGatewayId != lease.GatewayId || + _registry.GetById(lease.GatewayId) is not { OperatorAuthentication: OperatorAuthenticationMode.PersonalTailscale } record || + record.SshTunnel is not null || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(record.Url, out var route, out _) || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(client.CurrentGatewayUrl, out var connected, out _) || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(lease.GatewayUrl, out var leased, out _) || + route != connected || route != leased) + return null; + return lease; + } + } + + private async Task<(PersonalVerification Disposition, PersonalOperatorLease? Lease)> VerifyPersonalOperatorAsync(long generation) + { + var client = _activeLifecycle?.DataClient; + var record = _activeGatewayRecordId is null ? null : _registry.GetById(_activeGatewayRecordId); + if (record?.OperatorAuthentication != OperatorAuthenticationMode.PersonalTailscale) + { + return (PersonalVerification.NotRequired, null); + } + + if (client is not { IsPersonalTailscaleAuthentication: true } || + client.PersonalHandshakeConnectionEpoch is not { } epoch || + client.PersonalRecoveryScope is not { } scope || + record.SshTunnel is not null || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(record.Url, out var route, out _) || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(client.CurrentGatewayUrl, out var connected, out _) || + route != connected) + return (PersonalVerification.Rejected, null); + + try + { + var self = await client.ReadPersonalIdentityAsync(epoch).ConfigureAwait(false); + if (!IsCurrent()) return (PersonalVerification.Stale, null); + if (!GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(self, out var profile)) + return (PersonalVerification.Rejected, null); + client.VerifyPersonalIdentity(profile, epoch); + if (!IsCurrent() || client.SessionMutationConnectionEpoch != epoch || + client.AuthenticatedSigningDeviceId is not { Length: > 0 } deviceId) + return (PersonalVerification.Stale, null); + var lease = new PersonalOperatorLease(record.Id, route, profile, scope, deviceId, generation, epoch); + return (PersonalVerification.Verified, lease); + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or + OperationCanceledException or JsonException) + { + if (!IsCurrent()) return (PersonalVerification.Stale, null); + _diagnostics.Record("identity", "Personal profile verification unavailable", ex.GetType().Name); + return (PersonalVerification.Rejected, null); + } + + bool IsCurrent() => + generation == Interlocked.Read(ref _generation) && + ReferenceEquals(client, _activeLifecycle?.DataClient) && + client.PersonalHandshakeConnectionEpoch == epoch && + client.PersonalRecoveryScope == scope && + _registry.ActiveGatewayId == record.Id && + _registry.GetById(record.Id) is { OperatorAuthentication: OperatorAuthenticationMode.PersonalTailscale } current && + current.SshTunnel is null && + GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(current.Url, out var currentRoute, out _) && + currentRoute == route; + } + + public async Task CreatePersonalBrowserAuthResponseAsync( + string nonce, long signedAt, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(nonce) || System.Text.Encoding.UTF8.GetByteCount(nonce) > 512 || nonce.Contains('|') || + nonce.Any(character => char.IsControl(character) || character == '\uFEFF') || + signedAt <= 0 || Math.Abs((double)new DateTimeOffset(_clock.UtcNow).ToUnixTimeMilliseconds() - signedAt) > 300_000) + return null; + + var lease = CurrentPersonalOperatorLease; + var client = _activeLifecycle?.DataClient; + if (lease is null || client is null) return null; + try + { + var self = await client.ReadPersonalIdentityAsync(lease.TransportEpoch).ConfigureAwait(false); + if (cancellationToken.IsCancellationRequested || + !ReferenceEquals(lease, CurrentPersonalOperatorLease) || + !ReferenceEquals(client, _activeLifecycle?.DataClient)) + return null; + if (!GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(self, out var profile) || + profile != lease.IdentityProfileId) + { + await RevokePersonalOperatorAsync(lease).ConfigureAwait(false); + return null; + } + var response = client.CreatePersonalBrowserAuthResponse(nonce, signedAt, lease.TransportEpoch); + return ReferenceEquals(lease, CurrentPersonalOperatorLease) + ? JsonSerializer.Serialize(response) : null; + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or + OperationCanceledException or JsonException) + { + await RevokePersonalOperatorAsync(lease).ConfigureAwait(false); + return null; + } + } + + private async Task RevokePersonalOperatorAsync(PersonalOperatorLease expected) + { + await _transitionSemaphore.WaitAsync().ConfigureAwait(false); + try + { + if (!ReferenceEquals(expected, CurrentPersonalOperatorLease)) return; + _stateMachine.SetOperatorErrorKind(GatewayErrorKind.PersonalIdentityReverificationRequired); + _stateMachine.TryTransition(ConnectionTrigger.WebSocketError, + "Personal identity changed. Reconnect this Gateway."); + _stateMachine.Current = _stateMachine.Current with { PersonalIdentityProfileId = null }; + await DisposeActiveClientAsync().ConfigureAwait(false); + EmitStateChanged(); + } + finally + { + _transitionSemaphore.Release(); + } + } +} diff --git a/src/OpenClaw.Connection/GatewayConnectionManager.cs b/src/OpenClaw.Connection/GatewayConnectionManager.cs index 5aa04dd0fb..c490ab2fb6 100644 --- a/src/OpenClaw.Connection/GatewayConnectionManager.cs +++ b/src/OpenClaw.Connection/GatewayConnectionManager.cs @@ -14,7 +14,7 @@ namespace OpenClaw.Connection; /// Node, bootstrap-token, and device-pair workflows are delegated to their /// dedicated connection-domain owners through typed internal ports. /// -public sealed class GatewayConnectionManager : +public sealed partial class GatewayConnectionManager : IGatewayConnectionManager, INodeLifecycleSource, INodeConnectionStateSink, @@ -2402,6 +2402,8 @@ private static ConnectionErrorCategory MapConnectionErrorCategory( errorKind switch { GatewayErrorKind.Auth or + GatewayErrorKind.PersonalIdentityUnverified or + GatewayErrorKind.PersonalIdentityReverificationRequired or GatewayErrorKind.TokenDrift or GatewayErrorKind.DeviceTokenMismatch or GatewayErrorKind.ScopeMismatch => ConnectionErrorCategory.AuthFailure, @@ -2655,6 +2657,7 @@ expectedRecord.NativePackageFamilyName is not null private static bool IsSameCredentialHandoffRecord( GatewayRecord current, GatewayRecord expected) => + current.OperatorAuthentication == expected.OperatorAuthentication && string.Equals(current.Id, expected.Id, StringComparison.Ordinal) && string.Equals(current.Url, expected.Url, StringComparison.Ordinal) && string.Equals( @@ -2680,16 +2683,54 @@ private static bool IsSameCredentialHandoffRecord( private async Task HandleHandshakeSucceededAsync(long gen) { NodeAutomaticStartPlan? nodeStartPlan = null; + if (Interlocked.Read(ref _generation) != gen) return; + var personalClient = _activeLifecycle?.DataClient; + var personal = await VerifyPersonalOperatorAsync(gen).ConfigureAwait(false); await _transitionSemaphore.WaitAsync(); try { if (Interlocked.Read(ref _generation) != gen) return; + if (!ReferenceEquals(personalClient, _activeLifecycle?.DataClient)) return; + if (personal.Disposition == PersonalVerification.Stale) return; + if (personal.Disposition == PersonalVerification.Verified) + { + if (personal.Lease is not { } lease || personalClient is null || + personalClient.SessionMutationConnectionEpoch != lease.TransportEpoch || + personalClient.PersonalRecoveryScope != lease.RecoveryScope) + return; + Volatile.Write(ref _personalOperatorLease, lease); + if (CurrentPersonalOperatorLease is null) + { + Interlocked.CompareExchange(ref _personalOperatorLease, null, lease); + return; + } + } + else if (personal.Disposition == PersonalVerification.NotRequired) + { + Volatile.Write(ref _personalOperatorLease, null); + } + if (personal.Disposition == PersonalVerification.Rejected) + { + _stateMachine.SetOperatorErrorKind(GatewayErrorKind.PersonalIdentityUnverified); + _stateMachine.TryTransition(_stateMachine.Current.OperatorState == RoleConnectionState.Connected + ? ConnectionTrigger.WebSocketError : ConnectionTrigger.AuthenticationFailed, + "Personal Tailscale identity could not be verified. Reconnect this Gateway."); + _stateMachine.Current = _stateMachine.Current with { PersonalIdentityProfileId = null }; + CompleteOperatorTelemetryAttempt(gen, "failure", ConnectionErrorCategory.AuthFailure); + await DisposeActiveClientAsync().ConfigureAwait(false); + EmitStateChanged(); + return; + } var prev = _stateMachine.Current.OverallState; _diagnostics.Record("state", "Handshake succeeded (hello-ok)"); _stateMachine.SetOperatorProtocolCompatibility( ReadOperatorProtocolCompatibility(gen)); _stateMachine.TryTransition(ConnectionTrigger.HandshakeSucceeded); + _stateMachine.Current = _stateMachine.Current with + { + PersonalIdentityProfileId = CurrentPersonalOperatorLease?.IdentityProfileId + }; CompleteOperatorTelemetryAttempt(gen, "success"); var nodeModeIntended = SyncNodeIntentFromSettings(); _bootstrapTokenLifecycle.ResetOperatorRecoveryAfterHandshake( @@ -3712,6 +3753,7 @@ private async Task StopNativeGatewayAsync() private async Task DisposeActiveClientAsync() { + Volatile.Write(ref _personalOperatorLease, null); await _nodeConnectionCoordinator.RetireAsync().ConfigureAwait(false); _devicePairApprovalCoordinator.Reset(); diff --git a/src/OpenClaw.Connection/GatewayConnectionSnapshot.cs b/src/OpenClaw.Connection/GatewayConnectionSnapshot.cs index 6174a08574..990db59888 100644 --- a/src/OpenClaw.Connection/GatewayConnectionSnapshot.cs +++ b/src/OpenClaw.Connection/GatewayConnectionSnapshot.cs @@ -24,6 +24,7 @@ public sealed record GatewayConnectionSnapshot public OpenClaw.Shared.GatewayErrorKind? OperatorErrorKind { get; init; } public bool OperatorPairingRequired { get; init; } public string? OperatorDeviceId { get; init; } + public string? PersonalIdentityProfileId { get; init; } public string? OperatorCredentialSource { get; init; } public GatewayCredentialResolutionStatus? OperatorCredentialStatus { get; init; } public bool OperatorCredentialFallbackUsed { get; init; } diff --git a/src/OpenClaw.Connection/GatewayConnectionValidator.cs b/src/OpenClaw.Connection/GatewayConnectionValidator.cs index 70ff3a0c2f..85f49a84fa 100644 --- a/src/OpenClaw.Connection/GatewayConnectionValidator.cs +++ b/src/OpenClaw.Connection/GatewayConnectionValidator.cs @@ -151,7 +151,8 @@ internal static OpenClawGatewayClient CreateClient( ignoreStoredDeviceToken: credential.Source != CredentialResolver.SourceDeviceToken, persistHandshakeDeviceTokens: false, ephemeralOperatorCredential: ephemeralOperatorCredential, - useBoundedBootstrapScopes: useBoundedBootstrapScopes) + useBoundedBootstrapScopes: useBoundedBootstrapScopes, + operatorAuthentication: credential.OperatorAuthentication) { UseV2Signature = record.IsLocal || record.RequiresV2Signature || credential.IsBootstrapToken }; @@ -165,8 +166,27 @@ internal static async Task RunHandshakeAsync( OpenClawGatewayClient client, CancellationToken cancellationToken) { var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - void Handshake(object? sender, EventArgs e) => - completion.TrySetResult(new(SetupCodeOutcome.Success)); + void Handshake(object? sender, EventArgs e) => _ = VerifyHandshakeAsync(); + async Task VerifyHandshakeAsync() + { + try + { + if (client.IsPersonalTailscaleAuthentication) + { + if (client.PersonalHandshakeConnectionEpoch is not { } epoch) + throw new InvalidOperationException(); + var self = await client.ReadPersonalIdentityAsync(epoch).ConfigureAwait(false); + if (!GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(self, out var profile)) + throw new InvalidOperationException(); + client.VerifyPersonalIdentity(profile, epoch); + } + completion.TrySetResult(new(SetupCodeOutcome.Success)); + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or OperationCanceledException) + { + completion.TrySetResult(AuthenticationFailure("Personal Tailscale identity could not be verified.")); + } + } void AuthenticationFailed(object? sender, string message) => completion.TrySetResult(AuthenticationFailure(message)); // Pairing is reported before the Gateway closes the socket. Preserve it as the first result. diff --git a/src/OpenClaw.Connection/GatewayPersonalAuthenticationPolicy.cs b/src/OpenClaw.Connection/GatewayPersonalAuthenticationPolicy.cs new file mode 100644 index 0000000000..31684fc27d --- /dev/null +++ b/src/OpenClaw.Connection/GatewayPersonalAuthenticationPolicy.cs @@ -0,0 +1,54 @@ +using System.Net; + +namespace OpenClaw.Connection; + +public static class GatewayPersonalAuthenticationPolicy +{ + public const string AuthMethod = "tailscale"; + public const string CredentialSource = "auth.tailscale"; + + public static bool TryNormalizeGatewayUrl(string? value, out string normalizedUrl, out string error) => + OpenClaw.Shared.PersonalTailscaleGatewayRoute.TryNormalizeGatewayUrl(value, out normalizedUrl, out error); + + public static bool TryGetCanonicalProfileId(System.Text.Json.JsonElement response, out string profileId) + { + profileId = string.Empty; + if (response.ValueKind != System.Text.Json.JsonValueKind.Object || + !response.TryGetProperty("profile", out var profile) || + profile.ValueKind != System.Text.Json.JsonValueKind.Object || + !profile.TryGetProperty("id", out var id) || + id.ValueKind != System.Text.Json.JsonValueKind.String) + { + return false; + } + + profileId = id.GetString() ?? string.Empty; + return profileId != "gateway-owner" && !string.IsNullOrWhiteSpace(profileId) && + string.Equals(profileId, profileId.Trim(), StringComparison.Ordinal); + } + + public static bool IsTrustedDashboardSource(string sourceUrl, string expectedGatewayUrl) + { + if (!TryNormalizeGatewayUrl(expectedGatewayUrl, out var route, out _) || + !Uri.TryCreate(route, UriKind.Absolute, out var expected) || + !Uri.TryCreate(sourceUrl, UriKind.Absolute, out var source)) + { + return false; + } + + return string.Equals(source.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) && + string.IsNullOrEmpty(source.UserInfo) && + source.Port == expected.Port && + string.Equals(source.Host, expected.Host, StringComparison.OrdinalIgnoreCase) && + !IPAddress.TryParse(source.Host, out _); + } +} + +public sealed record PersonalOperatorLease( + string GatewayId, + string GatewayUrl, + string IdentityProfileId, + string RecoveryScope, + string DeviceId, + long Generation, + long TransportEpoch); diff --git a/src/OpenClaw.Connection/GatewayRecord.cs b/src/OpenClaw.Connection/GatewayRecord.cs index de142fc582..193902d2d0 100644 --- a/src/OpenClaw.Connection/GatewayRecord.cs +++ b/src/OpenClaw.Connection/GatewayRecord.cs @@ -6,6 +6,8 @@ namespace OpenClaw.Connection; /// public sealed record GatewayRecord { + public OpenClaw.Shared.OperatorAuthenticationMode OperatorAuthentication { get; init; } + /// Stable GUID, primary key. public string Id { get; init; } = ""; diff --git a/src/OpenClaw.Connection/ICredentialResolver.cs b/src/OpenClaw.Connection/ICredentialResolver.cs index 92fc9ef296..88d601696b 100644 --- a/src/OpenClaw.Connection/ICredentialResolver.cs +++ b/src/OpenClaw.Connection/ICredentialResolver.cs @@ -7,6 +7,8 @@ namespace OpenClaw.Connection; /// public sealed record GatewayCredential(string Token, bool IsBootstrapToken, string Source) { + public OperatorAuthenticationMode OperatorAuthentication { get; init; } + public GatewayCredentialResolutionStatus ResolutionStatus { get; init; } = GatewayCredentialResolutionStatus.Resolved; public bool FallbackUsed { get; init; } diff --git a/src/OpenClaw.Connection/IGatewayConnectionManager.cs b/src/OpenClaw.Connection/IGatewayConnectionManager.cs index c27a662b50..f0761ab120 100644 --- a/src/OpenClaw.Connection/IGatewayConnectionManager.cs +++ b/src/OpenClaw.Connection/IGatewayConnectionManager.cs @@ -12,6 +12,10 @@ public interface IGatewayConnectionManager : IDisposable, IAsyncDisposable // ─── State ─── GatewayConnectionSnapshot CurrentSnapshot { get; } string? ActiveGatewayUrl { get; } + PersonalOperatorLease? CurrentPersonalOperatorLease => null; + Task CreatePersonalBrowserAuthResponseAsync( + string nonce, long signedAt, CancellationToken cancellationToken = default) => + Task.FromResult(null); // ─── Events ─── event EventHandler StateChanged; diff --git a/src/OpenClaw.Connection/InteractiveGatewayCredentialResolver.cs b/src/OpenClaw.Connection/InteractiveGatewayCredentialResolver.cs index d69fc8f740..8763579276 100644 --- a/src/OpenClaw.Connection/InteractiveGatewayCredentialResolver.cs +++ b/src/OpenClaw.Connection/InteractiveGatewayCredentialResolver.cs @@ -13,6 +13,7 @@ public static class InteractiveGatewayCredentialResolver internal static GatewayCredential? ResolveForAssistantMediaHttpSurface( GatewayRecord record, GatewayCredential? fallback) => + record.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale ? null : !string.IsNullOrWhiteSpace(record.SharedGatewayToken) ? new GatewayCredential( record.SharedGatewayToken!, @@ -60,6 +61,11 @@ public static bool TryResolve( var active = registry?.GetActive(); if (active != null && !string.IsNullOrWhiteSpace(active.Url)) { + if (active.OperatorAuthentication != OperatorAuthenticationMode.GatewayCredential) + { + credential = null; + return false; + } if (active.NativePackageFamilyName is not null && authorizeCredential is null) { credential = null; diff --git a/src/OpenClaw.Shared/AssistantMediaResolution.cs b/src/OpenClaw.Shared/AssistantMediaResolution.cs index 4a4088a20f..0a4d048e1d 100644 --- a/src/OpenClaw.Shared/AssistantMediaResolution.cs +++ b/src/OpenClaw.Shared/AssistantMediaResolution.cs @@ -36,4 +36,7 @@ public enum AssistantFileDownloadStatus internal readonly record struct GatewayConnectionLease( Guid ClientId, long Generation, - Uri HttpBaseUri); + Uri HttpBaseUri) +{ + internal object? PersonalAuthority { get; init; } +} diff --git a/src/OpenClaw.Shared/ConnectEnvelopeBuilder.cs b/src/OpenClaw.Shared/ConnectEnvelopeBuilder.cs index 89573d44d7..a1d8098423 100644 --- a/src/OpenClaw.Shared/ConnectEnvelopeBuilder.cs +++ b/src/OpenClaw.Shared/ConnectEnvelopeBuilder.cs @@ -19,13 +19,19 @@ protected ConnectCredential(string value) internal string Value { get; } internal abstract string FieldName { get; } - internal Dictionary ToAuthPayload() => + internal virtual Dictionary ToAuthPayload() => new() { [FieldName] = Value }; public sealed override string ToString() => $"ConnectCredential {{ Kind = {FieldName} }}"; } +internal sealed class TailscaleConnectCredential() : ConnectCredential(string.Empty) +{ + internal override string FieldName => "tailscale"; + internal override Dictionary ToAuthPayload() => []; +} + internal sealed class TokenConnectCredential(string token) : ConnectCredential(token) { diff --git a/src/OpenClaw.Shared/GatewayErrorClassifier.cs b/src/OpenClaw.Shared/GatewayErrorClassifier.cs index 2428927e38..2211a2785a 100644 --- a/src/OpenClaw.Shared/GatewayErrorClassifier.cs +++ b/src/OpenClaw.Shared/GatewayErrorClassifier.cs @@ -69,6 +69,12 @@ public enum GatewayErrorKind /// The Gateway wire protocol is incompatible with this client. ProtocolMismatch, + + /// The personal operator identity could not be verified. + PersonalIdentityUnverified, + + /// The current personal operator identity must be verified again. + PersonalIdentityReverificationRequired, } /// diff --git a/src/OpenClaw.Shared/OpenClawGatewayClient.AssistantMedia.cs b/src/OpenClaw.Shared/OpenClawGatewayClient.AssistantMedia.cs index f1f4cc63b5..2ca1990a73 100644 --- a/src/OpenClaw.Shared/OpenClawGatewayClient.AssistantMedia.cs +++ b/src/OpenClaw.Shared/OpenClawGatewayClient.AssistantMedia.cs @@ -197,6 +197,9 @@ private async Task ResolveLegacyMediaAsync( if (string.IsNullOrWhiteSpace(media.GatewaySource) || !AssistantMediaDirectiveParser.IsSendableLegacySource(media.GatewaySource)) return AssistantMediaResolutionResult.Unavailable; + if (IsPersonalTailscaleAuthentication && + !await VerifyPersonalMediaIdentityAsync(lease, cancellationToken).ConfigureAwait(false)) + return AssistantMediaResolutionResult.Unavailable; var metadataUri = BuildLegacyMediaUri( lease.HttpBaseUri, @@ -262,6 +265,7 @@ private async Task DownloadMediaBytesAsync( int maximumBytes, CancellationToken cancellationToken) { + if (!IsCurrentMediaLease(lease)) return AssistantMediaResolutionResult.Unavailable; using var request = CreateAuthenticatedMediaRequest(uri, kind == ChatMediaContentKind.File ? "*/*" : $"{MimePrefix(kind)}/*"); using var response = await _assistantMediaHttpClient.SendAsync( request, @@ -297,7 +301,12 @@ private HttpRequestMessage CreateAuthenticatedMediaRequest(Uri uri, string accep var request = new HttpRequestMessage(HttpMethod.Get, uri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); var authToken = Volatile.Read(ref _assistantMediaAuthToken); - if (!string.IsNullOrWhiteSpace(authToken)) + if (IsPersonalTailscaleAuthentication) + { + request.Headers.Add("Origin", uri.GetLeftPart(UriPartial.Authority)); + request.Headers.TryAddWithoutValidation("x-openclaw-scopes", string.Join(",", GrantedOperatorScopes)); + } + else if (!string.IsNullOrWhiteSpace(authToken)) request.Headers.Authorization = new AuthenticationHeaderValue( "Bearer", authToken); @@ -309,13 +318,17 @@ private bool TryCaptureMediaLease(out GatewayConnectionLease lease) lease = default; if (!IsConnectedToGateway || !TryBuildMediaHttpBaseUri(_currentGatewayUrl, out var baseUri)) return false; - lease = new GatewayConnectionLease(_mediaClientId, ConnectionGeneration, baseUri); + lease = new GatewayConnectionLease(_mediaClientId, ConnectionGeneration, baseUri) + { + PersonalAuthority = IsPersonalTailscaleAuthentication ? Volatile.Read(ref _personalHandshake) : null + }; return true; } private bool IsCurrentMediaLease(GatewayConnectionLease lease) => lease.ClientId == _mediaClientId && lease.Generation == ConnectionGeneration + && (!IsPersonalTailscaleAuthentication || ReferenceEquals(lease.PersonalAuthority, Volatile.Read(ref _personalHandshake))) && IsConnectedToGateway; internal static bool TryBuildMediaHttpBaseUri(string gatewayUrl, out Uri baseUri) diff --git a/src/OpenClaw.Shared/OpenClawGatewayClient.PersonalAuthentication.cs b/src/OpenClaw.Shared/OpenClawGatewayClient.PersonalAuthentication.cs new file mode 100644 index 0000000000..c2664ed9ee --- /dev/null +++ b/src/OpenClaw.Shared/OpenClawGatewayClient.PersonalAuthentication.cs @@ -0,0 +1,154 @@ +using System.Text.Json; + +namespace OpenClaw.Shared; + +public partial class OpenClawGatewayClient +{ + private sealed record PersonalHandshake(long Epoch, string RecoveryScope, string? ProfileId = null, string? ExpectedProfileId = null); + private readonly OperatorAuthenticationMode _operatorAuthentication; + private PersonalHandshake? _personalHandshake; + + public bool IsPersonalTailscaleAuthentication => + _operatorAuthentication == OperatorAuthenticationMode.PersonalTailscale; + + public long? PersonalHandshakeConnectionEpoch => + TryGetHandshakeConnectionGeneration(out var epoch) && + Volatile.Read(ref _personalHandshake)?.Epoch == epoch ? epoch : null; + + public string? PersonalRecoveryScope => + PersonalHandshakeConnectionEpoch is { } epoch && + Volatile.Read(ref _personalHandshake) is { } handshake && handshake.Epoch == epoch + ? handshake.RecoveryScope : null; + + public string CurrentGatewayUrl => _currentGatewayUrl; + + public async Task ReadPersonalIdentityAsync(long expectedEpoch) + { + if (!IsPersonalTailscaleAuthentication || PersonalHandshakeConnectionEpoch != expectedEpoch) + throw new InvalidOperationException("The personal Gateway connection changed."); + var result = await SendResponseRequestAsync( + "users.self", new { }, 30000, expectedEpoch, allowPersonalIdentityRead: true).ConfigureAwait(false); + if (PersonalHandshakeConnectionEpoch != expectedEpoch) + throw new InvalidOperationException("The personal Gateway connection changed."); + return result; + } + + public void VerifyPersonalIdentity(string profileId, long expectedEpoch) + { + ArgumentException.ThrowIfNullOrWhiteSpace(profileId); + var handshake = Volatile.Read(ref _personalHandshake); + if (profileId == "gateway-owner" || !IsPersonalTailscaleAuthentication || handshake is null || + handshake.ExpectedProfileId is { } expectedProfile && profileId != expectedProfile || + handshake.Epoch != expectedEpoch || PersonalHandshakeConnectionEpoch != expectedEpoch) + throw new InvalidOperationException("The personal Gateway connection changed."); + var verified = handshake with { ProfileId = profileId }; + if (!ReferenceEquals(Interlocked.CompareExchange(ref _personalHandshake, verified, handshake), handshake)) + throw new InvalidOperationException("The personal Gateway connection changed."); + if (PersonalHandshakeConnectionEpoch != expectedEpoch) + { + Interlocked.CompareExchange(ref _personalHandshake, null, verified); + throw new InvalidOperationException("The personal Gateway connection changed."); + } + RequestInitialState(expectedEpoch); + } + + private void InvalidatePersonalIdentity() + { + var handshake = Volatile.Read(ref _personalHandshake); + if (!IsPersonalTailscaleAuthentication || handshake is not { ProfileId: not null }) return; + var pending = handshake with { ProfileId = null, ExpectedProfileId = handshake.ProfileId }; + if (ReferenceEquals(Interlocked.CompareExchange(ref _personalHandshake, pending, handshake), handshake)) + HandshakeSucceeded?.Invoke(this, EventArgs.Empty); + } + + private async Task VerifyPersonalMediaIdentityAsync(GatewayConnectionLease lease, CancellationToken cancellationToken) + { + if (!IsCurrentMediaLease(lease) || lease.PersonalAuthority is not PersonalHandshake personal) return false; + try + { + var self = await ReadPersonalIdentityAsync(lease.Generation).WaitAsync(cancellationToken).ConfigureAwait(false); + if (!IsCurrentMediaLease(lease)) return false; + if (self.ValueKind == JsonValueKind.Object && self.TryGetProperty("profile", out var profile) && + profile.ValueKind == JsonValueKind.Object && profile.TryGetProperty("id", out var id) && + id.ValueKind == JsonValueKind.String && id.GetString() == personal.ProfileId) + return true; + InvalidatePersonalIdentity(); + return false; + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or OperationCanceledException or JsonException) + { + cancellationToken.ThrowIfCancellationRequested(); + return false; + } + } + + private void RequestInitialState(long epoch) + { + _ = Task.Run(async () => + { + await Task.Delay(500); + if (!TryGetReadyConnectionGeneration(out var current) || current != epoch) + return; + await CheckHealthAsync(); + await RequestSessionsAsync(); + await SubscribeSessionEventsAsync(); + await RequestUsageAsync(); + await RequestNodesAsync(); + await RequestAgentsListAsync(); + }); + } + + private bool HasVerifiedPersonalIdentity(long epoch) => + Volatile.Read(ref _personalHandshake) is { ProfileId: not null } handshake && handshake.Epoch == epoch; + + private bool TryAcceptPersonalHandshake(JsonElement payload, long epoch) + { + if (!payload.TryGetProperty("auth", out var auth) || + auth.ValueKind != JsonValueKind.Object || + !auth.TryGetProperty("method", out var method) || + method.ValueKind != JsonValueKind.String || method.GetString() != "tailscale" || + !auth.TryGetProperty("recoveryScope", out var scope) || + scope.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(scope.GetString())) + return false; + Volatile.Write(ref _personalHandshake, new PersonalHandshake(epoch, scope.GetString()!)); + return true; + } + + public object CreatePersonalBrowserAuthResponse(string nonce, long signedAt, long expectedEpoch) + { + var handshake = Volatile.Read(ref _personalHandshake); + if (string.IsNullOrWhiteSpace(nonce) || System.Text.Encoding.UTF8.GetByteCount(nonce) > 512 || + nonce.Contains('|') || nonce.Any(character => char.IsControl(character) || character == '\uFEFF') || + signedAt <= 0 || !IsPersonalTailscaleAuthentication || + !TryGetReadyConnectionGeneration(out var epoch) || epoch != expectedEpoch || + handshake is not { ProfileId: not null } || handshake.Epoch != epoch || + AuthenticatedSigningDeviceId != _deviceIdentity.DeviceId) + throw new InvalidOperationException("Personal Gateway identity is unavailable."); + + var scopes = GrantedOperatorScopes.ToArray(); + var signature = _deviceIdentity.SignConnectPayloadV3( + nonce, signedAt, "gateway-client", "ui", "operator", scopes, string.Empty, + WindowsClientMetadata.Platform, WindowsClientMetadata.DeviceFamily); + if (!TryGetReadyConnectionGeneration(out var currentEpoch) || currentEpoch != epoch || + !ReferenceEquals(handshake, Volatile.Read(ref _personalHandshake))) + throw new InvalidOperationException("The personal Gateway connection changed."); + + return new + { + client = new + { + id = "gateway-client", mode = "ui", version = AppVersionInfo.Version, + platform = WindowsClientMetadata.Platform, deviceFamily = WindowsClientMetadata.DeviceFamily + }, + scopes, + auth = new { }, + requiredAuthMethod = "tailscale", + expectedRecoveryScope = handshake.RecoveryScope, + device = new + { + id = _deviceIdentity.DeviceId, publicKey = _deviceIdentity.PublicKeyBase64Url, + signature, signedAt, nonce + } + }; + } +} diff --git a/src/OpenClaw.Shared/OpenClawGatewayClient.cs b/src/OpenClaw.Shared/OpenClawGatewayClient.cs index fc32a07127..fb788a19ad 100644 --- a/src/OpenClaw.Shared/OpenClawGatewayClient.cs +++ b/src/OpenClaw.Shared/OpenClawGatewayClient.cs @@ -327,6 +327,7 @@ private void ObserveHandshake(long generation, GatewayHandshakePhase phase, protected override Task OnConnectedAsync() { + Volatile.Write(ref _personalHandshake, null); Volatile.Write(ref _startupRejection, null); CancelScheduledSessionRefresh(); CancelScheduledAgentRosterRefresh(); @@ -386,6 +387,7 @@ public GatewayStartupUnavailable? StartupUnavailable protected override void OnDisconnected() { + Volatile.Write(ref _personalHandshake, null); CancelScheduledSessionRefresh(); CancelScheduledAgentRosterRefresh(); // Invalidate the handshake snapshot — the next hello-ok must @@ -411,6 +413,7 @@ protected override void OnDisconnected() protected override void OnDisposing() { + Volatile.Write(ref _personalHandshake, null); Volatile.Write(ref _startupRejection, null); CancelScheduledSessionRefresh(); CancelScheduledAgentRosterRefresh(); @@ -536,7 +539,11 @@ public string? AuthenticatedSigningDeviceId public long ServerHandshakeGeneration => Interlocked.Read(ref _serverHandshakeGeneration); public int? LastRemoteCloseStatusCode => RemoteCloseStatusCode; - private bool TryGetReadyConnectionGeneration(out long connectionGeneration) + private bool TryGetReadyConnectionGeneration(out long connectionGeneration) => + TryGetHandshakeConnectionGeneration(out connectionGeneration) && + (!IsPersonalTailscaleAuthentication || HasVerifiedPersonalIdentity(connectionGeneration)); + + private bool TryGetHandshakeConnectionGeneration(out long connectionGeneration) { connectionGeneration = CurrentConnectionGeneration; return IsConnected && @@ -598,12 +605,20 @@ public OpenClawGatewayClient( HttpMessageHandler? assistantMediaHandler = null, DeviceTokenReceivedEventArgs? ephemeralOperatorCredential = null, bool useBoundedBootstrapScopes = false, - bool requireExistingIdentity = false) - : base(gatewayUrl, token, logger) - { + bool requireExistingIdentity = false, + OperatorAuthenticationMode operatorAuthentication = OperatorAuthenticationMode.GatewayCredential) + : base(gatewayUrl, token, logger, allowEmptyToken: operatorAuthentication == OperatorAuthenticationMode.PersonalTailscale) + { + _operatorAuthentication = operatorAuthentication; + if (IsPersonalTailscaleAuthentication && + (!string.IsNullOrEmpty(token) || !PersonalTailscaleGatewayRoute.TryNormalizeGatewayUrl(gatewayUrl, out _, out _))) + throw new ArgumentException("Personal authentication requires a credential-free managed Tailscale route.", nameof(gatewayUrl)); + if (!Enum.IsDefined(operatorAuthentication) || + IsPersonalTailscaleAuthentication && (tokenIsBootstrapToken || bootstrapPairAsNode || ephemeralOperatorCredential is not null)) + throw new ArgumentException("Personal authentication cannot use bootstrap or operator credentials.", nameof(operatorAuthentication)); _tokenIsBootstrapToken = tokenIsBootstrapToken; _bootstrapPairAsNode = bootstrapPairAsNode; - _ignoreStoredDeviceToken = ignoreStoredDeviceToken; + _ignoreStoredDeviceToken = ignoreStoredDeviceToken || IsPersonalTailscaleAuthentication; _persistHandshakeDeviceTokens = persistHandshakeDeviceTokens; if (ephemeralOperatorCredential is not null && (ephemeralOperatorCredential.Role != "operator" || string.IsNullOrWhiteSpace(ephemeralOperatorCredential.Token))) @@ -611,9 +626,9 @@ public OpenClawGatewayClient( _ephemeralOperatorCredential = ephemeralOperatorCredential; _useBoundedBootstrapScopes = useBoundedBootstrapScopes; _assistantMediaHttpClient = assistantMediaHandler is null - ? new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) + ? new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = !IsPersonalTailscaleAuthentication }) : new HttpClient(assistantMediaHandler, disposeHandler: true); - SetAssistantMediaAuthToken(assistantMediaAuthToken); + SetAssistantMediaAuthToken(IsPersonalTailscaleAuthentication ? null : assistantMediaAuthToken); _currentGatewayUrl = gatewayUrl; var dataPath = identityPath ?? OpenClawAppIdentity.ResolveRoamingDataDirectory( Environment.GetEnvironmentVariable); @@ -622,7 +637,8 @@ public OpenClawGatewayClient( if (requireExistingIdentity) _deviceIdentity.LoadExisting(); else _deviceIdentity.Initialize(); _connectEnvelopeSigner = new DeviceIdentityConnectEnvelopeSigner(_deviceIdentity); - _connectAuthToken = HasUsableOperatorDeviceToken ? EffectiveOperatorDeviceToken! : (_tokenIsBootstrapToken ? string.Empty : _token); + _connectAuthToken = IsPersonalTailscaleAuthentication ? string.Empty : + HasUsableOperatorDeviceToken ? EffectiveOperatorDeviceToken! : (_tokenIsBootstrapToken ? string.Empty : _token); _useV2Signature |= _tokenIsBootstrapToken && !HasUsableOperatorDeviceToken; } @@ -633,7 +649,7 @@ public OpenClawGatewayClient( public void SetAssistantMediaAuthToken(string? token) => Volatile.Write( ref _assistantMediaAuthToken, - string.IsNullOrWhiteSpace(token) ? null : token); + IsPersonalTailscaleAuthentication || string.IsNullOrWhiteSpace(token) ? null : token); /// Closes the active transport, drains pending requests, and publishes disconnected state. public async Task DisconnectAsync() @@ -1918,12 +1934,15 @@ public Task SendWizardRequestOnConnectionAsync( private async Task SendResponseRequestAsync( string method, object? parameters, int timeoutMs, long? expectedConnectionEpoch = null, - CancellationToken requestCancellationToken = default, bool searchRead = false) + CancellationToken requestCancellationToken = default, bool searchRead = false, + bool allowPersonalIdentityRead = false) { using var requestCancellation = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, requestCancellationToken); var requestToken = requestCancellation.Token; requestToken.ThrowIfCancellationRequested(); - var connectionGeneration = GetReadyConnectionGeneration(method); + var connectionGeneration = allowPersonalIdentityRead && method == "users.self" && + TryGetHandshakeConnectionGeneration(out var handshakeEpoch) + ? handshakeEpoch : GetReadyConnectionGeneration(method); if (expectedConnectionEpoch.HasValue && connectionGeneration != expectedConnectionEpoch.Value) throw new GatewayRequestNotSentException(ConnectionChangedBeforeSendError); @@ -2612,7 +2631,7 @@ private async Task SendConnectMessageAsync( _challengeTimestampMs, _useV2Signature, SupportsExecApprovals, - ClientIdentity), + IsPersonalTailscaleAuthentication ? OperatorClientIdentity.Interactive : ClientIdentity), _connectEnvelopeSigner); var signedAt = envelope.SignedAt; var connectNonce = envelope.Nonce!; @@ -2712,6 +2731,9 @@ private Dictionary BuildAuthPayload() private ConnectCredential SelectConnectCredential() { + if (IsPersonalTailscaleAuthentication) + return new TailscaleConnectCredential(); + if (HasUsableOperatorDeviceToken) return new DeviceTokenConnectCredential(EffectiveOperatorDeviceToken!); @@ -3004,6 +3026,14 @@ HandshakeAuthorizationAsync is not null && return; } + if (IsPersonalTailscaleAuthentication && !TryAcceptPersonalHandshake(payload, sourceConnectionGeneration)) + { + _authFailed = true; + RaiseConnectionFailure(GatewayErrorKind.PersonalIdentityUnverified); + RaiseAuthenticationFailed("The Gateway did not verify personal Tailscale authentication."); + return; + } + _logger.Info($"[HANDSHAKE] Received hello-ok!"); Volatile.Write(ref _startupRejection, null); Volatile.Write(ref _pairingRequiredAwaitingApproval, false); @@ -3048,6 +3078,8 @@ HandshakeAuthorizationAsync is not null && var persistedRoleTokens = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var roleToken in EnumerateHandshakeDeviceTokens(payload)) { + if (IsPersonalTailscaleAuthentication && roleToken.Role != "node") + continue; var stored = TryStoreHandshakeDeviceToken(roleToken.Role, roleToken.Token, roleToken.Scopes); persistedRoleTokens.Add(roleToken.Role); if (stored && roleToken.Role.Equals("node", StringComparison.OrdinalIgnoreCase)) @@ -3071,7 +3103,7 @@ HandshakeAuthorizationAsync is not null && } } - var newDeviceToken = !_bootstrapPairAsNode + var newDeviceToken = IsPersonalTailscaleAuthentication ? null : !_bootstrapPairAsNode ? (persistedRoleTokens.Contains(OperatorRole) ? null : TryGetHandshakeDeviceTokenCore(payload, preferredRole: null)) : TryGetHandshakeDeviceTokenCore(payload, OperatorRole, allowDirectDeviceTokenFallback: false); if (!string.IsNullOrWhiteSpace(newDeviceToken)) @@ -3104,17 +3136,8 @@ HandshakeAuthorizationAsync is not null && RaiseStatusChanged(ConnectionStatus.Connected); - // Request initial state after handshake - _ = Task.Run(async () => - { - await Task.Delay(500); - await CheckHealthAsync(); - await RequestSessionsAsync(); - await SubscribeSessionEventsAsync(); - await RequestUsageAsync(); - await RequestNodesAsync(); - await RequestAgentsListAsync(); - }); + if (!IsPersonalTailscaleAuthentication) + RequestInitialState(sourceConnectionGeneration); } // Handle health response — channels @@ -4095,6 +4118,7 @@ private void HandleEventForConnection( && changeReason.ValueKind == JsonValueKind.String && changeReason.GetString() == "profile-identity") { + InvalidatePersonalIdentity(); SelfProfileChanged?.Invoke(this, EventArgs.Empty); } if (sessionChange.TryGetProperty("catalogChanged", out var catalogChanged) diff --git a/src/OpenClaw.Shared/OperatorAuthenticationMode.cs b/src/OpenClaw.Shared/OperatorAuthenticationMode.cs new file mode 100644 index 0000000000..a28bdf0578 --- /dev/null +++ b/src/OpenClaw.Shared/OperatorAuthenticationMode.cs @@ -0,0 +1,7 @@ +namespace OpenClaw.Shared; + +public enum OperatorAuthenticationMode +{ + GatewayCredential, + PersonalTailscale +} diff --git a/src/OpenClaw.Shared/PersonalTailscaleGatewayRoute.cs b/src/OpenClaw.Shared/PersonalTailscaleGatewayRoute.cs new file mode 100644 index 0000000000..110e73d10c --- /dev/null +++ b/src/OpenClaw.Shared/PersonalTailscaleGatewayRoute.cs @@ -0,0 +1,36 @@ +using System.Net; + +namespace OpenClaw.Shared; + +public static class PersonalTailscaleGatewayRoute +{ + public static bool TryNormalizeGatewayUrl(string? value, out string normalizedUrl, out string error) + { + normalizedUrl = string.Empty; + error = "Personal Tailscale authentication requires a credential-free wss:// host.ts.net URL."; + if (string.IsNullOrWhiteSpace(value) || !Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri)) + return false; + + if (!string.Equals(uri.Scheme, "wss", StringComparison.OrdinalIgnoreCase) || + !string.IsNullOrEmpty(uri.UserInfo) || + !string.IsNullOrEmpty(uri.Query) || + !string.IsNullOrEmpty(uri.Fragment) || + uri.Port < 1 || + IPAddress.TryParse(uri.Host, out _) || + uri.Host.EndsWith(".", StringComparison.Ordinal) || + !uri.Host.EndsWith(".ts.net", StringComparison.OrdinalIgnoreCase) || + uri.Host.Length <= ".ts.net".Length) + { + return false; + } + + var normalized = new UriBuilder(uri) + { + Scheme = Uri.UriSchemeWss, + Port = uri.IsDefaultPort ? -1 : uri.Port + }; + normalizedUrl = normalized.Uri.GetLeftPart(UriPartial.Path).TrimEnd('/'); + return true; + } + +} diff --git a/src/OpenClaw.Shared/WebSocketClientBase.cs b/src/OpenClaw.Shared/WebSocketClientBase.cs index cf8610cb34..4a30332d8f 100644 --- a/src/OpenClaw.Shared/WebSocketClientBase.cs +++ b/src/OpenClaw.Shared/WebSocketClientBase.cs @@ -244,11 +244,11 @@ protected virtual void OnDisposing() { } /// A protocol-specific retry delay for the rejected socket, or normal transport backoff. protected virtual int? GetReconnectDelayMs(long sourceConnectionGeneration) => null; - protected WebSocketClientBase(string gatewayUrl, string token, IOpenClawLogger? logger = null) + protected WebSocketClientBase(string gatewayUrl, string token, IOpenClawLogger? logger = null, bool allowEmptyToken = false) { if (string.IsNullOrEmpty(gatewayUrl)) throw new ArgumentException("Gateway URL is required.", nameof(gatewayUrl)); - if (string.IsNullOrEmpty(token)) + if (!allowEmptyToken && string.IsNullOrEmpty(token)) throw new ArgumentException("Token is required.", nameof(token)); _gatewayUrl = GatewayUrlHelper.NormalizeForWebSocket(gatewayUrl); diff --git a/src/OpenClaw.Tray.WinUI/App.xaml.cs b/src/OpenClaw.Tray.WinUI/App.xaml.cs index 3fb09b6570..04554d3e88 100644 --- a/src/OpenClaw.Tray.WinUI/App.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/App.xaml.cs @@ -2955,11 +2955,14 @@ private static bool TryBuildConnectionIssueNotification( { title = LocalizationHelper.GetString("AppNotification_GatewayConnectionFailed_Title"); var rawError = snapshot.OperatorError; - message = string.IsNullOrWhiteSpace(rawError) - ? LocalizationHelper.GetString("AppNotification_GatewayConnectionFailed_DefaultMessage") - : rawError; + var personalErrorKey = GatewayPersonalErrorPresentation.ResourceKey(snapshot.OperatorErrorKind); + message = personalErrorKey is not null + ? LocalizationHelper.GetString(personalErrorKey) + : string.IsNullOrWhiteSpace(rawError) + ? LocalizationHelper.GetString("AppNotification_GatewayConnectionFailed_DefaultMessage") + : rawError; severity = AppNotificationSeverity.Error; - key = $"operator-error:{rawError ?? "default"}"; + key = $"operator-error:{personalErrorKey ?? rawError ?? "default"}"; return true; } @@ -4159,19 +4162,20 @@ private void OpenNativeSetupCompletion(string handle, bool explicitRetry = false }, new AppLogger(), nameof(OpenNativeSetupCompletion)); } - private void OpenDashboard(string? path = null) + private void OpenDashboard(string? path = null, string? expectedPersonalGatewayId = null) { - AsyncEventHandlerGuard.Run(async () => await TryOpenDashboardAsync(path), + AsyncEventHandlerGuard.Run(async () => await TryOpenDashboardAsync(path, expectedPersonalGatewayId), new AppLogger(), nameof(OpenDashboard)); } - private Task TryOpenDashboardAsync(string? path) + private Task TryOpenDashboardAsync(string? path, string? expectedPersonalGatewayId = null) { var launcher = CreateDashboardLauncher( () => AsyncEventHandlerGuard.Run( () => _windowManager?.ShowDashboardLaunchFailureAsync( - () => OpenDashboard(path)) - ?? Task.CompletedTask, new AppLogger(), "Dashboard launch error")); + () => OpenDashboard(path, expectedPersonalGatewayId)) + ?? Task.CompletedTask, new AppLogger(), "Dashboard launch error"), + expectedPersonalGatewayId: expectedPersonalGatewayId); return launcher.OpenAsync(path); } @@ -4193,19 +4197,26 @@ private void RequireSetupDashboardAuthority(SetupNativeCompletion completion) } private GatewayDashboardLauncher CreateDashboardLauncher( - Action reportFailure, SetupNativeCompletion? setupCompletion = null) => new( + Action reportFailure, SetupNativeCompletion? setupCompletion = null, + string? expectedPersonalGatewayId = null) => new( EnsureSshTunnelConfigured, () => TryResolveChatCredentials(out var url, out var token, out var source, out var bootstrap, setupCompletion) ? new InteractiveGatewayCredential(url, token, bootstrap, source) : null, new DashboardBrowser( async url => await global::Windows.System.Launcher.LaunchUriAsync(new Uri(url)), Logger.Info).OpenAsync, reportFailure, - () => _appNotificationService?.Dismiss(GatewayDashboardLauncher.FailureNotificationId)); + () => _appNotificationService?.Dismiss(GatewayDashboardLauncher.FailureNotificationId), + isPersonalMode: () => expectedPersonalGatewayId is not null || + _gatewayRegistry?.GetActive()?.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale, + openPersonalDashboard: setupCompletion is null + ? target => _windowManager?.ShowPersonalDashboardAsync(target, expectedPersonalGatewayId) ?? Task.FromResult(false) + : null); // ── IAppCommands implementation ───────────────────────────────────── void IAppCommands.OpenDashboard(string? path) => OpenDashboard(path); - Task IAppCommands.TryOpenDashboardAsync(string? path) => TryOpenDashboardAsync(path); + Task IAppCommands.TryOpenDashboardAsync(string? path, string? expectedPersonalGatewayId) => + TryOpenDashboardAsync(path, expectedPersonalGatewayId); void IAppCommands.Navigate(string pageTag) => ShowHub(pageTag); Task IAppCommands.TryNavigateAsync(string pageTag, string? chatSessionKey) => _windowManager?.TryShowHubAsync(pageTag, chatSessionKey) ?? Task.FromResult(false); diff --git a/src/OpenClaw.Tray.WinUI/Helpers/GatewayPersonalErrorPresentation.cs b/src/OpenClaw.Tray.WinUI/Helpers/GatewayPersonalErrorPresentation.cs new file mode 100644 index 0000000000..3a4cde31c1 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Helpers/GatewayPersonalErrorPresentation.cs @@ -0,0 +1,24 @@ +// Maps personal identity failures to native recovery resources. +using OpenClaw.Shared; + +namespace OpenClawTray.Helpers; + +/// Native recovery resources for personal identity failures, without raw Gateway diagnostics. +/// +/// Resolve ResourceKey(result.ErrorKind, result.RollbackIncomplete) through native localization; +/// a null result leaves non-personal error presentation with its existing owner. +/// +internal static class GatewayPersonalErrorPresentation +{ + /// Returns the recovery resource for a personal failure, or null for other error kinds. + public static string? ResourceKey(GatewayErrorKind? kind, bool rollbackIncomplete = false) + { + if (kind is not (GatewayErrorKind.PersonalIdentityUnverified or GatewayErrorKind.PersonalIdentityReverificationRequired)) + return null; + if (rollbackIncomplete) + return "ConnectionPage_PersonalIdentityRecoveryIncomplete"; + return kind == GatewayErrorKind.PersonalIdentityUnverified + ? "ConnectionPage_PersonalIdentityUnverified" + : "ConnectionPage_PersonalIdentityReverificationRequired"; + } +} diff --git a/src/OpenClaw.Tray.WinUI/Helpers/PersonalDashboardWindowReusePolicy.cs b/src/OpenClaw.Tray.WinUI/Helpers/PersonalDashboardWindowReusePolicy.cs new file mode 100644 index 0000000000..ec20e562ad --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Helpers/PersonalDashboardWindowReusePolicy.cs @@ -0,0 +1,16 @@ +using OpenClaw.Connection; + +namespace OpenClawTray.Helpers; + +internal static class PersonalDashboardWindowReusePolicy +{ + internal static bool CanReuse( + PersonalOperatorLease? currentLease, + PersonalOperatorLease windowLease, + PersonalOperatorLease requestedLease, + bool isClosed, + bool isRetired) => + !isClosed && !isRetired && + ReferenceEquals(currentLease, requestedLease) && + ReferenceEquals(windowLease, requestedLease); +} diff --git a/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayAuthChallenge.cs b/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayAuthChallenge.cs new file mode 100644 index 0000000000..55247d24c8 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayAuthChallenge.cs @@ -0,0 +1,78 @@ +using System.Text; +using System.Text.Json; +using OpenClaw.Connection; + +namespace OpenClawTray.Helpers; + +/// A nonce challenge received from the trusted personal Gateway Dashboard. +/// The request identifier to correlate with the Dashboard reply. +/// The Gateway-issued nonce included in the signed response. +/// The Gateway-issued Unix timestamp, in milliseconds. +public sealed record PersonalGatewayAuthChallenge(string Id, string Nonce, long SignedAt); + +/// Validates and parses Dashboard challenges for the current personal Gateway route. +public static class PersonalGatewayAuthChallengeParser +{ + /// Parses a challenge only when its source belongs to the expected Gateway Dashboard. + /// The serialized message received from the Dashboard. + /// The sending document URL reported by the native host. + /// The Gateway route whose identity is being verified. + /// The parsed challenge, or when rejected. + /// only for a well-formed challenge from the expected trusted route. + public static bool TryParse( + string messageJson, + string sourceUrl, + string expectedGatewayUrl, + out PersonalGatewayAuthChallenge? challenge) + { + challenge = null; + if (!GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource(sourceUrl, expectedGatewayUrl)) + return false; + + try + { + using var outer = JsonDocument.Parse(messageJson); + var body = outer.RootElement; + if (body.ValueKind == JsonValueKind.String) + { + using var inner = JsonDocument.Parse(body.GetString() ?? string.Empty); + return TryReadChallenge(inner.RootElement, out challenge); + } + + return TryReadChallenge(body, out challenge); + } + catch (JsonException) + { + return false; + } + } + + private static bool TryReadChallenge(JsonElement body, out PersonalGatewayAuthChallenge? challenge) + { + challenge = null; + if (body.ValueKind != JsonValueKind.Object || body.EnumerateObject().Count() != 3 || + !body.TryGetProperty("id", out var id) || id.ValueKind != JsonValueKind.String || + !body.TryGetProperty("nonce", out var nonce) || nonce.ValueKind != JsonValueKind.String || + !body.TryGetProperty("signedAt", out var signedAt) || + signedAt.ValueKind != JsonValueKind.Number || + !signedAt.TryGetInt64(out var signedAtMs)) + { + return false; + } + + var idValue = id.GetString() ?? string.Empty; + var nonceValue = nonce.GetString() ?? string.Empty; + if (string.IsNullOrWhiteSpace(idValue) || Encoding.UTF8.GetByteCount(idValue) > 128 || + string.IsNullOrWhiteSpace(nonceValue) || Encoding.UTF8.GetByteCount(nonceValue) > 512 || + nonceValue.Contains('|') || + nonceValue.Any(character => char.IsControl(character) || character == '\uFEFF') || + !nonceValue.Any(character => !char.IsWhiteSpace(character)) || + signedAtMs <= 0 || signedAtMs > 9_007_199_254_740_991) + { + return false; + } + + challenge = new PersonalGatewayAuthChallenge(idValue, nonceValue, signedAtMs); + return true; + } +} diff --git a/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayNativeBridgeScript.cs b/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayNativeBridgeScript.cs new file mode 100644 index 0000000000..94e6a11d04 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Helpers/PersonalGatewayNativeBridgeScript.cs @@ -0,0 +1,37 @@ +using System.Text.Json; + +namespace OpenClawTray.Helpers; + +internal static class PersonalGatewayNativeBridgeScript +{ + private const string BridgeScript = """ + (() => { + if (!window.chrome?.webview) return; + const bridge = window.OpenClawNativeGatewayAuth || {}; + bridge.postMessage = (message) => window.chrome.webview.postMessage( + typeof message === "string" ? message : JSON.stringify(message)); + bridge.onmessage = bridge.onmessage || null; + Object.defineProperty(window, "OpenClawNativeGatewayAuth", { + configurable: true, value: bridge + }); + window.chrome.webview.addEventListener("message", (event) => { + const handler = window.OpenClawNativeGatewayAuth; + if (typeof handler?.onmessage === "function") { + handler.onmessage({ data: typeof event.data === "string" + ? event.data : JSON.stringify(event.data) }); + } + }); + })(); + """; + + internal static string Create(string gatewayUrl) + { + var nativeControlAuth = JsonSerializer.Serialize(new + { + gatewayUrl, + nativeConnectAuth = true + }); + + return $"window.__OPENCLAW_NATIVE_CONTROL_AUTH__ = {nativeControlAuth};\n{BridgeScript}"; + } +} diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml index eda5193fee..43c0f8fd16 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml @@ -1008,6 +1008,15 @@ TextChanged="OnDirectInputChanged" LostFocus="OnDirectUrlLostFocus" AutomationProperties.AutomationId="AddDirectUrl"/> + + + + + @@ -2932,7 +2952,8 @@ private async Task DoDirectConnectFromAddFormAsync() if (_gatewayDirectConnectService is null) return; var url = DirectUrlBox.Text?.Trim(); - var token = DirectTokenBox.Text?.Trim(); + var personal = DirectOperatorAuthentication.SelectedIndex == 1; + var token = personal ? null : DirectTokenBox.Text?.Trim(); var friendly = DirectNameBox.Text?.Trim(); if (string.IsNullOrWhiteSpace(url)) { @@ -2940,6 +2961,11 @@ private async Task DoDirectConnectFromAddFormAsync() return; } + if (personal && !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(url, out _, out _)) + { + AddResultText.Text = LocalizationHelper.GetString("ConnectionPage_PersonalRouteRequired"); + return; + } url = GatewayUrlHelper.NormalizeForWebSocket(url); if (!TryBuildAddSshTunnelConfig(out var sshConfig, out var sshError)) @@ -2948,6 +2974,11 @@ private async Task DoDirectConnectFromAddFormAsync() return; } + if (personal && sshConfig is not null) + { + AddResultText.Text = LocalizationHelper.GetString("ConnectionPage_PersonalRouteRequired"); + return; + } AddSaveButton.IsEnabled = false; AddResultText.Text = sshConfig is null ? LocalizationHelper.GetString("ConnectionPage_Connecting") @@ -2976,17 +3007,20 @@ private async Task DoDirectConnectFromAddFormAsync() friendly, sshConfig, _editingGatewayId, - PreserveExistingSharedTokenWhenMissing: true) + PreserveExistingSharedTokenWhenMissing: true, + OperatorAuthentication: personal ? OperatorAuthenticationMode.PersonalTailscale : OperatorAuthenticationMode.GatewayCredential) : new GatewayDirectConnectRequest( url, submittedToken, friendly, sshConfig, _editingGatewayId, - PreserveExistingSharedTokenWhenMissing: false)); + PreserveExistingSharedTokenWhenMissing: personal, + OperatorAuthentication: personal ? OperatorAuthenticationMode.PersonalTailscale : OperatorAuthenticationMode.GatewayCredential)); if (result.Outcome == GatewayDirectConnectOutcome.Failed) { - AddResultText.Text = $"✗ {result.Error}"; + var errorKey = GatewayPersonalErrorPresentation.ResourceKey(result.ErrorKind, result.RollbackIncomplete); + AddResultText.Text = $"✗ {(errorKey is null ? result.Error : LocalizationHelper.GetString(errorKey))}"; return; } diff --git a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPagePlan.cs b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPagePlan.cs index c7ffa2c67d..b1b6dea139 100644 --- a/src/OpenClaw.Tray.WinUI/Pages/ConnectionPagePlan.cs +++ b/src/OpenClaw.Tray.WinUI/Pages/ConnectionPagePlan.cs @@ -123,6 +123,7 @@ internal enum RecoveryCategory LocalPortConflict, /// The Gateway and Windows app do not share a supported wire protocol. ProtocolMismatch, + PersonalIdentity, } /// @@ -247,6 +248,25 @@ private static ConnectionPagePlan BuildDerived( if (snap.ProtocolCompatibility.IsMismatch) return BuildProtocolMismatchRecovery(snap, activeRecord, displayName); + if (snap.OperatorState == RoleConnectionState.Error && + OpenClawTray.Helpers.GatewayPersonalErrorPresentation.ResourceKey(snap.OperatorErrorKind) is { } personalErrorKey) + { + return new ConnectionPagePlan + { + Mode = ConnectionPageMode.Recovery, + Recovery = RecoveryCategory.PersonalIdentity, + StripGlyph = OpenClawTray.Helpers.FluentIconCatalog.StatusErr, + StripAccent = ConnectionAccent.Critical, + StripHeadlineResourceKey = "ConnectionPage_PersonalIdentityHeader", + StripSubResourceKey = personalErrorKey, + RecoveryHeaderResourceKey = "ConnectionPage_PersonalIdentityHeader", + RecoveryBulletResourceKeys = [personalErrorKey], + ActiveGatewayDisplayName = displayName, + ActiveGatewayDetailLine = ConnectionCardPlanSanitizer.SanitizeGatewayUrl(activeRecord?.Url ?? snap.GatewayUrl), + RelevantGatewayId = activeRecord?.Id, + }; + } + // ─── Derived layout ─── return snap.OverallState switch { diff --git a/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs index 83171b7945..58b651efe5 100644 --- a/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs +++ b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs @@ -12,13 +12,22 @@ internal sealed class GatewayDashboardLauncher( Func resolveCredential, Func> launchBrowser, Action reportFailure, - Action? reportOpened = null) + Action? reportOpened = null, + Func? isPersonalMode = null, + Func>? openPersonalDashboard = null) { internal const string FailureNotificationId = "setup-dashboard-launch"; public async Task OpenAsync(string? path = null, Action? authorizeDispatch = null) { try { + if (isPersonalMode?.Invoke() == true) + { + if (openPersonalDashboard is null || !await openPersonalDashboard(path)) + throw new InvalidOperationException("Personal Gateway identity is unavailable."); + reportOpened?.Invoke(); + return true; + } if (!ensureTunnel()) throw new InvalidOperationException("The Gateway tunnel is unavailable."); var credential = resolveCredential() diff --git a/src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs b/src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs index ee21d91d6e..0011ad5055 100644 --- a/src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs +++ b/src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs @@ -18,7 +18,8 @@ internal sealed record GatewayDirectConnectRequest( string? EditingGatewayId = null, bool PreserveExistingSharedTokenWhenMissing = false, string? BootstrapToken = null, - bool NativeSetup = false); + bool NativeSetup = false, + OperatorAuthenticationMode OperatorAuthentication = OperatorAuthenticationMode.GatewayCredential); internal sealed record GatewayDirectConnectResult( GatewayDirectConnectOutcome Outcome, @@ -26,7 +27,8 @@ internal sealed record GatewayDirectConnectResult( bool GatewayCommitted, string? Error = null, bool RollbackIncomplete = false, - string? EndpointBinding = null); + string? EndpointBinding = null, + GatewayErrorKind? ErrorKind = null); /// /// Owns the direct-connect commit/rollback workflow. WinUI surfaces provide input and render the @@ -71,6 +73,14 @@ public async Task ConnectAsync( CancellationToken cancellationToken = default, GatewayValidationIdentity? preparedIdentity = null) { + if (!Enum.IsDefined(request.OperatorAuthentication) || + request.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale && + (request.NativeSetup || request.SshTunnel is not null || + !string.IsNullOrWhiteSpace(request.SharedToken) || !string.IsNullOrWhiteSpace(request.BootstrapToken) || + !GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(request.GatewayUrl, out _, out _))) + return Failed(GatewayConnectionSnapshot.Idle, false, + "Personal Tailscale authentication requires a direct credential-free wss:// host.ts.net route."); + if (!GatewayUrlHelper.IsValidGatewayUrl(request.GatewayUrl)) { return Failed( @@ -113,6 +123,7 @@ previousActiveId is not null && var settingsMutated = false; var connectionAttemptStarted = false; var previousConnectionStopped = false; + GatewayErrorKind? connectionFailureKind = null; DeviceIdentityReplacementTransaction? candidateIdentityCreation = null; GatewayValidationIdentity? validationIdentity = null; DeviceIdentityReplacementTransaction? nativeIdentityRollback = null; @@ -180,6 +191,7 @@ existing is not null && !replacesCredentialRealm cancellationToken.ThrowIfCancellationRequested(); if (snapshot.OperatorState == RoleConnectionState.Error) { + connectionFailureKind = snapshot.OperatorErrorKind; throw new InvalidOperationException( snapshot.OperatorError ?? snapshot.NodeError ?? @@ -287,7 +299,8 @@ existing is not null && !replacesCredentialRealm error, rollbackIncomplete: !string.IsNullOrWhiteSpace(cleanupError) || !string.IsNullOrWhiteSpace(rollback.Error) || - !string.IsNullOrWhiteSpace(connectionRestoreError)); + !string.IsNullOrWhiteSpace(connectionRestoreError), + errorKind: connectionFailureKind); } finally { @@ -373,6 +386,7 @@ internal static GatewayRecord BuildCandidate( { Id = recordId, Url = request.GatewayUrl, + OperatorAuthentication = request.OperatorAuthentication, FriendlyName = string.IsNullOrWhiteSpace(request.FriendlyName) ? existing?.FriendlyName : request.FriendlyName, @@ -718,13 +732,15 @@ private static GatewayDirectConnectResult Failed( GatewayConnectionSnapshot snapshot, bool gatewayCommitted, string error, - bool rollbackIncomplete = false) => + bool rollbackIncomplete = false, + GatewayErrorKind? errorKind = null) => new( GatewayDirectConnectOutcome.Failed, snapshot, gatewayCommitted, error, - rollbackIncomplete); + rollbackIncomplete, + ErrorKind: errorKind); private sealed record ConnectionSettingsSnapshot( string GatewayUrl, diff --git a/src/OpenClaw.Tray.WinUI/Services/IAppCommands.cs b/src/OpenClaw.Tray.WinUI/Services/IAppCommands.cs index f7fb91cb21..607dcf2d97 100644 --- a/src/OpenClaw.Tray.WinUI/Services/IAppCommands.cs +++ b/src/OpenClaw.Tray.WinUI/Services/IAppCommands.cs @@ -19,8 +19,8 @@ internal interface IAppCommands { /// Opens the dashboard, optionally at a supplied path. void OpenDashboard(string? path = null); - /// Returns whether Windows accepted the Dashboard browser launch, not whether the page loaded. - Task TryOpenDashboardAsync(string? path = null); + /// Returns native personal admission or accepted browser launch, not page readiness. + Task TryOpenDashboardAsync(string? path = null, string? expectedPersonalGatewayId = null); /// Navigates the application shell to a page tag. void Navigate(string pageTag); /// diff --git a/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs b/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs index 87cd9bd1ac..f3c92100d2 100644 --- a/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs +++ b/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs @@ -23,6 +23,7 @@ internal interface IWindowManager Window? ActiveHubWindow { get; } bool IsHubOpen { get; } bool IsChatVisible { get; } + Task ShowPersonalDashboardAsync(string? path, string? expectedGatewayId = null) => Task.FromResult(false); bool HasVisibleMainWindow { get; } XamlRoot? DialogXamlRoot { get; } XamlRoot? RuntimeAnchorXamlRoot { get; } diff --git a/src/OpenClaw.Tray.WinUI/Services/WindowManager.PersonalDashboard.cs b/src/OpenClaw.Tray.WinUI/Services/WindowManager.PersonalDashboard.cs new file mode 100644 index 0000000000..3e05f14d83 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Services/WindowManager.PersonalDashboard.cs @@ -0,0 +1,52 @@ +using OpenClawTray.Windows; + +namespace OpenClawTray.Services; + +internal sealed partial class WindowManager +{ + private PersonalDashboardWindow? _personalDashboardWindow; + + public async Task ShowPersonalDashboardAsync(string? path = null, string? expectedGatewayId = null) + { + if (_isShuttingDown || !_dispatcherQueue.HasThreadAccess) + return false; + + var manager = _callbacks.GetConnectionManager(); + var lease = manager?.CurrentPersonalOperatorLease; + if (manager is null || lease is null || + (expectedGatewayId is not null && lease.GatewayId != expectedGatewayId)) + return false; + + if (_personalDashboardWindow is not null && !_personalDashboardWindow.CanReuseFor(lease)) + { + var retiring = _personalDashboardWindow; + await retiring.CloseAsync(); + if (ReferenceEquals(_personalDashboardWindow, retiring)) + _personalDashboardWindow = null; + if (_isShuttingDown || !ReferenceEquals(lease, manager.CurrentPersonalOperatorLease)) + return false; + } + + if (_personalDashboardWindow is not null && !_personalDashboardWindow.CanReuseFor(lease)) + return false; + + if (_personalDashboardWindow is null) + { + var window = new PersonalDashboardWindow(manager, lease, path); + _personalDashboardWindow = window; + window.Closed += (_, _) => + { + if (ReferenceEquals(_personalDashboardWindow, window)) + _personalDashboardWindow = null; + }; + _callbacks.ApplyTheme(window); + } + else + { + _personalDashboardWindow.NavigateToPath(path); + } + + _personalDashboardWindow.Activate(); + return true; + } +} diff --git a/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs b/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs index b59204e305..5cd5bc2b35 100644 --- a/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs +++ b/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs @@ -55,7 +55,7 @@ internal sealed record WindowManagerCallbacks( /// Coordinates every application-owned window and transitions between workspace, onboarding and setup UI. /// Callers interact through so this class retains lifetime ownership. /// -internal sealed class WindowManager : IWindowManager +internal sealed partial class WindowManager : IWindowManager { private const string ShuttingDownMessage = "The application is shutting down."; @@ -1088,6 +1088,7 @@ public void ApplyThemeToOpenWindows() _callbacks.ApplyTheme(_setupWindow); _callbacks.ApplyTheme(_readyWindow); _callbacks.ApplyTheme(_restartProgressWindow); + _callbacks.ApplyTheme(_personalDashboardWindow); } public void UpdateHubTitleBarStatus( @@ -1145,6 +1146,15 @@ public Task CloseForShutdownAsync() private async Task CloseOwnedWindowsAsync() { List? failures = null; + if (_personalDashboardWindow is { } personalDashboard) + { + try { await personalDashboard.CloseAsync(); } + catch (Exception ex) + { + (failures ??= []).Add(new InvalidOperationException("Personal Dashboard shutdown failed.", ex)); + } + _personalDashboardWindow = null; + } if (_workspaceWindow is not null) { diff --git a/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw index dcdbaad847..cf536f4413 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw @@ -10325,4 +10325,16 @@ After enrolling, return to Settings > Windows Update and check for updates. I Follow delegated work from this conversation. Widgets and tabs this session published. No panels are available for this conversation yet. + Operator authentication + Gateway credential + Personal Tailscale identity + Requires a secure Tailscale Gateway address and personal identity support on the Gateway. No shared token is sent. + Personal sign-in changed + Reconnect this Gateway in OpenClaw Companion, then reopen the Dashboard. + Personal sign-in is unavailable. Reconnect in the app. + Personal sign-in requires a secure wss:// Tailscale Gateway address ending in .ts.net, without an SSH tunnel. + Personal sign-in unavailable + Your Tailscale identity could not be verified. Reconnect this Gateway. Shared credentials will not be used. + Your Tailscale identity needs to be verified again. Reconnect this Gateway. Shared credentials will not be used. + Personal sign-in failed, and recovery did not complete. Review Connection settings before retrying. diff --git a/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw index 460d6edcf8..644d70e94b 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw @@ -10254,4 +10254,16 @@ Après votre inscription, revenez dans Paramètres > Windows Update et recher Suivez le travail délégué depuis cette conversation. Widgets et onglets publiés par cette session. Aucun panneau n'est encore disponible pour cette conversation. + Authentification de l’opérateur + Identifiant de la passerelle + Identité Tailscale personnelle + Nécessite une adresse Tailscale sécurisée et la prise en charge de l’identité personnelle par la passerelle. Aucun jeton partagé n’est envoyé. + La connexion personnelle a changé + Reconnectez cette passerelle dans OpenClaw Companion, puis rouvrez le tableau de bord. + La connexion personnelle est indisponible. Reconnectez-vous dans l’application. + La connexion personnelle nécessite une adresse Gateway Tailscale sécurisée en wss:// se terminant par .ts.net, sans tunnel SSH. + Connexion personnelle indisponible + Votre identité Tailscale n’a pas pu être vérifiée. Reconnectez cette passerelle. Les identifiants partagés ne seront pas utilisés. + Votre identité Tailscale doit être vérifiée à nouveau. Reconnectez cette passerelle. Les identifiants partagés ne seront pas utilisés. + La connexion personnelle a échoué et la récupération n’a pas abouti. Vérifiez les paramètres de connexion avant de réessayer. diff --git a/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw index eb0df6713f..ba2a19d08c 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw @@ -10255,4 +10255,16 @@ Ga na inschrijving terug naar Instellingen > Windows Update en controleer op Volg gedelegeerd werk vanuit dit gesprek. Widgets en tabbladen die deze sessie heeft gepubliceerd. Er zijn nog geen panelen beschikbaar voor dit gesprek. + Operatorverificatie + Gatewayreferentie + Persoonlijke Tailscale-identiteit + Vereist een beveiligd Tailscale Gateway-adres en ondersteuning voor persoonlijke identiteit op de Gateway. Er wordt geen gedeeld token verzonden. + Persoonlijke aanmelding gewijzigd + Verbind deze Gateway opnieuw in OpenClaw Companion en open daarna het dashboard opnieuw. + Persoonlijke aanmelding is niet beschikbaar. Verbind opnieuw in de app. + Persoonlijke aanmelding vereist een beveiligd wss:// Tailscale Gateway-adres dat eindigt op .ts.net, zonder SSH-tunnel. + Persoonlijk aanmelden niet beschikbaar + Je Tailscale-identiteit kon niet worden geverifieerd. Maak opnieuw verbinding met deze Gateway. Gedeelde inloggegevens worden niet gebruikt. + Je Tailscale-identiteit moet opnieuw worden geverifieerd. Maak opnieuw verbinding met deze Gateway. Gedeelde inloggegevens worden niet gebruikt. + Persoonlijk aanmelden is mislukt en het herstel is niet voltooid. Controleer de verbindingsinstellingen voordat je het opnieuw probeert. diff --git a/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw index 7bea878790..6407730212 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw @@ -10307,4 +10307,16 @@ Após a inscrição, volte para Configurações > Windows Update e verifique Acompanhe o trabalho delegado desta conversa. Widgets e guias publicados por esta sessão. Ainda não há painéis disponíveis para esta conversa. + Autenticação do operador + Credencial do Gateway + Identidade pessoal Tailscale + Requer um endereço Tailscale seguro e suporte à identidade pessoal no Gateway. Nenhum token compartilhado é enviado. + O acesso pessoal mudou + Reconecte este Gateway no OpenClaw Companion e reabra o painel. + O acesso pessoal está indisponível. Reconecte no aplicativo. + O acesso pessoal requer um endereço seguro wss:// do Gateway Tailscale terminado em .ts.net, sem túnel SSH. + Login pessoal indisponível + Não foi possível verificar sua identidade do Tailscale. Reconecte este Gateway. As credenciais compartilhadas não serão usadas. + Sua identidade do Tailscale precisa ser verificada novamente. Reconecte este Gateway. As credenciais compartilhadas não serão usadas. + O login pessoal falhou e a recuperação não foi concluída. Revise as configurações de Conexão antes de tentar novamente. diff --git a/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw index 28acaf22bd..446c76fcff 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw @@ -10254,4 +10254,16 @@ 跟踪此对话中委派的工作。 此会话发布的小组件和选项卡。 此对话暂无可用的面板。 + 操作员身份验证 + 网关凭据 + 个人 Tailscale 身份 + 需要安全的 Tailscale 网关地址,且网关支持个人身份。不会发送共享令牌。 + 个人登录已更改 + 请在 OpenClaw Companion 中重新连接此网关,然后重新打开仪表板。 + 个人登录不可用。请在应用中重新连接。 + 个人登录需要以 .ts.net 结尾的安全 wss:// Tailscale Gateway 地址,且不能使用 SSH 隧道。 + 个人登录不可用 + 无法验证你的 Tailscale 身份。请重新连接此网关。不会使用共享凭据。 + 需要重新验证你的 Tailscale 身份。请重新连接此网关。不会使用共享凭据。 + 个人登录失败,且恢复未完成。请先检查“连接”设置,然后重试。 diff --git a/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw index a55818141a..906445c914 100644 --- a/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw +++ b/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw @@ -10254,4 +10254,16 @@ 追蹤此對話中委派的工作。 此工作階段發布的小工具和索引標籤。 此對話尚無可用的面板。 + 操作員身分驗證 + 閘道憑證 + 個人 Tailscale 身分 + 需要安全的 Tailscale 閘道位址,且閘道支援個人身分。不會傳送共用權杖。 + 個人登入已變更 + 請在 OpenClaw Companion 中重新連線此閘道,然後重新開啟儀表板。 + 個人登入無法使用。請在應用程式中重新連線。 + 個人登入需要以 .ts.net 結尾的安全 wss:// Tailscale Gateway 位址,且不能使用 SSH 通道。 + 個人登入無法使用 + 無法驗證你的 Tailscale 身分。請重新連線至此閘道。不會使用共用認證。 + 需要重新驗證你的 Tailscale 身分。請重新連線至此閘道。不會使用共用認證。 + 個人登入失敗,且復原未完成。請先檢查「連線」設定,再重試。 diff --git a/src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs b/src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs index 095cf01d31..c4a0bf4b33 100644 --- a/src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs +++ b/src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs @@ -115,7 +115,10 @@ private void OnManagerStateChanged(object? sender, GatewayConnectionSnapshot sna else if (snapshot.OverallState == OverallConnectionState.Error) { ConnectButton.Content = LocalizationHelper.GetString("ConnectionStatus_Connect"); - var errorText = $"✗ {snapshot.OperatorError ?? snapshot.NodeError ?? LocalizationHelper.GetString("ConnectionPage_GatewayConnectionFailed")}"; + var personalErrorKey = GatewayPersonalErrorPresentation.ResourceKey(snapshot.OperatorErrorKind); + var errorText = $"✗ {(personalErrorKey is null + ? snapshot.OperatorError ?? snapshot.NodeError ?? LocalizationHelper.GetString("ConnectionPage_GatewayConnectionFailed") + : LocalizationHelper.GetString(personalErrorKey))}"; SetupCodeResult.Text = errorText; DirectConnectResult.Text = errorText; } @@ -170,10 +173,12 @@ private void RefreshStateMachine(GatewayConnectionSnapshot snapshot) var elapsed = DateTime.Now - _lastStateChangeTime; var elapsedStr = elapsed.TotalSeconds < 60 ? $"{elapsed.TotalSeconds:F0}s" : $"{elapsed.TotalMinutes:F0}m"; + var personalErrorKey = GatewayPersonalErrorPresentation.ResourceKey(snapshot.OperatorErrorKind); + var operatorError = personalErrorKey is null ? snapshot.OperatorError : LocalizationHelper.GetString(personalErrorKey); OpDetailText.Text = snapshot.OperatorState switch { RoleConnectionState.Connected => $"✓ {elapsedStr} device={snapshot.OperatorDeviceId ?? "—"}", - RoleConnectionState.Error => $"✗ {elapsedStr}: {snapshot.OperatorError ?? "unknown"}", + RoleConnectionState.Error => $"✗ {elapsedStr}: {operatorError ?? "unknown"}", RoleConnectionState.PairingRequired => $"⏳ {LocalizationHelper.GetString("ConnectionStatus_AwaitingApproval")}", _ => elapsedStr }; @@ -463,7 +468,8 @@ private async Task OnDirectConnectAsync() if (result.Outcome == GatewayDirectConnectOutcome.Failed) { InvalidatePendingStatusMessages(); - DirectConnectResult.Text = $"✗ {result.Error}"; + var errorKey = GatewayPersonalErrorPresentation.ResourceKey(result.ErrorKind, result.RollbackIncomplete); + DirectConnectResult.Text = $"✗ {(errorKey is null ? result.Error : LocalizationHelper.GetString(errorKey))}"; return; } diff --git a/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml b/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml new file mode 100644 index 0000000000..adb8bbff83 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml.cs b/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml.cs new file mode 100644 index 0000000000..8a1cffbec7 --- /dev/null +++ b/src/OpenClaw.Tray.WinUI/Windows/PersonalDashboardWindow.xaml.cs @@ -0,0 +1,374 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Windowing; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml.Controls; +using Microsoft.Web.WebView2.Core; +using System.Collections.Concurrent; +using System.Text.Json; +using OpenClaw.Connection; +using OpenClaw.Shared; +using OpenClawTray.Helpers; + +namespace OpenClawTray.Windows; + +public sealed partial class PersonalDashboardWindow : Window +{ + private static string UnavailableMessage => LocalizationHelper.GetString("PersonalDashboard_Unavailable"); + private readonly IGatewayConnectionManager _manager; + private readonly PersonalOperatorLease _initialLease; + private readonly string _expectedGatewayUrl; + private readonly ConcurrentDictionary _activeRequestIds = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _seenNonces = new(StringComparer.Ordinal); + private readonly string _profileName = "personal-" + Guid.NewGuid().ToString("N"); + private CoreWebView2Profile? _ownedProfile; + private CoreWebView2? _bridgeCore; + private bool _browserClosed; + private Task? _browserRetirementTask; + private Task? _closeTask; + private bool _profileDeletionRequested; + private bool _allowNativeClose; + private bool _retired; + private bool _closed; + private bool _initialized; + private long _navigationGeneration; + private string? _path; + + public PersonalDashboardWindow( + IGatewayConnectionManager manager, + PersonalOperatorLease lease, + string? path = null) + { + _manager = manager ?? throw new ArgumentNullException(nameof(manager)); + _initialLease = lease ?? throw new ArgumentNullException(nameof(lease)); + _expectedGatewayUrl = lease.GatewayUrl; + _path = path; + InitializeComponent(); + DashboardWebView.CoreWebView2Initialized += OnCoreInitialized; + _manager.StateChanged += OnManagerStateChanged; + AppWindow.Closing += OnClosing; + Closed += OnClosed; + _ = InitializeWebViewAsync(path); + } + + private async Task InitializeWebViewAsync(string? path) + { + try + { + var environment = await CoreWebView2Environment.CreateWithOptionsAsync(null, + System.IO.Path.Combine(AppIdentity.ResolveLocalDataDirectory(), "PersonalDashboard"), null); + if (_closed || _retired) + { + await CloseOwnedBrowserAsync(); + return; + } + var options = environment.CreateCoreWebView2ControllerOptions(); + options.ProfileName = _profileName; + options.IsInPrivateModeEnabled = true; + await DashboardWebView.EnsureCoreWebView2Async(environment, options); + var core = DashboardWebView.CoreWebView2; + if (core is null) + { + if (_closed || _retired) return; + throw new InvalidOperationException("Personal browser initialization is unavailable."); + } + var profile = core.Profile; + if (!string.Equals(profile.ProfileName, _profileName, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("Personal browser profile ownership changed."); + _ownedProfile = profile; + if (_closed || _retired) + { + await CloseOwnedBrowserAsync(); + return; + } + + core.Settings.IsStatusBarEnabled = false; + core.Settings.IsPasswordAutosaveEnabled = false; + core.Settings.IsGeneralAutofillEnabled = false; + core.Settings.AreDefaultContextMenusEnabled = true; + core.NavigationStarting += OnNavigationStarting; + core.NewWindowRequested += OnNewWindowRequested; + _bridgeCore = core; + core.WebMessageReceived += (_, args) => OnWebMessageReceived(core, args); + await core.AddScriptToExecuteOnDocumentCreatedAsync( + PersonalGatewayNativeBridgeScript.Create(_expectedGatewayUrl)); + _initialized = true; + + var lease = _manager.CurrentPersonalOperatorLease; + if (!ReferenceEquals(lease, _initialLease)) + { + RetireForAuthorityChange(); + return; + } + + NavigateToPath(_path); + } + catch (Exception ex) + { + new OpenClawTray.AppLogger().Warn($"Personal browser initialization failed ({ex.GetType().Name}, 0x{ex.HResult:X8})."); + _retired = true; + await CloseOwnedBrowserAsync(); + if (!_closed) ShowRecoveryPanel(); + } + } + + private void OnCoreInitialized(WebView2 sender, CoreWebView2InitializedEventArgs args) + { + try + { + var profile = sender.CoreWebView2?.Profile; + if (profile is not null && string.Equals(profile.ProfileName, _profileName, StringComparison.OrdinalIgnoreCase)) + { + _ownedProfile = profile; + if (_closed || _retired) _ = CloseOwnedBrowserAsync(); + } + } + catch (System.Runtime.InteropServices.COMException) + { + if (!_closed && !_retired) + new OpenClawTray.AppLogger().Warn("Personal browser profile ownership could not be captured."); + } + } + + public void NavigateToPath(string? path) + { + _path = path; + if (!_initialized || _retired || DashboardWebView.CoreWebView2 is null || + !ReferenceEquals(_manager.CurrentPersonalOperatorLease, _initialLease)) + { + return; + } + + var url = GatewayDashboardUrlBuilder.Build( + _expectedGatewayUrl, path, null, appendSharedGatewayToken: false); + DashboardWebView.CoreWebView2.Navigate(url); + } + + internal bool CanReuseFor(PersonalOperatorLease lease) => + PersonalDashboardWindowReusePolicy.CanReuse( + _manager.CurrentPersonalOperatorLease, _initialLease, lease, _closed, _retired); + + private void OnNavigationStarting(CoreWebView2 sender, CoreWebView2NavigationStartingEventArgs args) + { + _navigationGeneration++; + if (!GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource(args.Uri, _expectedGatewayUrl) && + !string.Equals(args.Uri, "about:blank", StringComparison.OrdinalIgnoreCase)) + args.Cancel = true; + } + + private static void OnNewWindowRequested(CoreWebView2 sender, CoreWebView2NewWindowRequestedEventArgs args) => + args.Handled = true; + + private void OnWebMessageReceived(CoreWebView2 sender, CoreWebView2WebMessageReceivedEventArgs args) => + AsyncEventHandlerGuard.Run( + () => OnWebMessageReceivedAsync(sender, args), + new OpenClawTray.AppLogger(), + nameof(OnWebMessageReceived)); + + private async Task OnWebMessageReceivedAsync(CoreWebView2 sender, CoreWebView2WebMessageReceivedEventArgs args) + { + if (_closed || _retired || !ReferenceEquals(sender, _bridgeCore) || !PersonalGatewayAuthChallengeParser.TryParse( + args.WebMessageAsJson, args.Source, _expectedGatewayUrl, out var challenge) || + challenge == null) + { + return; + } + + if (!_activeRequestIds.TryAdd(challenge.Id, 0)) + { + ReplyError(sender, challenge.Id); + return; + } + + if (!TryRegisterNonce(challenge.Nonce, challenge.SignedAt)) + { + _activeRequestIds.TryRemove(challenge.Id, out _); + ReplyError(sender, challenge.Id); + return; + } + + var navigationGeneration = _navigationGeneration; + try + { + var lease = _manager.CurrentPersonalOperatorLease; + if (!ReferenceEquals(lease, _initialLease)) + { + ReplyError(sender, challenge.Id); + RetireForAuthorityChange(); + return; + } + + var responseJson = await _manager.CreatePersonalBrowserAuthResponseAsync( + challenge.Nonce, challenge.SignedAt); + if (responseJson == null || _closed || _retired || navigationGeneration != _navigationGeneration || + !ReferenceEquals(sender, _bridgeCore) || + !GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource(sender.Source, _expectedGatewayUrl) || + !ReferenceEquals(_manager.CurrentPersonalOperatorLease, _initialLease)) + { + if (!_closed && !_retired && navigationGeneration == _navigationGeneration) + ReplyError(sender, challenge.Id); + return; + } + + using var response = JsonDocument.Parse(responseJson); + sender.PostWebMessageAsJson(JsonSerializer.Serialize(new + { + id = challenge.Id, + result = response.RootElement + })); + } + catch + { + if (!_closed && !_retired && navigationGeneration == _navigationGeneration) + ReplyError(sender, challenge.Id); + } + finally + { + _activeRequestIds.TryRemove(challenge.Id, out _); + } + } + + private bool TryRegisterNonce(string nonce, long signedAt) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + foreach (var entry in _seenNonces) + { + if (entry.Value < now - 300_000) + _seenNonces.TryRemove(entry.Key, out _); + } + + if (_seenNonces.Count >= 1024 || Math.Abs(now - signedAt) > 300_000) + return false; + return _seenNonces.TryAdd(nonce, signedAt); + } + + private static void ReplyError(CoreWebView2 core, string id) + { + try + { + core.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = UnavailableMessage })); + } + catch (Exception ex) + { + new OpenClawTray.AppLogger().Warn( + $"Personal Dashboard error reply was unavailable ({ex.GetType().Name}, 0x{ex.HResult:X8})."); + } + } + + private void OnManagerStateChanged(object? sender, GatewayConnectionSnapshot snapshot) + { + if (ReferenceEquals(_manager.CurrentPersonalOperatorLease, _initialLease)) + return; + DispatcherQueue?.TryEnqueue(RetireForAuthorityChange); + } + + private void RetireForAuthorityChange() => AsyncEventHandlerGuard.Run( + RetireAsync, new OpenClawTray.AppLogger(), nameof(RetireForAuthorityChange)); + + private async Task RetireAsync() + { + if (_retired) return; + _retired = true; + await CloseOwnedBrowserAsync(); + if (!_closed) ShowRecoveryPanel(); + } + + public new void Close() => AsyncEventHandlerGuard.Run( + CloseAsync, new OpenClawTray.AppLogger(), nameof(Close)); + + internal Task CloseAsync() => _closeTask ??= CloseCoreAsync(); + + private async Task CloseCoreAsync() + { + _retired = true; + try { await CloseOwnedBrowserAsync(); } + finally + { + _allowNativeClose = true; + base.Close(); + } + } + + private Task CloseOwnedBrowserAsync() + { + if (_ownedProfile is { } profile && !_profileDeletionRequested) + { + _profileDeletionRequested = true; + return _browserRetirementTask = DeleteProfileAndCloseAsync(profile); + } + if (_browserRetirementTask is not null) return _browserRetirementTask; + CloseBrowserControl(); + return Task.CompletedTask; + } + + private async Task DeleteProfileAndCloseAsync(CoreWebView2Profile profile) + { + var deleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + void OnDeleted(CoreWebView2Profile sender, object args) => deleted.TrySetResult(); + var subscribed = false; + try + { + if (!_initialized) await DrainDispatcherAsync(); + profile.Deleted += OnDeleted; + subscribed = true; + profile.Delete(); + await deleted.Task; + } + catch (System.Runtime.InteropServices.COMException) + { + new OpenClawTray.AppLogger().Warn("Personal browser profile cleanup was unavailable."); + } + finally + { + try + { + if (subscribed) profile.Deleted -= OnDeleted; + } + catch (System.Runtime.InteropServices.COMException) + { + } + finally + { + CloseBrowserControl(); + } + } + } + + private Task DrainDispatcherAsync() + { + var drained = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (!DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => drained.TrySetResult())) + drained.TrySetResult(); + return drained.Task; + } + + private void CloseBrowserControl() + { + if (_browserClosed) return; + _browserClosed = true; + _bridgeCore = null; + DashboardWebView.Close(); + } + + private void OnClosing(AppWindow sender, AppWindowClosingEventArgs args) + { + if (_allowNativeClose) return; + args.Cancel = true; + Close(); + } + + private void ShowRecoveryPanel() + { + DashboardWebView.Visibility = Visibility.Collapsed; + RecoveryPanel.Visibility = Visibility.Visible; + } + + private void OnClosed(object sender, WindowEventArgs args) + { + _closed = true; + _retired = true; + _manager.StateChanged -= OnManagerStateChanged; + AppWindow.Closing -= OnClosing; + _ = CloseOwnedBrowserAsync(); + } + +} diff --git a/tests/OpenClaw.Connection.Tests/CredentialResolverTests.cs b/tests/OpenClaw.Connection.Tests/CredentialResolverTests.cs index bfd708341c..211efa5756 100644 --- a/tests/OpenClaw.Connection.Tests/CredentialResolverTests.cs +++ b/tests/OpenClaw.Connection.Tests/CredentialResolverTests.cs @@ -13,6 +13,21 @@ public CredentialResolverTests() _resolver = new CredentialResolver(_mockReader); } + [Fact] + public void PersonalOperatorIgnoresStoredOperatorCredentialsAndPreservesNodeResolution() + { + var record = new GatewayRecord { Id = "personal", Url = "wss://fixture.example.ts.net", + OperatorAuthentication = OperatorAuthenticationMode.PersonalTailscale, + SharedGatewayToken = "shared", BootstrapToken = "bootstrap" }; + _mockReader.OperatorReadResult = DeviceTokenReadResult.Corrupt("must not be used"); + _mockReader.NodeToken = "node-token"; + var personal = Assert.IsType(_resolver.ResolveOperator(record, "/fixture")); + Assert.Empty(personal.Token); + Assert.Equal(OperatorAuthenticationMode.PersonalTailscale, personal.OperatorAuthentication); + Assert.Equal("node-token", _resolver.ResolveNode(record, "/fixture")!.Token); + Assert.Equal("shared", record.SharedGatewayToken); + } + // ─── Operator resolution ─── [Fact] diff --git a/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerPersonalIdentityTests.cs b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerPersonalIdentityTests.cs new file mode 100644 index 0000000000..783be800d0 --- /dev/null +++ b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerPersonalIdentityTests.cs @@ -0,0 +1,241 @@ +using System.Text.Json; +using OpenClaw.Shared; +using OpenClaw.TestSupport; + +namespace OpenClaw.Connection.Tests; + +public sealed class GatewayConnectionManagerPersonalIdentityTests +{ + [Fact] + public async Task PersonalConnectionPublishesOnlyAfterCurrentSocketSelfVerificationAndNeverUsesSavedToken() + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + var self = await peer.ReceiveAsync(); + Assert.Equal("users.self", self.GetProperty("method").GetString()); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + Assert.NotEqual(RoleConnectionState.Connected, harness.Manager.CurrentSnapshot.OperatorState); + await peer.SelfAsync(self); + await harness.WaitAsync(RoleConnectionState.Connected); + var lease = Assert.IsType(harness.Manager.CurrentPersonalOperatorLease); + Assert.Equal("person-42", lease.IdentityProfileId); + Assert.Equal("fixture-scope", lease.RecoveryScope); + var signing = harness.Manager.CreatePersonalBrowserAuthResponseAsync("browser-nonce", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + var refresh = await peer.ReceiveAsync(); + Assert.Equal("users.self", refresh.GetProperty("method").GetString()); + await peer.SelfAsync(refresh); + using var response = JsonDocument.Parse(Assert.IsType(await signing)); + Assert.Empty(response.RootElement.GetProperty("auth").EnumerateObject()); + Assert.Equal("tailscale", response.RootElement.GetProperty("requiredAuthMethod").GetString()); + Assert.Equal(lease.RecoveryScope, response.RootElement.GetProperty("expectedRecoveryScope").GetString()); + Assert.Equal(lease.DeviceId, response.RootElement.GetProperty("device").GetProperty("id").GetString()); + Assert.Equal("saved-shared", harness.Registry.GetById("personal")!.SharedGatewayToken); + await harness.Manager.DisconnectAsync(); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + } + + [Theory] + [InlineData(null)] + [InlineData("gateway-owner")] + public async Task MissingOrSharedOwnerSelfProfileRejectsPersonalConnection(string? profile) + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + var self = await peer.ReceiveAsync(); + await peer.SelfAsync(self, profile); + await harness.WaitAsync(RoleConnectionState.Error); + Assert.Equal(GatewayErrorKind.PersonalIdentityUnverified, harness.Manager.CurrentSnapshot.OperatorErrorKind); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + Assert.Null(harness.Manager.CurrentSnapshot.PersonalIdentityProfileId); + } + + [Theory] + [InlineData("gateway-owner")] + [InlineData("different-person")] + public async Task ProfileInvalidationWithholdsOldLeaseAndRejectsChangedPerson(string profile) + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + await peer.SelfAsync(await peer.ReceiveAsync()); + await harness.WaitAsync(RoleConnectionState.Connected); + await peer.ProfileChangedAsync(); + var self = await peer.ReceiveAsync(); + Assert.Equal("users.self", self.GetProperty("method").GetString()); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + await peer.SelfAsync(self, profile); + await harness.WaitAsync(RoleConnectionState.Error); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + Assert.Null(harness.Manager.CurrentSnapshot.PersonalIdentityProfileId); + } + + [Fact] + public async Task ProfileInvalidationReverifiesSamePersonBeforeReplacingLease() + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + await peer.SelfAsync(await peer.ReceiveAsync()); + await harness.WaitAsync(RoleConnectionState.Connected); + var previous = harness.Manager.CurrentPersonalOperatorLease; + var renewed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + harness.Manager.StateChanged += (_, _) => + { + if (harness.Manager.CurrentPersonalOperatorLease is { } lease && !ReferenceEquals(lease, previous)) + renewed.TrySetResult(lease); + }; + await peer.ProfileChangedAsync(); + var self = await peer.ReceiveAsync(); + Assert.Equal("users.self", self.GetProperty("method").GetString()); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + await peer.SelfAsync(self); + Assert.Equal("person-42", (await renewed.Task.WaitAsync(TimeSpan.FromSeconds(5))).IdentityProfileId); + } + + [Fact] + public async Task PendingIdentityReadDoesNotBlockDisconnectOrPublishAnOldLease() + { + await using var harness = new Harness(); + var first = await harness.HelloAsync(); + Assert.Equal("users.self", (await first.ReceiveAsync()).GetProperty("method").GetString()); + await harness.Manager.DisconnectAsync().WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + var second = await harness.HelloAsync(); + var self = await second.ReceiveAsync(); + await second.SelfAsync(self, "replacement-person"); + await harness.WaitAsync(RoleConnectionState.Connected); + Assert.Equal("replacement-person", harness.Manager.CurrentPersonalOperatorLease!.IdentityProfileId); + } + + [Fact] + public async Task BrowserProfileChangeRetiresOnlyItsCurrentPersonalConnection() + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + await peer.SelfAsync(await peer.ReceiveAsync()); + await harness.WaitAsync(RoleConnectionState.Connected); + var signing = harness.Manager.CreatePersonalBrowserAuthResponseAsync("browser-nonce", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + await peer.SelfAsync(await peer.ReceiveAsync(), "different-person"); + Assert.Null(await signing); + Assert.Null(harness.Manager.CurrentPersonalOperatorLease); + Assert.Equal(GatewayErrorKind.PersonalIdentityReverificationRequired, harness.Manager.CurrentSnapshot.OperatorErrorKind); + Assert.NotEqual(RoleConnectionState.Connected, harness.Manager.CurrentSnapshot.OperatorState); + } + + [Fact] + public async Task InvalidBrowserChallengesNeverProducePersonalProof() + { + await using var harness = new Harness(); + var peer = await harness.HelloAsync(); + await peer.SelfAsync(await peer.ReceiveAsync()); + await harness.WaitAsync(RoleConnectionState.Connected); + foreach (var nonce in new[] { "", "a|b", "a\n", "\uFEFFnonce", new string('é', 257) }) + Assert.Null(await harness.Manager.CreatePersonalBrowserAuthResponseAsync(nonce, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())); + Assert.Null(await harness.Manager.CreatePersonalBrowserAuthResponseAsync("expired", 1)); + Assert.NotNull(harness.Manager.CurrentPersonalOperatorLease); + } + + [Fact] + public async Task RetiredBrowserReadCannotRevokeReplacementLease() + { + await using var harness = new Harness(); + var first = await harness.HelloAsync(); + await first.SelfAsync(await first.ReceiveAsync()); + await harness.WaitAsync(RoleConnectionState.Connected); + var oldLease = harness.Manager.CurrentPersonalOperatorLease; + var signing = harness.Manager.CreatePersonalBrowserAuthResponseAsync("browser-nonce", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + Assert.Equal("users.self", (await first.ReceiveAsync()).GetProperty("method").GetString()); + await harness.Manager.DisconnectAsync().WaitAsync(TimeSpan.FromSeconds(5)); + var replacement = await harness.HelloAsync(); + await replacement.SelfAsync(await replacement.ReceiveAsync(), "replacement-person"); + await harness.WaitAsync(RoleConnectionState.Connected); + var currentLease = harness.Manager.CurrentPersonalOperatorLease; + Assert.Null(await signing); + Assert.NotSame(oldLease, currentLease); + Assert.Same(currentLease, harness.Manager.CurrentPersonalOperatorLease); + Assert.Equal("replacement-person", currentLease!.IdentityProfileId); + } + + private sealed class Harness : IAsyncDisposable, IGatewayClientFactory + { + private readonly TempDirectory _directory = new("personal-manager-wire-"); + private readonly List _peers = []; + public GatewayRegistry Registry { get; } + public GatewayConnectionManager Manager { get; } + + public Harness() + { + Registry = new GatewayRegistry(_directory.Path); + Registry.AddOrUpdate(new GatewayRecord { Id = "personal", Url = PersonalGatewayProtocolFixture.Route, + OperatorAuthentication = OperatorAuthenticationMode.PersonalTailscale, + SharedGatewayToken = "saved-shared", BootstrapToken = "saved-bootstrap" }); + Registry.SetActive("personal"); + Manager = new GatewayConnectionManager(new CredentialResolver(new NoOperatorTokenReads()), this, Registry, NullLogger.Instance); + } + + public IGatewayClientLifecycle Create(string gatewayUrl, GatewayCredential credential, string identityPath, IOpenClawLogger logger) + { + Assert.Empty(credential.Token); + Assert.Equal(OperatorAuthenticationMode.PersonalTailscale, credential.OperatorAuthentication); + var peer = new PersonalGatewayProtocolFixture(); + _peers.Add(peer); + return new Lifecycle(peer.CreateClient(identityPath)); + } + + public async Task HelloAsync() + { + await Manager.ConnectAsync("personal"); + var peer = _peers[^1]; + await peer.ChallengeAsync(); + var connect = await peer.ReceiveAsync(); + Assert.Equal("connect", connect.GetProperty("method").GetString()); + Assert.Empty(connect.GetProperty("params").GetProperty("auth").EnumerateObject()); + await peer.HelloAsync(connect); + return peer; + } + + public async Task WaitAsync(RoleConnectionState state) + { + var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + void OnState(object? sender, GatewayConnectionSnapshot snapshot) + { + if (snapshot.OperatorState == state) changed.TrySetResult(); + } + Manager.StateChanged += OnState; + try + { + if (Manager.CurrentSnapshot.OperatorState == state) return; + await changed.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + finally { Manager.StateChanged -= OnState; } + } + + public async ValueTask DisposeAsync() + { + Manager.Dispose(); + foreach (var peer in _peers) await peer.DisposeAsync(); + _directory.Dispose(); + } + } + + private sealed class NoOperatorTokenReads : IDeviceIdentityReader + { + public string? TryReadStoredDeviceToken(string dataPath) => throw new InvalidOperationException("Personal mode read a saved operator token."); + public string? TryReadStoredNodeDeviceToken(string dataPath) => null; + } + + private sealed class Lifecycle(OpenClawGatewayClient client) : IGatewayClientLifecycle + { + public OpenClawGatewayClient DataClient => client; + public event EventHandler? StatusChanged + { + add => client.StatusChanged += value; + remove => client.StatusChanged -= value; + } + public event EventHandler? AuthenticationFailed + { + add => client.AuthenticationFailed += value; + remove => client.AuthenticationFailed -= value; + } + public Task ConnectAsync(CancellationToken ct) => client.ConnectAsync(); + public void Dispose() => client.Dispose(); + } +} diff --git a/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs index 210a793398..28fb7ac97b 100644 --- a/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs +++ b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs @@ -7,6 +7,7 @@ using OpenClaw.Connection; using OpenClaw.Connection.NativeGateway; using OpenClaw.TestSupport; +using OpenClaw.TestSupport.Gateway; namespace OpenClaw.Connection.Tests; @@ -3039,10 +3040,13 @@ public async Task StaleOldGatewayV2FallbackAfterSwitch_DoesNotMarkCurrentGateway [Fact] public async Task ConnectWithSharedTokenAsync_RevalidatesDurableTokensUnderTransitionSemaphore() { + await using var server = await FixtureGatewayServer.StartAsync( + GatewayScenario.CreateBrowse(), "valid-shared-token"); + var gatewayUrl = server.Endpoint.AbsoluteUri; _registry.AddOrUpdate(new GatewayRecord { Id = "gw-1", - Url = "ws://127.0.0.1:9", + Url = gatewayUrl, SshTunnel = new SshTunnelConfig("user", "host.example", 18789, 45678) }); _registry.SetActive("gw-1"); @@ -3057,17 +3061,23 @@ public async Task ConnectWithSharedTokenAsync_RevalidatesDurableTokensUnderTrans var connectTask = manager.ConnectAsync("gw-1"); await tunnel.Started.Task.WaitAsync(TimeSpan.FromSeconds(2)); - var replaceTask = manager.ConnectWithSharedTokenAsync("ws://127.0.0.1:9", "bad-shared-token"); + var replaceTask = manager.ConnectWithSharedTokenAsync(gatewayUrl, "bad-shared-token"); var identityDir = _registry.GetIdentityDirectory("gw-1"); var identity = new DeviceIdentity(identityDir, NullLogger.Instance); identity.Initialize(); identity.StoreDeviceTokenForRole("operator", "operator-token"); + Assert.Empty(server.Requests); tunnel.AllowStart.SetResult(true); await connectTask.WaitAsync(TimeSpan.FromSeconds(2)); - var result = await replaceTask.WaitAsync(TimeSpan.FromSeconds(10)); + var rejectionTask = server.WaitForCompletedRequestAsync("connect"); + await Task.WhenAll(replaceTask, rejectionTask).WaitAsync(TimeSpan.FromSeconds(10)); + var result = await replaceTask; Assert.Equal(SetupCodeOutcome.ConnectionFailed, result.Outcome); + var rejection = await rejectionTask; + Assert.Equal(rejection, Assert.Single(server.Requests, request => request.Method == "connect")); + Assert.Equal("error:AUTH_TOKEN_MISMATCH", rejection.Outcome); Assert.Null(_registry.GetById("gw-1")?.SharedGatewayToken); Assert.Equal("operator-token", DeviceIdentity.TryReadStoredDeviceToken(identityDir)); } diff --git a/tests/OpenClaw.Connection.Tests/GatewayPersonalAuthenticationPolicyTests.cs b/tests/OpenClaw.Connection.Tests/GatewayPersonalAuthenticationPolicyTests.cs new file mode 100644 index 0000000000..77f885d070 --- /dev/null +++ b/tests/OpenClaw.Connection.Tests/GatewayPersonalAuthenticationPolicyTests.cs @@ -0,0 +1,54 @@ +using System.Text.Json; + +namespace OpenClaw.Connection.Tests; + +public sealed class GatewayPersonalAuthenticationPolicyTests +{ + [Theory] + [InlineData("wss://node.example.ts.net", "wss://node.example.ts.net")] + [InlineData("wss://node.example.ts.net:443/", "wss://node.example.ts.net")] + [InlineData("wss://node.example.ts.net:9443/", "wss://node.example.ts.net:9443")] + [InlineData("wss://node.example.ts.net/gateway", "wss://node.example.ts.net/gateway")] + public void TryNormalizeGatewayUrl_AcceptsCredentialFreeTailscaleTlsRoutes(string input, string expected) + { + Assert.True(GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(input, out var route, out _)); + Assert.Equal(expected, route); + } + + [Theory] + [InlineData("ws://node.example.ts.net")] + [InlineData("wss://node.example.com")] + [InlineData("wss://ts.net")] + [InlineData("wss://user:password@node.example.ts.net")] + [InlineData("wss://node.example.ts.net/?token=secret")] + [InlineData("wss://node.example.ts.net/#token=secret")] + [InlineData("wss://node.example.ts.net:0")] + public void TryNormalizeGatewayUrl_RejectsNonPersonalOrCredentialBearingRoutes(string input) + { + Assert.False(GatewayPersonalAuthenticationPolicy.TryNormalizeGatewayUrl(input, out _, out _)); + } + + [Fact] + public void TryGetCanonicalProfileId_RequiresNonemptyProfileId() + { + using var valid = JsonDocument.Parse("{\"profile\":{\"id\":\"person-42\"}}"); + using var missing = JsonDocument.Parse("{\"profile\":{\"name\":\"V\"}}"); + using var whitespace = JsonDocument.Parse("{\"profile\":{\"id\":\" \"}}"); + + Assert.True(GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(valid.RootElement, out var id)); + Assert.Equal("person-42", id); + Assert.False(GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(missing.RootElement, out _)); + Assert.False(GatewayPersonalAuthenticationPolicy.TryGetCanonicalProfileId(whitespace.RootElement, out _)); + } + + [Fact] + public void IsTrustedDashboardSource_MatchesTheConfiguredTlsPort() + { + Assert.True(GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource( + "https://node.example.ts.net:9443/chat", "wss://node.example.ts.net:9443")); + Assert.False(GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource( + "https://node.example.ts.net:9444/chat", "wss://node.example.ts.net:9443")); + Assert.False(GatewayPersonalAuthenticationPolicy.IsTrustedDashboardSource( + "https://node.example.ts.net/chat", "wss://node.example.ts.net:9443")); + } +} diff --git a/tests/OpenClaw.Shared.Tests/PersonalTailscaleGatewayClientTests.cs b/tests/OpenClaw.Shared.Tests/PersonalTailscaleGatewayClientTests.cs new file mode 100644 index 0000000000..0f61f4db62 --- /dev/null +++ b/tests/OpenClaw.Shared.Tests/PersonalTailscaleGatewayClientTests.cs @@ -0,0 +1,85 @@ +using System.Text.Json; +using OpenClaw.TestSupport; +using Xunit; + +namespace OpenClaw.Shared.Tests; + +public sealed class PersonalTailscaleGatewayClientTests +{ + [Fact] + public async Task CurrentSocketRequiresPersonalHelloAndVerifiedProfileBeforeApplicationReadiness() + { + using var identity = new TempDirectory("personal-wire-"); + await using var peer = new PersonalGatewayProtocolFixture(); + using var client = peer.CreateClient(identity.Path); + var hello = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + client.HandshakeSucceeded += (_, _) => hello.TrySetResult(); + await client.ConnectAsync(); + await peer.ChallengeAsync(); + var connect = await peer.ReceiveAsync(); + Assert.Equal("connect", connect.GetProperty("method").GetString()); + var parameters = connect.GetProperty("params"); + Assert.Empty(parameters.GetProperty("auth").EnumerateObject()); + Assert.Equal("gateway-client", parameters.GetProperty("client").GetProperty("id").GetString()); + Assert.Equal("ui", parameters.GetProperty("client").GetProperty("mode").GetString()); + Assert.False(string.IsNullOrWhiteSpace(parameters.GetProperty("device").GetProperty("signature").GetString())); + await peer.HelloAsync(connect); + await hello.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.False(client.IsConnectedToGateway); + Assert.Null(client.SessionMutationConnectionEpoch); + var epoch = Assert.IsType(client.PersonalHandshakeConnectionEpoch); + Assert.Throws(() => client.CreatePersonalBrowserAuthResponse("nonce", 1, epoch)); + var reading = client.ReadPersonalIdentityAsync(epoch); + var self = await peer.ReceiveAsync(); + Assert.Equal("users.self", self.GetProperty("method").GetString()); + await peer.SelfAsync(self); + var profile = await reading; + client.VerifyPersonalIdentity(profile.GetProperty("profile").GetProperty("id").GetString()!, epoch); + Assert.True(client.IsConnectedToGateway); + using var signed = JsonDocument.Parse(JsonSerializer.Serialize(client.CreatePersonalBrowserAuthResponse("browser-nonce", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), epoch))); + Assert.Empty(signed.RootElement.GetProperty("auth").EnumerateObject()); + Assert.Equal("tailscale", signed.RootElement.GetProperty("requiredAuthMethod").GetString()); + Assert.Equal("fixture-scope", signed.RootElement.GetProperty("expectedRecoveryScope").GetString()); + Assert.Equal(client.AuthenticatedSigningDeviceId, signed.RootElement.GetProperty("device").GetProperty("id").GetString()); + await client.DisconnectAsync(); + Assert.Null(client.PersonalHandshakeConnectionEpoch); + Assert.False(client.IsConnectedToGateway); + Assert.Throws(() => client.CreatePersonalBrowserAuthResponse("late", 1, epoch)); + } + + [Theory] + [InlineData("token", "fixture-scope")] + [InlineData("tailscale", "")] + [InlineData("tailscale", " ")] + [InlineData("", "fixture-scope")] + public async Task HelloWithWrongMethodOrMissingScopeNeverPublishesPersonalReadiness(string method, string scope) + { + using var identity = new TempDirectory("personal-invalid-wire-"); + await using var peer = new PersonalGatewayProtocolFixture(); + using var client = peer.CreateClient(identity.Path); + var failed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var failureKind = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + client.AuthenticationFailed += (_, _) => failed.TrySetResult(); + client.ConnectionFailure += (_, kind) => failureKind.TrySetResult(kind); + await client.ConnectAsync(); + await peer.ChallengeAsync(); + var connect = await peer.ReceiveAsync(); + await peer.HelloAsync(connect, method, scope); + await failed.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(GatewayErrorKind.PersonalIdentityUnverified, await failureKind.Task.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.Null(client.PersonalHandshakeConnectionEpoch); + Assert.False(client.IsConnectedToGateway); + } + + [Theory] + [InlineData("ws://protocol.example.ts.net", "")] + [InlineData("wss://127.0.0.1", "")] + [InlineData("wss://protocol.example.ts.net?token=private", "")] + [InlineData("wss://protocol.example.ts.net", "shared")] + public void PersonalConstructorRejectsUnsafeRoutesAndMixedCredentials(string route, string token) + { + using var identity = new TempDirectory("personal-route-"); + Assert.Throws(() => new OpenClawGatewayClient(route, token, + identityPath: identity.Path, operatorAuthentication: OperatorAuthenticationMode.PersonalTailscale)); + } +} diff --git a/tests/OpenClaw.Shared.Tests/PersonalTailscaleMediaTests.cs b/tests/OpenClaw.Shared.Tests/PersonalTailscaleMediaTests.cs new file mode 100644 index 0000000000..02a02c0d53 --- /dev/null +++ b/tests/OpenClaw.Shared.Tests/PersonalTailscaleMediaTests.cs @@ -0,0 +1,133 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using OpenClaw.TestSupport; +using Xunit; + +namespace OpenClaw.Shared.Tests; + +public sealed class PersonalTailscaleMediaTests +{ + [Theory] + [InlineData(HttpStatusCode.OK, AssistantMediaResolutionStatus.Ready, 2)] + [InlineData(HttpStatusCode.Forbidden, AssistantMediaResolutionStatus.Unavailable, 1)] + public async Task LegacyMediaUsesCurrentServeIdentityAndScopeCeilingWithoutBearerFallback( + HttpStatusCode status, AssistantMediaResolutionStatus expected, int requests) + { + using var identity = new TempDirectory("personal-media-"); + await using var peer = new PersonalGatewayProtocolFixture(); + using var handler = new MediaHandler((_, count) => Task.FromResult(count == 1 ? Metadata(status) : Image())); + using var client = peer.CreateClient(identity.Path, handler); + await ReadyAsync(peer, client); + var media = client.ResolveAssistantMediaAsync("main", Legacy()); + await SelfAsync(peer); + Assert.Equal(expected, (await media).Status); + Assert.Equal(requests, handler.Requests.Count); + Assert.All(handler.Requests, request => + { + Assert.Equal("https://protocol.example.ts.net", request.Uri.GetLeftPart(UriPartial.Authority)); + Assert.Null(request.Authorization); + Assert.Equal("https://protocol.example.ts.net", request.Origin); + Assert.Equal("operator.read,operator.write", request.Scopes); + Assert.False(request.HasAmbientCredentials); + }); + if (requests == 2) + Assert.Contains("mediaTicket=fixture-ticket", handler.Requests[1].Uri.Query, StringComparison.Ordinal); + } + + [Fact] + public async Task ChangedCanonicalPersonBeforeHttpRefusesMediaAndRetiresReadiness() + { + using var identity = new TempDirectory("personal-media-person-"); + await using var peer = new PersonalGatewayProtocolFixture(); + using var handler = new MediaHandler((_, _) => Task.FromResult(Metadata(HttpStatusCode.OK))); + using var client = peer.CreateClient(identity.Path, handler); + await ReadyAsync(peer, client); + var media = client.ResolveAssistantMediaAsync("main", Legacy()); + await SelfAsync(peer, "another-person"); + Assert.Equal(AssistantMediaResolutionStatus.Unavailable, (await media).Status); + Assert.Empty(handler.Requests); + Assert.False(client.IsConnectedToGateway); + } + + [Fact] + public async Task ProfileInvalidationDuringMetadataCannotFetchBytesWithRetiredAuthority() + { + using var identity = new TempDirectory("personal-media-retire-"); + await using var peer = new PersonalGatewayProtocolFixture(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var handler = new MediaHandler(async (_, _) => + { + entered.TrySetResult(); + await release.Task; + return Metadata(HttpStatusCode.OK); + }); + using var client = peer.CreateClient(identity.Path, handler); + await ReadyAsync(peer, client); + var invalidated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + client.SelfProfileChanged += (_, _) => invalidated.TrySetResult(); + var media = client.ResolveAssistantMediaAsync("main", Legacy()); + await SelfAsync(peer); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await peer.ProfileChangedAsync(); + await invalidated.Task.WaitAsync(TimeSpan.FromSeconds(5)); + release.TrySetResult(); + Assert.Equal(AssistantMediaResolutionStatus.Unavailable, (await media).Status); + Assert.Single(handler.Requests); + } + + private static ChatMediaContentInfo Legacy() => new() + { + Kind = ChatMediaContentKind.Image, Source = ChatMediaContentSource.LegacyDirective, + GatewaySource = "/fixture/banner.png" + }; + + private static async Task ReadyAsync(PersonalGatewayProtocolFixture peer, OpenClawGatewayClient client) + { + var hello = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + client.HandshakeSucceeded += (_, _) => hello.TrySetResult(); + await client.ConnectAsync(); + await peer.ChallengeAsync(); + await peer.HelloAsync(await peer.ReceiveAsync()); + await hello.Task.WaitAsync(TimeSpan.FromSeconds(5)); + var epoch = client.PersonalHandshakeConnectionEpoch!.Value; + var self = client.ReadPersonalIdentityAsync(epoch); + await SelfAsync(peer); + await self; + client.VerifyPersonalIdentity("person-42", epoch); + } + + private static async Task SelfAsync(PersonalGatewayProtocolFixture peer, string profile = "person-42") + { + var request = await peer.ReceiveAsync(); + Assert.Equal("users.self", request.GetProperty("method").GetString()); + await peer.SelfAsync(request, profile); + } + + private static HttpResponseMessage Metadata(HttpStatusCode status) => new(status) + { + Content = new StringContent("""{"available":true,"mimeType":"image/png","sizeBytes":3,"mediaTicket":"fixture-ticket"}""", Encoding.UTF8, "application/json") + }; + + private static HttpResponseMessage Image() + { + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent([1, 2, 3]) }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); + return response; + } + + private sealed record Request(Uri Uri, string? Authorization, string? Origin, string? Scopes, bool HasAmbientCredentials); + private sealed class MediaHandler(Func> respond) : HttpMessageHandler + { + public List Requests { get; } = []; + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + string? Header(string name) => request.Headers.TryGetValues(name, out var values) ? string.Join(",", values) : null; + Requests.Add(new(request.RequestUri!, request.Headers.Authorization?.ToString(), Header("Origin"), Header("x-openclaw-scopes"), + request.Headers.Any(header => header.Key.StartsWith("Tailscale-", StringComparison.OrdinalIgnoreCase) || + header.Key.StartsWith("X-Forwarded-", StringComparison.OrdinalIgnoreCase) || header.Key is "Cookie" or "Sec-Fetch-Site"))); + return respond(request, Requests.Count); + } + } +} diff --git a/tests/OpenClaw.TestSupport/PersonalGatewayProtocolFixture.cs b/tests/OpenClaw.TestSupport/PersonalGatewayProtocolFixture.cs new file mode 100644 index 0000000000..668251b483 --- /dev/null +++ b/tests/OpenClaw.TestSupport/PersonalGatewayProtocolFixture.cs @@ -0,0 +1,133 @@ +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using OpenClaw.Shared; + +namespace OpenClaw.TestSupport; + +public sealed class PersonalGatewayProtocolFixture : IAsyncDisposable +{ + public const string Route = "wss://protocol.example.ts.net"; + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _lifetime = new(); + private readonly Task _socket; + private TcpClient? _tcp; + private Task? _pump; + private readonly Channel _frames = Channel.CreateUnbounded(); + + public PersonalGatewayProtocolFixture() + { + _listener.Start(); + _socket = AcceptAsync(); + } + + public OpenClawGatewayClient CreateClient(string identityPath, HttpMessageHandler? httpHandler = null) + { + var client = new OpenClawGatewayClient(Route, string.Empty, + identityPath: identityPath, operatorAuthentication: OperatorAuthenticationMode.PersonalTailscale, + assistantMediaHandler: httpHandler); + typeof(WebSocketClientBase).GetField("_gatewayUrl", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(client, $"ws://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/"); + return client; + } + + private async Task AcceptAsync() + { + _tcp = await _listener.AcceptTcpClientAsync(_lifetime.Token); + var stream = _tcp.GetStream(); + var header = new StringBuilder(); + var one = new byte[1]; + while (!header.ToString().EndsWith("\r\n\r\n", StringComparison.Ordinal)) + { + if (header.Length >= 16384 || await stream.ReadAsync(one, _lifetime.Token) == 0) + throw new IOException("Invalid fixture upgrade."); + header.Append((char)one[0]); + } + var key = header.ToString().Split("\r\n") + .Single(line => line.StartsWith("Sec-WebSocket-Key:", StringComparison.OrdinalIgnoreCase)).Split(':', 2)[1].Trim(); + var accept = Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); + await stream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n"), _lifetime.Token); + var socket = WebSocket.CreateFromStream(stream, isServer: true, subProtocol: null, keepAliveInterval: Timeout.InfiniteTimeSpan); + _pump = PumpAsync(socket); + return socket; + } + + public async Task ChallengeAsync() => await SendAsync(new + { + type = "event", @event = "connect.challenge", payload = new { nonce = "fixture-challenge", ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } + }); + + public Task ProfileChangedAsync() => SendAsync(new + { + type = "event", @event = "sessions.changed", payload = new { reason = "profile-identity" } + }); + + public async Task ReceiveAsync() => + await _frames.Reader.ReadAsync(_lifetime.Token).AsTask().WaitAsync(TimeSpan.FromSeconds(5)); + + private async Task PumpAsync(WebSocket socket) + { + try + { + while (!_lifetime.IsCancellationRequested) + { + using var frame = new MemoryStream(); + var buffer = new byte[8192]; + WebSocketReceiveResult result; + do + { + result = await socket.ReceiveAsync(new ArraySegment(buffer), _lifetime.Token); + if (result.MessageType == WebSocketMessageType.Close) + { + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Fixture closed", _lifetime.Token); + _frames.Writer.TryComplete(); + return; + } + if (result.MessageType != WebSocketMessageType.Text) throw new IOException("Expected fixture text frame."); + frame.Write(buffer, 0, result.Count); + } while (!result.EndOfMessage); + using var json = JsonDocument.Parse(frame.ToArray()); + await _frames.Writer.WriteAsync(json.RootElement.Clone(), _lifetime.Token); + } + } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or WebSocketException or IOException) + { + _frames.Writer.TryComplete(ex); + } + } + + public async Task SendAsync(object value) + { + var socket = await _socket.WaitAsync(TimeSpan.FromSeconds(5)); + await socket.SendAsync(new ArraySegment(JsonSerializer.SerializeToUtf8Bytes(value)), WebSocketMessageType.Text, true, _lifetime.Token); + } + + public Task HelloAsync(JsonElement connect, string method = "tailscale", string scope = "fixture-scope") => SendAsync(new + { + type = "res", id = connect.GetProperty("id").GetString(), ok = true, + payload = new { type = "hello-ok", protocol = GatewayProtocolContract.CurrentVersion, + auth = new { method, recoveryScope = scope, deviceId = "fixture-operator", scopes = new[] { "operator.read", "operator.write" } } } + }); + + public Task SelfAsync(JsonElement request, string? profile = "person-42") => SendAsync(new + { + type = "res", id = request.GetProperty("id").GetString(), ok = true, + payload = new { profile = new { id = profile } } + }); + + public async ValueTask DisposeAsync() + { + _lifetime.Cancel(); + _listener.Stop(); + _tcp?.Dispose(); + try { (await _socket).Dispose(); } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or SocketException or IOException) { } + if (_pump is not null) await _pump; + _lifetime.Dispose(); + } +} diff --git a/tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs b/tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs index 19a9776df4..b8a0b4796c 100644 --- a/tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs +++ b/tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs @@ -620,7 +620,7 @@ public void Dashboard_SurfacesSshTunnelConfigurationFailure() { var source = ReadAppSources(); var entry = ExtractMethod(source, "OpenDashboard"); - Assert.Contains("TryOpenDashboardAsync(path)", entry); + Assert.Contains("TryOpenDashboardAsync(path, expectedPersonalGatewayId)", entry); Assert.Contains("AsyncEventHandlerGuard.Run(", entry); var method = ExtractMethod(source, "TryOpenDashboardAsync"); @@ -635,6 +635,38 @@ public void Dashboard_SurfacesSshTunnelConfigurationFailure() Assert.DoesNotContain("Process.Start", method); } + [Fact] + public void SavedPersonalDashboard_CarriesRequestedGatewayThroughAdmissionAndRetry() + { + var root = TestRepositoryPaths.GetRepositoryRoot(); + var page = File.ReadAllText(Path.Combine(root, + "src", "OpenClaw.Tray.WinUI", "Pages", "ConnectionPage.xaml.cs")); + var saved = ExtractMethod(page, "OnSavedRowOpenDashboardAsync"); + AssertInOrder(saved, + "rec.OperatorAuthentication == OperatorAuthenticationMode.PersonalTailscale", + "TryOpenDashboardAsync(expectedPersonalGatewayId: gwId)", + "return;", + "rec.SharedGatewayToken"); + + var app = ReadAppSources(); + var open = ExtractMethod(app, "TryOpenDashboardAsync"); + Assert.Contains("expectedPersonalGatewayId: expectedPersonalGatewayId", open); + Assert.Contains("OpenDashboard(path, expectedPersonalGatewayId)", open); + var factory = app[app.IndexOf("private GatewayDashboardLauncher CreateDashboardLauncher", StringComparison.Ordinal)..]; + factory = factory[..factory.IndexOf("// ── IAppCommands", StringComparison.Ordinal)]; + Assert.Contains("expectedPersonalGatewayId is not null ||", factory); + Assert.Contains("ShowPersonalDashboardAsync(target, expectedPersonalGatewayId)", factory); + + var windows = File.ReadAllText(Path.Combine(root, + "src", "OpenClaw.Tray.WinUI", "Services", "WindowManager.PersonalDashboard.cs")); + var admission = ExtractMethod(windows, "ShowPersonalDashboardAsync"); + AssertInOrder(admission, + "lease.GatewayId != expectedGatewayId", + "await retiring.CloseAsync()", + "!ReferenceEquals(lease, manager.CurrentPersonalOperatorLease)", + "new PersonalDashboardWindow(manager, lease, path)"); + } + [Fact] public void SavedDashboard_InvalidUrl_UsesLocalizedCopy() { diff --git a/tests/OpenClaw.Tray.Tests/ConnectionPagePersonalIdentityTests.cs b/tests/OpenClaw.Tray.Tests/ConnectionPagePersonalIdentityTests.cs new file mode 100644 index 0000000000..69389bde08 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/ConnectionPagePersonalIdentityTests.cs @@ -0,0 +1,43 @@ +using System.Xml.Linq; +using OpenClaw.Connection; +using OpenClaw.Shared; +using OpenClawTray.Pages; + +namespace OpenClaw.Tray.Tests; + +public sealed class ConnectionPagePersonalIdentityTests +{ + [Theory] + [InlineData(GatewayErrorKind.PersonalIdentityUnverified, "ConnectionPage_PersonalIdentityUnverified", + "Votre identité Tailscale n’a pas pu être vérifiée. Reconnectez cette passerelle. Les identifiants partagés ne seront pas utilisés.")] + [InlineData(GatewayErrorKind.PersonalIdentityReverificationRequired, "ConnectionPage_PersonalIdentityReverificationRequired", + "Votre identité Tailscale doit être vérifiée à nouveau. Reconnectez cette passerelle. Les identifiants partagés ne seront pas utilisés.")] + public void PersonalFailureUsesLocalizedGuidanceInsteadOfRawDiagnostics(GatewayErrorKind kind, string detailKey, string french) + { + const string raw = "untrusted-remote-detail-314159"; + var snapshot = new GatewayConnectionSnapshot + { + OverallState = OverallConnectionState.Error, + OperatorState = RoleConnectionState.Error, + OperatorErrorKind = kind, + OperatorError = raw, + }; + var plan = ConnectionPagePlan.Build(snapshot, new GatewayRecord + { + Id = "personal", Url = "wss://personal.example.ts.net", + OperatorAuthentication = OperatorAuthenticationMode.PersonalTailscale, + }, self: null, settings: null, savedGatewayCount: 1); + + Assert.Equal(ConnectionPageMode.Recovery, plan.Mode); + Assert.Equal("ConnectionPage_PersonalIdentityHeader", plan.StripHeadlineResourceKey); + Assert.Equal(detailKey, plan.StripSubResourceKey); + Assert.Equal(detailKey, Assert.Single(plan.RecoveryBulletResourceKeys)); + Assert.DoesNotContain(raw, plan.StripSub); + Assert.Null(plan.RecoveryDetail); + Assert.DoesNotContain(plan.Recovery, new[] { RecoveryCategory.Auth, RecoveryCategory.TokenDrift, RecoveryCategory.Scope }); + var document = XDocument.Load(Path.Combine(TestRepositoryPaths.GetRepositoryRoot(), + "src", "OpenClaw.Tray.WinUI", "Strings", "fr-fr", "Resources.resw")); + Assert.Equal(french, document.Root!.Elements("data") + .Single(element => (string?)element.Attribute("name") == detailKey).Element("value")!.Value); + } +} diff --git a/tests/OpenClaw.Tray.Tests/GatewayDirectConnectServiceTests.cs b/tests/OpenClaw.Tray.Tests/GatewayDirectConnectServiceTests.cs index 88e21bb7fc..bb3e322a7f 100644 --- a/tests/OpenClaw.Tray.Tests/GatewayDirectConnectServiceTests.cs +++ b/tests/OpenClaw.Tray.Tests/GatewayDirectConnectServiceTests.cs @@ -10,6 +10,48 @@ namespace OpenClaw.Tray.Tests; public sealed class GatewayDirectConnectServiceTests : IDisposable { + [Theory] + [InlineData(GatewayErrorKind.PersonalIdentityUnverified, true, "ConnectionPage_PersonalIdentityUnverified")] + [InlineData(GatewayErrorKind.PersonalIdentityReverificationRequired, true, "ConnectionPage_PersonalIdentityReverificationRequired")] + [InlineData(GatewayErrorKind.PersonalIdentityUnverified, false, "ConnectionPage_PersonalIdentityRecoveryIncomplete")] + [InlineData(GatewayErrorKind.PersonalIdentityReverificationRequired, false, "ConnectionPage_PersonalIdentityRecoveryIncomplete")] + public async Task PersonalFailureKindSurvivesRestoringThePreviousConnection(GatewayErrorKind kind, bool restoreSucceeds, string resourceKey) + { + var previous = AddPreviousGateway(); + _manager.SetCurrentSnapshot(Connected(previous.Id)); + _manager.NextSnapshot = Failed(previous.Id, "untrusted-remote-detail-314159") with { OperatorErrorKind = kind }; + _manager.RestoreSnapshot = restoreSucceeds ? Connected(previous.Id) + : Failed(previous.Id, "restoration-diagnostic") with { OperatorErrorKind = GatewayErrorKind.Network }; + + var result = await CreateService().ConnectAsync(new( + "wss://personal.example.ts.net", null, null, null, + OperatorAuthentication: OperatorAuthenticationMode.PersonalTailscale)); + + Assert.Equal(GatewayDirectConnectOutcome.Failed, result.Outcome); + Assert.Equal(kind, result.ErrorKind); + Assert.Equal(previous.Id, _manager.CurrentSnapshot.GatewayId); + Assert.Equal(restoreSucceeds ? RoleConnectionState.Connected : RoleConnectionState.Error, _manager.CurrentSnapshot.OperatorState); + Assert.Equal(restoreSucceeds ? null : (GatewayErrorKind?)GatewayErrorKind.Network, _manager.CurrentSnapshot.OperatorErrorKind); + Assert.Equal(!restoreSucceeds, result.RollbackIncomplete); + Assert.Equal(resourceKey, OpenClawTray.Helpers.GatewayPersonalErrorPresentation.ResourceKey(result.ErrorKind, result.RollbackIncomplete)); + Assert.False(result.GatewayCommitted); + } + + [Theory] + [InlineData("ws://fixture.example.ts.net", null, false)] + [InlineData("wss://fixture.example.com", null, false)] + [InlineData("wss://fixture.example.ts.net", "shared", false)] + [InlineData("wss://fixture.example.ts.net", null, true)] + public async Task InvalidPersonalRequestCannotMutateRegistryOrStartConnection(string url, string? token, bool nativeSetup) + { + var previous = AddPreviousGateway(); + var result = await CreateService().ConnectAsync(new(url, token, null, null, + NativeSetup: nativeSetup, OperatorAuthentication: OperatorAuthenticationMode.PersonalTailscale)); + Assert.False(result.GatewayCommitted); + Assert.Equal(previous.Id, _registry.ActiveGatewayId); + Assert.Equal(0, _manager.ConnectCount); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj b/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj index d9ee7128c0..2d81cf6d2c 100644 --- a/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj +++ b/tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj @@ -240,6 +240,10 @@ + + + + @@ -268,6 +272,7 @@ + diff --git a/tests/OpenClaw.Tray.Tests/PersonalDashboardNativeBridgeTests.cs b/tests/OpenClaw.Tray.Tests/PersonalDashboardNativeBridgeTests.cs new file mode 100644 index 0000000000..c079b282e6 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/PersonalDashboardNativeBridgeTests.cs @@ -0,0 +1,42 @@ +using System.Text.Json; +using OpenClaw.Connection; +using OpenClawTray.Helpers; + +namespace OpenClaw.Tray.Tests; + +public sealed class PersonalDashboardNativeBridgeTests +{ + [Fact] + public void NativeBridgeScriptSelectsPersonalAuthAdapterBeforeBridgeStartup() + { + const string gatewayUrl = "wss://node.example.ts.net:9443"; + var script = PersonalGatewayNativeBridgeScript.Create(gatewayUrl); + const string assignment = "window.__OPENCLAW_NATIVE_CONTROL_AUTH__ = "; + var assignmentStart = script.IndexOf(assignment, StringComparison.Ordinal); + Assert.True(assignmentStart >= 0, "The script must select native personal authentication."); + + var jsonStart = assignmentStart + assignment.Length; + var jsonEnd = script.IndexOf(';', jsonStart); + using var config = JsonDocument.Parse(script[jsonStart..jsonEnd]); + Assert.Equal(gatewayUrl, config.RootElement.GetProperty("gatewayUrl").GetString()); + Assert.True(config.RootElement.GetProperty("nativeConnectAuth").GetBoolean()); + Assert.True(script.IndexOf("window.OpenClawNativeGatewayAuth", StringComparison.Ordinal) > jsonEnd, + "Native authentication selection must precede bridge startup."); + } + + [Fact] + public void ReusePolicyRequiresTheSameCurrentLeaseAndAnActiveWindow() + { + var lease = new PersonalOperatorLease( + "gateway-1", "wss://node.example.ts.net", "person-42", "scope-9", "device-7", 3, 7); + var nextLease = lease with { Generation = 4 }; + var identicalReplacement = lease with { }; + Assert.False(PersonalDashboardWindowReusePolicy.CanReuse(identicalReplacement, lease, lease, false, false)); + + Assert.True(PersonalDashboardWindowReusePolicy.CanReuse(lease, lease, lease, false, false)); + Assert.False(PersonalDashboardWindowReusePolicy.CanReuse(lease, lease, lease, true, false)); + Assert.False(PersonalDashboardWindowReusePolicy.CanReuse(lease, lease, lease, false, true)); + Assert.False(PersonalDashboardWindowReusePolicy.CanReuse(nextLease, lease, nextLease, false, false)); + Assert.False(PersonalDashboardWindowReusePolicy.CanReuse(lease, lease, nextLease, false, false)); + } +} diff --git a/tests/OpenClaw.Tray.Tests/PersonalGatewayAuthChallengeParserTests.cs b/tests/OpenClaw.Tray.Tests/PersonalGatewayAuthChallengeParserTests.cs new file mode 100644 index 0000000000..35e072ac81 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/PersonalGatewayAuthChallengeParserTests.cs @@ -0,0 +1,69 @@ +using OpenClawTray.Helpers; + +namespace OpenClaw.Tray.Tests; + +public sealed class PersonalGatewayAuthChallengeParserTests +{ + private const string Route = "wss://node.example.ts.net"; + + [Theory] + [InlineData("{\"id\":\"challenge-1\",\"nonce\":\"nonce-123\",\"signedAt\":1793563200000}")] + [InlineData("\"{\\\"id\\\":\\\"challenge-1\\\",\\\"nonce\\\":\\\"nonce-123\\\",\\\"signedAt\\\":1793563200000}\"")] + public void TryParse_AcceptsNarrowChallengeFromCurrentTlsAuthority(string message) + { + Assert.True(PersonalGatewayAuthChallengeParser.TryParse( + message, + "https://node.example.ts.net/chat", + Route, + out var challenge)); + + Assert.NotNull(challenge); + Assert.Equal("challenge-1", challenge.Id); + Assert.Equal("nonce-123", challenge.Nonce); + Assert.Equal(1793563200000, challenge.SignedAt); + } + + [Fact] + public void TryParse_AcceptsChallengeFromMatchingCustomTlsPort() + { + Assert.True(PersonalGatewayAuthChallengeParser.TryParse( + "{\"id\":\"challenge-1\",\"nonce\":\"nonce-123\",\"signedAt\":1793563200000}", + "https://node.example.ts.net:9443/chat", + "wss://node.example.ts.net:9443", + out _)); + } + + [Fact] + public void TryParse_RejectsChallengeFromDifferentTlsPort() + { + Assert.False(PersonalGatewayAuthChallengeParser.TryParse( + "{\"id\":\"challenge-1\",\"nonce\":\"nonce-123\",\"signedAt\":1793563200000}", + "https://node.example.ts.net:9444/chat", + "wss://node.example.ts.net:9443", + out _)); + } + + [Theory] + [InlineData("https://attacker.ts.net/chat", "{\"id\":\"id\",\"nonce\":\"n\",\"signedAt\":1}")] + [InlineData("http://node.example.ts.net/chat", "{\"id\":\"id\",\"nonce\":\"n\",\"signedAt\":1}")] + [InlineData("https://node.example.ts.net/chat", "{\"id\":\"id\",\"nonce\":\"n|token\",\"signedAt\":1}")] + [InlineData("https://node.example.ts.net/chat", "{\"id\":\"id\",\"nonce\":\"n\",\"signedAt\":1,\"auth\":{\"token\":\"secret\"}}")] + public void TryParse_RejectsUntrustedOrCredentialBearingMessages(string source, string message) + { + Assert.False(PersonalGatewayAuthChallengeParser.TryParse(message, source, Route, out _)); + } + + [Theory] + [InlineData("\"1793563200000\"")] + [InlineData("null")] + [InlineData("true")] + [InlineData("{}")] + [InlineData("[]")] + public void TryParse_RejectsNonNumericSignedAtWithoutThrowing(string signedAt) + { + var message = $"{{\"id\":\"challenge-1\",\"nonce\":\"nonce-123\",\"signedAt\":{signedAt}}}"; + + Assert.False(PersonalGatewayAuthChallengeParser.TryParse( + message, "https://node.example.ts.net/chat", Route, out _)); + } +} diff --git a/tests/OpenClaw.Tray.Tests/Presentation/PresentationTestDoubles.cs b/tests/OpenClaw.Tray.Tests/Presentation/PresentationTestDoubles.cs index 3b1125edef..e14fb108be 100644 --- a/tests/OpenClaw.Tray.Tests/Presentation/PresentationTestDoubles.cs +++ b/tests/OpenClaw.Tray.Tests/Presentation/PresentationTestDoubles.cs @@ -73,7 +73,7 @@ internal sealed class FakeAppCommands : IAppCommands, IDisposable public void ClearOperationLog() => _operationLog.Clear(); public void OpenDashboard(string? path = null) => DashboardPaths.Add(path); - public Task TryOpenDashboardAsync(string? path = null) => Task.FromResult(false); + public Task TryOpenDashboardAsync(string? path = null, string? expectedPersonalGatewayId = null) => Task.FromResult(false); public void Navigate(string pageTag) => Navigations.Add(pageTag); public Task TryNavigateAsync(string pageTag, string? chatSessionKey = null) => Task.FromResult(false); public void Reconnect() => ReconnectCount++; @@ -144,7 +144,7 @@ public SelfWritingAppCommands(ISettingsStore store) } public void OpenDashboard(string? path = null) { } - public Task TryOpenDashboardAsync(string? path = null) => Task.FromResult(false); + public Task TryOpenDashboardAsync(string? path = null, string? expectedPersonalGatewayId = null) => Task.FromResult(false); public void Navigate(string pageTag) { } public Task TryNavigateAsync(string pageTag, string? chatSessionKey = null) => Task.FromResult(false); public void Reconnect() { } diff --git a/tests/OpenClaw.Tray.Tests/SetupDashboardHandoffTests.cs b/tests/OpenClaw.Tray.Tests/SetupDashboardHandoffTests.cs index 0e365cff84..0db342efb3 100644 --- a/tests/OpenClaw.Tray.Tests/SetupDashboardHandoffTests.cs +++ b/tests/OpenClaw.Tray.Tests/SetupDashboardHandoffTests.cs @@ -165,6 +165,29 @@ public async Task Failure_IsReportedOnceWithoutAutomaticRetry(string failure) Assert.Equal(1, failures); } + [Theory] + [InlineData(true)] + [InlineData(false)] + [InlineData(null)] + public async Task PersonalDashboardNeverFallsBackToBrowserOrSavedCredentials(bool? available) + { + var failures = 0; + var opened = 0; + string? path = null; + var launcher = new GatewayDashboardLauncher( + () => throw new InvalidOperationException("Personal mode accessed the shared tunnel route."), + () => throw new InvalidOperationException("Personal mode resolved saved credentials."), + _ => throw new InvalidOperationException("Personal mode opened the shared browser route."), + () => failures++, () => opened++, () => true, + available.HasValue + ? target => { path = target; return Task.FromResult(available.Value); } + : null); + Assert.Equal(available == true, await launcher.OpenAsync("channels")); + Assert.Equal(available.HasValue ? "channels" : null, path); + Assert.Equal(available == true ? 0 : 1, failures); + Assert.Equal(available == true ? 1 : 0, opened); + } + [Fact] public void EndpointBinding_ExcludesRotatingTokensButIncludesSshRealm() { diff --git a/tests/OpenClaw.Tray.UITests/GatewayFixtureUiTests.UsageResponsive.cs b/tests/OpenClaw.Tray.UITests/GatewayFixtureUiTests.UsageResponsive.cs index 14ef794fae..8377619045 100644 --- a/tests/OpenClaw.Tray.UITests/GatewayFixtureUiTests.UsageResponsive.cs +++ b/tests/OpenClaw.Tray.UITests/GatewayFixtureUiTests.UsageResponsive.cs @@ -145,7 +145,27 @@ await WaitUiAsync(run, () => FindById(run, "SettingsPageAppTheme") is { Current. await run.InvokeAsync("app.navigate", new { page = "chat" }); await WaitUiAsync(run, () => FindById(run, "WorkspacePagesCustomize") is { Current.IsOffscreen: false }, "Chat pin customization"); - var window = await WaitForHubAsync(run, "pinned Usage chat window"); + AutomationElement window; + try { window = await WaitForHubAsync(run, "pinned Usage chat window"); } + catch (InvalidOperationException error) + { + string diagnostic; + try + { + diagnostic = JsonSerializer.Serialize(AppWindows(run).Select(candidate => new + { + window = Describe(candidate), + hasComposer = candidate.FindFirst(TreeScope.Descendants, + new PropertyCondition(AutomationElement.AutomationIdProperty, "ChatComposerInput")) is not null, + hasCustomizer = candidate.FindFirst(TreeScope.Descendants, + new PropertyCondition(AutomationElement.AutomationIdProperty, "WorkspacePagesCustomize")) is not null, + }).ToArray()); + } + catch (Exception diagnosticError) { diagnostic = diagnosticError.ToString(); } + throw new InvalidOperationException( + $"Pinned Usage {theme}: owned chat-window lookup failed after the customize control became visible. Owned-window observations: {diagnostic}", error); + } + var handle = new IntPtr(window.Current.NativeWindowHandle); await NativeKeyboardProof.ActivateAsync(handle); var scale = UsageGetDpiForWindow(handle) / 96d; @@ -711,6 +731,13 @@ await run.WaitForAsync(async () => return true; } } + if (candidate is null && FindById(run, "UsageSessionsShowAll") is { Current.IsOffscreen: false } more) + { + Invoke(more); + requestedPercent = 0; + scroll.SetScrollPercent(ScrollPattern.NoScroll, requestedPercent); + return false; + } Assert.True(requestedPercent < 100 && position.VerticalViewSize is > 0 and < 100, "Main Usage session header has no visible measured geometry at the end of the page."); // Overlapping half-viewport steps reveal the intended row, not a calendar-dependent offset. diff --git a/tests/OpenClaw.Tray.UITests/LocalAiHardwareProfileTests.cs b/tests/OpenClaw.Tray.UITests/LocalAiHardwareProfileTests.cs index 0ad17a9427..75e7fac165 100644 --- a/tests/OpenClaw.Tray.UITests/LocalAiHardwareProfileTests.cs +++ b/tests/OpenClaw.Tray.UITests/LocalAiHardwareProfileTests.cs @@ -309,7 +309,7 @@ public event EventHandler? Changed { a private sealed class InertCommands : IAppCommands { public Task TryNavigateAsync(string pageTag, string? chatSessionKey = null) => Task.FromResult(false); - public Task TryOpenDashboardAsync(string? path = null) => Task.FromResult(false); + public Task TryOpenDashboardAsync(string? path = null, string? expectedPersonalGatewayId = null) => Task.FromResult(false); public void OpenDashboard(string? path = null) => throw new NotSupportedException(); public void Navigate(string pageTag) => throw new NotSupportedException(); public void Reconnect() => throw new NotSupportedException(); diff --git a/tests/OpenClaw.Tray.UITests/OpenClaw.Tray.UITests.csproj b/tests/OpenClaw.Tray.UITests/OpenClaw.Tray.UITests.csproj index c4686637a3..a3655222f2 100644 --- a/tests/OpenClaw.Tray.UITests/OpenClaw.Tray.UITests.csproj +++ b/tests/OpenClaw.Tray.UITests/OpenClaw.Tray.UITests.csproj @@ -96,6 +96,8 @@ + WithBrowserAsync(async (window, core, manager) => + { + await core.ExecuteScriptAsync("OpenClawNativeGatewayAuth.postMessage({id:'current',nonce:'current-nonce',signedAt:Date.now()})"); + await manager.Started.Task.WaitAsync(TimeSpan.FromSeconds(10)); + manager.Response.SetResult("{\"fixture\":\"accepted\"}"); + await WaitForReplyAsync(core, "current"); + Assert.Equal("\"accepted\"", await core.ExecuteScriptAsync("fixtureReplies.find(x=>x.id==='current').result.fixture")); + + manager.PrepareRequest(); + await core.ExecuteScriptAsync("OpenClawNativeGatewayAuth.postMessage({id:'retired',nonce:'retired-nonce',signedAt:Date.now()})"); + await manager.Started.Task.WaitAsync(TimeSpan.FromSeconds(10)); + manager.Lease = manager.Lease with { Generation = manager.Lease.Generation + 1 }; + manager.Response.SetResult("{\"fixture\":\"must-not-be-delivered\"}"); + await WaitForReplyAsync(core, "retired"); + Assert.Equal("false", await core.ExecuteScriptAsync("fixtureReplies.some(x=>x.id==='retired' && x.result)")); + }); + + [Fact] + public Task CloseDeletesOwnedInPrivateProfile() => WithBrowserAsync(async (window, core, manager) => + { + var profile = core.Profile; + Assert.True(profile.IsInPrivateModeEnabled); + Assert.StartsWith("personal-", profile.ProfileName); + var deleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + profile.Deleted += (_, _) => deleted.TrySetResult(); + await window.CloseAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(deleted.Task.IsCompletedSuccessfully); + GC.KeepAlive(profile); + }); + + private Task WithBrowserAsync(Func test) => ui.RunOnUIAsync(async () => + { + using var directory = new TempDirectory("personal-browser-ui-"); + using var environment = new EnvironmentScope("OPENCLAW_TRAY_DATA_DIR", directory.Path); + var page = directory.Combine("page"); + Directory.CreateDirectory(page); + File.WriteAllText(Path.Combine(page, "index.html"), """ + Native authentication fixture + + """); + var contract = DispatchProxy.Create(); + var manager = (ManagerProxy)(object)contract; + var window = new PersonalDashboardWindow(contract, manager.Lease, "/index.html"); + var view = (WebView2)((FrameworkElement)window.Content).FindName("DashboardWebView"); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + view.CoreWebView2Initialized += (_, _) => + { + var core = view.CoreWebView2; + if (core is null) { ready.TrySetException(new InvalidOperationException("Native Core initialization failed.")); return; } + core.SetVirtualHostNameToFolderMapping(Host, page, CoreWebView2HostResourceAccessKind.DenyCors); + core.NavigationCompleted += (_, result) => + { + if (result.IsSuccess) ready.TrySetResult(core); + else ready.TrySetException(new InvalidOperationException("Native fixture page did not load.")); + }; + }; + window.Activate(); + try + { + await test(window, await ready.Task.WaitAsync(TimeSpan.FromSeconds(15)), manager); + } + finally + { + manager.Response.TrySetResult(null); + await window.CloseAsync().WaitAsync(TimeSpan.FromSeconds(10)); + } + }); + + private static async Task WaitForReplyAsync(CoreWebView2 core, string id) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (await core.ExecuteScriptAsync($"fixtureReplies.some(x=>x.id==='{id}')") != "true") + { + Assert.True(DateTime.UtcNow < deadline, "Native browser reply did not arrive."); + await Task.Delay(25); + } + } + + public class ManagerProxy : DispatchProxy + { + public PersonalOperatorLease Lease { get; set; } = new("fixture", "wss://" + Host, "person", "scope", "device", 1, 1); + public TaskCompletionSource Started { get; private set; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Response { get; private set; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void PrepareRequest() + { + Started = new(TaskCreationOptions.RunContinuationsAsynchronously); + Response = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + protected override object? Invoke(MethodInfo? method, object?[]? args) + { + if (method?.Name == "get_CurrentPersonalOperatorLease") return Lease; + if (method?.Name == "CreatePersonalBrowserAuthResponseAsync") + { + Started.TrySetResult(); + return Response.Task; + } + return null; + } + } +} diff --git a/tests/OpenClaw.Tray.UITests/UIThreadFixture.cs b/tests/OpenClaw.Tray.UITests/UIThreadFixture.cs index d3f9878341..9b138ac3c0 100644 --- a/tests/OpenClaw.Tray.UITests/UIThreadFixture.cs +++ b/tests/OpenClaw.Tray.UITests/UIThreadFixture.cs @@ -392,7 +392,7 @@ public void Dispose() /// All UI tests share one Application/Window — declare them in this collection /// so xUnit serializes them and reuses the fixture. /// -[CollectionDefinition(Name)] +[CollectionDefinition(Name, DisableParallelization = true)] public sealed class UICollection : ICollectionFixture { public const string Name = "UI"; diff --git a/tests/OpenClaw.Tray.UITests/UsagePageRenderingTests.cs b/tests/OpenClaw.Tray.UITests/UsagePageRenderingTests.cs index 60ace8733d..a8ea0a7fc7 100644 --- a/tests/OpenClaw.Tray.UITests/UsagePageRenderingTests.cs +++ b/tests/OpenClaw.Tray.UITests/UsagePageRenderingTests.cs @@ -193,7 +193,7 @@ private sealed class RecordingCommands : IAppCommands public readonly List PendingChatKeys = []; public void OpenDashboard(string? path = null) => DashboardPaths.Add(path); - public Task TryOpenDashboardAsync(string? path = null) => throw new NotSupportedException(); + public Task TryOpenDashboardAsync(string? path = null, string? expectedPersonalGatewayId = null) => throw new NotSupportedException(); public void Navigate(string pageTag) => Navigations.Add(pageTag); public Task TryNavigateAsync(string pageTag, string? chatSessionKey = null) => throw new NotSupportedException(); public void Reconnect() => throw new NotSupportedException();