blob: ab41806c0fb4983aebdb48b33c804d11bc821aa2 (
plain) (
blame)
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
|
namespace slskd
{
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
public static class HTMLInjectionMiddlewareExtensions
{
public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html)
{
return builder.UseMiddleware<HTMLInjectionMiddleware>(html);
}
}
public class HTMLInjectionMiddleware
{
public HTMLInjectionMiddleware(RequestDelegate next, string html)
{
Next = next;
HTML = html;
}
private string HTML { get; }
private RequestDelegate Next { get; }
public async Task InvokeAsync(HttpContext context)
{
context.Request.Headers.TryGetValue("accept", out var accept);
var requestedTypes = accept.ToString().Split(',');
var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" };
var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
var isGET = context.Request.Method == "GET";
var isInjectableType = requestedTypes
.Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase)
.Any();
if (!isApiRoute && isGET && isInjectableType)
{
context.Request.EnableBuffering();
await Next.Invoke(context);
if (context.Response.StatusCode == 200)
{
await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(HTML));
}
}
else
{
await Next.Invoke(context);
}
}
}
}
|