summaryrefslogtreecommitdiff
path: root/Program.cs
blob: 2c56209a2ca012bbcc8571fb6f299f22421d855b (plain)
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
using HyperBooru.Server.Components;
using HyperBooru.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Text.Json.Serialization;

namespace HyperBooru.Server;

public class Program {
    public static void Main(string[] args) {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddHttpContextAccessor();
        builder.Services.AddControllers().AddJsonOptions(o => {
            var converter = new JsonStringEnumConverter();
            o.JsonSerializerOptions.Converters.Add(converter);
        });
        builder.Services.Configure<JsonOptions>(o => {
            o.SerializerOptions.TypeInfoResolverChain.Insert(0, new ExceptionJsonResolver());
        });
        builder.Services.AddRazorComponents()
            .AddInteractiveWebAssemblyComponents();

        // Add our custom services
        builder.Services.AddSingleton<IConfigService, ConfigService>();
        builder.Services.AddDbContextFactory<HBContext>();
        builder.Services.AddScoped<IFeedService, FeedService>();
        builder.Services.AddScoped<ITagService, TagService>();
        builder.Services.AddScoped<IMediaService, MediaService>();
        builder.Services.AddSingleton<IGlobalUserService, GlobalUserService>();
        builder.Services.AddScoped<IUserService, UserService>();
        builder.Services.AddHostedService<OcrService>();

        // Ensure session keys are stored in a persistent location on all platforms
        builder.Services.AddDataProtection()
            .PersistKeysToFileSystem(new(
                builder.Services.BuildServiceProvider()
                    .GetRequiredService<IConfigService>()
                    .KeyPath));

        // Load our persistently-stored JWT signing key
        builder.Services.AddSingleton<RSA>(sp => {
            var keyPath = Path.Combine(
                sp.GetRequiredService<IConfigService>().KeyPath,
                "jwt_key");

            var protector = sp.GetRequiredService<IDataProtectionProvider>()
                .CreateProtector("jwt-signing-key");

            try {
                var unprotected = protector.Unprotect(File.ReadAllBytes(keyPath));
                var rsa = RSA.Create();
                rsa.ImportRSAPrivateKey(unprotected, out var _);
                return rsa;
            } catch {
                var rsa = RSA.Create(4096);
                var privKey = rsa.ExportRSAPrivateKey();
                File.WriteAllBytes(keyPath, protector.Protect(privKey));
                return rsa;
            }
        });

        // Configure JWT token-based authentication
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(o => {
                var rsa = builder.Services.BuildServiceProvider().GetRequiredService<RSA>();
                o.TokenValidationParameters  = new TokenValidationParameters {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new RsaSecurityKey(rsa)
                };
            });

        // Configure custom authorization policies
        builder.Services.AddAuthorization(o => {
            o.AddPolicy(AuthorizationPolicy.NsfwPolicy, p => {
                p.RequireClaim("nsfw", "true");
            });
        });

        var app = builder.Build();

        // Ensure database is created and it's schema is up to date
        using var scope = app.Services.CreateScope();
        using var db    = scope.ServiceProvider.GetRequiredService<HBContext>();
        db.Database.Migrate();

        if(app.Environment.IsDevelopment()) {
            app.UseWebAssemblyDebugging();
        } else {
            app.UseExceptionHandler("/Error");
        }

        app.UseAuthentication();
        app.UseAuthorization();
        app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
        app.UseHsts();
        app.UseHttpsRedirection();
        app.MapStaticAssets();
        app.UseMiddleware<ExceptionMiddleware>();
        app.UseAntiforgery();
        app.MapControllers().DisableAntiforgery();
        app.MapRazorComponents<App>()
            .AddInteractiveWebAssemblyRenderMode()
            .AddAdditionalAssemblies(typeof(Client._Imports).Assembly);

        app.Run();
    }
}