-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathDevToolsPlugin.cs
More file actions
1074 lines (945 loc) · 38.8 KB
/
Copy pathDevToolsPlugin.cs
File metadata and controls
1074 lines (945 loc) · 38.8 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using DevProxy.Abstractions.Proxy;
using DevProxy.Abstractions.Plugins;
using DevProxy.Abstractions.Utils;
using DevProxy.Plugins.Inspection.CDP;
using DevProxy.Plugins.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Globalization;
using System.Text;
namespace DevProxy.Plugins.Inspection;
public enum PreferredBrowser
{
Edge,
Chrome,
EdgeDev,
EdgeBeta
}
public sealed class DevToolsPluginConfiguration
{
public PreferredBrowser PreferredBrowser { get; set; } = PreferredBrowser.Edge;
/// <summary>
/// Path to the browser executable. If not set, the plugin will try to find
/// the browser executable based on the PreferredBrowser.
/// </summary>
/// <remarks>Use this value when you install the browser in a non-standard
/// path.</remarks>
public string PreferredBrowserPath { get; set; } = string.Empty;
}
public sealed class DevToolsPlugin(
HttpClient httpClient,
ILogger<DevToolsPlugin> logger,
ISet<UrlToWatch> urlsToWatch,
IProxyConfiguration proxyConfiguration,
IConfigurationSection pluginConfigurationSection) :
BasePlugin<DevToolsPluginConfiguration>(
httpClient,
logger,
urlsToWatch,
proxyConfiguration,
pluginConfigurationSection)
{
private readonly ConcurrentDictionary<string, GetResponseBodyResultParams> _responseBody = [];
// Track stdio request data for response body retrieval
private readonly ConcurrentDictionary<string, StdioRequestData> _stdioRequests = [];
// Track JSON-RPC request IDs to CDP request IDs: key = "{processId}_{jsonRpcId}"
private readonly ConcurrentDictionary<string, string> _jsonRpcToCdpRequestId = [];
// Track pending stdin request IDs (queue) for matching with stdout (fallback for non-JSON-RPC)
private readonly ConcurrentDictionary<int, ConcurrentQueue<string>> _pendingStdinRequestIds = [];
// Buffer for partial stdout responses: key = processId
private readonly ConcurrentDictionary<int, StdioResponseBuffer> _stdoutBuffers = [];
// Buffer CDP messages until WebSocket connects
private readonly ConcurrentQueue<Func<CancellationToken, Task>> _pendingCdpMessages = [];
// Counter for generating unique request IDs
private long _stdioRequestCounter;
// Flag to track if we've replayed buffered messages
private volatile bool _hasReplayedBufferedMessages;
// Lock for replay synchronization
private readonly Lock _replayLock = new();
private CancellationToken? _cancellationToken;
private WebSocketServer? _webSocket;
public override string Name => nameof(DevToolsPlugin);
public override async Task InitializeAsync(InitArgs e, CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
await base.InitializeAsync(e, cancellationToken);
InitInspector();
}
public override async Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(BeforeRequestAsync));
ArgumentNullException.ThrowIfNull(e);
if (_webSocket?.IsConnected != true)
{
return;
}
if (!e.HasRequestUrlMatch(UrlsToWatch))
{
Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(e.Session));
return;
}
var requestId = GetRequestId(e.Session.HttpClient.Request);
var headers = e.Session.HttpClient.Request.Headers
.GroupBy(h => h.Name)
.ToDictionary(g => g.Key, g => string.Join(", ", g.Select(h => h.Value)));
var requestWillBeSentMessage = new RequestWillBeSentMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
DocumentUrl = e.Session.HttpClient.Request.Url,
Request = new()
{
Url = e.Session.HttpClient.Request.Url,
Method = e.Session.HttpClient.Request.Method,
Headers = headers,
PostData = e.Session.HttpClient.Request.HasBody ? HttpUtils.GetBodyString(e.Session.HttpClient.Request.ContentType, e.Session.HttpClient.Request.Body) : null
},
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
WallTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Initiator = new()
{
Type = "other"
}
}
};
await _webSocket.SendAsync(requestWillBeSentMessage, cancellationToken);
// must be included to avoid the "Provisional headers are shown" warning
var requestWillBeSentExtraInfoMessage = new RequestWillBeSentExtraInfoMessage
{
Params = new()
{
RequestId = requestId,
// must be included in the message or the message will be rejected
AssociatedCookies = [],
Headers = headers
}
};
await _webSocket.SendAsync(requestWillBeSentExtraInfoMessage, cancellationToken);
}
public override async Task AfterResponseAsync(ProxyResponseArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(AfterResponseAsync));
ArgumentNullException.ThrowIfNull(e);
await base.AfterResponseAsync(e, cancellationToken);
if (_webSocket?.IsConnected != true)
{
return;
}
if (!e.HasRequestUrlMatch(UrlsToWatch))
{
Logger.LogRequest("URL not matched", MessageType.Skipped, new LoggingContext(e.Session));
return;
}
var body = new GetResponseBodyResultParams
{
Body = string.Empty,
Base64Encoded = false
};
if (e.Session.HttpClient.Response.HasBody)
{
if (IsTextResponse(e.Session.HttpClient.Response.ContentType))
{
body.Body = HttpUtils.GetBodyString(e.Session.HttpClient.Response.ContentType, e.Session.HttpClient.Response.Body);
body.Base64Encoded = false;
}
else
{
body.Body = Convert.ToBase64String(e.Session.HttpClient.Response.Body);
body.Base64Encoded = true;
}
}
_responseBody[e.Session.HttpClient.Request.GetHashCode().ToString(CultureInfo.InvariantCulture)] = body;
var requestId = GetRequestId(e.Session.HttpClient.Request);
var responseReceivedMessage = new ResponseReceivedMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
Type = "XHR",
Response = new()
{
Url = e.Session.HttpClient.Request.Url,
Status = e.Session.HttpClient.Response.StatusCode,
StatusText = e.Session.HttpClient.Response.StatusDescription,
Headers = e.Session.HttpClient.Response.Headers
.GroupBy(h => h.Name)
.ToDictionary(g => g.Key, g => string.Join(", ", g.Select(h => h.Value))),
MimeType = e.Session.HttpClient.Response.ContentType
},
HasExtraInfo = true
}
};
await _webSocket.SendAsync(responseReceivedMessage, cancellationToken);
if (e.Session.HttpClient.Response.ContentType == "text/event-stream")
{
await SendBodyAsDataReceivedAsync(requestId, body.Body, cancellationToken);
}
var loadingFinishedMessage = new LoadingFinishedMessage
{
Params = new()
{
RequestId = requestId,
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
EncodedDataLength = e.Session.HttpClient.Response.HasBody ? e.Session.HttpClient.Response.Body.Length : 0
}
};
await _webSocket.SendAsync(loadingFinishedMessage, cancellationToken);
}
public override async Task AfterRequestLogAsync(RequestLogArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(AfterRequestLogAsync));
ArgumentNullException.ThrowIfNull(e);
if (_webSocket?.IsConnected != true ||
e.RequestLog.MessageType == MessageType.InterceptedRequest ||
e.RequestLog.MessageType == MessageType.InterceptedResponse)
{
return;
}
var message = new EntryAddedMessage
{
Params = new()
{
Entry = new()
{
Source = "network",
Text = string.Join(" ", e.RequestLog.Message),
Level = Entry.GetLevel(e.RequestLog.MessageType),
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
Url = e.RequestLog.Context?.Session.HttpClient.Request.Url,
NetworkRequestId = GetRequestId(e.RequestLog.Context?.Session.HttpClient.Request)
}
}
};
await _webSocket.SendAsync(message, cancellationToken);
Logger.LogTrace("Left {Name}", nameof(AfterRequestLogAsync));
}
#region IStdioPlugin Implementation
public override async Task BeforeStdinAsync(StdioRequestArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(BeforeStdinAsync));
ArgumentNullException.ThrowIfNull(e);
var requestId = GenerateStdioRequestId(e.Session);
var url = GetStdioUrl(e.Session);
var body = e.BodyString;
// Try to parse JSON-RPC id for better request/response matching
var jsonRpcId = TryGetJsonRpcId(body);
var isJsonRpcRequest = jsonRpcId is not null;
if (isJsonRpcRequest && e.Session.ProcessId.HasValue)
{
// Store mapping from JSON-RPC id to CDP request ID
var key = GetJsonRpcKey(e.Session.ProcessId.Value, jsonRpcId);
_jsonRpcToCdpRequestId[key] = requestId;
}
else if (e.Session.ProcessId.HasValue)
{
// Fallback: queue the request ID for non-JSON-RPC or notifications
EnqueueStdinRequestId(e.Session.ProcessId.Value, requestId);
}
// Store the stdin data for potential response body retrieval
_stdioRequests[requestId] = new StdioRequestData
{
RequestBody = body,
Timestamp = DateTimeOffset.UtcNow
};
var requestWillBeSentMessage = new RequestWillBeSentMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
DocumentUrl = url,
Request = new()
{
Url = url,
Method = "STDIN",
Headers = new Dictionary<string, string>
{
["Content-Type"] = "application/octet-stream",
["X-Stdio-Command"] = e.Session.Command,
["X-Stdio-Args"] = string.Join(" ", e.Session.Args),
["X-Stdio-PID"] = e.Session.ProcessId?.ToString(CultureInfo.InvariantCulture) ?? "unknown"
},
PostData = body
},
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
WallTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Initiator = new()
{
Type = "other"
}
}
};
var requestWillBeSentExtraInfoMessage = new RequestWillBeSentExtraInfoMessage
{
Params = new()
{
RequestId = requestId,
AssociatedCookies = [],
Headers = new Dictionary<string, string>
{
["Content-Type"] = "application/octet-stream"
}
}
};
await SendOrBufferAsync(async ct =>
{
await _webSocket!.SendAsync(requestWillBeSentMessage, ct);
await _webSocket.SendAsync(requestWillBeSentExtraInfoMessage, ct);
}, cancellationToken);
}
public override async Task AfterStdoutAsync(StdioResponseArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(AfterStdoutAsync));
ArgumentNullException.ThrowIfNull(e);
var url = GetStdioUrl(e.Session);
var body = e.BodyString;
var processId = e.Session.ProcessId ?? 0;
// Try to find matching request using JSON-RPC id
string? requestId = null;
var jsonRpcId = TryGetJsonRpcId(body);
if (jsonRpcId is not null)
{
var key = GetJsonRpcKey(processId, jsonRpcId);
if (_jsonRpcToCdpRequestId.TryRemove(key, out var cdpRequestId))
{
requestId = cdpRequestId;
}
}
// If we couldn't parse JSON-RPC id, this might be a partial response
// Buffer it until we get a complete message with an id
if (jsonRpcId is null)
{
// Buffer this partial response
var buffer = _stdoutBuffers.GetOrAdd(processId, _ => new StdioResponseBuffer());
// Clear stale buffer if needed
if (buffer.IsStale)
{
Logger.LogDebug("Clearing stale stdout buffer for process {ProcessId}", processId);
buffer.Clear();
}
buffer.Append(body);
// Try parsing the accumulated buffer
jsonRpcId = TryGetJsonRpcId(buffer.Content);
if (jsonRpcId is null)
{
// Still can't parse, wait for more data
Logger.LogTrace("Buffering partial stdout response ({Length} bytes total)", buffer.Content.Length);
return;
}
// We now have a complete message!
body = buffer.Content;
buffer.Clear();
var key = GetJsonRpcKey(processId, jsonRpcId);
if (_jsonRpcToCdpRequestId.TryRemove(key, out var cdpRequestId))
{
requestId = cdpRequestId;
}
}
else
{
// We got a valid JSON-RPC message, but check if there's buffered data to prepend
if (_stdoutBuffers.TryGetValue(processId, out var buffer) && buffer.Content.Length > 0)
{
body = buffer.Content + body;
buffer.Clear();
}
}
// Fallback: try queue-based matching (for non-JSON-RPC protocols)
requestId ??= DequeueStdinRequestId(processId);
// Last resort: generate a new ID for standalone stdout
requestId ??= GenerateStdioRequestId(e.Session);
// Update stored request with response data
if (_stdioRequests.TryGetValue(requestId, out var requestData))
{
requestData.ResponseBody = body;
}
// Store for response body retrieval
_responseBody[requestId] = new GetResponseBodyResultParams
{
Body = body,
Base64Encoded = false
};
var responseReceivedMessage = new ResponseReceivedMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
Type = "XHR",
Response = new()
{
Url = url,
Status = 200,
StatusText = "OK",
Headers = new Dictionary<string, string>
{
["Content-Type"] = "application/octet-stream",
["X-Stdio-Direction"] = "STDOUT"
},
MimeType = "application/octet-stream"
},
HasExtraInfo = true
}
};
var loadingFinishedMessage = new LoadingFinishedMessage
{
Params = new()
{
RequestId = requestId,
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
EncodedDataLength = Encoding.UTF8.GetByteCount(body)
}
};
await SendOrBufferAsync(async ct =>
{
await _webSocket!.SendAsync(responseReceivedMessage, ct);
await _webSocket.SendAsync(loadingFinishedMessage, ct);
}, cancellationToken);
}
public override async Task AfterStderrAsync(StdioResponseArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(AfterStderrAsync));
ArgumentNullException.ThrowIfNull(e);
// For stderr, we create a separate "request" with an error status
var requestId = GenerateStderrRequestId(e.Session);
var url = GetStdioUrl(e.Session);
var body = e.BodyString;
// Store for response body retrieval
_responseBody[requestId] = new GetResponseBodyResultParams
{
Body = body,
Base64Encoded = false
};
// Send request for stderr
var requestWillBeSentMessage = new RequestWillBeSentMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
DocumentUrl = url,
Request = new()
{
Url = url,
Method = "STDERR",
Headers = new Dictionary<string, string>
{
["Content-Type"] = "text/plain",
["X-Stdio-Command"] = e.Session.Command,
["X-Stdio-Direction"] = "STDERR"
},
PostData = null
},
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
WallTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Initiator = new()
{
Type = "other"
}
}
};
// Send response with error status
var responseReceivedMessage = new ResponseReceivedMessage
{
Params = new()
{
RequestId = requestId,
LoaderId = "1",
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
Type = "XHR",
Response = new()
{
Url = url,
Status = 500,
StatusText = "STDERR",
Headers = new Dictionary<string, string>
{
["Content-Type"] = "text/plain",
["X-Stdio-Direction"] = "STDERR"
},
MimeType = "text/plain"
},
HasExtraInfo = true
}
};
var loadingFinishedMessage = new LoadingFinishedMessage
{
Params = new()
{
RequestId = requestId,
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
EncodedDataLength = Encoding.UTF8.GetByteCount(body)
}
};
// Also send a log entry for stderr
var entryMessage = new EntryAddedMessage
{
Params = new()
{
Entry = new()
{
Source = "network",
Text = $"[STDERR] {body}",
Level = "error",
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
Url = url,
NetworkRequestId = requestId
}
}
};
await SendOrBufferAsync(async ct =>
{
await _webSocket!.SendAsync(requestWillBeSentMessage, ct);
await _webSocket.SendAsync(responseReceivedMessage, ct);
await _webSocket.SendAsync(loadingFinishedMessage, ct);
await _webSocket.SendAsync(entryMessage, ct);
}, cancellationToken);
}
public override async Task AfterStdioRequestLogAsync(StdioRequestLogArgs e, CancellationToken cancellationToken)
{
Logger.LogTrace("{Method} called", nameof(AfterStdioRequestLogAsync));
ArgumentNullException.ThrowIfNull(e);
if (e.RequestLog.MessageType is MessageType.InterceptedRequest or
MessageType.InterceptedResponse)
{
return;
}
// Encode slashes so DevTools shows full command in Name column instead of just last path segment
var url = $"stdio://{e.RequestLog.Command.Replace("/", "%2F", StringComparison.Ordinal)}";
var message = new EntryAddedMessage
{
Params = new()
{
Entry = new()
{
Source = "network",
Text = e.RequestLog.Message ?? $"[{e.RequestLog.PluginName}]",
Level = Entry.GetLevel(e.RequestLog.MessageType),
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
Url = url,
NetworkRequestId = null
}
}
};
await SendOrBufferAsync(ct => _webSocket!.SendAsync(message, ct), cancellationToken);
}
public override Task AfterStdioRecordingStopAsync(StdioRecordingArgs e, CancellationToken cancellationToken)
{
// No special handling needed for recording stop
return Task.CompletedTask;
}
/// <summary>
/// Replays all buffered CDP messages. Thread-safe and idempotent.
/// </summary>
private async Task ReplayBufferedMessagesAsync(CancellationToken cancellationToken)
{
using (_replayLock.EnterScope())
{
if (_hasReplayedBufferedMessages)
{
return;
}
_hasReplayedBufferedMessages = true;
}
Logger.LogTrace("Replaying buffered CDP messages");
while (_pendingCdpMessages.TryDequeue(out var bufferedAction))
{
try
{
await bufferedAction(cancellationToken);
}
catch (Exception ex)
{
Logger.LogDebug(ex, "Error replaying buffered CDP message");
}
}
}
/// <summary>
/// Sends CDP message immediately if WebSocket is connected, otherwise buffers it for later replay.
/// </summary>
private async Task SendOrBufferAsync(Func<CancellationToken, Task> sendAction, CancellationToken cancellationToken)
{
if (_webSocket is null)
{
return;
}
// Check if we need to replay buffered messages
if (_webSocket.IsConnected && !_hasReplayedBufferedMessages)
{
await ReplayBufferedMessagesAsync(cancellationToken);
}
if (_webSocket.IsConnected)
{
await sendAction(cancellationToken);
}
else
{
// Buffer for later
_pendingCdpMessages.Enqueue(sendAction);
Logger.LogTrace("Buffered CDP message (WebSocket not connected yet)");
}
}
private static string GetStdioUrl(StdioSession session)
{
var commandWithArgs = session.Args.Count > 0
? $"{session.Command} {string.Join(" ", session.Args)}"
: session.Command;
// Encode slashes so DevTools shows full command in Name column instead of just last path segment
return $"stdio://{commandWithArgs.Replace("/", "%2F", StringComparison.Ordinal)}";
}
private string GenerateStdioRequestId(StdioSession session)
{
// Generate a unique ID for each stdin message using an incrementing counter
var counter = Interlocked.Increment(ref _stdioRequestCounter);
var baseId = $"{session.Command}_{session.ProcessId}_{counter}";
return baseId.GetHashCode(StringComparison.Ordinal).ToString(CultureInfo.InvariantCulture);
}
private void EnqueueStdinRequestId(int processId, string requestId)
{
var queue = _pendingStdinRequestIds.GetOrAdd(processId, _ => new ConcurrentQueue<string>());
queue.Enqueue(requestId);
}
private string? DequeueStdinRequestId(int processId)
{
if (_pendingStdinRequestIds.TryGetValue(processId, out var queue) && queue.TryDequeue(out var requestId))
{
return requestId;
}
return null;
}
private static string GenerateStderrRequestId(StdioSession session)
{
// Stderr gets its own unique ID since it shows as a separate request
var baseId = $"{session.Command}_{session.ProcessId}_stderr_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
return baseId.GetHashCode(StringComparison.Ordinal).ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Tries to extract the JSON-RPC "id" field from a message body.
/// Returns null if the body is not valid JSON or doesn't have an "id" field.
/// </summary>
private static string? TryGetJsonRpcId(string body)
{
try
{
using var doc = JsonDocument.Parse(body);
if (doc.RootElement.TryGetProperty("id", out var idElement))
{
// JSON-RPC id can be string, number, or null
#pragma warning disable IDE0072 // Add missing cases
return idElement.ValueKind switch
{
JsonValueKind.String => idElement.GetString(),
JsonValueKind.Number => idElement.GetRawText(),
_ => null
};
#pragma warning restore IDE0072 // Add missing cases
}
}
catch (JsonException)
{
// Not valid JSON, ignore
}
return null;
}
private static string GetJsonRpcKey(int processId, string? jsonRpcId)
{
return $"{processId}_{jsonRpcId}";
}
#endregion
private sealed class StdioRequestData
{
public string RequestBody { get; set; } = string.Empty;
public string? ResponseBody { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
private sealed class StdioResponseBuffer
{
private const int MaxBufferSizeBytes = 1024 * 1024; // 1MB max buffer size
private static readonly TimeSpan StaleBufferTimeout = TimeSpan.FromSeconds(30);
private readonly StringBuilder _buffer = new();
private DateTimeOffset _lastAppendTime = DateTimeOffset.UtcNow;
private readonly Lock _lock = new();
public string Content
{
get
{
using (_lock.EnterScope())
{
return _buffer.ToString();
}
}
}
/// <summary>
/// Returns true if the buffer is stale (no data appended within the timeout period).
/// </summary>
public bool IsStale => DateTimeOffset.UtcNow - _lastAppendTime > StaleBufferTimeout;
/// <summary>
/// Appends data to the buffer. Returns false if the buffer would exceed the maximum size.
/// </summary>
public bool TryAppend(string data)
{
using (_lock.EnterScope())
{
// Check if adding this data would exceed the maximum buffer size
if (_buffer.Length + data.Length > MaxBufferSizeBytes)
{
return false;
}
_buffer.Append(data);
_lastAppendTime = DateTimeOffset.UtcNow;
return true;
}
}
public void Append(string data)
{
using (_lock.EnterScope())
{
// Enforce maximum buffer size - clear if exceeded
if (_buffer.Length + data.Length > MaxBufferSizeBytes)
{
_buffer.Clear();
}
_buffer.Append(data);
_lastAppendTime = DateTimeOffset.UtcNow;
}
}
public void Clear()
{
using (_lock.EnterScope())
{
_buffer.Clear();
_lastAppendTime = DateTimeOffset.UtcNow;
}
}
}
private string GetBrowserPath()
{
if (!string.IsNullOrEmpty(Configuration.PreferredBrowserPath))
{
Logger.LogInformation("{PreferredBrowserPath} was set to {Path}. Ignoring {PreferredBrowser} setting.", nameof(Configuration.PreferredBrowserPath), Configuration.PreferredBrowserPath, nameof(Configuration.PreferredBrowser));
return Configuration.PreferredBrowserPath;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Configuration.PreferredBrowser switch
{
PreferredBrowser.Chrome => Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Google\Chrome\Application\chrome.exe"),
PreferredBrowser.Edge => Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"),
PreferredBrowser.EdgeDev => Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft\Edge Dev\Application\msedge.exe"),
PreferredBrowser.EdgeBeta => Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft\Edge Beta\Application\msedge.exe"),
_ => throw new NotSupportedException($"{Configuration.PreferredBrowser} is an unsupported browser. Please change your PreferredBrowser setting for {Name}.")
};
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return Configuration.PreferredBrowser switch
{
PreferredBrowser.Chrome => "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
PreferredBrowser.Edge => "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
PreferredBrowser.EdgeDev => "/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev",
PreferredBrowser.EdgeBeta => "/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Beta",
_ => throw new NotSupportedException($"{Configuration.PreferredBrowser} is an unsupported browser. Please change your PreferredBrowser setting for {Name}.")
};
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return Configuration.PreferredBrowser switch
{
PreferredBrowser.Chrome => "/opt/google/chrome/chrome",
PreferredBrowser.Edge => "/opt/microsoft/msedge/msedge",
PreferredBrowser.EdgeDev => "/opt/microsoft/msedge-dev/msedge",
PreferredBrowser.EdgeBeta => "/opt/microsoft/msedge-beta/msedge",
_ => throw new NotSupportedException($"{Configuration.PreferredBrowser} is an unsupported browser. Please change your PreferredBrowser setting for {Name}.")
};
}
else
{
throw new NotSupportedException("Unsupported operating system.");
}
}
private void InitInspector()
{
var browserPath = string.Empty;
try
{
browserPath = GetBrowserPath();
}
catch (NotSupportedException ex)
{
Logger.LogError(ex, "Error starting {Plugin}. Error finding the browser.", Name);
return;
}
// check if the browser is installed
if (!File.Exists(browserPath))
{
Logger.LogError("Error starting {Plugin}. Browser executable not found at {BrowserPath}", Name, browserPath);
return;
}
var port = GetFreePort();
_webSocket = new(port, Logger);
_webSocket.MessageReceived += SocketMessageReceived;
_webSocket.ClientConnected += OnWebSocketClientConnected;
_ = _webSocket.StartAsync();
var inspectionUrl = $"http://localhost:9222/devtools/inspector.html?ws=127.0.0.1:{port}";
var profilePath = Path.Combine(Path.GetTempPath(), "devtools-devproxy");
var args = $"{inspectionUrl} --remote-debugging-port=9222 --user-data-dir=\"{profilePath}\"";
Logger.LogInformation("{Name} available at {InspectionUrl}", Name, inspectionUrl);
using var process = new Process
{
StartInfo = new()
{
FileName = browserPath,
Arguments = args,
// suppress default output
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
_ = process.Start();
}
private void OnWebSocketClientConnected()
{
Logger.LogTrace("WebSocket client connected");
// Use the shared replay method - run synchronously on the event callback
ReplayBufferedMessagesAsync(_cancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
}
private void SocketMessageReceived(string msg)
{
if (_webSocket is null)
{
return;
}
try
{
var message = JsonSerializer.Deserialize<Message>(msg, ProxyUtils.JsonSerializerOptions);
switch (message?.Method)
{
case "Network.getResponseBody":
var getResponseBodyMessage = JsonSerializer.Deserialize<GetResponseBodyMessage>(msg, ProxyUtils.JsonSerializerOptions);
if (getResponseBodyMessage is null)
{
return;
}
_ = HandleNetworkGetResponseBodyAsync(getResponseBodyMessage, _cancellationToken ?? CancellationToken.None);
break;
case "Network.streamResourceContent":
_ = HandleNetworkStreamResourceContentAsync(message, _cancellationToken ?? CancellationToken.None);
break;
default:
break;
}
}
catch { }
}
private async Task HandleNetworkStreamResourceContentAsync(Message message, CancellationToken cancellationToken)
{
if (_webSocket is null || message.Id is null)
{
return;
}
var result = new StreamResourceContentResult
{
Id = (int)message.Id,
Result = new()
{
BufferedData = string.Empty
}
};
await _webSocket.SendAsync(result, cancellationToken);
}
private async Task HandleNetworkGetResponseBodyAsync(GetResponseBodyMessage message, CancellationToken cancellationToken)
{
if (_webSocket is null || message.Params?.RequestId is null)
{
return;
}
if (!_responseBody.TryGetValue(message.Params.RequestId, out var value) ||
// should never happen because the message is sent from devtools
// and Id is required on all socket messages but theoretically
// it is possible
message.Id is null)
{
return;
}
var result = new GetResponseBodyResult
{
Id = (int)message.Id,
Result = new()