-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1215 lines (1026 loc) · 46.3 KB
/
Program.cs
File metadata and controls
1215 lines (1026 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Spectre.Console;
namespace HookReplay.Cli;
// JSON source generator for AOT/trimming compatibility
[JsonSerializable(typeof(CliConfig))]
[JsonSerializable(typeof(ReplayRequest))]
[JsonSerializable(typeof(JsonDocument))]
[JsonSerializable(typeof(JsonElement))]
[JsonSerializable(typeof(Dictionary<string, string>))]
[JsonSerializable(typeof(SseConnectedEvent))]
[JsonSerializable(typeof(TelemetryPayload))]
[JsonSerializable(typeof(NpmPackageInfo))]
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal partial class CliJsonContext : JsonSerializerContext
{
}
internal class Program
{
private const string DefaultServerUrl = "https://hookreplay.dev";
private const string NpmPackageName = "hookreplay";
private static readonly string CurrentVersion = typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "1.0.0";
private static readonly string ConfigFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".hookreplay",
"config.json");
private static CliConfig _config = new();
private static HttpClient? _sseClient;
private static bool _isConnected;
private static readonly List<ReplayRequest> RequestHistory = [];
private static CancellationTokenSource? _connectionCts;
private static Task? _sseListenerTask;
private static string? _latestVersion;
private static string? _currentSseUrl;
private static string? _currentApiKey;
private static bool _autoReconnectEnabled = true;
private static int _reconnectAttempts = 0;
private const int MaxReconnectAttempts = 10;
private static readonly int[] ReconnectDelaysMs = [1000, 2000, 5000, 10000, 30000];
private static async Task<int> Main(string[] args)
{
_config = LoadConfig();
// Track first run (anonymous, non-blocking)
_ = TrackFirstRunAsync();
// Show welcome screen
Console.Clear();
ShowWelcome();
// Check for updates (non-blocking, then prompt if available)
await CheckForUpdatesAsync();
// Main interactive loop
await RunInteractiveMode();
return 0;
}
private static void ShowWelcome()
{
// Professional gradient ASCII art logo
var logo = new[]
{
"██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗██████╗ ███████╗██████╗ ██╗ █████╗ ██╗ ██╗",
"██║ ██║██╔═══██╗██╔═══██╗██║ ██╔╝██╔══██╗██╔════╝██╔══██╗██║ ██╔══██╗╚██╗ ██╔╝",
"███████║██║ ██║██║ ██║█████╔╝ ██████╔╝█████╗ ██████╔╝██║ ███████║ ╚████╔╝ ",
"██╔══██║██║ ██║██║ ██║██╔═██╗ ██╔══██╗██╔══╝ ██╔═══╝ ██║ ██╔══██║ ╚██╔╝ ",
"██║ ██║╚██████╔╝╚██████╔╝██║ ██╗██║ ██║███████╗██║ ███████╗██║ ██║ ██║ ",
"╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ "
};
// Gradient colors from cyan to blue to purple
var gradientColors = new[] { Color.Cyan1, Color.DeepSkyBlue1, Color.DodgerBlue1, Color.Blue, Color.Purple, Color.MediumPurple };
AnsiConsole.WriteLine();
for (var i = 0; i < logo.Length; i++)
{
var color = gradientColors[i % gradientColors.Length];
AnsiConsole.MarkupLine($"[{color.ToMarkup()}]{logo[i].EscapeMarkup()}[/]");
}
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[silver]v{CurrentVersion}[/] [silver]Catch, inspect, and replay webhooks locally[/]");
AnsiConsole.WriteLine();
var statusTable = new Table().Border(TableBorder.Rounded).BorderColor(Color.Grey);
statusTable.AddColumn("Status");
statusTable.AddColumn("Value");
statusTable.AddRow("Connection", "[red]Disconnected[/]");
statusTable.AddRow("API Key", string.IsNullOrEmpty(_config.ApiKey) ? "[yellow]Not configured[/]" : $"[green]{_config.ApiKey[..Math.Min(8, _config.ApiKey.Length)]}****[/]");
statusTable.AddRow("Server", _config.ServerUrl ?? DefaultServerUrl);
AnsiConsole.Write(statusTable);
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[silver]Type[/] [white]help[/] [silver]for available commands, or[/] [white]quit[/] [silver]to exit.[/]");
AnsiConsole.WriteLine();
}
private static async Task CheckForUpdatesAsync()
{
try
{
using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("HookReplay-CLI");
// Check npm registry for latest version
var response = await httpClient.GetStringAsync($"https://registry.npmjs.org/{NpmPackageName}/latest");
using var doc = JsonDocument.Parse(response);
if (doc.RootElement.TryGetProperty("version", out var versionElement))
{
_latestVersion = versionElement.GetString();
if (!string.IsNullOrEmpty(_latestVersion) && IsNewerVersion(_latestVersion, CurrentVersion))
{
AnsiConsole.WriteLine();
AnsiConsole.Write(new Rule($"[yellow]Update Available[/]").RuleStyle("yellow"));
AnsiConsole.MarkupLine($"[yellow]A new version of HookReplay CLI is available:[/] [green]{_latestVersion}[/] [silver](current: {CurrentVersion})[/]");
AnsiConsole.WriteLine();
if (AnsiConsole.Confirm("[yellow]Would you like to update now?[/]", defaultValue: false))
{
await RunUpdateAsync();
}
else
{
AnsiConsole.MarkupLine("[silver]You can update later with the[/] [white]update[/] [silver]command.[/]");
}
AnsiConsole.WriteLine();
}
}
}
catch
{
// Silently ignore update check failures
}
}
private static bool IsNewerVersion(string latest, string current)
{
try
{
var latestParts = latest.Split('.').Select(int.Parse).ToArray();
var currentParts = current.Split('.').Select(int.Parse).ToArray();
for (var i = 0; i < Math.Min(latestParts.Length, currentParts.Length); i++)
{
if (latestParts[i] > currentParts[i]) return true;
if (latestParts[i] < currentParts[i]) return false;
}
return latestParts.Length > currentParts.Length;
}
catch
{
return false;
}
}
private static async Task RunUpdateAsync()
{
if (string.IsNullOrEmpty(_latestVersion))
{
AnsiConsole.MarkupLine("[yellow]No update information available. Please try again later.[/]");
return;
}
await AnsiConsole.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("cyan"))
.StartAsync("Updating HookReplay CLI...", async ctx =>
{
try
{
var executablePath = Environment.ProcessPath;
if (string.IsNullOrEmpty(executablePath))
{
AnsiConsole.MarkupLine("[red]Could not determine executable path.[/]");
return;
}
// Determine platform RID
var rid = GetRuntimeIdentifier();
if (string.IsNullOrEmpty(rid))
{
AnsiConsole.MarkupLine("[red]Unsupported platform for auto-update.[/]");
AnsiConsole.MarkupLine("[silver]Please update manually: npm install -g hookreplay[/]");
return;
}
var isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
var ext = isWindows ? "zip" : "tar.gz";
var downloadUrl = $"https://github.com/ahmedmandur/hookreplay-cli/releases/download/v{_latestVersion}/hookreplay-{_latestVersion}-{rid}.{ext}";
ctx.Status($"Downloading v{_latestVersion}...");
using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("HookReplay-CLI", CurrentVersion));
var response = await client.GetAsync(downloadUrl);
if (!response.IsSuccessStatusCode)
{
AnsiConsole.MarkupLine($"[red]Download failed:[/] HTTP {(int)response.StatusCode}");
AnsiConsole.MarkupLine("[silver]Please update manually: npm install -g hookreplay[/]");
return;
}
var archiveBytes = await response.Content.ReadAsByteArrayAsync();
ctx.Status("Extracting...");
// Extract binary from archive
byte[] binaryBytes;
if (isWindows)
{
binaryBytes = ExtractFromZip(archiveBytes, "hookreplay.exe");
}
else
{
binaryBytes = ExtractFromTarGz(archiveBytes, "hookreplay");
}
if (binaryBytes.Length == 0)
{
AnsiConsole.MarkupLine("[red]Failed to extract binary from archive.[/]");
return;
}
ctx.Status("Installing...");
// Determine target path - for npm installs, replace hookreplay-bin
var targetPath = executablePath;
var binDir = Path.GetDirectoryName(executablePath) ?? "";
// Check if this is an npm install (binary is named hookreplay-bin)
if (Path.GetFileName(executablePath) == "hookreplay-bin" ||
Path.GetFileName(executablePath) == "hookreplay-bin.exe")
{
targetPath = executablePath;
}
else if (File.Exists(Path.Combine(binDir, "hookreplay-bin")))
{
targetPath = Path.Combine(binDir, "hookreplay-bin");
}
else if (File.Exists(Path.Combine(binDir, "hookreplay-bin.exe")))
{
targetPath = Path.Combine(binDir, "hookreplay-bin.exe");
}
// On Unix, we can replace the running binary by writing to a temp file and moving
// On Windows, we need to rename the old file first
var tempPath = targetPath + ".new";
var oldPath = targetPath + ".old";
// Write new binary to temp file
await File.WriteAllBytesAsync(tempPath, binaryBytes);
// Make executable on Unix
if (!isWindows)
{
var chmod = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "chmod",
Arguments = $"+x \"{tempPath}\"",
UseShellExecute = false,
CreateNoWindow = true
}
};
chmod.Start();
await chmod.WaitForExitAsync();
}
// Atomic replace: rename current to .old, rename .new to current
if (File.Exists(oldPath))
File.Delete(oldPath);
File.Move(targetPath, oldPath);
File.Move(tempPath, targetPath);
// Clean up old file
try { File.Delete(oldPath); } catch { /* ignore */ }
AnsiConsole.MarkupLine($"[green]✓ Updated to v{_latestVersion}![/]");
AnsiConsole.MarkupLine("[yellow]Please restart the CLI to use the new version.[/]");
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Update failed:[/] {ex.Message}");
AnsiConsole.MarkupLine("[silver]Please update manually: npm install -g hookreplay[/]");
}
});
}
private static string? GetRuntimeIdentifier()
{
var arch = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture;
var archStr = arch switch
{
System.Runtime.InteropServices.Architecture.X64 => "x64",
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
_ => null
};
if (archStr == null) return null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
return $"win-{archStr}";
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
// Check if macOS or Linux
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
return $"osx-{archStr}";
return $"linux-{archStr}";
}
return null;
}
private static byte[] ExtractFromZip(byte[] zipBytes, string fileName)
{
using var stream = new MemoryStream(zipBytes);
using var archive = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Read);
foreach (var entry in archive.Entries)
{
if (entry.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase))
{
using var entryStream = entry.Open();
using var ms = new MemoryStream();
entryStream.CopyTo(ms);
return ms.ToArray();
}
}
return Array.Empty<byte>();
}
private static byte[] ExtractFromTarGz(byte[] tarGzBytes, string fileName)
{
using var gzStream = new MemoryStream(tarGzBytes);
using var decompressed = new System.IO.Compression.GZipStream(gzStream, System.IO.Compression.CompressionMode.Decompress);
using var tarStream = new MemoryStream();
decompressed.CopyTo(tarStream);
tarStream.Position = 0;
// Simple tar parsing (POSIX ustar format)
var buffer = tarStream.ToArray();
var offset = 0;
while (offset < buffer.Length - 512)
{
// Read header
var header = new byte[512];
Array.Copy(buffer, offset, header, 0, 512);
// Check for empty block (end of archive)
if (header[0] == 0) break;
// Get filename (first 100 bytes, null-terminated)
var nameBytes = new byte[100];
Array.Copy(header, 0, nameBytes, 0, 100);
var name = Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim();
// Get file size (bytes 124-135, octal)
var sizeBytes = new byte[12];
Array.Copy(header, 124, sizeBytes, 0, 12);
var sizeStr = Encoding.ASCII.GetString(sizeBytes).TrimEnd('\0').Trim();
var size = string.IsNullOrEmpty(sizeStr) ? 0 : Convert.ToInt64(sizeStr, 8);
offset += 512; // Move past header
if (name == fileName || name.EndsWith("/" + fileName))
{
var content = new byte[size];
Array.Copy(buffer, offset, content, 0, (int)size);
return content;
}
// Move to next file (size rounded up to 512-byte boundary)
offset += (int)((size + 511) / 512 * 512);
}
return Array.Empty<byte>();
}
private static void ShowVersion()
{
var versionPanel = new Panel(
new Markup($"[bold cyan]HookReplay CLI[/]\n" +
$"[silver]Version:[/] [white]{CurrentVersion}[/]\n" +
$"[silver]Runtime:[/] [white].NET {Environment.Version}[/]\n" +
$"[silver]OS:[/] [white]{Environment.OSVersion.Platform} {Environment.OSVersion.Version}[/]\n" +
$"[silver]Architecture:[/] [white]{System.Runtime.InteropServices.RuntimeInformation.OSArchitecture}[/]"))
.Header("[cyan]Version Info[/]")
.Border(BoxBorder.Rounded)
.BorderColor(Color.Cyan1);
AnsiConsole.Write(versionPanel);
if (!string.IsNullOrEmpty(_latestVersion) && IsNewerVersion(_latestVersion, CurrentVersion))
{
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[yellow]Update available:[/] [green]{_latestVersion}[/] [silver](run[/] [white]update[/] [silver]to install)[/]");
}
}
private static async Task RunInteractiveMode()
{
while (true)
{
var prompt = _isConnected ? "[green]hookreplay[/]" : "[blue]hookreplay[/]";
var statusIndicator = _isConnected ? "[green]●[/]" : "[red]●[/]";
AnsiConsole.Markup($"{statusIndicator} {prompt}> ");
var input = Console.ReadLine()?.Trim();
if (string.IsNullOrEmpty(input))
continue;
var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var command = parts[0].ToLower();
var args = parts.Skip(1).ToArray();
try
{
switch (command)
{
case "help":
case "?":
ShowHelp();
break;
case "connect":
await ConnectAsync(args);
break;
case "disconnect":
await DisconnectAsync();
break;
case "status":
ShowStatus();
break;
case "config":
HandleConfig(args);
break;
case "history":
ShowHistory();
break;
case "replay":
await ReplayFromHistory(args);
break;
case "clear":
Console.Clear();
ShowWelcome();
break;
case "version":
case "v":
case "--version":
case "-v":
ShowVersion();
break;
case "update":
await RunUpdateAsync();
break;
case "quit":
case "exit":
case "q":
await DisconnectAsync();
AnsiConsole.MarkupLine("[silver]Goodbye![/]");
return;
default:
AnsiConsole.MarkupLine($"[red]Unknown command:[/] {command}. Type [white]help[/] for available commands.");
break;
}
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Error:[/] {ex.Message}");
}
AnsiConsole.WriteLine();
}
}
private static void ShowHelp()
{
var table = new Table().Border(TableBorder.Rounded).BorderColor(Color.Grey);
table.AddColumn(new TableColumn("[cyan]Command[/]").Width(20));
table.AddColumn(new TableColumn("[cyan]Description[/]"));
table.AddRow("[white]connect[/]", "Connect to HookReplay server");
table.AddRow("[white]disconnect[/]", "Disconnect from server");
table.AddRow("[white]status[/]", "Show connection status");
table.AddRow("[white]config[/]", "Manage configuration (api-key, server)");
table.AddRow("[white]history[/]", "Show received request history");
table.AddRow("[white]replay <number>[/]", "Replay a request from history");
table.AddRow("[white]version[/]", "Show version and system info");
table.AddRow("[white]update[/]", "Check for and install updates");
table.AddRow("[white]clear[/]", "Clear the screen");
table.AddRow("[white]help[/]", "Show this help message");
table.AddRow("[white]quit[/]", "Exit the CLI");
AnsiConsole.Write(table);
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[silver]Examples:[/]");
AnsiConsole.MarkupLine(" [white]config api-key hr_abc123...[/] [silver]- Set your API key[/]");
AnsiConsole.MarkupLine(" [white]config server https://hookreplay.dev[/] [silver]- Set server URL[/]");
AnsiConsole.MarkupLine(" [white]connect[/] [silver]- Connect to server[/]");
AnsiConsole.MarkupLine(" [white]replay 1[/] [silver]- Replay first request in history[/]");
}
private static async Task ConnectAsync(string[] args)
{
if (_isConnected)
{
AnsiConsole.MarkupLine("[yellow]Already connected. Use [white]disconnect[/] first.[/]");
return;
}
// Check for API key in args or config
var apiKey = args.Length > 0 ? args[0] : _config.ApiKey;
if (string.IsNullOrEmpty(apiKey))
{
AnsiConsole.MarkupLine("[red]No API key configured.[/]");
AnsiConsole.MarkupLine("[silver]Use [white]config api-key <your-key>[/] to set it.[/]");
// Offer to set it now
if (AnsiConsole.Confirm("Would you like to enter your API key now?"))
{
apiKey = AnsiConsole.Prompt(
new TextPrompt<string>("[blue]API Key:[/]")
.Secret());
_config.ApiKey = apiKey;
SaveConfig(_config);
AnsiConsole.MarkupLine("[green]API key saved![/]");
}
else
{
return;
}
}
var serverUrl = _config.ServerUrl ?? DefaultServerUrl;
await AnsiConsole.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("blue"))
.StartAsync($"Connecting to {serverUrl}...", async ctx =>
{
var sseUrl = $"{serverUrl.TrimEnd('/')}/api/cli/events";
// Create HTTP handler that bypasses SSL for localhost
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (message.RequestUri?.Host == "localhost" || message.RequestUri?.Host == "127.0.0.1")
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
_sseClient = new HttpClient(handler)
{
Timeout = Timeout.InfiniteTimeSpan // SSE connections are long-lived
};
// Set Authorization header (more secure than query string)
_sseClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
_connectionCts = new CancellationTokenSource();
// Store connection info for reconnection
_currentSseUrl = sseUrl;
_currentApiKey = apiKey;
_autoReconnectEnabled = true;
_reconnectAttempts = 0;
// Start listening to SSE events in background
_sseListenerTask = ListenToSseAsync(sseUrl, _connectionCts.Token);
// Wait a bit to see if connection succeeds
await Task.Delay(1000);
if (!_isConnected)
{
// Connection might take a bit longer, wait more
await Task.Delay(2000);
}
});
if (_isConnected)
{
AnsiConsole.MarkupLine("[green]Connected![/] Waiting for replay requests...");
}
else
{
AnsiConsole.MarkupLine("[red]Failed to connect. Check your API key and server URL.[/]");
}
}
private static async Task ListenToSseAsync(string url, CancellationToken cancellationToken)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
using var response = await _sseClient!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[red]Connection failed: {response.StatusCode} - {error}[/]");
return;
}
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var reader = new StreamReader(stream);
string? eventType = null;
var dataBuilder = new StringBuilder();
while (!cancellationToken.IsCancellationRequested)
{
var line = await reader.ReadLineAsync(cancellationToken);
if (line == null)
{
// Stream ended
break;
}
if (line.StartsWith("event:"))
{
eventType = line[6..].Trim();
}
else if (line.StartsWith("data:"))
{
dataBuilder.Append(line[5..].Trim());
}
else if (string.IsNullOrEmpty(line))
{
// Empty line = end of event
if (!string.IsNullOrEmpty(eventType) && dataBuilder.Length > 0)
{
var data = dataBuilder.ToString();
await HandleSseEvent(eventType, data);
}
eventType = null;
dataBuilder.Clear();
}
}
}
catch (OperationCanceledException)
{
// Normal disconnection - don't auto-reconnect
_autoReconnectEnabled = false;
}
catch (Exception ex)
{
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[red]SSE connection error:[/] {Markup.Escape(ex.Message)}");
}
finally
{
_isConnected = false;
AnsiConsole.WriteLine();
}
// Attempt auto-reconnect if not manually disconnected (moved outside finally)
if (_autoReconnectEnabled && !cancellationToken.IsCancellationRequested && _reconnectAttempts < MaxReconnectAttempts)
{
_reconnectAttempts++;
var delayIndex = Math.Min(_reconnectAttempts - 1, ReconnectDelaysMs.Length - 1);
var delayMs = ReconnectDelaysMs[delayIndex];
AnsiConsole.MarkupLine($"[yellow]Connection lost. Reconnecting in {delayMs / 1000}s (attempt {_reconnectAttempts}/{MaxReconnectAttempts})...[/]");
try
{
await Task.Delay(delayMs, cancellationToken);
if (!cancellationToken.IsCancellationRequested && _currentSseUrl != null)
{
// Reconnect
await ListenToSseAsync(_currentSseUrl, cancellationToken);
return; // Don't show disconnected message
}
}
catch (OperationCanceledException)
{
// Cancelled during reconnect delay
}
}
else if (_reconnectAttempts >= MaxReconnectAttempts)
{
AnsiConsole.MarkupLine("[red]Max reconnection attempts reached. Use 'connect' to reconnect manually.[/]");
}
else if (!_autoReconnectEnabled || cancellationToken.IsCancellationRequested)
{
AnsiConsole.MarkupLine("[yellow]Disconnected from server.[/]");
}
AnsiConsole.Markup(_isConnected ? "[green]●[/] [green]hookreplay[/]> " : "[red]●[/] [blue]hookreplay[/]> ");
}
private static async Task HandleSseEvent(string eventType, string data)
{
switch (eventType)
{
case "connected":
_isConnected = true;
_reconnectAttempts = 0; // Reset reconnect counter on successful connection
try
{
var connectedEvent = JsonSerializer.Deserialize(data, CliJsonContext.Default.SseConnectedEvent);
AnsiConsole.MarkupLine($"[silver]Server confirmed connection: {connectedEvent?.Message}[/]");
}
catch
{
AnsiConsole.MarkupLine($"[silver]Server confirmed connection[/]");
}
break;
case "replay":
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[cyan]>>> Received ReplayRequest from server![/]");
try
{
using var jsonDoc = JsonDocument.Parse(data);
var jsonElement = jsonDoc.RootElement;
var request = new ReplayRequest
{
Method = jsonElement.GetProperty("method").GetString() ?? "GET",
Url = jsonElement.GetProperty("url").GetString() ?? "",
Body = jsonElement.TryGetProperty("body", out var bodyProp) ? bodyProp.GetString() : null,
QueryString = jsonElement.TryGetProperty("queryString", out var qsProp) ? qsProp.GetString() : null,
RequestId = jsonElement.TryGetProperty("requestId", out var idProp) ? idProp.GetGuid() : Guid.Empty
};
// Parse headers
if (jsonElement.TryGetProperty("headers", out var headersProp) && headersProp.ValueKind == JsonValueKind.Object)
{
request.Headers = new Dictionary<string, string>();
foreach (var header in headersProp.EnumerateObject())
{
request.Headers[header.Name] = header.Value.GetString() ?? "";
}
}
await HandleIncomingRequest(request);
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Error parsing request: {ex.Message}[/]");
AnsiConsole.MarkupLine($"[silver]Raw data: {data}[/]");
}
AnsiConsole.Markup(_isConnected ? "[green]●[/] [green]hookreplay[/]> " : "[red]●[/] [blue]hookreplay[/]> ");
break;
default:
AnsiConsole.MarkupLine($"[silver]Unknown event: {eventType}[/]");
break;
}
}
private static async Task HandleIncomingRequest(ReplayRequest request)
{
// Add to history
RequestHistory.Insert(0, request);
if (RequestHistory.Count > 50) RequestHistory.RemoveAt(RequestHistory.Count - 1);
if (string.IsNullOrEmpty(request.Url))
{
AnsiConsole.MarkupLine("[red]Error: No target URL provided by server[/]");
return;
}
var fullUrl = request.Url + (request.QueryString ?? "");
AnsiConsole.Write(new Rule($"[blue]Incoming Request #{RequestHistory.Count}[/]").RuleStyle("grey"));
var infoTable = new Table().Border(TableBorder.Rounded).BorderColor(Color.Blue);
infoTable.AddColumn("Property");
infoTable.AddColumn("Value");
infoTable.AddRow("[blue]Method[/]", request.Method);
infoTable.AddRow("[blue]Target[/]", fullUrl);
infoTable.AddRow("[blue]Headers[/]", $"{request.Headers?.Count ?? 0} headers");
infoTable.AddRow("[blue]Body[/]", string.IsNullOrEmpty(request.Body) ? "[silver]empty[/]" : $"{request.Body.Length} chars");
AnsiConsole.Write(infoTable);
// Execute the request
await ExecuteRequest(request, fullUrl);
AnsiConsole.Write(new Rule().RuleStyle("grey"));
}
private static async Task ExecuteRequest(ReplayRequest request, string fullUrl)
{
try
{
using var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(30);
var httpRequest = new HttpRequestMessage(new HttpMethod(request.Method), fullUrl);
// Add headers
var excludeHeaders = new[] { "host", "content-length", "connection", "accept-encoding", "transfer-encoding" };
if (request.Headers != null)
{
foreach (var header in request.Headers)
{
if (excludeHeaders.Contains(header.Key.ToLower())) continue;
if (header.Key.StartsWith("Content-", StringComparison.OrdinalIgnoreCase)) continue;
try
{
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
catch { }
}
}
// Add body
if (!string.IsNullOrEmpty(request.Body))
{
var contentType = request.Headers?.GetValueOrDefault("Content-Type") ?? "application/json";
httpRequest.Content = new StringContent(request.Body, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
}
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var response = await httpClient.SendAsync(httpRequest);
stopwatch.Stop();
var responseBody = await response.Content.ReadAsStringAsync();
var statusColor = (int)response.StatusCode switch
{
>= 200 and < 300 => "green",
>= 300 and < 400 => "yellow",
>= 400 and < 500 => "orange3",
_ => "red"
};
AnsiConsole.MarkupLine($"[{statusColor}]Response: {(int)response.StatusCode} {response.StatusCode}[/] [silver]({stopwatch.ElapsedMilliseconds}ms)[/]");
if (!string.IsNullOrEmpty(responseBody))
{
var displayBody = responseBody;
try
{
var json = JsonDocument.Parse(responseBody);
displayBody = JsonSerializer.Serialize(json, CliJsonContext.Default.JsonDocument);
}
catch { }
if (displayBody.Length > 500)
{
displayBody = displayBody[..500] + "... (truncated)";
}
// Escape markup characters to prevent Spectre.Console from interpreting them
displayBody = Markup.Escape(displayBody);
AnsiConsole.Write(new Panel(displayBody)
.Header("[silver]Response Body[/]")
.Border(BoxBorder.Rounded)
.BorderColor(Color.Grey)
.Expand());
}
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Request failed:[/] {ex.Message}");
}
}
private static async Task DisconnectAsync()
{
if (!_isConnected && _sseClient == null)
{
AnsiConsole.MarkupLine("[silver]Not connected.[/]");
return;
}
// Disable auto-reconnect for manual disconnect
_autoReconnectEnabled = false;
await _connectionCts?.CancelAsync();
if (_sseListenerTask != null)
{
try
{
await _sseListenerTask.WaitAsync(TimeSpan.FromSeconds(2));
}
catch (TimeoutException)
{
// Ignore timeout
}
catch (OperationCanceledException)
{
// Expected
}
}
_sseClient?.Dispose();
_sseClient = null;
_sseListenerTask = null;
_isConnected = false;
AnsiConsole.MarkupLine("[green]Disconnected.[/]");
}
private static void ShowStatus()
{
var table = new Table().Border(TableBorder.Rounded);
table.AddColumn("Property");
table.AddColumn("Value");
table.AddRow("Connection", _isConnected ? "[green]Connected[/]" : "[red]Disconnected[/]");
table.AddRow("API Key", string.IsNullOrEmpty(_config.ApiKey) ? "[yellow]Not set[/]" : $"[green]{_config.ApiKey[..Math.Min(8, _config.ApiKey.Length)]}****[/]");
table.AddRow("Server", _config.ServerUrl ?? DefaultServerUrl);
table.AddRow("Requests Received", RequestHistory.Count.ToString());
AnsiConsole.Write(table);
}
private static void HandleConfig(string[] args)
{
if (args.Length == 0)
{
// Show current config
var table = new Table().Border(TableBorder.Rounded);
table.AddColumn("Setting");
table.AddColumn("Value");
table.AddRow("API Key", string.IsNullOrEmpty(_config.ApiKey) ? "[silver](not set)[/]" : $"{_config.ApiKey[..Math.Min(8, _config.ApiKey.Length)]}****");
table.AddRow("Server URL", _config.ServerUrl ?? DefaultServerUrl);
table.AddRow("Config File", ConfigFilePath);
AnsiConsole.Write(table);
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("[silver]Usage: [white]config <setting> <value>[/][/]");
AnsiConsole.MarkupLine("[silver] config api-key <key> - Set API key[/]");
AnsiConsole.MarkupLine("[silver] config server <url> - Set server URL[/]");
return;
}
var setting = args[0].ToLower();
var value = args.Length > 1 ? string.Join(" ", args.Skip(1)) : null;
switch (setting)
{
case "api-key":
case "apikey":
case "key":
if (string.IsNullOrEmpty(value))
{
value = AnsiConsole.Prompt(
new TextPrompt<string>("[blue]API Key:[/]")
.Secret());
}
_config.ApiKey = value;
SaveConfig(_config);
AnsiConsole.MarkupLine("[green]API key saved![/]");
break;
case "server":
case "url":
if (string.IsNullOrEmpty(value))
{
AnsiConsole.MarkupLine("[red]Please provide a server URL.[/]");