-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
224 lines (196 loc) · 10.9 KB
/
Copy pathProgram.cs
File metadata and controls
224 lines (196 loc) · 10.9 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
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using SerbleAPI.API;
using SerbleAPI.Authentication;
using SerbleAPI.Config;
using SerbleAPI.Data;
using SerbleAPI.Data.Raw;
using SerbleAPI.Models;
using SerbleAPI.Repositories;
using SerbleAPI.Repositories.Impl;
using SerbleAPI.Services;
using SerbleAPI.Services.Impl;
using Stripe;
using TokenService = SerbleAPI.Services.Impl.TokenService;
namespace SerbleAPI;
public static class Program {
private static bool _runApp = true;
private static int Main(string[] args) {
return Run(args);
}
private static int Run(string[] args) {
Console.CancelKeyPress += (_, eventArgs) => {
Console.WriteLine("Shutting down...");
_runApp = false;
eventArgs.Cancel = true;
};
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Startup time config info
StripeSettings? stripeSettings = builder.Configuration.GetSection("Stripe").Get<StripeSettings>();
ApiSettings? apiSettings = builder.Configuration.GetSection("Api").Get<ApiSettings>();
PasskeySettings? passkeySettings = builder.Configuration.GetSection("Passkey").Get<PasskeySettings>();
if (stripeSettings == null || apiSettings == null || passkeySettings == null) {
throw new Exception("Stripe or API or Passkey settings not found in configuration");
}
StripeConfiguration.ApiKey = stripeSettings.ApiKey;
RawDataManager.LoadRawData();
WordId.Load();
builder.Services.AddOptions<ApiSettings>().Bind(builder.Configuration.GetSection("Api"));
builder.Services.AddOptions<StripeSettings>().Bind(builder.Configuration.GetSection("Stripe"));
builder.Services.AddOptions<PasskeySettings>().Bind(builder.Configuration.GetSection("Passkey"));
builder.Services.AddOptions<EmailSettings>().Bind(builder.Configuration.GetSection("Email"));
builder.Services.AddOptions<ReCaptchaSettings>().Bind(builder.Configuration.GetSection("ReCaptcha"));
builder.Services.AddOptions<JwtSettings>().Bind(builder.Configuration.GetSection("Jwt"));
builder.Services.AddOptions<TurnstileSettings>().Bind(builder.Configuration.GetSection("Turnstile"));
builder.Services.AddOptions<OidcSettings>().Bind(builder.Configuration.GetSection("Oidc"));
builder.Services.AddControllers();
builder.Services.AddHttpClient();
builder.Services.AddSwaggerGen();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddMemoryCache();
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(5);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
builder.Services.AddDbContext<SerbleDbContext>(options => {
string? mySqlConnection = builder.Configuration.GetConnectionString("MySql");
// EF design-time tooling resolves the context from the application service provider,
// so AutoDetect would try to open a real connection during `migrations add`. When the
// tooling sets SERBLE_EF_DESIGNTIME=1 we use a fixed server version instead so
// scaffolding never needs a live database. Runtime behaviour is unchanged.
ServerVersion serverVersion = Environment.GetEnvironmentVariable("SERBLE_EF_DESIGNTIME") == "1"
? new MySqlServerVersion(new Version(8, 0, 24))
: ServerVersion.AutoDetect(mySqlConnection);
options.UseMySql(mySqlConnection, serverVersion);
});
builder.Services.AddScoped<IAntiSpamService, AntiSpamService>();
builder.Services.AddScoped<IGoogleReCaptchaService, GoogleReCaptchaService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<ITurnstileCaptchaService, TurnstileCaptchaService>();
builder.Services.AddScoped<IEmailConfirmationService, EmailConfirmationService>();
builder.Services.AddScoped<IRewardTaskService, RewardTaskService>();
builder.Services.AddScoped<IServerConfigService, ServerConfigService>();
builder.Services.AddScoped<IFeatureFlagService, FeatureFlagService>();
builder.Services.AddScoped<ITaxService, TaxService>();
builder.Services.AddHostedService<TaxBackgroundService>();
// OIDC provider services
builder.Services.AddSingleton<IOidcKeyService, OidcKeyService>();
builder.Services.AddScoped<IOidcTokenService, OidcTokenService>();
builder.Services.AddScoped<IOidcClaimsService, OidcClaimsService>();
builder.Services.AddScoped<IAppAccessPolicyService, AppAccessPolicyService>();
// db repos
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IBalanceRepository, BalanceRepository>();
builder.Services.AddScoped<ITransactionRepository, TransactionRepository>();
builder.Services.AddScoped<ITransactionProposalRepository, TransactionProposalRepository>();
builder.Services.AddScoped<IUserTradeRepository, UserTradeRepository>();
builder.Services.AddScoped<IAppApiKeyRepository, AppApiKeyRepository>();
builder.Services.AddScoped<IAppRepository, AppRepository>();
builder.Services.AddScoped<IPasskeyRepository, PasskeyRepository>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<INoteRepository, NoteRepository>();
builder.Services.AddScoped<IKvRepository, KvRepository>();
builder.Services.AddScoped<IGroupRepository, GroupRepository>();
builder.Services.AddScoped<IServiceCatalogRepository, ServiceCatalogRepository>();
builder.Services.AddScoped<ICompletedRewardTaskRepository, CompletedRewardTaskRepository>();
builder.Services.AddScoped<IItemRepository, ItemRepository>();
builder.Services.AddScoped<IItemTransactionRepository, ItemTransactionRepository>();
builder.Services.AddScoped<IAppAccessRepository, AppAccessRepository>();
builder.Services.AddScoped<IOidcCodeRepository, OidcCodeRepository>();
builder.Services.AddScoped<IOidcRefreshRepository, OidcRefreshRepository>();
// Authentication
builder.Services.AddAuthentication(SerbleAuthenticationHandler.SchemeName)
.AddScheme<SerbleAuthenticationOptions, SerbleAuthenticationHandler>(
SerbleAuthenticationHandler.SchemeName, _ => { });
// Authorisation
// Register one policy per scope: [Authorize(Policy = "Scope:Vault")] etc.
// Also a UserOnly policy that blocks app tokens.
builder.Services.AddAuthorization(opts => {
foreach (ScopeHandler.ScopesEnum scope in Enum.GetValues<ScopeHandler.ScopesEnum>()) {
ScopeHandler.ScopesEnum captured = scope;
opts.AddPolicy($"Scope:{captured}", p =>
p.RequireAuthenticatedUser()
.RequireAssertion(ctx => ctx.User.HasScope(captured)));
}
opts.AddPolicy("UserOnly", p =>
p.RequireAuthenticatedUser()
.RequireAssertion(ctx => ctx.User.IsUser()));
opts.AddPolicy("AdminOnly", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new AdminOnlyRequirement()));
opts.AddPolicy("OfficialAppOnly", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new OfficialAppOnlyRequirement()));
opts.AddPolicy("AppOnly", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new AppKeyOnlyRequirement()));
opts.AddPolicy("OfficialAppKeyOnly", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new OfficialAppKeyOnlyRequirement()));
opts.AddPolicy("EconomyAccess", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new EconomyAccessRequirement()));
opts.AddPolicy("EconomyManage", p =>
p.RequireAuthenticatedUser()
.AddRequirements(new EconomyManageRequirement()));
});
builder.Services.AddScoped<IAuthorizationHandler, AdminAuthorizationHandler>();
builder.Services.AddScoped<IAuthorizationHandler, OfficialAppAuthorizationHandler>();
builder.Services.AddScoped<IAuthorizationHandler, AppKeyOnlyAuthorizationHandler>();
builder.Services.AddScoped<IAuthorizationHandler, OfficialAppKeyOnlyAuthorizationHandler>();
builder.Services.AddScoped<IAuthorizationHandler, EconomyAccessAuthorizationHandler>();
builder.Services.AddScoped<IAuthorizationHandler, EconomyManageAuthorizationHandler>();
builder.WebHost.UseUrls(apiSettings.BindUrl); // move IP binding to config because I hate launchSettings.json
builder.Services.AddFido2(options => {
options.ServerDomain = passkeySettings.RelyingPartyId;
options.ServerName = passkeySettings.RelyingPartyName;
options.Origins = passkeySettings.AllowedOrigins.ToHashSet();
options.TimestampDriftTolerance = 1000 * 60 * 5;
options.ServerIcon = passkeySettings.ServerIconUrl;
}).AddCachedMetadataService(config => {
config.AddFidoMetadataRepository(_ => {
});
});
// Init services
ServicesStatusService.Init();
WebApplication app = builder.Build();
if (!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
using (IServiceScope scope = app.Services.CreateScope()) {
SerbleDbContext db = scope.ServiceProvider.GetRequiredService<SerbleDbContext>();
if (db.Database.IsRelational()) {
db.Database.Migrate();
}
else {
db.Database.EnsureCreated();
}
db.SaveChanges();
}
// Middleware order: cors/options -> redirects -> session -> auth -> controllers
app.UseMiddleware<SerbleCorsMiddleware>();
app.UseMiddleware<RedirectsMiddleware>();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseSwagger();
app.UseSwaggerUI();
CancellationTokenSource tokenSource = new();
CancellationToken cancellationToken = tokenSource.Token;
Task appTask = app.RunAsync(cancellationToken);
while (_runApp) {
if (appTask.IsCompleted) {
break;
}
Thread.Sleep(100);
}
tokenSource.Cancel();
Console.WriteLine("Attempting to stop application (Will abort after 10 seconds)");
appTask.Wait(new TimeSpan(0, 0, 10));
return 0;
}
}