/
Injector.cs
388 lines (353 loc) · 12.1 KB
/
Injector.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
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
#region
using System.Text.RegularExpressions;
using PuppeteerSharp;
using SFP.Models.Injection.Config;
using SFP.Properties;
#endregion
namespace SFP.Models.Injection;
public static partial class Injector
{
private static Browser? s_browser;
private static bool s_isInjected;
private static bool s_manualDisconnect;
private static readonly SemaphoreSlim s_semaphore = new(1, 1);
public static bool IsInjected => s_isInjected && s_browser != null;
public static event EventHandler? InjectionStateChanged;
public static async Task StartInjectionAsync(bool noError = false)
{
if (s_browser is { IsConnected: true })
{
Log.Logger.Warn("Injection already started, skipping injection");
return;
}
if (!await s_semaphore.WaitAsync(TimeSpan.Zero))
{
Log.Logger.Warn("Injection already in progress, skipping injection");
return;
}
if (!Settings.Default.InjectJS && !Settings.Default.InjectCSS)
{
Log.Logger.Warn("No injection type is enabled, skipping injection");
return;
}
try
{
if (File.Exists(Steam.MillenniumPath))
{
Log.Logger.Warn("Millennium is already injected, skipping injection");
return;
}
var browserEndpoint = (await BrowserEndpoint.GetBrowserEndpointAsync()).WebSocketDebuggerUrl!;
ConnectOptions options = new()
{
BrowserWSEndpoint = browserEndpoint,
DefaultViewport = null,
EnqueueAsyncMessages = false,
EnqueueTransportMessages = false
};
Log.Logger.Info("Connecting to " + browserEndpoint);
s_browser = await Puppeteer.ConnectAsync(options);
s_browser.Disconnected += OnDisconnected;
Log.Logger.Info("Connected");
s_browser.TargetCreated += Browser_TargetUpdate;
s_browser.TargetChanged += Browser_TargetUpdate;
await InjectAsync();
s_isInjected = true;
InjectionStateChanged?.Invoke(null, EventArgs.Empty);
Log.Logger.Info("Initial injection finished");
}
catch (Exception e)
{
StopInjection();
if (noError)
{
return;
}
Log.Logger.Error(e);
}
finally
{
s_semaphore.Release();
}
}
private static async Task InjectAsync()
{
if (s_browser == null)
{
Log.Logger.Warn("Inject was called but CEF instance is not connected");
return;
}
var pages = await s_browser.PagesAsync();
Log.Logger.Info("Found " + pages.Length + " pages");
var processTasks = pages.Select(ProcessPage);
await Task.WhenAll(processTasks);
}
public static void StopInjection()
{
if (s_browser?.IsConnected ?? false)
{
Log.Logger.Info("Disconnecting from Steam instance");
}
s_isInjected = false;
s_manualDisconnect = true;
s_browser?.Disconnect();
s_browser = null;
InjectionStateChanged?.Invoke(null, EventArgs.Empty);
}
// injection after reload occurs before content is fully loaded, needs investigation
public static async void Reload()
{
if (s_browser == null)
{
return;
}
var pages = await s_browser.PagesAsync();
foreach (var page in pages)
{
try
{
var title = await page.MainFrame.GetTitleAsync();
if (title != "SharedJSContext")
{
continue;
}
await page.ReloadAsync();
break;
}
catch (PuppeteerException)
{
// ignored
}
}
}
private static async void OnDisconnected(object? sender, EventArgs e)
{
Log.Logger.Info("Disconnected from Steam instance");
var manualDisconnect = s_manualDisconnect;
StopInjection();
if (manualDisconnect)
{
s_manualDisconnect = false;
return;
}
await Task.Delay(500);
if (!Steam.IsSteamWebHelperRunning)
{
return;
}
Log.Logger.Warn("Unexpected disconnect, trying to reconnect to Steam instance");
await Steam.TryInject();
}
private static async void Browser_TargetUpdate(object? sender, TargetChangedArgs e)
{
try
{
var page = await e.Target.PageAsync();
await ProcessPage(page);
}
catch (EvaluationFailedException err)
{
Log.Logger.Warn("Evaluation failed exception when trying to get page");
Log.Logger.Debug(err);
}
catch (PuppeteerException err)
{
Log.Logger.Warn("Puppeteer exception when trying to get page");
Log.Logger.Debug(err);
}
}
private static async Task ProcessPage(Page? page)
{
if (page == null)
{
return;
}
page.FrameNavigated -= Frame_Navigate;
page.FrameNavigated += Frame_Navigate;
await ProcessFrame(page.MainFrame);
}
private static async Task ProcessFrame(Frame frame)
{
var config = SfpConfig.GetConfig();
var patches = config.Patches as PatchEntry[] ?? config.Patches.ToArray();
if (!IsFrameWebkit(frame))
{
string? title;
try
{
title = await frame.GetTitleAsync();
}
catch (PuppeteerException e)
{
Log.Logger.Error("Unexpected error when trying to get frame title");
Log.Logger.Debug("url: " + frame.Url);
Log.Logger.Debug(e);
return;
}
foreach (var patch in patches)
{
var regex = patch.MatchRegexString;
if (regex.StartsWith('.') || regex.StartsWith('#') || regex.StartsWith('['))
{
try
{
if (await frame.QuerySelectorAsync(patch.MatchRegexString) == null)
{
continue;
}
await InjectAsync(frame, patch, title);
return;
}
catch (PuppeteerException e)
{
Log.Logger.Error("Unexpected error when trying to query frame selector");
Log.Logger.Debug("url: " + frame.Url);
Log.Logger.Debug(e);
}
}
else
{
switch (config._isFromMillennium)
{
case false when patch.MatchRegex.IsMatch(title):
case true when regex == title:
await InjectAsync(frame, patch, title);
return;
}
}
}
}
else
{
// needed to accept including css and js from steamloopback.host
// only needed for css in certain instances, needs investigation
await SetBypassCsp(frame);
var url = GetDomainRegex().Match(frame.Url).Groups[1].Value;
if (!config._isFromMillennium)
{
var httpPatches = patches.Where(p => p.MatchRegexString.ToLower().StartsWith("http"));
var patchEntries = httpPatches as PatchEntry[] ?? httpPatches.ToArray();
if (patchEntries.Any(p => p.MatchRegex.IsMatch(frame.Url)))
{
foreach (var patch in patchEntries)
{
await InjectAsync(frame, patch, url);
return;
}
}
}
else
{
if (patches.Any(p => p.MatchRegex.IsMatch(frame.Url)))
{
foreach (var patch in patches)
{
await InjectAsync(frame, patch, url);
return;
}
}
}
}
}
private static async Task SetBypassCsp(Frame frame)
{
var pageTask = s_browser?.Targets().FirstOrDefault(t => t.TargetId == frame.Id)?.PageAsync();
if (pageTask == null)
{
return;
}
var page = await pageTask;
if (page == null)
{
return;
}
try
{
await page.SetBypassCSPAsync(true);
}
catch (PuppeteerException e)
{
Log.Logger.Warn("Failed to bypass content security policy");
Log.Logger.Debug(e);
}
}
private static async void Frame_Navigate(object? sender, FrameEventArgs e)
{
await ProcessFrame(e.Frame);
}
private static async Task InjectAsync(Frame frame, PatchEntry patch, string tabFriendlyName)
{
if (Settings.Default.InjectCSS && !string.IsNullOrWhiteSpace(patch.TargetCss))
{
if (!patch.TargetCss.EndsWith(".css"))
{
Log.Logger.Info("Target CSS file does not end in .css for patch " + patch.MatchRegexString);
}
else
{
await InjectResourceAsync(frame, patch.TargetCss, tabFriendlyName, patch.MatchRegexString);
}
}
if (Settings.Default.InjectJS && !string.IsNullOrWhiteSpace(patch.TargetJs))
{
if (!patch.TargetJs.EndsWith(".js"))
{
Log.Logger.Info("Target Js file does not end in .js for patch " + patch.MatchRegexString);
}
else
{
await InjectResourceAsync(frame, patch.TargetJs, tabFriendlyName, patch.MatchRegexString);
}
}
}
private static async Task InjectResourceAsync(Frame frame, string fileRelativePath, string tabFriendlyName,
string patchName)
{
var relativeSkinDir = Steam.GetRelativeSkinDir().Replace('\\', '/');
if (!string.IsNullOrWhiteSpace(relativeSkinDir))
{
relativeSkinDir += '/';
}
var resourceType = fileRelativePath.EndsWith(".css") ? "css" : "js";
fileRelativePath = $"{relativeSkinDir}{fileRelativePath}";
var injectString =
$@"function inject() {{
if (document.getElementById('{frame.Id}{resourceType}') !== null) return;
const element = document.createElement('{(resourceType == "css" ? "link" : "script")}');
element.id = '{frame.Id}{resourceType}';
{(resourceType == "css" ? "element.rel = 'stylesheet';" : "")}
element.type = '{(resourceType == "css" ? "text/css" : "module")}';
element.{(resourceType == "css" ? "href" : "src")} = 'https://steamloopback.host/{fileRelativePath}';
document.head.append(element);
}}
if ((document.readyState === 'loading') && '{IsFrameWebkit(frame)}' === 'True') {{
addEventListener('DOMContentLoaded', inject);
}} else {{
inject();
}}
";
try
{
if (!IsFrameWebkit(frame) && resourceType == "js")
{
await Task.Delay(500);
}
await frame.EvaluateExpressionAsync(injectString);
Log.Logger.Info($"Injected {Path.GetFileName(fileRelativePath)} into {tabFriendlyName} from patch {patchName}");
}
catch (PuppeteerException e)
{
if (!tabFriendlyName.StartsWith("http"))
{
Log.Logger.Error($"Failed to inject {resourceType} into {tabFriendlyName}");
Log.Logger.Debug(e);
}
}
}
private static bool IsFrameWebkit(Frame frame)
{
return !frame.Url.StartsWith("https://steamloopback.host");
}
[GeneratedRegex(@"^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)")]
private static partial Regex GetDomainRegex();
}