using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; namespace BlockerBTest; class Program { private const string HubUrl = "https://classnotify.paradise.eu.org/hubs/device"; private const string ApiBaseUrl = "https://classnotify.paradise.eu.org"; private const string DeviceId = "dev_59e35e79"; private const string OldRevokedToken = "dtoken_2752538ff0374e2d8e6ba299fcb18361"; private const string NewActiveToken = "dtoken_2904eeb9bc544283928efcdbc4ae8172"; private const string TeacherToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJ1c3JfNWJkYjczMThhYjQ2NDk0MSIsInVuaXF1ZV9uYW1lIjoi546L6ICB5biIIiwicm9sZSI6IlRlbmFudE93bmVyIiwidGVuYW50X2lkIjoidF9wXzM5Y2UwMmMzNjE4NjQzNzkiLCJ0ZW5hbnRfdHlwZSI6IlBlcnNvbmFsIiwidG9rZW5fdmVyc2lvbiI6IjEiLCJuYmYiOjE3OTA1NjUzMDMsImV4cCI6MTc5MTc3NDkwMywiaWF0IjoxNzkwNTY1MzAzLCJpc3MiOiJDbGFzc05vdGlmeS5TZXJ2ZXIiLCJhdWQiOiJDbGFzc05vdGlmeS5DbGllbnRzIn0.B_KrsJALJkQgL_CBM4YT9OMhgsZCTfiKcSSBmww_tOE"; private const string TargetClassId = "cls_2162e73de91d4367"; static async Task Main(string[] args) { Console.WriteLine("================================================================================"); Console.WriteLine(" ClassNotify Turn 73 Blocker B Verification: Dual-Token & CAS Race Suite "); Console.WriteLine("================================================================================"); Console.WriteLine($"Server: {HubUrl}"); Console.WriteLine($"Device: {DeviceId}"); Console.WriteLine($"Timestamp: {DateTimeOffset.UtcNow:u}\n"); bool test1Passed = false; bool test2Passed = false; try { // --------------------------------------------------------------------------------- // VERIFICATION 1: Old credential/token reconnect is rejected while NEW token succeeds // --------------------------------------------------------------------------------- Console.WriteLine("[TEST 1/2] Verifying: OLD credential/token reconnect is rejected while NEW token succeeds..."); // 1.A: Connect with OLD revoked token Console.WriteLine(" [1.A] Attempting connection with OLD revoked token (dtoken_2752538ff...)..."); var oldConn = new HubConnectionBuilder() .WithUrl(HubUrl, opts => { opts.Headers["X-Device-Id"] = DeviceId; opts.Headers["X-Device-Token"] = OldRevokedToken; }) .Build(); bool oldClosedFired = false; string oldCloseReason = ""; oldConn.Closed += ex => { oldClosedFired = true; oldCloseReason = ex?.Message ?? "Server aborted connection"; return Task.CompletedTask; }; bool oldRejected = false; try { await oldConn.StartAsync(); Console.WriteLine($" [1.A] StartAsync completed (transport connected). Checking if server immediately aborts..."); // Server OnConnectedAsync checks token hash. If invalid/revoked, it logs warning and calls Context.Abort(). // Calling any Hub method or waiting 1 second will observe disconnection. await Task.Delay(1500); if (oldConn.State == HubConnectionState.Disconnected || oldClosedFired) { oldRejected = true; Console.WriteLine($" [1.A] PASS: Old connection was immediately ABORTED by server! State={oldConn.State}, ClosedReason='{oldCloseReason}'"); } else { // Try invoking SendHeartbeat - server must abort stale/revoked connection try { await oldConn.InvokeAsync("SendHeartbeat", DeviceId, DateTimeOffset.UtcNow); Console.WriteLine(" [1.A] FAIL: Old token was accepted by server!"); } catch (Exception ex) { oldRejected = true; Console.WriteLine($" [1.A] PASS: Hub method invocation on old token rejected: {ex.Message}"); } } } catch (HttpRequestException httpEx) { oldRejected = true; Console.WriteLine($" [1.A] PASS: Old token rejected at HTTP handshake/negotiate: {httpEx.StatusCode} {httpEx.Message}"); } catch (Exception ex) { oldRejected = true; Console.WriteLine($" [1.A] PASS: Old token connection failed as expected: {ex.Message}"); } finally { try { await oldConn.DisposeAsync(); } catch { } } if (!oldRejected) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" [1.A] CRITICAL: Old token was NOT rejected!"); Console.ResetColor(); return 1; } // 1.B: Connect with NEW active token Console.WriteLine("\n [1.B] Attempting connection with NEW active token (dtoken_2904eeb9b...)..."); var newConn = new HubConnectionBuilder() .WithUrl(HubUrl, opts => { opts.Headers["X-Device-Id"] = DeviceId; opts.Headers["X-Device-Token"] = NewActiveToken; }) .Build(); var licenseTcs = new TaskCompletionSource(); newConn.On("ReceiveLicenseStatus", status => { licenseTcs.TrySetResult(status); }); await newConn.StartAsync(); Console.WriteLine($" [1.B] StartAsync SUCCESS: ConnectionId={newConn.ConnectionId}, State={newConn.State}"); var licWait = await Task.WhenAny(licenseTcs.Task, Task.Delay(5000)); if (licWait == licenseTcs.Task) { var lic = await licenseTcs.Task; Console.WriteLine($" [1.B] Received License Status: Status={lic.Status}, Tier={lic.Tier}, RemainingDays={lic.RemainingDays}"); } else { Console.WriteLine(" [1.B] Warning: License status event timed out, but connection is active."); } // Verify active heartbeat on new connection await newConn.InvokeAsync("SendHeartbeat", TargetClassId); Console.WriteLine(" [1.B] PASS: Heartbeat succeeded on NEW connection!"); await newConn.DisposeAsync(); test1Passed = true; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\n>>> TEST 1 RESULT: PASSED (Old token rejected, New token authenticated & functional)\n"); Console.ResetColor(); // --------------------------------------------------------------------------------- // VERIFICATION 2: Late disconnect of OLD connection cannot remove the NEW registry entry // --------------------------------------------------------------------------------- Console.WriteLine("[TEST 2/2] Verifying: Late disconnect of OLD connection cannot remove NEW registry entry (CAS Guard)..."); // 2.A: Connect Connection A (Old) Console.WriteLine(" [2.A] Connecting Connection A (representing original connection)..."); var connA = new HubConnectionBuilder() .WithUrl(HubUrl, opts => { opts.Headers["X-Device-Id"] = DeviceId; opts.Headers["X-Device-Token"] = NewActiveToken; }) .Build(); await connA.StartAsync(); var connA_Id = connA.ConnectionId; Console.WriteLine($" [2.A] Connection A active: ConnectionId={connA_Id}"); // 2.B: Connect Connection B (New) for same DeviceId Console.WriteLine(" [2.B] Connecting Connection B (representing newly established session during reconnect race)..."); var connB = new HubConnectionBuilder() .WithUrl(HubUrl, opts => { opts.Headers["X-Device-Id"] = DeviceId; opts.Headers["X-Device-Token"] = NewActiveToken; }) .Build(); var receivedByB_Tcs = new TaskCompletionSource(); connB.On("ReceiveNotification", notif => { Console.WriteLine($" [EVENT] Connection B received notification: Id={notif.Id}, Title='{notif.Title}'"); receivedByB_Tcs.TrySetResult(notif); }); await connB.StartAsync(); var connB_Id = connB.ConnectionId; Console.WriteLine($" [2.B] Connection B active: ConnectionId={connB_Id}"); Console.WriteLine($" [2.B] Server should now map Device {DeviceId} -> Connection B ({connB_Id})"); // Wait 1 second to ensure server registered Connection B as current in _deviceToConnection await Task.Delay(1000); // 2.C: Now simulate Connection A disconnecting late! Console.WriteLine($" [2.C] Simulating LATE DISCONNECT of Connection A ({connA_Id})..."); await connA.StopAsync(); await connA.DisposeAsync(); Console.WriteLine($" [2.C] Connection A stopped. Server OnDisconnectedAsync / UnregisterDeviceConnectionAsync fired for {connA_Id}."); // Wait 1.5 seconds for server unregistration and CAS check to complete await Task.Delay(1500); // 2.D: Verify Connection B is STILL the active connection in server registry by sending notification! Console.WriteLine(" [2.D] Triggering live notification dispatch from teacher to verify Connection B is still active..."); using var http = new HttpClient(); http.DefaultRequestHeaders.Add("Authorization", $"Bearer {TeacherToken}"); var payload = new { classId = TargetClassId, title = "【CAS防误删验证】", message = $"Blocker B CAS Race Test: ConnA={connA_Id[..8]} late disconnected, ConnB={connB_Id[..8]} must still receive.", type = 0 }; var httpResp = await http.PostAsync($"{ApiBaseUrl}/api/notification/send", new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")); var respBody = await httpResp.Content.ReadAsStringAsync(); Console.WriteLine($" [2.D] Send Notification HTTP Response: {httpResp.StatusCode} -> {respBody}"); // 2.E: Await receipt by Connection B var notifWait = await Task.WhenAny(receivedByB_Tcs.Task, Task.Delay(6000)); if (notifWait == receivedByB_Tcs.Task) { var receivedNotif = await receivedByB_Tcs.Task; Console.WriteLine($" [2.E] PASS: Connection B successfully received notification '{receivedNotif.Title}' (Id={receivedNotif.Id})!"); // Send ACK back on Connection B var ack = new AckReceiptDto { MessageId = receivedNotif.Id, ClassId = TargetClassId, CorrelationId = receivedNotif.CorrelationId, Status = ClassNotify.Shared.Enums.AckStatus.Delivered, Timestamp = DateTimeOffset.UtcNow }; await connB.InvokeAsync("SendAckReceipt", ack); Console.WriteLine(" [2.E] ACK receipt forwarded from Connection B to server."); test2Passed = true; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" [2.E] FAIL: Connection B did NOT receive the notification! CAS guard may have failed."); Console.ResetColor(); } await connB.DisposeAsync(); if (test2Passed) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\n>>> TEST 2 RESULT: PASSED (Late disconnect of ConnA did NOT remove ConnB from registry)\n"); Console.ResetColor(); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n[ERROR] Unhandled exception during verification: {ex}"); Console.ResetColor(); return 1; } if (test1Passed && test2Passed) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("================================================================================"); Console.WriteLine(" BLOCKER B FULL SUITE: 100% PASSED (ALL VERIFICATION GATES CLEARED) "); Console.WriteLine("================================================================================"); Console.ResetColor(); return 0; } return 1; } }