Files
sor/Server/src/SOR.Website/Program.cs
T
70e62263d3 feat(website): routing fixes, login by username, leaderboard stats, news CMS, CDN art
Website fixes:
- /how-to-play and /ai-assets and /ai-assets/report: add explicit @page routes
  (default Razor Pages routes were PascalCase, nav links used kebab-case)
- Webclient: redirect to webclient.aeternalisgames.com instead of /webclient/app
- Login: accept display name (username) or email; looks up by email first, then
  by DisplayName — uses TUser overload of PasswordSignInAsync with lockout support

Leaderboard:
- Add GamesPlayed, GamesWon, WinRate columns
- Inject GameDbContext; query completed sessions for the top-N account IDs and
  aggregate wins/plays in memory (cross-schema, no EF join)

News CMS:
- NewsPost entity in catalog schema (slug, title, summary, bodyHtml, heroImageUrl,
  author, published state, timestamps)
- CatalogDbContext: add DbSet<NewsPost> + model config
- Migration: 20260423000001_AddNewsPosts
- Website Program.cs: register AddGameDatabase
- News/Index.cshtml: list published posts with hero image + summary
- News/Post.cshtml: individual post detail page at /news/{slug}
- Admin NewsPostList.razor: list all posts, delete with confirm modal
- Admin NewsPostEditor.razor: full CRUD editor — title, slug (auto from title),
  summary, HTML body with live preview toggle, hero image with preview,
  publish toggle + date/time, author
- Admin NavMenu: add Website section with News Posts link

CDN art:
- Index.cshtml.cs: inject IConfiguration, expose CdnBaseUrl
- Index.cshtml: add hero-bg-img <img> sourced from {cdnBase}/website/hero-bg.jpg
  (upload hero-bg.jpg to CDN /website/ to activate; no image = no broken element)

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-04-23 08:50:14 -04:00

269 lines
14 KiB
C#

// SOR.Website — Public game website and player account portal
//
// This is the entry point for aeternalisgames.com. It runs independently of
// SOR.Host and connects to the same databases (Identity, Catalog) so player
// accounts created here work immediately in the game client.
//
// Security design:
// - All HTML rendered by Razor Pages is HTML-encoded by default (XSS impossible).
// - Content-Security-Policy blocks all inline scripts/styles (SecurityHeadersMiddleware).
// - Anti-forgery tokens are validated on every POST handler (Razor Pages default).
// - Auth cookie uses __Host- prefix: forces Secure, Path=/, and no Domain attribute.
// - Data Protection keys stored in Redis: all pods decrypt each other's cookies.
// - Rate limiting applied per-IP to all auth endpoints.
// - Forwarded-header trust enables accurate IP tracking behind the ingress.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.DataProtection;
using Serilog;
using StackExchange.Redis;
using SOR.Database;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using SOR.Website;
var builder = WebApplication.CreateBuilder(args);
// ── Logging ───────────────────────────────────────────────────────────────────
builder.Host.UseSerilog((ctx, cfg) =>
cfg.ReadFrom.Configuration(ctx.Configuration));
// ── Redis ─────────────────────────────────────────────────────────────────────
// Create the Redis connection eagerly so DataProtection can share it.
var redisConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379";
var redisConfig = ConfigurationOptions.Parse(redisConnectionString);
redisConfig.AbortOnConnectFail = false;
var redis = ConnectionMultiplexer.Connect(redisConfig);
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
// ── DataProtection ────────────────────────────────────────────────────────────
// Persist keys in Redis so all pod replicas can decrypt each other's session cookies.
// SetApplicationName ensures cookie protection is scoped to this app — different apps
// sharing the same Redis instance cannot accidentally decrypt each other's cookies.
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "SOR.Website:DataProtection-Keys")
.SetApplicationName("SOR.Website");
// ── Identity databases ────────────────────────────────────────────────────────
builder.Services.AddIdentityDatabase(builder.Configuration);
builder.Services.AddCatalogDatabase(builder.Configuration);
builder.Services.AddGameDatabase(builder.Configuration);
// ── ASP.NET Core Identity ─────────────────────────────────────────────────────
// Registers UserManager<Account>, SignInManager<Account>, and all token providers.
// Password rules and lockout here MUST match SOR.Auth/ServiceRegistration.cs so that
// passwords set via the website are accepted by the game client and vice versa.
builder.Services.AddIdentity<Account, IdentityRole<Guid>>(options =>
{
// Password policy (must match SOR.Auth)
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
// Account lockout after 5 failed attempts
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.AllowedForNewUsers = true;
// Email is the unique login identifier
options.User.RequireUniqueEmail = true;
// Email verification is advisory for now (players can play before verifying).
// Set RequireConfirmedEmail = true when an email provider is configured.
options.SignIn.RequireConfirmedEmail = false;
})
.AddEntityFrameworkStores<SorIdentityDbContext>()
.AddDefaultTokenProviders();
// ── Cookie configuration ──────────────────────────────────────────────────────
// AddIdentity registers the application cookie automatically.
// ConfigureApplicationCookie overrides the defaults to apply maximum security.
//
// __Host- prefix requirements (enforced by the browser, not us):
// - The Secure attribute must be set.
// - The Path attribute must be "/".
// - The Domain attribute must NOT be set.
// Together these prevent the cookie from being set by a subdomain compromise
// and ensure it is never sent over plain HTTP even if a redirect occurs.
builder.Services.ConfigureApplicationCookie(opts =>
{
opts.Cookie.Name = "__Host-sor-web-session";
opts.Cookie.HttpOnly = true; // inaccessible to JavaScript — blocks XSS token theft
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always; // never sent over HTTP
opts.Cookie.SameSite = SameSiteMode.Strict; // never sent on cross-site requests
opts.Cookie.Path = "/"; // required for __Host- prefix
opts.LoginPath = "/auth/login";
opts.LogoutPath = "/auth/logout";
opts.AccessDeniedPath = "/auth/login"; // unauthorized → login, not 403 page
opts.ReturnUrlParameter = "returnUrl"; // param name in /auth/login?returnUrl=...
opts.SlidingExpiration = true;
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
// SecurityStampValidator re-checks the stamp every 30 minutes by default.
// This means password changes and bans take effect within that window
// without a full DB hit on every single request.
});
// ── Anti-forgery ──────────────────────────────────────────────────────────────
// Razor Pages validates anti-forgery tokens on every POST handler by default.
// We apply the same strict cookie security as the session cookie.
// The HeaderName allows JavaScript fetch requests to send the token via header
// rather than form body (needed for AJAX calls with JSON bodies).
builder.Services.AddAntiforgery(opts =>
{
opts.Cookie.Name = "__Host-sor-csrf";
opts.Cookie.HttpOnly = true;
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opts.Cookie.SameSite = SameSiteMode.Strict;
opts.Cookie.Path = "/";
opts.HeaderName = "X-CSRF-TOKEN";
});
// ── Razor Pages ───────────────────────────────────────────────────────────────
// AuthorizeFolder("/Account") applies [Authorize] to every page under /Account.
// No individual page needs the attribute — it is enforced at the routing layer.
// This is the privilege-escalation control: unauthenticated requests to any
// /Account/* page are automatically redirected to /auth/login?returnUrl=...
builder.Services.AddRazorPages(opts =>
{
opts.Conventions.AuthorizeFolder("/Account");
});
// ── Rate limiting ─────────────────────────────────────────────────────────────
// Applied per-IP address to auth endpoints to slow brute-force attacks.
// IP is obtained from the RemoteIpAddress, which reflects the real client IP
// because UseForwardedHeaders() is applied early in the pipeline below.
//
// Policies are applied via [EnableRateLimiting("policy-name")] on page models.
builder.Services.AddRateLimiter(opts =>
{
opts.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Login: 10 attempts per IP per 5 minutes
opts.AddPolicy("auth-login", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(5),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
// Registration: 5 per IP per hour
opts.AddPolicy("auth-register", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromHours(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
// Password reset: 3 per IP per 15 minutes
opts.AddPolicy("auth-reset", httpCtx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpCtx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 3,
Window = TimeSpan.FromMinutes(15),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
});
// ── Forwarded headers ─────────────────────────────────────────────────────────
// The pod runs plain HTTP behind a TLS-terminating ingress (nginx/Traefik/etc.).
// Without this, ASP.NET Core sees the ingress IP as the client, breaking rate
// limiting (all clients appear to share one IP) and HSTS redirect logic.
// Clearing KnownNetworks/KnownProxies trusts any upstream proxy — safe because
// the pod is only reachable from within the cluster network.
builder.Services.Configure<ForwardedHeadersOptions>(opts =>
{
opts.ForwardedHeaders =
ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto |
ForwardedHeaders.XForwardedHost;
opts.KnownNetworks.Clear();
opts.KnownProxies.Clear();
});
// ── Health checks ─────────────────────────────────────────────────────────────
builder.Services.AddHealthChecks();
// ── BUILD ─────────────────────────────────────────────────────────────────────
var app = builder.Build();
// ── Middleware pipeline ───────────────────────────────────────────────────────
// Order is critical. Each line's comment explains why it must be at this position.
// 1. Forwarded headers: must be first so all subsequent middleware sees the
// real client IP, scheme, and host from proxy headers.
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
// 2a. Exception handler in production: inline so it never redirects to a
// protected route that would trigger an auth challenge loop.
app.UseExceptionHandler(err => err.Run(async ctx =>
{
ctx.Response.StatusCode = 500;
ctx.Response.ContentType = "text/html; charset=utf-8";
await ctx.Response.WriteAsync(
"<!DOCTYPE html><html><body><h1>An error occurred.</h1></body></html>");
}));
// 2b. HSTS: instructs browsers to always use HTTPS for this domain.
// The ingress terminates TLS; the pod itself is plain HTTP.
// UseHttpsRedirection is intentionally omitted — the pod never receives
// HTTPS directly, so redirecting would cause an infinite loop.
app.UseHsts();
}
// 3. Security headers: must come before static files so every response (including
// CSS, JS, images) carries the full security header set.
app.UseMiddleware<SecurityHeadersMiddleware>();
// 4. Static files: serves wwwroot/ content.
// Comes before routing so requests for .css/.js/.png etc. short-circuit here
// without hitting the Razor Pages routing layer.
app.UseStaticFiles();
// 5. Routing: maps URL paths to page handlers.
app.UseRouting();
// 6. Rate limiting: must come after UseRouting (needs endpoint metadata) and
// before UseAuthentication (so we can reject before doing any DB work).
app.UseRateLimiter();
// 7. Authentication: reads the __Host-sor-web-session cookie and populates
// HttpContext.User with the signed-in Account's claims.
app.UseAuthentication();
// 8. Authorization: enforces [Authorize] and AuthorizeFolder conventions.
// Must come after UseAuthentication.
app.UseAuthorization();
// ── Endpoints ─────────────────────────────────────────────────────────────────
app.MapRazorPages();
// Health check: AllowAnonymous so Kubernetes probes work before any session exists.
app.MapHealthChecks("/health").AllowAnonymous();
// ── RUN ───────────────────────────────────────────────────────────────────────
Log.Information("SOR.Website starting");
await app.RunAsync();