using System.Diagnostics; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Text.Json; using ClassNotify.Shared.Ipc; using ClassNotify.Shared.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Ipc; public class NamedPipeServer { private readonly ILogger _logger; private readonly string _pipeName; private NamedPipeServerStream? _pipeStream; private StreamWriter? _writer; private readonly SemaphoreSlim _writeLock = new(1, 1); private readonly object _stateLock = new(); private volatile bool _isAuthenticated = false; private TaskCompletionSource? _ttsCheckTcs; private readonly SemaphoreSlim _ttsCheckLock = new(1, 1); private readonly object _authLock = new(); private string? _authorizedToken; private int? _authorizedPid; private uint? _authorizedSessionId; public bool HasAuthorizedClient { get { lock (_authLock) { return !string.IsNullOrEmpty(_authorizedToken) && _authorizedPid.HasValue; } } } public void SetAuthorizedClient(string token, int pid, uint sessionId) { lock (_authLock) { _authorizedToken = token; _authorizedPid = pid; _authorizedSessionId = sessionId; _logger.LogInformation("[NamedPipeServer] Registered authorized client: PID={Pid}, SessionId={SessionId}.", pid, sessionId); } } public void InvalidateAuthorization() { lock (_authLock) { _authorizedToken = null; _authorizedPid = null; _authorizedSessionId = null; _isAuthenticated = false; _logger.LogInformation("[NamedPipeServer] Client authorization invalidated."); } } public event Action? OnAckReceived; public event Action? OnHealthReportReceived; public event Action? OnVisualReceiptReceived; public event Action? OnClientConnected; public event Func>? OnRenewRequested; public event Func>? OnActivateRequested; public event Func>? OnUpdateClassNameRequested; public event Func>? OnRequestPairingMode; public event Func>? OnRequestPairingSession; public event Action? OnBootstrapRequested; public event Func>? OnGetClientStateRequested; public string ExpectedProcessName { get; set; } = "ClassNotify.Client"; public bool IsClientConnected => _pipeStream != null && _pipeStream.IsConnected && _isAuthenticated; public DateTimeOffset LastClientHeartbeatUtc { get; private set; } = DateTimeOffset.MinValue; [DllImport("kernel32.dll", SetLastError = true)] private static extern uint WTSGetActiveConsoleSessionId(); [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr phToken); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetNamedPipeClientSessionId(IntPtr Pipe, out uint ClientSessionId); public NamedPipeServer(IConfiguration configuration, ILogger logger) { _logger = logger; _pipeName = configuration["ClassNotify:PipeName"] ?? "ClassNotify_Ipc_Pipe"; } public void StartListening(CancellationToken stoppingToken) { Task.Run(async () => { while (!stoppingToken.IsCancellationRequested) { try { // Step 0: Ensure an active interactive user session exists before creating the pipe var activeUser = TryGetActiveUserIdentity(); if (activeUser == null) { _logger.LogInformation("No active interactive user; delaying pipe creation."); await Task.Delay(3000, stoppingToken); continue; } _logger.LogInformation("Creating NamedPipeServerStream: {PipeName} for Active User SID: {Sid} (Session {SessionId})", _pipeName, activeUser.Value.Sid.Value, activeUser.Value.SessionId); EnsureBootstrapPipeRunning(activeUser.Value.SessionId, stoppingToken); var pipeSecurity = CreateHardenedPipeSecurity(activeUser.Value.Sid); _pipeStream = NamedPipeServerStreamAcl.Create( _pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, inBufferSize: 4096, outBufferSize: 4096, pipeSecurity); _logger.LogInformation("Waiting for WinUI 3 client connection on named pipe (timeout 5s)..."); using (var connectCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken)) { connectCts.CancelAfter(TimeSpan.FromSeconds(5)); try { await _pipeStream.WaitForConnectionAsync(connectCts.Token); } catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) { // 5s elapsed without client connection. Check if active user changed or logged off var currentActive = TryGetActiveUserIdentity(); if (currentActive == null || currentActive.Value.SessionId != activeUser.Value.SessionId || !currentActive.Value.Sid.Equals(activeUser.Value.Sid)) { _logger.LogInformation("[NamedPipeServer] Active user session changed (old: Session {OldSess}, new: {NewUser}). Recreating pipe with new ACL.", activeUser.Value.SessionId, currentActive.HasValue ? $"Session {currentActive.Value.SessionId} ({currentActive.Value.Sid})" : "None"); } _pipeStream.Dispose(); _pipeStream = null; continue; } } _isAuthenticated = false; _writer = new StreamWriter(_pipeStream, Encoding.UTF8) { AutoFlush = true }; var reader = new StreamReader(_pipeStream, Encoding.UTF8); // Step 1: Enforce Hello Handshake as the very first message var handshakeLine = await reader.ReadLineAsync(stoppingToken); if (string.IsNullOrEmpty(handshakeLine)) { _logger.LogWarning("[NamedPipeServer] Client disconnected without sending handshake."); continue; } if (!ValidateHandshake(handshakeLine, _pipeStream.SafePipeHandle.DangerousGetHandle())) { _logger.LogWarning("[NamedPipeServer] Invalid or unauthorized handshake received. Disconnecting client."); continue; } _isAuthenticated = true; _logger.LogInformation("[NamedPipeServer] client reconnected and authenticated via handshake"); LastClientHeartbeatUtc = DateTimeOffset.UtcNow; OnClientConnected?.Invoke(); // Step 2: Main message loop while (_pipeStream.IsConnected && !stoppingToken.IsCancellationRequested) { var line = await reader.ReadLineAsync(stoppingToken); if (string.IsNullOrEmpty(line)) break; HandleClientMessage(line); } } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "Named Pipe server encountered an error. Recreating pipe..."); await Task.Delay(2000, stoppingToken); } finally { await _writeLock.WaitAsync(CancellationToken.None); try { _isAuthenticated = false; _writer?.Dispose(); _writer = null; _pipeStream?.Dispose(); _pipeStream = null; } finally { _writeLock.Release(); } } } }, stoppingToken); } private PipeSecurity CreateHardenedPipeSecurity(SecurityIdentifier userSid) { var pipeSecurity = new PipeSecurity(); // 1. LocalSystem: FullControl pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); // 2. Administrators: FullControl pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); // 3. Active Interactive User: ReadWrite (strictly restrict to current active session user) pipeSecurity.AddAccessRule(new PipeAccessRule( userSid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); _logger.LogInformation("[NamedPipeServer] Pipe ACL configured for Active User SID: {Sid}", userSid.Value); return pipeSecurity; } private (uint SessionId, SecurityIdentifier Sid)? TryGetActiveUserIdentity() { uint activeSessionId = WTSGetActiveConsoleSessionId(); if (activeSessionId != 0xFFFFFFFF && WTSQueryUserToken(activeSessionId, out IntPtr token)) { try { using var identity = new WindowsIdentity(token); if (identity.User != null) { return (activeSessionId, identity.User); } } finally { CloseHandle(token); } } for (uint s = 1; s <= 32; s++) { if (WTSQueryUserToken(s, out IntPtr userToken)) { try { using var identity = new WindowsIdentity(userToken); if (identity.User != null) { return (s, identity.User); } } finally { CloseHandle(userToken); } } } try { var currentUser = WindowsIdentity.GetCurrent().User; if (currentUser != null) { uint currentSession = (uint)Process.GetCurrentProcess().SessionId; return (currentSession, currentUser); } } catch { } return null; } private bool ValidateHandshake(string line, IntPtr pipeHandle) { try { // 1. Query Win32 client PID if (!GetNamedPipeClientProcessId(pipeHandle, out uint clientPid) || clientPid == 0) { _logger.LogWarning("[NamedPipeServer] SECURITY: Failed to obtain client PID from named pipe handle."); return false; } // 2. Query Win32 client Session ID if (!GetNamedPipeClientSessionId(pipeHandle, out uint clientSessionId)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Failed to obtain client Session ID from named pipe handle."); return false; } // 3. Verify process name string procName = string.Empty; try { using var proc = Process.GetProcessById((int)clientPid); procName = proc.ProcessName; } catch (Exception ex) { _logger.LogWarning(ex, "[NamedPipeServer] SECURITY: Unable to inspect client process PID={Pid}.", clientPid); return false; } if (!procName.Equals(ExpectedProcessName, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting process '{Name}' (PID={Pid}) is not {Expected}.", procName, clientPid, ExpectedProcessName); return false; } // 4. Validate handshake JSON payload using var doc = JsonDocument.Parse(line); var root = doc.RootElement; if (!root.TryGetProperty("type", out var typeElem) || typeElem.GetString() != "hello" || !root.TryGetProperty("client", out var clientElem) || clientElem.GetString() != "ClassNotify.Client") { _logger.LogWarning("[NamedPipeServer] SECURITY: Invalid handshake payload structure from PID={Pid}.", clientPid); return false; } if (!root.TryGetProperty("protocolVersion", out var verElem) || verElem.GetInt32() < 2) { _logger.LogWarning("[NamedPipeServer] SECURITY: Rejected handshake with protocolVersion < 2 from PID={Pid}.", clientPid); return false; } if (!root.TryGetProperty("token", out var tokenElem) || string.IsNullOrEmpty(tokenElem.GetString())) { _logger.LogWarning("[NamedPipeServer] SECURITY: Missing launch token from PID={Pid}.", clientPid); return false; } string clientToken = tokenElem.GetString()!; // 5. Verify token, PID, and Session against registered authorization lock (_authLock) { if (string.IsNullOrEmpty(_authorizedToken)) { _logger.LogWarning("[NamedPipeServer] SECURITY: No active launch authorization registered on service. Rejecting PID={Pid}.", clientPid); return false; } if (!string.Equals(_authorizedToken, clientToken, StringComparison.Ordinal)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Launch token mismatch from PID={Pid}.", clientPid); return false; } if (_authorizedPid.HasValue && _authorizedPid.Value > 0 && _authorizedPid.Value != (int)clientPid) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting PID={ActualPid} does not match expected PID={ExpectedPid}.", clientPid, _authorizedPid.Value); return false; } if (_authorizedSessionId.HasValue && _authorizedSessionId.Value != clientSessionId) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting SessionId={ActualSession} does not match expected SessionId={ExpectedSession}.", clientSessionId, _authorizedSessionId.Value); return false; } } _logger.LogInformation("[NamedPipeServer] Client verified successfully: PID={Pid}, Session={SessionId}.", clientPid, clientSessionId); return true; } catch (Exception ex) { _logger.LogWarning(ex, "[NamedPipeServer] SECURITY: Handshake validation exception."); return false; } } private async Task SendMessageInternalAsync(IpcMessage message, CancellationToken cancellationToken = default) { if (!_isAuthenticated) { _logger.LogWarning("Cannot send message over Named Pipe: Client is not authenticated via handshake."); return false; } await _writeLock.WaitAsync(cancellationToken); try { if (_writer == null || _pipeStream == null || !_pipeStream.IsConnected) { _logger.LogWarning("Cannot send message: Named Pipe is disconnected."); return false; } var json = JsonSerializer.Serialize(message); await _writer.WriteLineAsync(json); await _writer.FlushAsync(); return true; } catch (IOException ioEx) { _logger.LogWarning(ioEx, "IOException while writing to Named Pipe. Client likely disconnected."); return false; } catch (ObjectDisposedException odEx) { _logger.LogWarning(odEx, "ObjectDisposedException while writing to Named Pipe."); return false; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error writing to Named Pipe."); return false; } finally { _writeLock.Release(); } } public async Task SendNotificationToClientAsync(NotificationDto notification) { var ipcMsg = new IpcMessage { Type = IpcCommandType.ShowNotification, PayloadJson = JsonSerializer.Serialize(notification) }; bool sent = await SendMessageInternalAsync(ipcMsg); if (sent) { _logger.LogInformation("Relayed notification {NotificationId} to WinUI 3 client via Named Pipe.", notification.Id); } return sent; } public async Task SendCloseNotificationAsync(string notificationId) { var ipcMsg = new IpcMessage { Type = IpcCommandType.CloseNotification, PayloadJson = notificationId }; return await SendMessageInternalAsync(ipcMsg); } public async Task SendLicenseStatusToClientAsync(DeviceLicenseStatusDto status) { var ipcMsg = new IpcMessage { Type = IpcCommandType.UpdateLicenseStatus, PayloadJson = JsonSerializer.Serialize(status) }; bool sent = await SendMessageInternalAsync(ipcMsg); if (sent) { _logger.LogInformation("Sent UpdateLicenseStatus ({Status}, Tier={Tier}, RemainingDays={Days}) to client via Named Pipe.", status.Status, status.Tier, status.RemainingDays); } return sent; } public async Task NotifyClassDisplayNameChangedAsync(string newClassName) { var ipcMsg = new IpcMessage { Type = IpcCommandType.ClassDisplayNameChanged, PayloadJson = JsonSerializer.Serialize(new { className = newClassName }) }; bool sent = await SendMessageInternalAsync(ipcMsg); if (sent) { _logger.LogInformation("[NamedPipeServer] Dispatched ClassDisplayNameChanged to client: '{Name}'", newClassName); } return sent; } public async Task SendPairingModeToClientAsync(string pairingCode, int ttlSeconds) { var ipcMsg = new IpcMessage { Type = IpcCommandType.EnterPairingMode, PayloadJson = JsonSerializer.Serialize(new { PairingCode = pairingCode, TtlSeconds = ttlSeconds }) }; bool sent = await SendMessageInternalAsync(ipcMsg); if (sent) { _logger.LogInformation("[NamedPipeServer] Dispatched EnterPairingMode to client: Code={Code}, TTL={TTL}s", pairingCode, ttlSeconds); } return sent; } private readonly System.Collections.Concurrent.ConcurrentDictionary _activeBootstrapSessions = new(); public void EnsureBootstrapPipeRunning(uint sessionId, CancellationToken stoppingToken) { if (!_activeBootstrapSessions.TryAdd(sessionId, true)) { return; } Task.Run(async () => { string pipeName = $"ClassNotify_Service_Bootstrap_{sessionId}"; _logger.LogInformation("[NamedPipeServer] Starting Bootstrap Named Pipe listener: {PipeName}", pipeName); var pipeSecurity = new PipeSecurity(); pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); while (!stoppingToken.IsCancellationRequested) { try { using var server = NamedPipeServerStreamAcl.Create( pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, pipeSecurity); await server.WaitForConnectionAsync(stoppingToken); using var reader = new StreamReader(server, Encoding.UTF8); using var writer = new StreamWriter(server, Encoding.UTF8) { AutoFlush = true }; var cmd = await reader.ReadLineAsync(stoppingToken); _logger.LogInformation("[NamedPipeServer] Bootstrap pipe received command: '{Cmd}' on session {SessionId}", cmd, sessionId); bool showUi = cmd == "ENSURE_CLIENT_AND_SHOW" || cmd == "SHOW_UI"; OnBootstrapRequested?.Invoke(sessionId, showUi); await writer.WriteLineAsync("OK"); await writer.FlushAsync(); } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogWarning(ex, "[NamedPipeServer] Error in bootstrap pipe {PipeName}", pipeName); await Task.Delay(1000, stoppingToken); } } }, stoppingToken); } public async Task SendPingAsync() { var pingMsg = new IpcMessage { Type = IpcCommandType.Ping, PayloadJson = DateTimeOffset.UtcNow.ToString("O") }; return await SendMessageInternalAsync(pingMsg); } public async Task SendTtsCheckAsync(TimeSpan timeout) { if (!await _ttsCheckLock.WaitAsync(timeout)) { _logger.LogWarning("[NamedPipeServer] Concurrent TtsCheck request timed out waiting for lock."); return null; } try { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _ttsCheckTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.TtsCheck, PayloadJson = "{}" }; bool sent = await SendMessageInternalAsync(msg); if (!sent) { _ttsCheckTcs = null; return null; } using var cts = new CancellationTokenSource(timeout); cts.Token.Register(() => tcs.TrySetCanceled()); try { return await tcs.Task; } catch { return null; } finally { _ttsCheckTcs = null; } } finally { _ttsCheckLock.Release(); } } private void HandleClientMessage(string json) { if (!_isAuthenticated) { _logger.LogWarning("[NamedPipeServer] Ignoring message received before handshake completion."); return; } try { var msg = JsonSerializer.Deserialize(json); if (msg == null) return; // Any message from client indicates active IPC connection LastClientHeartbeatUtc = DateTimeOffset.UtcNow; switch (msg.Type) { case IpcCommandType.Pong: _logger.LogDebug("Received Pong heartbeat from client."); break; case IpcCommandType.ReportAck: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var ack = JsonSerializer.Deserialize(msg.PayloadJson); if (ack != null) OnAckReceived?.Invoke(ack); } break; case IpcCommandType.HealthCheck: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var report = JsonSerializer.Deserialize(msg.PayloadJson); if (report != null) OnHealthReportReceived?.Invoke(report); } break; case IpcCommandType.TtsCheckResult: _logger.LogInformation("[NamedPipeServer] Received TtsCheckResult from client: {Payload}", msg.PayloadJson); if (!string.IsNullOrEmpty(msg.PayloadJson)) { var result = JsonSerializer.Deserialize(msg.PayloadJson); if (result != null) { _ttsCheckTcs?.TrySetResult(result); } } break; case IpcCommandType.ReportVisualReceipt: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var visualReceipt = JsonSerializer.Deserialize(msg.PayloadJson); if (visualReceipt != null) { OnVisualReceiptReceived?.Invoke(visualReceipt); } } break; case IpcCommandType.RequestRenew: if (!string.IsNullOrEmpty(msg.PayloadJson)) { _logger.LogInformation("[NamedPipeServer] Client requested license renewal: {Code}", msg.PayloadJson); _ = Task.Run(async () => { try { if (OnRenewRequested != null) { var (ok, replyMsg) = await OnRenewRequested.Invoke(msg.PayloadJson); var replyIpc = new IpcMessage { Type = IpcCommandType.RenewResult, PayloadJson = JsonSerializer.Serialize(new { success = ok, message = replyMsg }) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnRenewRequested."); } }); } break; case IpcCommandType.RequestActivate: if (!string.IsNullOrEmpty(msg.PayloadJson)) { _logger.LogInformation("[NamedPipeServer] Client requested device activation: payload={Payload}", msg.PayloadJson); _ = Task.Run(async () => { try { if (OnActivateRequested != null) { DeviceActivationRequestDto? req = null; if (msg.PayloadJson.Trim().StartsWith("{")) { try { req = JsonSerializer.Deserialize(msg.PayloadJson); } catch {} } if (req == null || string.IsNullOrEmpty(req.ActivationCode)) { req = new DeviceActivationRequestDto { ActivationCode = msg.PayloadJson }; } var (ok, replyMsg, className, expireDate) = await OnActivateRequested.Invoke(req); var replyIpc = new IpcMessage { Type = IpcCommandType.ActivateResult, PayloadJson = JsonSerializer.Serialize(new { success = ok, message = replyMsg, className = className, expireDate = expireDate }) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnActivateRequested."); } }); } break; case IpcCommandType.RequestUpdateClassName: if (!string.IsNullOrEmpty(msg.PayloadJson)) { _logger.LogInformation("[NamedPipeServer] Client requested class name update: {Payload}", msg.PayloadJson); _ = Task.Run(async () => { try { var req = JsonSerializer.Deserialize(msg.PayloadJson); if (req != null && OnUpdateClassNameRequested != null) { var (ok, replyMsg) = await OnUpdateClassNameRequested.Invoke(req); var replyIpc = new IpcMessage { Type = IpcCommandType.UpdateClassNameResult, PayloadJson = JsonSerializer.Serialize(new { success = ok, message = replyMsg }) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnUpdateClassNameRequested."); } }); } break; case IpcCommandType.GetClientState: _logger.LogInformation("[NamedPipeServer] Client requested client state snapshot."); _ = Task.Run(async () => { try { if (OnGetClientStateRequested != null) { var stateDto = await OnGetClientStateRequested.Invoke(); var replyIpc = new IpcMessage { Type = IpcCommandType.ClientStateResult, PayloadJson = JsonSerializer.Serialize(stateDto) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnGetClientStateRequested."); } }); break; case IpcCommandType.RequestPairingMode: _logger.LogInformation("[NamedPipeServer] Client requested temporary pairing mode."); _ = Task.Run(async () => { try { if (OnRequestPairingMode != null) { var (ok, code, ttl, err) = await OnRequestPairingMode.Invoke(); var replyIpc = new IpcMessage { Type = IpcCommandType.PairingModeResult, PayloadJson = JsonSerializer.Serialize(new { success = ok, pairingCode = code, ttlSeconds = ttl, errorMessage = err }) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnRequestPairingMode."); } }); break; case IpcCommandType.RequestPairingSession: _logger.LogInformation("[NamedPipeServer] Client requested pairing session."); _ = Task.Run(async () => { try { PairingPurpose purpose = PairingPurpose.InitialDeviceBinding; if (!string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); if (doc.RootElement.TryGetProperty("purpose", out var pElem)) { if (Enum.TryParse(pElem.GetString(), out var parsed)) purpose = parsed; } } catch { } } if (OnRequestPairingSession != null) { var session = await OnRequestPairingSession.Invoke(purpose); var replyIpc = new IpcMessage { Type = IpcCommandType.PairingSessionResult, PayloadJson = JsonSerializer.Serialize(session) }; await SendMessageInternalAsync(replyIpc); } } catch (Exception ex) { _logger.LogError(ex, "[NamedPipeServer] Error processing OnRequestPairingSession."); } }); break; } } catch (Exception ex) { _logger.LogError(ex, "Error processing IPC message from client: {Json}", json); } } }