using System.Net; using System.Security.Claims; using System.Text; using System.Threading.RateLimiting; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Server.Infrastructure.Logging; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Options; using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .CreateLogger(); try { var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); builder.Services.AddControllers(); builder.Services.AddSignalR(); // 1. PostgreSQL EF Core DbContext var defaultConn = builder.Configuration.GetConnectionString("DefaultConnection") ?? Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") ?? "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=CHANGEME_DEV;"; builder.Services.AddDbContext(options => { options.UseNpgsql(defaultConn); }); // 2. Data Protection for Encrypted Recoverable Device Tokens var keysPath = OperatingSystem.IsLinux() ? "/var/lib/classnotify/keys" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "keys"); if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); } builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)) .SetApplicationName("ClassNotify"); // 3. ASP.NET Core PasswordHasher builder.Services.AddSingleton, PasswordHasher>(); // 4. JWT Options Binding & Strict Production Guard builder.Services.Configure(builder.Configuration.GetSection("Jwt")); var jwtOptions = builder.Configuration.GetSection("Jwt").Get() ?? new JwtOptions(); if (builder.Environment.IsProduction()) { if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 64) { throw new InvalidOperationException("Production Guard: Jwt__SigningKey is missing or has insufficient length (minimum 64 bytes required in Production). Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) { throw new InvalidOperationException("Production Guard: Jwt__Issuer is missing. Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) { throw new InvalidOperationException("Production Guard: Jwt__Audience is missing. Refusing to start."); } // 4.1 Device Trial Security Guard: Cryptographically random server-only secret (>= 32 bytes / 256 bits) var trialKeyRaw = builder.Configuration["Security:DeviceTrialHmacKey"] ?? builder.Configuration["Security__DeviceTrialHmacKey"] ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY") ?? builder.Configuration["CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY"]; if (string.IsNullOrWhiteSpace(trialKeyRaw)) { throw new InvalidOperationException("Production Guard: Security__DeviceTrialHmacKey (or CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY) is missing. Refusing to start (Fail-Closed)."); } ClassNotify.Server.Services.SecurityService.GetDeviceTrialHmacKeyBytes(trialKeyRaw, isDevelopment: false); } else { // Non-production fallback for design-time / local dev if unconfigured if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 32) { jwtOptions.SigningKey = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) jwtOptions.Issuer = "ClassNotify.Server"; if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) jwtOptions.Audience = "ClassNotify.Clients"; } builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection("DeviceVersionPolicy")); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // P2.5 RC1-3 Support Bundle Services builder.Services.Configure(builder.Configuration.GetSection("SupportBundles")); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // P2.5 RC1-4 Online Update Services builder.Services.Configure(builder.Configuration.GetSection("UpdateStorage")); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHostedService(); // Commercial Services (P3 Monetization & Multi-Screen Pairing) builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); // 5. JWT Authentication with Strict Validation builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { // Support SignalR query string token for WebSocket connections options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/teacher") || path.StartsWithSegments("/hubs/device"))) { context.Token = accessToken; } return Task.CompletedTask; }, OnTokenValidated = async context => { var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var tenantId = context.Principal?.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(userId)) { context.Fail("Invalid token claims: missing NameIdentifier."); return; } var dbContext = context.HttpContext.RequestServices.GetRequiredService(); var user = await dbContext.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == userId); if (user == null || user.IsLocked) { context.Fail("User account has been locked or deactivated."); return; } var tokenVersionClaim = context.Principal?.FindFirst("token_version")?.Value; if (string.IsNullOrWhiteSpace(tokenVersionClaim) || !int.TryParse(tokenVersionClaim, out var tokenVersion)) { context.Fail("Invalid token claims: missing or invalid token_version (fail-closed against legacy tokens)."); return; } if (user.TokenVersion != tokenVersion) { context.Fail("Token has been revoked due to security event or password reset."); return; } if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { var tenant = await dbContext.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { context.Fail("Tenant is inactive or suspended."); return; } } } }; }); builder.Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) .Configure>((options, jwtOptAccessor) => { var currentJwt = jwtOptAccessor.Value; var keyStr = currentJwt.SigningKey; if (string.IsNullOrWhiteSpace(keyStr) || Encoding.UTF8.GetByteCount(keyStr) < 32) { keyStr = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } var iss = !string.IsNullOrWhiteSpace(currentJwt.Issuer) ? currentJwt.Issuer : "ClassNotify.Server"; var aud = !string.IsNullOrWhiteSpace(currentJwt.Audience) ? currentJwt.Audience : "ClassNotify.Clients"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = iss, ValidAudience = aud, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyStr)), ClockSkew = TimeSpan.FromMinutes(1) }; }); builder.Services.AddAuthorization(); // 6. Partitioned Rate Limiting (按来源分区,避免全局限流瓶颈) builder.Services.Configure(builder.Configuration.GetSection("RateLimit")); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; // AuthLimiter: requests / minute / IP options.AddPolicy("AuthLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.AuthPermitLimit > 0 ? rateOpts.AuthPermitLimit : 60, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // ActivationLimiter: requests / minute / IP options.AddPolicy("ActivationLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.ActivationPermitLimit > 0 ? rateOpts.ActivationPermitLimit : 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // SendLimiter: notifications / minute / user (fallback to IP) options.AddPolicy("SendLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var partitionKey = !string.IsNullOrEmpty(userId) ? $"user_{userId}" : $"ip_{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"}"; return RateLimitPartition.GetFixedWindowLimiter(partitionKey, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.SendPermitLimit > 0 ? rateOpts.SendPermitLimit : 120, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); }); // 7. CORS Hardening (Production strictly allows official domain only) builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", policy => { if (builder.Environment.IsDevelopment()) { policy.WithOrigins("http://localhost:5173", "http://127.0.0.1:5173") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } else { policy.WithOrigins("https://classnotify.paradise.eu.org") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } }); }); // 6. Forwarded Headers for Linux reverse proxy (Caddy / Nginx) // Only trust loopback reverse proxy (Caddy on same host) with ForwardLimit = 1 builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); options.KnownProxies.Add(IPAddress.Loopback); options.KnownProxies.Add(IPAddress.IPv6Loopback); options.ForwardLimit = 1; }); var app = builder.Build(); app.UseForwardedHeaders(); app.UseMiddleware(); // Database Initialization & One-Time JSON Migration using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); try { if (db.Database.IsRelational()) { await db.Database.MigrateAsync(); } await DbInitializer.InitializeAsync(db, app.Environment, app.Configuration, app.Logger); await JsonMigrationService.MigrateAsync(db, null, app.Logger); } catch (Exception ex) { app.Logger.LogError(ex, "Error during database initialization or JSON migration."); throw; } } // Serve React SPA static files from wwwroot app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); // Turn 75 Frozen Requirement: Temporary password sessions cannot access normal business APIs app.Use(async (context, next) => { var user = context.User; if (user?.Identity?.IsAuthenticated == true) { var mustChange = user.FindFirst("must_change_password")?.Value; var path = context.Request.Path.Value ?? ""; if (string.Equals(mustChange, "true", StringComparison.OrdinalIgnoreCase)) { if (!path.StartsWith("/api/auth/change-password", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("/api/auth/logout", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("/api/auth/me", StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json"; await context.Response.WriteAsync("{\"success\":false,\"passwordChangeRequired\":true,\"message\":\"管理员已为您重置临时密码,在完成设置新密码前禁止访问系统业务接口\"}"); return; } } } await next(); }); app.UseRateLimiter(); app.MapControllers(); app.MapHub("/hubs/device"); app.MapHub("/hubs/teacher"); // Dedicated Real PostgreSQL Health Check Endpoint app.MapGet("/api/health", async (ClassNotifyDbContext dbContext) => { bool dbOk = false; string? dbError = null; try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); dbOk = await dbContext.Database.CanConnectAsync(cts.Token); if (dbOk) { await dbContext.Database.ExecuteSqlRawAsync("SELECT 1", cts.Token); } } catch (Exception ex) { dbError = ex.Message; } var status = dbOk ? "Healthy" : "Degraded"; var result = new { service = "ClassNotify Commercial Server (ASP.NET Core on Linux)", version = "2.1.0", status = status, database = dbOk ? "Connected" : "Disconnected", databaseError = dbError, hubs = new[] { "/hubs/device", "/hubs/teacher" } }; return dbOk ? Results.Ok(result) : Results.Json(result, statusCode: 503); }); // Fallback to index.html for React SPA client-side routing app.MapFallbackToFile("index.html"); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "ClassNotify Server terminated unexpectedly."); } finally { Log.CloseAndFlush(); } namespace ClassNotify.Server { public partial class Program { } }