using Microsoft.AspNetCore.RateLimiting; using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.FileProviders; using PlotLine.Hubs; namespace PlotLine; public class Program { public static void Main(string[] args) => BuildApplication(args).Run(); public static WebApplication BuildApplication(string[] args, Action? configure = null) { var builder = WebApplication.CreateBuilder(args); if (builder.Environment.IsDevelopment()) builder.Configuration.AddJsonFile("sql-diagnostics.Development.json", optional: true, reloadOnChange: true); builder.Logging.ClearProviders(); builder.Logging.AddConsole(); builder.Logging.AddDebug(); builder.Services.AddControllersWithViews(options => { options.Filters.Add(); options.Filters.Add(); options.Filters.Add(); }); builder.Services.AddSignalR(options => { options.MaximumReceiveMessageSize = 1024 * 1024; }).AddHubOptions(options=>options.MaximumReceiveMessageSize=4096); builder.Services.AddHttpContextAccessor(); builder.Services.AddMemoryCache(); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Lax; }); builder.Services.Configure(builder.Configuration.GetSection("EmailSettings")); builder.Services.Configure(builder.Configuration.GetSection("Stripe")); builder.Services.Configure(builder.Configuration.GetSection("Storage")); builder.Services.Configure(options => { builder.Configuration.GetSection("OpenAI").Bind(options); builder.Configuration.GetSection("StoryIntelligence").Bind(options); }); builder.Services.Configure(builder.Configuration.GetSection("StoryIntelligence:Pricing")); var dataProtectionKeyPath = GetDataProtectionKeyPath( builder.Environment.ContentRootPath, builder.Configuration["DataProtection:KeysPath"]); Directory.CreateDirectory(dataProtectionKeyPath); builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(dataProtectionKeyPath)); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "PlotLine.Auth"; options.LoginPath = "/Account/Login"; options.LogoutPath = "/Account/Logout"; options.AccessDeniedPath = "/Account/AccessDenied"; options.SlidingExpiration = true; options.ExpireTimeSpan = TimeSpan.FromDays(14); options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.Lax; options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { var userIdValue = context.Principal?.FindFirstValue(ClaimTypes.NameIdentifier); var securityStampValue = context.Principal?.FindFirstValue("PlotLine.SecurityStamp"); if (!int.TryParse(userIdValue, out var userId) || !Guid.TryParse(securityStampValue, out var securityStamp)) { context.RejectPrincipal(); await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return; } using var scope = context.HttpContext.RequestServices.CreateScope(); var users = scope.ServiceProvider.GetRequiredService(); var user = await users.GetByIdAsync(userId); var isLocked = user?.IsLocked == true && (!user.LockoutEndUtc.HasValue || user.LockoutEndUtc > DateTime.UtcNow); if (user is null || user.SecurityStamp != securityStamp || isLocked) { context.RejectPrincipal(); await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } }; }); builder.Services.AddRateLimiter(options => options.AddPolicy("native-pair", context => System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions { PermitLimit=120, Window=TimeSpan.FromMinutes(1), QueueLimit=0 }))); builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddAuthentication().AddScheme(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { }); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => { policy.RequireAuthenticatedUser(); policy.RequireAssertion(context => { var email = context.User.FindFirstValue(ClaimTypes.Email); var allowedEmails = builder.Configuration.GetSection("Admin:AllowedEmails").Get() ?? []; return !string.IsNullOrWhiteSpace(email) && allowedEmails.Any(allowed => string.Equals(allowed, email, StringComparison.OrdinalIgnoreCase)); }); }); }); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(services => services.GetRequiredService()); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(services=>new WritingSolverPayoff(Path.Combine(services.GetRequiredService().ContentRootPath,"Content/WritingSolver/Presentation/payoff-v1.json"))); builder.Services.AddSingleton(services => new WritingProblemEditorial(Path.Combine(services.GetRequiredService().ContentRootPath,"Content/WritingSolver/Editorial/pages-v1.json"))); builder.Services.AddSingleton(services => new WritingSolverResults(Path.Combine(services.GetRequiredService().ContentRootPath,"Content/WritingSolver/Presentation/results-v1.json"))); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(sp=>sp.GetRequiredService()); builder.Services.AddSingleton(new GeographicRules(Path.Combine(builder.Environment.ContentRootPath, "Data", "Reference", "Geography"))); builder.Services.Configure(builder.Configuration.GetSection("Geography")); builder.Services.AddHttpClient("Geocoding", client=>client.Timeout=TimeSpan.FromSeconds(25)) .RemoveAllLoggers() .ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler { AllowAutoRedirect=false }); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHttpClient(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHostedService(); if (builder.Configuration.GetValue("StoryIntelligence:WorkersEnabled", true)) { builder.Services.AddHostedService(); } if (builder.Configuration.GetValue("Illustrations:GenerationWorkerEnabled", true)) { builder.Services.AddHostedService(); } configure?.Invoke(builder); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseDevelopmentNoIndex(); app.UseHttpsRedirection(); // Keep PWA metadata/worker revalidating even when served by static-asset endpoints. app.Use(async (context, next) => { if (context.Request.Path == "/service-worker.js" || context.Request.Path == "/site.webmanifest") { context.Response.OnStarting(() => { context.Response.Headers.CacheControl = "no-cache"; return Task.CompletedTask; }); } await next(); }); app.UseStaticFiles(); var uploadStorage = app.Services.GetRequiredService(); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(uploadStorage.UploadsRootPath), RequestPath = "/uploads" }); app.UseWritingSolverReviewBoundary(); app.UseRouting(); var sqlDiagnostics = app.Services.GetRequiredService(); if (sqlDiagnostics.Enabled) app.Use(async (context, next) => { if (!sqlDiagnostics.Enabled) { await next(context); return; } var frame = sqlDiagnostics.BeginRequest(context.TraceIdentifier); context.Response.Headers["X-Sql-Correlation"] = frame.Correlation; var start = System.Diagnostics.Stopwatch.GetTimestamp(); var completed = false; try { await next(context); completed = true; } finally { var route = (context.GetEndpoint() as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern.RawText ?? "[unmatched]"; route = context.Request.RouteValues.TryGetValue("controller", out var controller) ? $"{controller}/{context.Request.RouteValues["action"]}" : route; sqlDiagnostics.EndRequest(frame, route, System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds, completed || context.Response.HasStarted ? context.Response.StatusCode : 500, context.RequestAborted.IsCancellationRequested ? "cancelled" : completed ? "complete" : "error"); } }); app.UseRateLimiter(); app.UseSession(); app.UseAuthentication(); app.UseAuthorization(); app.MapStaticAssets(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}") .WithStaticAssets(); app.MapHub("/hubs/native-companion"); app.MapHub("/hubs/native-companion-agent", options=>options.CloseOnAuthenticationExpiration=true); app.MapHub("/hubs/word-companion-follow"); app.MapHub("/hubs/story-intelligence"); return app; } private static string GetDataProtectionKeyPath(string contentRootPath, string? configuredPath) { if (!string.IsNullOrWhiteSpace(configuredPath)) { return Path.GetFullPath(configuredPath); } var contentRoot = new DirectoryInfo(contentRootPath); if (string.Equals(contentRoot.Name, "current", StringComparison.OrdinalIgnoreCase) && contentRoot.Parent is not null) { return Path.Combine(contentRoot.Parent.FullName, "App_Data", "DataProtectionKeys"); } return Path.Combine(contentRoot.FullName, "App_Data", "DataProtectionKeys"); } }