-
Notifications
You must be signed in to change notification settings - Fork 54
/
DevToolsPlugin.cs
302 lines (267 loc) · 10.3 KB
/
DevToolsPlugin.cs
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.DevProxy.Abstractions;
using Microsoft.DevProxy.Plugins.Inspection.CDP;
using Microsoft.Extensions.Logging;
namespace Microsoft.DevProxy.Plugins.Inspection;
public enum PreferredBrowser
{
Edge,
Chrome,
EdgeDev
}
public class DevToolsPluginConfiguration
{
public PreferredBrowser PreferredBrowser { get; set; } = PreferredBrowser.Edge;
}
public class DevToolsPlugin : BaseProxyPlugin
{
private string socketUrl = string.Empty;
private WebSocketServer? webSocket;
private Dictionary<string, GetResponseBodyResultParams> responseBody = new();
public override string Name => nameof(DevToolsPlugin);
private readonly DevToolsPluginConfiguration _configuration = new();
public override void Register(IPluginEvents pluginEvents,
IProxyContext context,
ISet<UrlToWatch> urlsToWatch,
IConfigurationSection? configSection = null)
{
base.Register(pluginEvents, context, urlsToWatch, configSection);
configSection?.Bind(_configuration);
InitInspector();
pluginEvents.BeforeRequest += BeforeRequest;
pluginEvents.AfterResponse += AfterResponse;
pluginEvents.AfterRequestLog += AfterRequestLog;
}
private static int GetFreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private string GetChromiumProcessName(DevToolsPluginConfiguration configuration)
{
return configuration.PreferredBrowser switch
{
PreferredBrowser.Chrome => RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Google\Chrome\Application\chrome.exe")
: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
PreferredBrowser.EdgeDev => RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft\Edge Dev\Application\msedge.exe")
: "/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev",
_ => RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Environment.ExpandEnvironmentVariables(@"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe")
: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
};
}
private void InitInspector()
{
var port = GetFreePort();
webSocket = new WebSocketServer(port);
webSocket.MessageReceived += SocketMessageReceived;
webSocket.Start();
var processName = GetChromiumProcessName(_configuration);
var inspectionUrl = $"http://localhost:9222/devtools/inspector.html?ws=localhost:{port}";
var args = $"{inspectionUrl} --remote-debugging-port=9222 --profile-directory=devproxy";
_logger?.LogInformation("DevTools available at {inspectionUrl}", inspectionUrl);
var process = new Process
{
StartInfo = new()
{
FileName = processName,
Arguments = args,
// suppress default output
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
process.Start();
}
private void SocketMessageReceived(string msg)
{
if (webSocket is null)
{
return;
}
try
{
var message = JsonSerializer.Deserialize<GetResponseBodyMessage>(msg, ProxyUtils.JsonSerializerOptions);
if (message?.Method == "Network.getResponseBody")
{
var requestId = message.Params?.RequestId;
if (requestId is null ||
!responseBody.ContainsKey(requestId) ||
// 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()
{
Body = responseBody[requestId].Body,
Base64Encoded = responseBody[requestId].Base64Encoded
}
};
_ = webSocket.SendAsync(result);
}
}
catch { }
}
private string GetRequestId(Titanium.Web.Proxy.Http.Request? request)
{
if (request is null)
{
return string.Empty;
}
return request.GetHashCode().ToString();
}
private async Task BeforeRequest(object sender, ProxyRequestArgs e)
{
if (webSocket?.IsConnected != true)
{
return;
}
var requestId = GetRequestId(e.Session.HttpClient.Request);
var headers = e.Session.HttpClient.Request.Headers
.ToDictionary(h => h.Name, 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 ? e.Session.HttpClient.Request.BodyString : null
},
Timestamp = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000,
WallTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Initiator = new()
{
Type = "other"
}
}
};
await webSocket.SendAsync(requestWillBeSentMessage);
// 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 = new object[0],
Headers = headers
}
};
await webSocket.SendAsync(requestWillBeSentExtraInfoMessage);
}
private async Task AfterResponse(object sender, ProxyResponseArgs e)
{
if (webSocket?.IsConnected != true)
{
return;
}
var body = new GetResponseBodyResultParams
{
Body = string.Empty,
Base64Encoded = false
};
if (IsTextResponse(e.Session.HttpClient.Response.ContentType))
{
body.Body = e.Session.HttpClient.Response.BodyString;
body.Base64Encoded = false;
}
else
{
body.Body = Convert.ToBase64String(e.Session.HttpClient.Response.Body);
body.Base64Encoded = true;
}
responseBody.Add(e.Session.HttpClient.Request.GetHashCode().ToString(), 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
.ToDictionary(h => h.Name, h => h.Value),
MimeType = e.Session.HttpClient.Response.ContentType
}
}
};
await webSocket.SendAsync(responseReceivedMessage);
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);
}
private bool IsTextResponse(string? contentType)
{
var isTextResponse = false;
if (contentType is not null &&
(contentType.IndexOf("text") > -1 ||
contentType.IndexOf("json") > -1))
{
isTextResponse = true;
}
return isTextResponse;
}
private async void AfterRequestLog(object? sender, RequestLogArgs 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.MessageLines),
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);
}
}