using Asp.Versioning; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using NTP.Api.Auth; using NTP.Api.ErrorHandling; using NTP.Application; using NTP.Infrastructure; using NTP.Infrastructure.Persistence; var builder = WebApplication.CreateBuilder(args); // Optional per-machine overrides (git-ignored). Copy appsettings.Local.example.json to start. builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: false); builder.Services.AddControllers(); builder.Services .AddApiVersioning(o => { o.DefaultApiVersion = new ApiVersion(1, 0); o.AssumeDefaultVersionWhenUnspecified = true; o.ReportApiVersions = true; o.ApiVersionReader = new UrlSegmentApiVersionReader(); }) .AddMvc() .AddApiExplorer(o => { o.GroupNameFormat = "'v'VVV"; // -> "v1", matches the OpenAPI document name o.SubstituteApiVersionInUrl = true; // /api/v1/... instead of /api/v{version}/... }); builder.Services.AddOpenApi("v1", o => o.AddDocumentTransformer()); builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddNtpAuthentication(builder.Configuration, builder.Environment); // CORS for the Vite dev server (Cors:AllowedOrigins). Bearer tokens, so no credentials needed. var corsOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? ["http://localhost:5173"]; builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins(corsOrigins).AllowAnyHeader().AllowAnyMethod())); builder.Services.AddApplication(); builder.Services.AddInfrastructure(builder.Configuration); var app = builder.Build(); // Fails fast here if no connection is configured; logs the target DB without the password. var oracle = app.Services.GetRequiredService>().Value; app.Logger.LogInformation("Oracle connection: {ConnectionString}", oracle.ToSafeString()); // Browser hardening headers on every response (API and the web app it serves). The CSP fits the built web app: own scripts only, // MUI inline styles, the Cairo font from Google Fonts, PDFs shown in a blob: iframe. Not applied in Development (Vite hot reload). if (!app.Environment.IsDevelopment()) { const string csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + "font-src 'self' data: https://fonts.gstatic.com; img-src 'self' data: blob:; connect-src 'self'; " + "frame-src 'self' blob:; object-src 'self' blob:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"; app.Use(async (ctx, next) => { ctx.Response.OnStarting(() => { var h = ctx.Response.Headers; h["X-Content-Type-Options"] = "nosniff"; h["X-Frame-Options"] = "DENY"; h["Referrer-Policy"] = "same-origin"; h["Content-Security-Policy"] = csp; if (ctx.Request.IsHttps) h["Strict-Transport-Security"] = "max-age=31536000"; // https is known from X-Forwarded-Proto return Task.CompletedTask; }); await next(); }); } app.UseCors("Frontend"); // first, so error responses also carry CORS headers app.UseExceptionHandler(); app.UseStatusCodePages(); if (app.Environment.IsDevelopment()) { app.MapOpenApi().AllowAnonymous(); // /openapi/v1.json app.UseSwaggerUI(o => o.SwaggerEndpoint("/openapi/v1.json", "NTP API v1")); } // Container deployment: the image copies the built web app (web/dist) into wwwroot and the API serves it, so the // reverse proxy in front only needs this one upstream. Not present in Development (Vite serves the web app there). var serveWeb = app.Environment.WebRootPath is { } webRoot && File.Exists(Path.Combine(webRoot, "index.html")); if (serveWeb) { app.UseDefaultFiles(); app.UseStaticFiles(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); // Browser routes of the single page app: not the API, not a health check and not a file (no dot in the path). A matched // endpoint makes the static file middleware step aside, so file requests (assets/x.js) must NOT match this route. if (serveWeb) app.MapFallbackToFile("{*path:regex(^(?!api/|health/)[^.]*$)}", "index.html").AllowAnonymous(); // Liveness: process is up. Readiness: Oracle reachable. app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false }).AllowAnonymous(); app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = c => c.Tags.Contains("ready") }).AllowAnonymous(); app.Run();