Skip to content

Commit 64b650c

Browse files
authored
fix(pairing): harden Windows node bootstrap reconnects
1 parent f6a2d5d commit 64b650c

10 files changed

Lines changed: 352 additions & 2 deletions

File tree

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public sealed class GatewayConnectionManager : IGatewayConnectionManager
3333
private bool _disposed;
3434
private Task? _disposeTask;
3535
private bool _gatewayNeedsV2Signature; // remembered across reconnects
36+
private string? _operatorTokenRecoveryAttemptedGatewayId;
3637
private string? _lastAutoApprovedRequestId; // prevent auto-approve loops
3738
private string? _autoApproveInFlight; // atomic guard against concurrent approval of same requestId
3839

@@ -149,6 +150,7 @@ private async Task ConnectCoreAsync(string? gatewayId = null)
149150
_diagnostics.RecordCredentialResolution(credential);
150151
_activeIdentityPath = perGatewayIdentityDir;
151152
_activeGatewayRecordId = record.Id;
153+
_gatewayNeedsV2Signature = record.IsLocal || record.RequiresV2Signature;
152154

153155
if (credential == null)
154156
{
@@ -241,12 +243,13 @@ private async Task ConnectCoreAsync(string? gatewayId = null)
241243
};
242244
lifecycle.DataClient.V2SignatureFallback += (s, _) =>
243245
{
244-
_gatewayNeedsV2Signature = true;
246+
if (Interlocked.Read(ref _generation) != gen) return;
247+
RememberGatewayNeedsV2Signature(record.Id);
245248
};
246249

247250
// Local gateways only support v2 signatures — skip the v3 attempt entirely
248251
// to avoid a spurious "metadata-upgrade" re-pairing triggered by the v3→v2 fallback.
249-
if (record.IsLocal)
252+
if (record.IsLocal || record.RequiresV2Signature)
250253
_gatewayNeedsV2Signature = true;
251254

252255
// If we already know this gateway needs v2, tell the client upfront
@@ -488,6 +491,9 @@ private async Task HandleAuthenticationFailedAsync(string message, long gen)
488491
{
489492
if (Interlocked.Read(ref _generation) != gen) return;
490493

494+
if (TryScheduleOperatorTokenRecovery(message, gen))
495+
return;
496+
491497
var prev = _stateMachine.Current.OverallState;
492498
_diagnostics.Record("error", "Authentication failed", message);
493499
_stateMachine.TryTransition(ConnectionTrigger.AuthenticationFailed, message);
@@ -499,6 +505,48 @@ private async Task HandleAuthenticationFailedAsync(string message, long gen)
499505
}
500506
}
501507

508+
private bool TryScheduleOperatorTokenRecovery(string message, long gen)
509+
{
510+
if (!IsOperatorDeviceTokenMismatch(message) ||
511+
_activeGatewayRecordId == null ||
512+
_activeIdentityPath == null ||
513+
_operatorTokenRecoveryAttemptedGatewayId == _activeGatewayRecordId)
514+
{
515+
return false;
516+
}
517+
518+
var record = _registry.GetById(_activeGatewayRecordId);
519+
if (record == null || string.IsNullOrWhiteSpace(record.BootstrapToken))
520+
return false;
521+
522+
if (!DeviceIdentity.TryClearDeviceToken(_activeIdentityPath, _logger))
523+
return false;
524+
525+
_operatorTokenRecoveryAttemptedGatewayId = _activeGatewayRecordId;
526+
_diagnostics.Record("credential", "Cleared stale operator device token; reconnecting with bootstrap token");
527+
528+
_ = Task.Run(async () =>
529+
{
530+
try
531+
{
532+
await _reconnectDelay(TimeSpan.FromMilliseconds(200));
533+
if (Interlocked.Read(ref _generation) != gen || _disposed) return;
534+
await ReconnectAsync();
535+
}
536+
catch (ObjectDisposedException) { }
537+
catch (Exception ex)
538+
{
539+
_logger.Warn($"[ConnMgr] Operator token recovery reconnect failed: {ex.Message}");
540+
}
541+
});
542+
543+
return true;
544+
}
545+
546+
private static bool IsOperatorDeviceTokenMismatch(string message) =>
547+
message.Contains("device token mismatch", StringComparison.OrdinalIgnoreCase) ||
548+
message.Contains("AUTH_DEVICE_TOKEN_MISMATCH", StringComparison.OrdinalIgnoreCase);
549+
502550
private async Task HandleHandshakeSucceededAsync(long gen)
503551
{
504552
await _transitionSemaphore.WaitAsync();
@@ -510,6 +558,8 @@ private async Task HandleHandshakeSucceededAsync(long gen)
510558
_diagnostics.Record("state", "Handshake succeeded (hello-ok)");
511559
_stateMachine.TryTransition(ConnectionTrigger.HandshakeSucceeded);
512560
_diagnostics.RecordStateChange(prev, _stateMachine.Current.OverallState);
561+
if (_operatorTokenRecoveryAttemptedGatewayId == _activeGatewayRecordId)
562+
_operatorTokenRecoveryAttemptedGatewayId = null;
513563

514564
// Update device ID from client
515565
if (_activeLifecycle?.DataClient is { } client)
@@ -579,6 +629,25 @@ private void HandleDeviceTokenReceived(DeviceTokenReceivedEventArgs e)
579629
}
580630
}
581631

632+
private void RememberGatewayNeedsV2Signature(string? gatewayRecordId)
633+
{
634+
_gatewayNeedsV2Signature = true;
635+
636+
if (string.IsNullOrWhiteSpace(gatewayRecordId))
637+
return;
638+
639+
try
640+
{
641+
_registry.Update(gatewayRecordId, r => r.RequiresV2Signature ? r : r with { RequiresV2Signature = true });
642+
_registry.Save();
643+
_diagnostics.Record("credential", "Remembered gateway v2 signature requirement");
644+
}
645+
catch (Exception ex)
646+
{
647+
_logger.Warn($"[ConnMgr] Failed to persist v2 signature requirement: {ex.Message}");
648+
}
649+
}
650+
582651
private async Task HandlePairingRequiredAsync(string? requestId, long gen)
583652
{
584653
await _transitionSemaphore.WaitAsync();

‎src/OpenClaw.Connection/GatewayRecord.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ public sealed record GatewayRecord
2727
/// <summary>True for gateways provisioned locally (localhost/WSL).</summary>
2828
public bool IsLocal { get; init; }
2929

30+
/// <summary>True when this gateway is known to require v2 auth signatures.</summary>
31+
public bool RequiresV2Signature { get; init; }
32+
3033
/// <summary>WSL distro name for gateway records provisioned by SetupEngine.</summary>
3134
public string? SetupManagedDistroName { get; init; }
3235

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@ public OpenClawGatewayClient(string gatewayUrl, string token, IOpenClawLogger? l
244244
_deviceIdentity = new DeviceIdentity(dataPath, _logger);
245245
_deviceIdentity.Initialize();
246246
_connectAuthToken = _deviceIdentity.DeviceToken ?? (_tokenIsBootstrapToken ? string.Empty : _token);
247+
_useV2Signature |= _tokenIsBootstrapToken && string.IsNullOrEmpty(_deviceIdentity.DeviceToken);
247248
}
248249

249250
public async Task DisconnectAsync()

‎src/OpenClaw.Shared/WindowsNodeClient.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ public WindowsNodeClient(string gatewayUrl, string token, string dataPath, IOpen
117117
// Initialize device identity
118118
_deviceIdentity = new DeviceIdentity(dataPath, _logger);
119119
_deviceIdentity.Initialize();
120+
_useV2Signature |= !string.IsNullOrEmpty(_bootstrapToken) && string.IsNullOrEmpty(_deviceIdentity.NodeDeviceToken);
120121

121122
// Initialize registration
122123
_registration = new NodeRegistration

‎src/OpenClaw.Tray.WinUI/Services/SettingsManager.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,28 @@ public void Save()
424424
return ProtectedSecretPrefix + Convert.ToBase64String(protectedBytes);
425425
}
426426

427+
internal static bool CanProtectSettingSecretsForCurrentUser()
428+
{
429+
if (!OperatingSystem.IsWindows())
430+
return false;
431+
432+
try
433+
{
434+
var bytes = Encoding.UTF8.GetBytes("openclaw-dpapi-probe");
435+
var protectedBytes = ProtectedData.Protect(bytes, ProtectedSecretEntropy, DataProtectionScope.CurrentUser);
436+
var unprotectedBytes = ProtectedData.Unprotect(protectedBytes, ProtectedSecretEntropy, DataProtectionScope.CurrentUser);
437+
return bytes.SequenceEqual(unprotectedBytes);
438+
}
439+
catch (CryptographicException)
440+
{
441+
return false;
442+
}
443+
catch (NotSupportedException)
444+
{
445+
return false;
446+
}
447+
}
448+
427449
internal static string? UnprotectSettingSecret(string? value)
428450
{
429451
if (string.IsNullOrWhiteSpace(value))

‎tests/Directory.Build.props‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
<Nullable>enable</Nullable>
1212
<IsPackable>false</IsPackable>
1313
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
14+
<OpenClawLibsodiumVersion>1.0.20.1</OpenClawLibsodiumVersion>
1415
<!-- Audit direct + transitive dependencies for known CVEs during restore,
1516
matching the setting in src/Directory.Build.props. -->
1617
<NuGetAuditMode>all</NuGetAuditMode>
@@ -33,4 +34,12 @@
3334
<Using Include="Xunit" />
3435
</ItemGroup>
3536

37+
<Target Name="CopyWindowsNativeCryptoForTestHost" AfterTargets="Build" Condition="'$(OS)' == 'Windows_NT'">
38+
<ItemGroup>
39+
<OpenClawNativeCrypto Include="$(NuGetPackageRoot)libsodium\$(OpenClawLibsodiumVersion)\runtimes\win-x64\native\libsodium.dll" Condition="'$(PROCESSOR_ARCHITECTURE)' != 'ARM64' And Exists('$(NuGetPackageRoot)libsodium\$(OpenClawLibsodiumVersion)\runtimes\win-x64\native\libsodium.dll')" />
40+
<OpenClawNativeCrypto Include="$(NuGetPackageRoot)libsodium\$(OpenClawLibsodiumVersion)\runtimes\win-arm64\native\libsodium.dll" Condition="'$(PROCESSOR_ARCHITECTURE)' == 'ARM64' And Exists('$(NuGetPackageRoot)libsodium\$(OpenClawLibsodiumVersion)\runtimes\win-arm64\native\libsodium.dll')" />
41+
</ItemGroup>
42+
<Copy SourceFiles="@(OpenClawNativeCrypto)" DestinationFolder="$(TargetDir)" SkipUnchangedFiles="true" />
43+
</Target>
44+
3645
</Project>

0 commit comments

Comments
 (0)