diff --git a/Server/SOR.slnx b/Server/SOR.slnx index 7de3b62..a3f907c 100644 --- a/Server/SOR.slnx +++ b/Server/SOR.slnx @@ -1,6 +1,7 @@ + diff --git a/Server/src/SOR.Website/Pages/Account/Game.cshtml b/Server/src/SOR.Website/Pages/Account/Game.cshtml new file mode 100644 index 0000000..18c2307 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Game.cshtml @@ -0,0 +1,44 @@ +@page +@model GameModel +@{ + ViewData["Title"] = "Game Stats"; + var account = Model.AccountData!; +} + + + + diff --git a/Server/src/SOR.Website/Pages/Account/Game.cshtml.cs b/Server/src/SOR.Website/Pages/Account/Game.cshtml.cs new file mode 100644 index 0000000..da9462e --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Game.cshtml.cs @@ -0,0 +1,18 @@ +namespace SOR.Website.Pages.Account; + +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +public sealed class GameModel(UserManager userManager) : PageModel +{ + public Account? AccountData { get; private set; } + + public async Task OnGetAsync() + { + AccountData = await userManager.GetUserAsync(User); + if (AccountData is null) return RedirectToPage("/Auth/Logout"); + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Account/Index.cshtml b/Server/src/SOR.Website/Pages/Account/Index.cshtml new file mode 100644 index 0000000..225ab0e --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Index.cshtml @@ -0,0 +1,46 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "Account"; + var account = Model.AccountData!; +} + + + + diff --git a/Server/src/SOR.Website/Pages/Account/Index.cshtml.cs b/Server/src/SOR.Website/Pages/Account/Index.cshtml.cs new file mode 100644 index 0000000..c32e787 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Index.cshtml.cs @@ -0,0 +1,36 @@ +namespace SOR.Website.Pages.Account; + +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +/// +/// Account dashboard — authenticated users only. +/// Authorization is enforced by the AuthorizeFolder("/Account") convention in Program.cs. +/// +/// Security controls: +/// - Data shown is scoped to the currently signed-in account only. +/// - Account ID comes from the validated session cookie, never from query string or form. +/// - Fields that must not be public (email, internal ID, moderation state) are only +/// accessible here behind authentication. +/// +public sealed class IndexModel(UserManager userManager) : PageModel +{ + public Account? AccountData { get; private set; } + + public async Task OnGetAsync() + { + // GetUserAsync reads the account ID from the signed-in claims principal. + // It never trusts a user-supplied ID — the ID comes from the session cookie. + AccountData = await userManager.GetUserAsync(User); + + if (AccountData is null) + { + // Session exists but account was deleted — sign out cleanly. + return RedirectToPage("/Auth/Logout"); + } + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Account/Profile.cshtml b/Server/src/SOR.Website/Pages/Account/Profile.cshtml new file mode 100644 index 0000000..9b5b430 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Profile.cshtml @@ -0,0 +1,40 @@ +@page +@model ProfileModel +@{ + ViewData["Title"] = "Edit Profile"; +} + + + + diff --git a/Server/src/SOR.Website/Pages/Account/Profile.cshtml.cs b/Server/src/SOR.Website/Pages/Account/Profile.cshtml.cs new file mode 100644 index 0000000..febba57 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Profile.cshtml.cs @@ -0,0 +1,74 @@ +namespace SOR.Website.Pages.Account; + +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +/// +/// Allows the authenticated player to update their display name. +/// +/// Security controls: +/// - Account ID comes from the session cookie (GetUserAsync), never from the form. +/// - DisplayName validation mirrors registration rules — no special characters +/// that could cause downstream injection. +/// - UpdateSecurityStampAsync after profile change causes existing sessions on +/// other devices to be re-validated within 30 minutes (the ValidationInterval). +/// - Anti-forgery token validated on POST. +/// +public sealed class ProfileModel( + UserManager userManager, + SignInManager signInManager) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + public bool Saved { get; private set; } + + public sealed class InputModel + { + [Required(ErrorMessage = "Display name is required.")] + [MinLength(3, ErrorMessage = "Display name must be at least 3 characters.")] + [MaxLength(32, ErrorMessage = "Display name cannot exceed 32 characters.")] + [RegularExpression(@"^[\w\- ]+$", + ErrorMessage = "Display name may only contain letters, digits, spaces, hyphens, and underscores.")] + public string DisplayName { get; set; } = string.Empty; + } + + public async Task OnGetAsync() + { + var account = await userManager.GetUserAsync(User); + if (account is null) return RedirectToPage("/Auth/Logout"); + + Input.DisplayName = account.DisplayName ?? string.Empty; + return Page(); + } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + var account = await userManager.GetUserAsync(User); + if (account is null) return RedirectToPage("/Auth/Logout"); + + account.DisplayName = Input.DisplayName.Trim(); + var result = await userManager.UpdateAsync(account); + + if (!result.Succeeded) + { + foreach (var err in result.Errors) + ModelState.AddModelError(string.Empty, err.Description); + return Page(); + } + + // Refresh the session cookie so the nav bar immediately shows the new name. + var claims = new[] { new Claim("display_name", account.DisplayName ?? string.Empty) }; + await signInManager.SignInWithClaimsAsync(account, isPersistent: false, claims); + + Saved = true; + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Account/Security.cshtml b/Server/src/SOR.Website/Pages/Account/Security.cshtml new file mode 100644 index 0000000..957e188 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Security.cshtml @@ -0,0 +1,64 @@ +@page +@model SecurityModel +@{ + ViewData["Title"] = "Security"; +} + + + + diff --git a/Server/src/SOR.Website/Pages/Account/Security.cshtml.cs b/Server/src/SOR.Website/Pages/Account/Security.cshtml.cs new file mode 100644 index 0000000..7270776 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Account/Security.cshtml.cs @@ -0,0 +1,80 @@ +namespace SOR.Website.Pages.Account; + +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +/// +/// Allows the authenticated player to change their password. +/// +/// Security controls: +/// - Requires the current password before accepting a new one. This prevents +/// an attacker who has seized an unlocked browser session from silently changing +/// credentials without knowing the existing password. +/// - ChangePasswordAsync validates both the current password and the new password's +/// strength rules via Identity. +/// - UpdateSecurityStampAsync is called by ChangePasswordAsync — this invalidates +/// all other active sessions within 30 minutes (the cookie ValidationInterval). +/// - Account ID from session, not from form input. +/// - Anti-forgery token validated on POST. +/// +public sealed class SecurityModel( + UserManager userManager, + SignInManager signInManager) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + public bool Saved { get; private set; } + + public sealed class InputModel + { + [Required(ErrorMessage = "Current password is required.")] + [DataType(DataType.Password)] + [MaxLength(128)] + public string CurrentPassword { get; set; } = string.Empty; + + [Required(ErrorMessage = "New password is required.")] + [MinLength(8, ErrorMessage = "Password must be at least 8 characters.")] + [MaxLength(128)] + [DataType(DataType.Password)] + public string NewPassword { get; set; } = string.Empty; + + [Required(ErrorMessage = "Please confirm your new password.")] + [DataType(DataType.Password)] + [Compare(nameof(NewPassword), ErrorMessage = "Passwords do not match.")] + public string ConfirmPassword { get; set; } = string.Empty; + } + + public void OnGet() { } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + var account = await userManager.GetUserAsync(User); + if (account is null) return RedirectToPage("/Auth/Logout"); + + var result = await userManager.ChangePasswordAsync( + account, Input.CurrentPassword, Input.NewPassword); + + if (result.Succeeded) + { + // Re-sign-in to refresh the cookie after the security stamp changes. + // Without this the cookie is rejected on the next request (30 min gap). + await signInManager.RefreshSignInAsync(account); + Saved = true; + return Page(); + } + + // Generic: "Incorrect current password" is acceptable — it does not help + // an attacker because they must first be authenticated to reach this page. + foreach (var err in result.Errors) + ModelState.AddModelError(string.Empty, err.Description); + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml b/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml new file mode 100644 index 0000000..535af6b --- /dev/null +++ b/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml @@ -0,0 +1,79 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "AI Asset Disclosure"; + ViewData["MetaDescription"] = "Aeternalis AI asset usage disclosure. How AI tools are used, reviewed, and tracked."; +} + + + +
+ +
+

Summary

+

+ Some visual and audio assets in Aeternalis were created with the assistance of AI generation tools. + Every AI-assisted asset has been reviewed and modified by a human before being used in the game. + This page explains how and why, and links to the full asset report. +

+
+ +
+

Asset Categories That May Use AI Assistance

+
    +
  • Card art (2D illustrations) — some card art was generated or edited with AI tools.
  • +
  • Placeholder assets — early development assets may be AI-generated pending final art.
  • +
  • Promotional imagery — some marketing images may use AI assistance.
  • +
+
+ +
+

Asset Categories That Do Not Use AI Generation

+
    +
  • Game rules, card text, and mechanics.
  • +
  • Lore, story, and world-building content.
  • +
  • Code and game systems.
  • +
  • 3D board models (hand-crafted geometry).
  • +
+
+ +
+

Human Review and Editing Process

+

+ No AI-generated asset enters the game without human review. Reviewers check for: + inappropriate content, factual or lore inconsistencies, visual quality, and alignment + with the game's aesthetic. Assets may be edited, reprompted, or replaced entirely. +

+

+ The status of each asset (Active, Replaced, Placeholder, Deprecated) is tracked in + the full report below. +

+
+ +
+

Player-Facing Impact

+

+ AI-assisted assets are used for visual presentation only and have no effect on gameplay, + card mechanics, rules, or balance. The game's competitive systems are entirely human-designed. +

+
+ +
+

Reporting and Contact

+

+ If you notice an asset that appears to be AI-generated but is not listed in the report, + or if you have questions about our AI asset policy, please contact us via the + support page. +

+
+ + + +
diff --git a/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml.cs b/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml.cs new file mode 100644 index 0000000..63939eb --- /dev/null +++ b/Server/src/SOR.Website/Pages/AiAssets/Index.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages.AiAssets; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class IndexModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml b/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml new file mode 100644 index 0000000..964ede4 --- /dev/null +++ b/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml @@ -0,0 +1,87 @@ +@page +@model ReportModel +@{ + ViewData["Title"] = "AI Asset Report"; + ViewData["MetaDescription"] = "Full searchable report of AI-assisted assets in Aeternalis."; +} + + + +
+ +
+
+ + + + @if (!string.IsNullOrWhiteSpace(Model.Search)) + { + Clear + } +
+
+ + @if (!Model.Records.Any()) + { +
+

No AI-assisted assets found@(!string.IsNullOrWhiteSpace(Model.Search) ? " matching your search" : "").

+
+ } + else + { +
+ + + + + + + + + + + @foreach (var record in Model.Records) + { + + @* All values auto-encoded by Razor — no XSS *@ + + + + + + } + +
Object KeyPrefixTypeUploaded
@record.ObjectKey@record.Prefix@(record.ContentType ?? "—")@record.UploadedAt.ToString("yyyy-MM-dd")
+
+ + @if (Model.TotalPages > 1) + { + + } + } + + +
diff --git a/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml.cs b/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml.cs new file mode 100644 index 0000000..7e4d1d7 --- /dev/null +++ b/Server/src/SOR.Website/Pages/AiAssets/Report.cshtml.cs @@ -0,0 +1,57 @@ +namespace SOR.Website.Pages.AiAssets; + +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Catalog; + +/// +/// Full searchable AI asset report sourced from the CdnUploadRecord table. +/// Records with IsAiGenerated = true are the AI-assisted assets. +/// +/// Security controls: +/// - Read-only query from catalog — no user input modifies data. +/// - Search parameter used in a parameterized EF Core query only. +/// - Pagination prevents resource exhaustion. +/// +public sealed class ReportModel(CatalogDbContext catalog) : PageModel +{ + public const int PageSize = 50; + + public IReadOnlyList Records { get; private set; } = []; + public int TotalCount { get; private set; } + public int CurrentPage { get; private set; } = 1; + public int TotalPages => (int)Math.Ceiling((double)TotalCount / PageSize); + + public string? Search { get; private set; } + public int PageNumber { get; private set; } = 1; + + public async Task OnGetAsync( + [Microsoft.AspNetCore.Mvc.FromQuery] string? search, + [Microsoft.AspNetCore.Mvc.FromQuery] int page = 1) + { + Search = search; + PageNumber = Math.Max(1, page); + CurrentPage = PageNumber; + + var query = catalog.CdnUploadRecords + .Where(r => r.IsAiGenerated) + .AsNoTracking(); + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(r => + EF.Functions.ILike(r.ObjectKey, $"%{term}%") || + EF.Functions.ILike(r.Prefix, $"%{term}%")); + } + + TotalCount = await query.CountAsync(); + + Records = await query + .OrderByDescending(r => r.UploadedAt) + .Skip((CurrentPage - 1) * PageSize) + .Take(PageSize) + .ToListAsync(); + } +} diff --git a/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml b/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml new file mode 100644 index 0000000..c2aaf8f --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml @@ -0,0 +1,42 @@ +@page +@model ForgotPasswordModel +@{ + ViewData["Title"] = "Forgot Password"; +} + +
+
+

Reset Password

+ + @if (Model.EmailSent) + { +
+ If an account exists with that email, you'll receive a reset link shortly. + Check your spam folder if it doesn't arrive within a few minutes. +
+ Back to Login + } + else + { +

Enter your account email and we'll send you a reset link.

+ +
+
+ + + +
+ +
+ + + } +
+
diff --git a/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml.cs new file mode 100644 index 0000000..b0590ae --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/ForgotPassword.cshtml.cs @@ -0,0 +1,74 @@ +namespace SOR.Website.Pages.Auth; + +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.RateLimiting; +using SOR.Database.Entities.Identity; + +/// +/// Initiates password reset by sending a reset link to the supplied email. +/// +/// Security controls: +/// - [EnableRateLimiting]: 3 attempts per IP per 15 minutes — limits reset spam. +/// - Anti-enumeration: ALWAYS shows the same success message regardless of whether +/// the email is registered. An attacker cannot probe which emails have accounts. +/// - Reset token generated by ASP.NET Core Identity's built-in TOTP token provider +/// (time-limited, single-use). The raw token is sent in the email link only. +/// - TODO: wire up an actual email provider. Until then the reset link is logged +/// (only in Development) so developers can test the flow. +/// +[EnableRateLimiting("auth-reset")] +public sealed class ForgotPasswordModel( + UserManager userManager, + ILogger logger) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + public bool EmailSent { get; private set; } + + public sealed class InputModel + { + [Required(ErrorMessage = "Email is required.")] + [EmailAddress(ErrorMessage = "Enter a valid email address.")] + [MaxLength(254)] + public string Email { get; set; } = string.Empty; + } + + public void OnGet() { } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + // Look up the user — but do not reveal whether the email is registered. + var user = await userManager.FindByEmailAsync(Input.Email); + + if (user is not null && !user.IsAi) + { + var token = await userManager.GeneratePasswordResetTokenAsync(user); + var resetLink = Url.Page( + "/Auth/ResetPassword", + pageHandler: null, + values: new { token, email = Input.Email }, + protocol: Request.Scheme); + + // TODO: send resetLink via email provider. + // Log in development only so the link is accessible for manual testing. + if (HttpContext.RequestServices + .GetRequiredService() + .IsDevelopment()) + { + logger.LogWarning("DEV ONLY — password reset link for {Email}: {Link}", + Input.Email, resetLink); + } + } + + // Always show the same message — anti-enumeration. + EmailSent = true; + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Auth/Login.cshtml b/Server/src/SOR.Website/Pages/Auth/Login.cshtml new file mode 100644 index 0000000..7988ba5 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Login.cshtml @@ -0,0 +1,55 @@ +@page +@model LoginModel +@{ + ViewData["Title"] = "Log In"; +} + +
+
+

Log In

+ + @if (Model.ErrorMessage is not null) + { + + } + + @* asp-page-handler is omitted — Razor Pages routes POST to OnPostAsync by default. + The form tag helper automatically injects the anti-forgery hidden field. *@ +
+ + +
+ + + +
+ +
+ + + +
+ +
+ + +
+ + +
+ + +
+
diff --git a/Server/src/SOR.Website/Pages/Auth/Login.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/Login.cshtml.cs new file mode 100644 index 0000000..5c510a5 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Login.cshtml.cs @@ -0,0 +1,111 @@ +namespace SOR.Website.Pages.Auth; + +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.RateLimiting; +using SOR.Database.Entities.Identity; + +/// +/// Handles player login via email + password. +/// +/// Security controls: +/// - [EnableRateLimiting]: 10 attempts per IP per 5 minutes. +/// - lockoutOnFailure: true in PasswordSignInAsync — Identity locks the account +/// after 5 failures, defeating unlimited brute-force. +/// - ReturnUrl validated with Url.IsLocalUrl before redirect — no open redirect. +/// - Anti-forgery token validated by Razor Pages on every POST (default behavior). +/// - Generic error message: does NOT confirm whether the email exists (no enumeration). +/// - SignInWithClaimsAsync adds the display_name custom claim so the nav bar can +/// show the player's handle without a DB round-trip per request. +/// +[EnableRateLimiting("auth-login")] +public sealed class LoginModel( + SignInManager signInManager, + UserManager userManager) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + // returnUrl is injected by ASP.NET Core's cookie auth middleware when it + // redirects an unauthenticated request to the login page. + [BindProperty(SupportsGet = true)] + public string? ReturnUrl { get; set; } + + public string? ErrorMessage { get; private set; } + + public sealed class InputModel + { + [Required(ErrorMessage = "Email is required.")] + [EmailAddress(ErrorMessage = "Enter a valid email address.")] + [MaxLength(254)] + public string Email { get; set; } = string.Empty; + + [Required(ErrorMessage = "Password is required.")] + [DataType(DataType.Password)] + [MaxLength(128)] + public string Password { get; set; } = string.Empty; + + public bool RememberMe { get; set; } + } + + public IActionResult OnGet() + { + // Already signed in — send them where they were going. + if (User.Identity?.IsAuthenticated == true) + return SafeRedirect(ReturnUrl); + + return Page(); + } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + // PasswordSignInAsync with lockoutOnFailure:true — after 5 failures the + // account is locked for 30 minutes (configured in Program.cs). + var result = await signInManager.PasswordSignInAsync( + Input.Email, + Input.Password, + Input.RememberMe, + lockoutOnFailure: true); + + if (result.Succeeded) + { + // Add the display_name claim to the cookie so the layout can show + // the player's handle without a DB hit on every request. + var user = await userManager.FindByEmailAsync(Input.Email); + if (user is not null) + { + var extraClaims = new[] + { + new Claim("display_name", user.DisplayName ?? user.Email ?? string.Empty), + }; + await signInManager.SignInWithClaimsAsync(user, Input.RememberMe, extraClaims); + } + + return SafeRedirect(ReturnUrl); + } + + if (result.IsLockedOut) + { + // Generic message — does not reveal whether the email exists. + ErrorMessage = "Too many failed attempts. Please try again later."; + return Page(); + } + + // Generic: do not confirm whether the email is registered (prevents enumeration). + ErrorMessage = "Invalid email or password."; + return Page(); + } + + // Ensures the redirect target is local to this application. + // Url.IsLocalUrl rejects absolute URLs and protocol-relative URLs, + // preventing open redirect attacks where an attacker crafts a link like + // /auth/login?returnUrl=https://evil.com + private IActionResult SafeRedirect(string? url) + => Url.IsLocalUrl(url) ? LocalRedirect(url) : RedirectToPage("/Index"); +} diff --git a/Server/src/SOR.Website/Pages/Auth/Logout.cshtml b/Server/src/SOR.Website/Pages/Auth/Logout.cshtml new file mode 100644 index 0000000..3aa975a --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Logout.cshtml @@ -0,0 +1,18 @@ +@page +@model LogoutModel +@{ + ViewData["Title"] = "Sign Out"; +} + +
+
+

Sign Out

+

Are you sure you want to sign out?

+ + @* POST-only sign-out prevents CSRF-based forced logout via crafted GET links. *@ +
+ + Cancel +
+
+
diff --git a/Server/src/SOR.Website/Pages/Auth/Logout.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/Logout.cshtml.cs new file mode 100644 index 0000000..47981b5 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Logout.cshtml.cs @@ -0,0 +1,33 @@ +namespace SOR.Website.Pages.Auth; + +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +/// +/// Handles sign-out. +/// +/// Security controls: +/// - Only responds to POST requests. A GET to /auth/logout shows a confirmation +/// page rather than signing out immediately. This prevents CSRF-based forced +/// logout via a crafted link (e.g., <img src="/auth/logout"> on an external site). +/// - Anti-forgery token is validated on POST (Razor Pages default). +/// - After sign-out, redirects to the home page — no returnUrl accepted here to +/// prevent the sign-out endpoint from being used as an open redirector. +/// +public sealed class LogoutModel(SignInManager signInManager) : PageModel +{ + // GET: show a confirmation button. + // The confirmation step is a minor UX protection; the real protection is POST-only sign-out. + public void OnGet() { } + + public async Task OnPostAsync() + { + await signInManager.SignOutAsync(); + // Always redirect to home — do not accept a returnUrl parameter here, + // as sign-out is a natural session termination point and accepting redirects + // would allow the endpoint to be used as an open redirector. + return RedirectToPage("/Index"); + } +} diff --git a/Server/src/SOR.Website/Pages/Auth/Register.cshtml b/Server/src/SOR.Website/Pages/Auth/Register.cshtml new file mode 100644 index 0000000..7480314 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Register.cshtml @@ -0,0 +1,71 @@ +@page +@model RegisterModel +@{ + ViewData["Title"] = "Create Account"; +} + +
+
+

Create Account

+

Begin your journey as a Channeler.

+ +
+
+ +
+ + + +
+ +
+ + + + 3–32 characters. Letters, digits, spaces, hyphens, underscores. +
+ +
+ + + + At least 8 characters, including an uppercase letter, digit, and symbol. +
+ +
+ + + +
+ +
+ + + +
+ + +
+ + +
+
diff --git a/Server/src/SOR.Website/Pages/Auth/Register.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/Register.cshtml.cs new file mode 100644 index 0000000..dc54bbb --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/Register.cshtml.cs @@ -0,0 +1,114 @@ +namespace SOR.Website.Pages.Auth; + +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.RateLimiting; +using SOR.Database.Entities.Identity; + +/// +/// Handles new player registration. +/// +/// Security controls: +/// - [EnableRateLimiting]: 5 registrations per IP per hour. +/// - Anti-forgery token validated on every POST. +/// - Generic error response: does NOT distinguish "email taken" from validation errors +/// so an attacker cannot probe whether an email is registered. +/// - DisplayName length and character restrictions prevent injection into downstream +/// systems that consume this value. +/// - Password strength is enforced by Identity (RequireDigit, RequireUppercase, etc.). +/// - CreatedAt set server-side — never from user input. +/// +[EnableRateLimiting("auth-register")] +public sealed class RegisterModel( + UserManager userManager, + SignInManager signInManager) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + public bool Success { get; private set; } + + public sealed class InputModel + { + [Required(ErrorMessage = "Email is required.")] + [EmailAddress(ErrorMessage = "Enter a valid email address.")] + [MaxLength(254)] + public string Email { get; set; } = string.Empty; + + [Required(ErrorMessage = "Display name is required.")] + [MinLength(3, ErrorMessage = "Display name must be at least 3 characters.")] + [MaxLength(32, ErrorMessage = "Display name cannot exceed 32 characters.")] + // Allow letters, digits, spaces, hyphens, underscores only. + // This prevents special characters that could cause issues in downstream display. + [RegularExpression(@"^[\w\- ]+$", + ErrorMessage = "Display name may only contain letters, digits, spaces, hyphens, and underscores.")] + public string DisplayName { get; set; } = string.Empty; + + [Required(ErrorMessage = "Password is required.")] + [MinLength(8, ErrorMessage = "Password must be at least 8 characters.")] + [MaxLength(128)] + [DataType(DataType.Password)] + public string Password { get; set; } = string.Empty; + + [Required(ErrorMessage = "Please confirm your password.")] + [DataType(DataType.Password)] + [Compare(nameof(Password), ErrorMessage = "Passwords do not match.")] + public string ConfirmPassword { get; set; } = string.Empty; + + [Range(typeof(bool), "true", "true", + ErrorMessage = "You must accept the terms and privacy policy.")] + public bool AcceptTerms { get; set; } + } + + public void OnGet() { } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + var account = new Account + { + UserName = Input.Email, // Identity uses UserName as the login key + Email = Input.Email, + DisplayName = Input.DisplayName.Trim(), + CreatedAt = DateTimeOffset.UtcNow, + RankScore = 1000, + }; + + var result = await userManager.CreateAsync(account, Input.Password); + + if (result.Succeeded) + { + // Sign in immediately with the display_name claim. + var claims = new[] { new Claim("display_name", account.DisplayName ?? string.Empty) }; + await signInManager.SignInWithClaimsAsync(account, isPersistent: false, claims); + return RedirectToPage("/Account/Index"); + } + + // Do NOT enumerate specific errors back to the user (e.g. "email already taken"). + // Instead surface a single generic message. Detailed validation errors (password + // strength, display name format) are acceptable — they don't expose account info. + // + // We do add Identity errors but filter out DuplicateEmail/DuplicateUserName to + // prevent account enumeration. + foreach (var error in result.Errors) + { + if (error.Code is "DuplicateEmail" or "DuplicateUserName") + { + // Generic message: attacker cannot learn whether the email is taken. + ModelState.AddModelError(string.Empty, + "Unable to create account. Please check your details and try again."); + } + else + { + ModelState.AddModelError(string.Empty, error.Description); + } + } + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml b/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml new file mode 100644 index 0000000..08cb467 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml @@ -0,0 +1,56 @@ +@page +@model ResetPasswordModel +@{ + ViewData["Title"] = "Reset Password"; +} + +
+
+

Reset Password

+ + @if (Model.InvalidLink) + { + + Request Reset Link + } + else if (Model.Success) + { +
+ Your password has been reset. You can now log in with your new password. +
+ Log In + } + else + { +
+ @* Token and email from the reset link are hidden — not displayed to user. *@ + + + +
+ +
+ + + +
+ +
+ + + +
+ + +
+ } +
+
diff --git a/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml.cs new file mode 100644 index 0000000..5d3f383 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/ResetPassword.cshtml.cs @@ -0,0 +1,97 @@ +namespace SOR.Website.Pages.Auth; + +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.RateLimiting; +using SOR.Database.Entities.Identity; + +/// +/// Validates the reset token and applies a new password. +/// +/// Security controls: +/// - [EnableRateLimiting]: 3 per IP per 15 minutes (shared with forgot-password policy). +/// - Anti-forgery token validated on POST. +/// - Token validated by Identity's built-in TOTP provider — single-use, time-limited. +/// - Generic error on invalid/expired token — no detail about why it failed. +/// - Email is supplied via query string from the reset link (not from user input). +/// It is bound server-side only for the lookup, not displayed back to the user +/// in a way that could introduce reflected content. +/// - Password must meet the same strength rules as registration (Identity enforces this). +/// +[EnableRateLimiting("auth-reset")] +public sealed class ResetPasswordModel(UserManager userManager) : PageModel +{ + [BindProperty] + public InputModel Input { get; set; } = new(); + + public bool Success { get; private set; } + public bool InvalidLink { get; private set; } + + public sealed class InputModel + { + // These two come from the query string in the emailed link. + // They are not displayed to the user — only used server-side. + [Required] + public string Token { get; set; } = string.Empty; + + [Required] + [EmailAddress] + [MaxLength(254)] + public string Email { get; set; } = string.Empty; + + [Required(ErrorMessage = "New password is required.")] + [MinLength(8, ErrorMessage = "Password must be at least 8 characters.")] + [MaxLength(128)] + [DataType(DataType.Password)] + public string NewPassword { get; set; } = string.Empty; + + [Required(ErrorMessage = "Please confirm your new password.")] + [DataType(DataType.Password)] + [Compare(nameof(NewPassword), ErrorMessage = "Passwords do not match.")] + public string ConfirmPassword { get; set; } = string.Empty; + } + + public IActionResult OnGet([FromQuery] string? token, [FromQuery] string? email) + { + if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(email)) + { + InvalidLink = true; + return Page(); + } + + Input.Token = token; + Input.Email = email; + return Page(); + } + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + return Page(); + + var user = await userManager.FindByEmailAsync(Input.Email); + + // If the user doesn't exist, still show success (anti-enumeration). + if (user is null || user.IsAi) + { + Success = true; + return Page(); + } + + var result = await userManager.ResetPasswordAsync(user, Input.Token, Input.NewPassword); + + if (result.Succeeded) + { + Success = true; + return Page(); + } + + // Generic message — does not reveal whether the token expired, was already used, + // or the email was wrong. All failure modes look the same to the requester. + ModelState.AddModelError(string.Empty, + "This reset link is invalid or has expired. Please request a new one."); + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml b/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml new file mode 100644 index 0000000..0a0b6d7 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml @@ -0,0 +1,34 @@ +@page +@model VerifyEmailModel +@{ + ViewData["Title"] = "Verify Email"; +} + +
+
+

Email Verification

+ + @if (Model.Success) + { +
+ Your email has been verified. Your account is fully active. +
+ Go to Account + } + else if (Model.AlreadyVerified) + { +
+ Your email is already verified. +
+ Go to Account + } + else + { + + Log In + } +
+
diff --git a/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml.cs b/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml.cs new file mode 100644 index 0000000..b3656df --- /dev/null +++ b/Server/src/SOR.Website/Pages/Auth/VerifyEmail.cshtml.cs @@ -0,0 +1,55 @@ +namespace SOR.Website.Pages.Auth; + +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using SOR.Database.Entities.Identity; + +/// +/// Confirms a player's email address via a one-time token link. +/// +/// Security controls: +/// - Token validated by Identity's built-in provider (single-use, time-limited). +/// - Generic error shown on failure — no detail about whether email or token was wrong. +/// - This page does not require authentication — players reach it by clicking a link +/// in their registration email before they're signed in. +/// +public sealed class VerifyEmailModel(UserManager userManager) : PageModel +{ + public bool Success { get; private set; } + public bool AlreadyVerified { get; private set; } + public bool Failed { get; private set; } + + public async Task OnGetAsync( + [FromQuery] string? userId, + [FromQuery] string? token) + { + if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(token)) + { + Failed = true; + return Page(); + } + + var user = await userManager.FindByIdAsync(userId); + if (user is null) + { + // Anti-enumeration: don't reveal that the userId is invalid. + Failed = true; + return Page(); + } + + if (user.EmailConfirmed) + { + AlreadyVerified = true; + return Page(); + } + + var result = await userManager.ConfirmEmailAsync(user, token); + if (result.Succeeded) + Success = true; + else + Failed = true; + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Cards/Details.cshtml b/Server/src/SOR.Website/Pages/Cards/Details.cshtml new file mode 100644 index 0000000..f23b1ad --- /dev/null +++ b/Server/src/SOR.Website/Pages/Cards/Details.cshtml @@ -0,0 +1,113 @@ +@page "{id:guid}" +@model DetailsModel +@{ + var card = Model.Card!; +} + + + +
+ +
+ @* Art loaded from CDN — URL auto-encoded by Razor *@ + @{ + var art = card.Assets.FirstOrDefault(a => a.AssetType == SOR.Database.Enums.CardAssetType.Art2D); + } + @if (art is not null) + { + Art for @card.Name + } + else + { +
+ } +
+ +
+

@card.Name

+ +
+ @card.CardType + @card.Affinity + @card.Rarity + @if (card.Set is not null) + { + @card.Set.Name + } +
+ + @if (card.SpCost > 0 || card.StCost > 0) + { +
+ @if (card.SpCost > 0) { @card.SpCost SP } + @if (card.StCost > 0) { @card.StCost ST } +
+ } + + @if (card.MaxHealth.HasValue || card.Damage.HasValue) + { +
+ @if (card.Damage.HasValue) {
ATK@card.Damage
} + @if (card.MaxHealth.HasValue) {
HP@card.MaxHealth
} + @if (card.MaxDefense.HasValue) {
DEF@card.MaxDefense
} + @if (card.MovementPoints.HasValue) {
MOV@card.MovementPoints
} +
+ } + +
+ @* card.Description is plain text from the database — Razor auto-encodes it *@ +

@card.Description

+
+ + @if (card.Genus is { Length: > 0 }) + { +
+ @foreach (var g in card.Genus) + { + @g + } +
+ } + + @if (card.PreviousTier is not null) + { +
+ Ascends from: + @card.PreviousTier.Name +
+ } + + +
+
+ +@if (Model.RelatedCards.Any()) +{ + +} diff --git a/Server/src/SOR.Website/Pages/Cards/Details.cshtml.cs b/Server/src/SOR.Website/Pages/Cards/Details.cshtml.cs new file mode 100644 index 0000000..8006612 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Cards/Details.cshtml.cs @@ -0,0 +1,58 @@ +namespace SOR.Website.Pages.Cards; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Catalog; +using SOR.Database.Enums; + +/// +/// Individual card detail page. +/// +/// Security controls: +/// - Card ID is a GUID — cannot be manipulated to traverse to other resources. +/// - Only published, non-retired cards are shown; unpublished cards return 404. +/// - All card data rendered through Razor's auto-encoding (no Html.Raw). +/// +public sealed class DetailsModel(CatalogDbContext catalog) : PageModel +{ + public CardDefinition? Card { get; private set; } + public IList RelatedCards { get; private set; } = []; + + public async Task OnGetAsync(Guid id) + { + Card = await catalog.CardDefinitions + .Include(c => c.Set) + .Include(c => c.Assets) + .Include(c => c.PreviousTier) + .Where(c => c.Id == id && c.IsPublished && !c.IsRetired && c.CardType != CardType.SpiritToken) + .AsNoTracking() + .FirstOrDefaultAsync(); + + if (Card is null) + return NotFound(); + + // Load related cards: same set, same type, different card + if (Card.SetId.HasValue) + { + RelatedCards = await catalog.CardDefinitions + .Where(c => c.SetId == Card.SetId + && c.CardType == Card.CardType + && c.Id != Card.Id + && c.IsPublished + && !c.IsRetired) + .OrderBy(c => c.Name) + .Take(6) + .AsNoTracking() + .ToListAsync(); + } + + ViewData["Title"] = Card.Name; + ViewData["MetaDescription"] = Card.Description.Length > 160 + ? Card.Description[..160] + : Card.Description; + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/Cards/Index.cshtml b/Server/src/SOR.Website/Pages/Cards/Index.cshtml new file mode 100644 index 0000000..97e9bd3 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Cards/Index.cshtml @@ -0,0 +1,145 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "Card Catalog"; + ViewData["MetaDescription"] = "Browse the complete Aeternalis card catalog. Filter by type, affinity, set, and rarity."; +} + + + +
+ + + +
+ @if (!Model.Cards.Any()) + { +
+

No cards match your filters.

+ Clear Filters +
+ } + else + { + + + @if (Model.TotalPages > 1) + { + + } + } +
+
diff --git a/Server/src/SOR.Website/Pages/Cards/Index.cshtml.cs b/Server/src/SOR.Website/Pages/Cards/Index.cshtml.cs new file mode 100644 index 0000000..0286436 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Cards/Index.cshtml.cs @@ -0,0 +1,106 @@ +namespace SOR.Website.Pages.Cards; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Catalog; +using SOR.Database.Enums; + +/// +/// Public card catalog. Displays published, non-retired cards with filtering and search. +/// +/// Security controls: +/// - Only published, non-retired, non-SpiritToken cards are returned (server-side filter). +/// - All query parameters are strongly typed and validated — no raw SQL injection surface. +/// - Search input is passed as an EF Core parameterized query (never string-concatenated). +/// - Pagination prevents resource exhaustion from loading the entire catalog at once. +/// +public sealed class IndexModel(CatalogDbContext catalog) : PageModel +{ + public const int PageSize = 32; + + public IReadOnlyList Cards { get; private set; } = []; + public int TotalCount { get; private set; } + public int CurrentPage { get; private set; } = 1; + public int TotalPages => (int)Math.Ceiling((double)TotalCount / PageSize); + + // Filter state (all bound from query string — never from POST body) + [BindProperty(SupportsGet = true)] + public string? Search { get; set; } + + [BindProperty(SupportsGet = true)] + public CardType? Type { get; set; } + + [BindProperty(SupportsGet = true)] + public Affinity? FilterAffinity { get; set; } + + [BindProperty(SupportsGet = true)] + public CardRarity? Rarity { get; set; } + + [BindProperty(SupportsGet = true)] + public int PageNumber { get; set; } = 1; + + [BindProperty(SupportsGet = true)] + public string? Sort { get; set; } + + public IList CardSets { get; private set; } = []; + + [BindProperty(SupportsGet = true)] + public Guid? SetId { get; set; } + + public async Task OnGetAsync() + { + // Clamp page to valid range + CurrentPage = Math.Max(1, PageNumber); + + CardSets = await catalog.CardSets + .OrderBy(s => s.Name) + .AsNoTracking() + .ToListAsync(); + + // Base query: published + non-retired + no SpiritToken (internal engine card type) + var query = catalog.CardDefinitions + .Include(c => c.Set) + .Where(c => c.IsPublished && !c.IsRetired && c.CardType != CardType.SpiritToken) + .AsNoTracking(); + + // Filters — all applied as parameterized predicates (no string formatting) + if (!string.IsNullOrWhiteSpace(Search)) + { + var term = Search.Trim().ToLower(); + query = query.Where(c => + EF.Functions.ILike(c.Name, $"%{term}%") || + EF.Functions.ILike(c.Description, $"%{term}%")); + } + + if (Type.HasValue) + query = query.Where(c => c.CardType == Type.Value); + + if (FilterAffinity.HasValue) + query = query.Where(c => c.Affinity == FilterAffinity.Value); + + if (Rarity.HasValue) + query = query.Where(c => c.Rarity == Rarity.Value); + + if (SetId.HasValue) + query = query.Where(c => c.SetId == SetId.Value); + + // Sorting + query = (Sort ?? "name") switch + { + "cost-asc" => query.OrderBy(c => c.SpCost).ThenBy(c => c.Name), + "cost-desc" => query.OrderByDescending(c => c.SpCost).ThenBy(c => c.Name), + "rarity" => query.OrderByDescending(c => c.Rarity).ThenBy(c => c.Name), + "newest" => query.OrderByDescending(c => c.CreatedAt), + _ => query.OrderBy(c => c.Name), + }; + + TotalCount = await query.CountAsync(); + + Cards = await query + .Skip((CurrentPage - 1) * PageSize) + .Take(PageSize) + .ToListAsync(); + } +} diff --git a/Server/src/SOR.Website/Pages/HowToPlay.cshtml b/Server/src/SOR.Website/Pages/HowToPlay.cshtml new file mode 100644 index 0000000..75232e2 --- /dev/null +++ b/Server/src/SOR.Website/Pages/HowToPlay.cshtml @@ -0,0 +1,170 @@ +@page +@model HowToPlayModel +@{ + ViewData["Title"] = "How To Play"; + ViewData["MetaDescription"] = "Learn the rules of Aeternalis. Channel Archspirits, shape the mindscape with Terramorpha, and survive the psychic assault."; +} + + + +
+ + + +
+ +
+

What is Aeternalis?

+

+ Aeternalis is a tactical strategy card game played in a constructed mindscape. + Two Channelers face off, each commanding Archspirits, Spirits, Terramorpha, and other cards + drawn from their deck. The battlefield is a grid of affinity tiles that both players shape + during play. +

+
+ +
+

What is a Channeler?

+

+ You are the Channeler — the player. You reach into the Origin Stone to summon Archspirits, + cast Instincts, lay Terramorpha, and shape the battlefield. Your Channeler does not have + its own card: you are the will behind every action. +

+
+ +
+

How to Win

+

+ Reduce your opponent's Channeler to zero life points. Life is lost when your opponent's + units deal unblocked damage to you directly. Build your board, control the terrain, and + press the assault. +

+
+ +
+

Card Types

+
+
ArchSpirit
+
Powerful multi-tier units that evolve through Ascension. The core of most strategies.
+ +
Spirit
+
Smaller units that can be sacrificed to fuel growth and resource mechanics.
+ +
Terramorpha
+
Land-shaping cards that change the affinity of tiles on the battlefield.
+ +
Instinct
+
Instant-speed effects that can be played during your opponent's turn.
+ +
Repentance
+
Slow powerful effects that require preparation and setup.
+ +
Ruin
+
Persistent enchantments that modify the rules of the game while in play.
+
+
+ +
+

Resources and Costs

+

+ Cards cost SP (Spirit Points) and ST (Soul Tokens) to play. + SP regenerates each turn. ST is earned through sacrifice and specific card effects. + Managing both resources is the central economic challenge of Aeternalis. +

+
+ +
+

Turn Structure

+
    +
  1. Draw — Draw one card from your deck.
  2. +
  3. Upkeep — Trigger start-of-turn effects. SP regenerates.
  4. +
  5. Main Phase — Play cards, move units, use abilities.
  6. +
  7. Combat Phase — Declare attackers. Opponent declares blockers.
  8. +
  9. End Phase — Discard down to hand limit. End-of-turn effects trigger.
  10. +
+
+ +
+

Combat and Targeting

+

+ Units attack in the direction they face. Melee units must be adjacent to their target. + Ranged units attack within their range, requiring line-of-sight unless otherwise stated. + Flight units can only be blocked by other Flight units. +

+
+ +
+

Terramorpha and Land Shaping

+

+ Terramorpha cards reshape the affinity tiles on the battlefield. Units require matching + affinity tiles to be channeled. Control the terrain to control what your opponent can summon. + Mono Terramorpha changes one tile; Di changes two adjacent tiles; Tri changes three. +

+
+ +
+

Sacrifice and Spirit Growth

+

+ Spirits can be sacrificed to generate Soul Tokens and power high-cost abilities. + Strategic sacrifice is a core resource loop — spending small units to fuel larger threats. +

+
+ +
+

Glossary

+
+
Channeler
+
The player. The will behind every card played.
+ +
Origin Stone
+
The cosmic vessel that stores memories of all that has been and may yet be.
+ +
Archspirit
+
A mighty being of ages past, temporarily revived through channeling.
+ +
Terramorpha
+
The art of shaping mindscape terrain through will and memory.
+ +
Mindscape
+
The constructed psychic battlefield where all matches take place.
+ +
Spirit
+
A lesser being summoned through channeling. Can be sacrificed for resources.
+ +
Ruin
+
A persistent card type that modifies game rules while in play.
+ +
Instinct
+
An instant-speed card playable at any time, including your opponent's turn.
+ +
Repentance
+
A slow, powerful card that takes time to resolve after being played.
+ +
Fifth Star
+
The impossible new star that appeared after the first encounter with the unknown entity. A symbol of hope.
+
+
+ + + +
+
diff --git a/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs b/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs new file mode 100644 index 0000000..bb2e681 --- /dev/null +++ b/Server/src/SOR.Website/Pages/HowToPlay.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class HowToPlayModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Index.cshtml b/Server/src/SOR.Website/Pages/Index.cshtml new file mode 100644 index 0000000..6f7dfca --- /dev/null +++ b/Server/src/SOR.Website/Pages/Index.cshtml @@ -0,0 +1,102 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = null; // Home page title is just "Aeternalis" + ViewData["MetaDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars. Aeternalis is a tactical strategy card game."; + ViewData["OgTitle"] = "Aeternalis"; + ViewData["OgDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars."; +} + +
+
+

Aeternalis

+

Channel the Archspirits. Shape the mindscape. Fill the void with stars.

+ +
+ +
+ + + +
+
+

How a Match Unfolds

+
    +
  1. + +
    + Channel an Archspirit +

    Reach into the Origin Stone and revive a mighty being of ages past.

    +
    +
  2. +
  3. + +
    + Shape terrain with Terramorpha +

    Construct mindscape worlds through thought and will. The land obeys.

    +
    +
  4. +
  5. + +
    + Sacrifice and empower Spirits +

    Every sacrifice fuels something greater. Growth through loss.

    +
    +
  6. +
  7. + +
    + Survive the psychic assault +

    An unknown corrosive entity attacks through the mindscape. Hold the line.

    +
    +
  8. +
  9. + +
    + Birth a new star +

    Victory creates a world. The sky fills with proof of your will.

    +
    +
  10. +
+ Learn the Rules +
+
+ +
+
+
+

Begin Channeling

+

Create your account and enter the mindscape.

+ +
+
+

Browse the Cards

+

Explore Archspirits, Spirits, Terramorpha, and more.

+ Open Card Catalog +
+
+
diff --git a/Server/src/SOR.Website/Pages/Index.cshtml.cs b/Server/src/SOR.Website/Pages/Index.cshtml.cs new file mode 100644 index 0000000..7fecf27 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Index.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class IndexModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Leaderboard.cshtml b/Server/src/SOR.Website/Pages/Leaderboard.cshtml new file mode 100644 index 0000000..0cb4ddb --- /dev/null +++ b/Server/src/SOR.Website/Pages/Leaderboard.cshtml @@ -0,0 +1,64 @@ +@page +@model LeaderboardModel +@{ + ViewData["Title"] = "Leaderboard"; + ViewData["MetaDescription"] = "Top Channelers ranked by score. Who has filled the most stars?"; +} + + + +
+ @if (!Model.Entries.Any()) + { +
+

No ranked games have been played yet. Be the first Channeler.

+ Play Now +
+ } + else + { + + + + + + + + + + @for (int i = 0; i < Model.Entries.Count; i++) + { + var entry = Model.Entries[i]; + var rank = i + 1; + var isSelf = Model.CurrentUserDisplayName is not null + && entry.DisplayName == Model.CurrentUserDisplayName; + + + + @* DisplayName auto-encoded by Razor *@ + + + + } + +
#ChannelerRank Score
+ @if (rank <= 3) + { + @* Rank icons use plain text fallbacks — no image dependency *@ + @rank + } + else + { + @rank + } + + @entry.DisplayName + @if (isSelf) { (you) } + @entry.RankScore
+ } +
diff --git a/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs b/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs new file mode 100644 index 0000000..7737bee --- /dev/null +++ b/Server/src/SOR.Website/Pages/Leaderboard.cshtml.cs @@ -0,0 +1,52 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Identity; + +/// +/// Public leaderboard showing top ranked players. +/// +/// Security controls: +/// - Only exposes: DisplayName, RankScore. Never: Email, AccountId, or internal fields. +/// - AI accounts and accounts hidden from leaderboard are excluded at query level. +/// - Pagination limits response size. +/// +public sealed class LeaderboardModel(SorIdentityDbContext identity) : PageModel +{ + public const int PageSize = 50; + + public IReadOnlyList Entries { get; private set; } = []; + public string? CurrentUserDisplayName { get; private set; } + + public async Task OnGetAsync() + { + // Only safe-to-display fields are projected — email and internal IDs are excluded. + Entries = await identity.Users + .Where(a => !a.IsAi && !a.IsHiddenFromLeaderboard) + .OrderByDescending(a => a.RankScore) + .Take(PageSize) + .Select(a => new LeaderboardEntry + { + DisplayName = a.DisplayName ?? "Channeler", + RankScore = a.RankScore, + }) + .AsNoTracking() + .ToListAsync(); + + // Current user's display name (to highlight their entry) + if (User.Identity?.IsAuthenticated == true) + CurrentUserDisplayName = User.FindFirst("display_name")?.Value; + } + + /// + /// Public-safe projection: only display name and rank score. + /// Email, AccountId, and moderation state are intentionally excluded. + /// + public sealed class LeaderboardEntry + { + public string DisplayName { get; init; } = string.Empty; + public int RankScore { get; init; } + } +} diff --git a/Server/src/SOR.Website/Pages/News/Index.cshtml b/Server/src/SOR.Website/Pages/News/Index.cshtml new file mode 100644 index 0000000..92e21ba --- /dev/null +++ b/Server/src/SOR.Website/Pages/News/Index.cshtml @@ -0,0 +1,19 @@ +@page +@model IndexModel +@{ + ViewData["Title"] = "News"; +} + + + +
+
+

News and patch notes are coming soon. Check back after launch.

+ Back to Home +
+
diff --git a/Server/src/SOR.Website/Pages/News/Index.cshtml.cs b/Server/src/SOR.Website/Pages/News/Index.cshtml.cs new file mode 100644 index 0000000..c206284 --- /dev/null +++ b/Server/src/SOR.Website/Pages/News/Index.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages.News; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class IndexModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Privacy.cshtml b/Server/src/SOR.Website/Pages/Privacy.cshtml new file mode 100644 index 0000000..5295fd2 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Privacy.cshtml @@ -0,0 +1,74 @@ +@page +@model PrivacyModel +@{ + ViewData["Title"] = "Privacy Policy"; +} + + + +
+ +
+

What We Collect

+
    +
  • Account data: email address, display name, and password hash.
  • +
  • Game data: match results, rank score, and card collection.
  • +
  • Technical data: IP address (for security and rate limiting), user agent string, and session metadata.
  • +
+
+ +
+

What We Do Not Collect

+
    +
  • We do not sell your data to third parties.
  • +
  • We do not collect payment information directly (payments processed by third-party providers).
  • +
  • We do not use tracking pixels or third-party advertising cookies.
  • +
+
+ +
+

How We Use Your Data

+
    +
  • To operate your account and game access.
  • +
  • To provide customer support.
  • +
  • To detect and prevent abuse, cheating, and unauthorized access.
  • +
  • To display your display name on the public leaderboard (opt-out available in account settings).
  • +
+
+ +
+

Data Retention

+

+ Account data is retained while your account is active. You may request account deletion + by contacting support. Game match records may be retained for statistical purposes in + anonymized form after deletion. +

+
+ +
+

Security

+

+ Passwords are hashed using industry-standard algorithms (bcrypt via ASP.NET Core Identity). + Session cookies are encrypted, HTTP-only, and marked Secure. Communication with this site + is encrypted via HTTPS. +

+
+ +
+

Contact

+

+ For privacy questions or data deletion requests, contact us via the + support page. +

+
+ +

+ This is a placeholder privacy policy. A complete policy will be provided before public launch. +

+ +
diff --git a/Server/src/SOR.Website/Pages/Privacy.cshtml.cs b/Server/src/SOR.Website/Pages/Privacy.cshtml.cs new file mode 100644 index 0000000..905946a --- /dev/null +++ b/Server/src/SOR.Website/Pages/Privacy.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class PrivacyModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml b/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml new file mode 100644 index 0000000..df47920 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Shared/_Layout.cshtml @@ -0,0 +1,92 @@ + + + + + + @(ViewData["Title"] != null ? ViewData["Title"] + " — " : "")Aeternalis + + @if (ViewData["MetaDescription"] != null) + { + + } + @if (ViewData["OgTitle"] != null) + { + + + @if (ViewData["OgImage"] != null) + { + + } + @if (ViewData["OgDescription"] != null) + { + + } + } + + @* No inline styles — required for strict style-src 'self' CSP. All styles in site.css. *@ + + + + + + +
+ @RenderBody() +
+ + + +@* No inline scripts — required for strict script-src 'self' CSP. *@ + +@await RenderSectionAsync("Scripts", required: false) + + diff --git a/Server/src/SOR.Website/Pages/Story.cshtml b/Server/src/SOR.Website/Pages/Story.cshtml new file mode 100644 index 0000000..eedbb04 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Story.cshtml @@ -0,0 +1,121 @@ +@page +@model StoryModel +@{ + ViewData["Title"] = "Story"; + ViewData["MetaDescription"] = "The story of Origin: Stone of Revival. Channel Archspirits. Shape the mindscape. Fill the void with stars."; +} + +
+
+

Origin: Stone of Revival

+

The story of the Channelers and the impossible fifth star.

+
+
+ +
+
+ +
+

That We Know

+ +
+

The Four Stars

+

+ From time immemorial, the sky held only four stars: the life-giving Sun and three + distant sister planets, fixed in an endless dark. Humanity believed it was alone. + The void beyond was assumed to be desolate, empty, and permanent. +

+
+ +
+

The Origin Stone

+

+ The Origin Stone is a cosmic vessel whose surface protects the memories of what + has been, what is, and what may yet be. It remembers what reality has forgotten. + To touch it is to reach into living memory itself. +

+
+ +
+

Channelers

+

+ Channelers are those who have learned to reach into the Origin Stone — to recover + knowledge from the past and strengthen the present. Great Channelers can commune + directly with the Stone, accessing the memories of entire worlds. +

+
+ +
+

Archspirits

+

+ Through the Origin Stone, Channelers connect with Archspirits: mighty beings of + ages past whose memories, worlds, experiences, and powers can be temporarily + revived. To channel an Archspirit is to revive a world for one decisive moment. +

+
+ +
+

Terramorpha

+

+ Channelers use Terramorpha to shape constructed mindscape worlds — bringing lands, + paths, and battlefields into being through thought and will. The terrain obeys. + Every tile of the mindscape is an act of intention. +

+
+
+ +
+

That We Do Not

+ +
+

The Unknown Entity

+

+ During one communion, the player encounters an unknown corrosive entity deep within + the Origin Stone. It attacks through psychic space with strange spirits, impossible + powers, and violence from lands never seen. It should not exist. +

+
+ +
+

Survival

+

+ The Channeler forms defensive worlds, summons Archspirits, sacrifices spirits to fuel + growth, and reshapes terrain mid-conflict. Victory forces the entity back. But the + mindscape is changed. +

+
+ +
+

The Fifth Star

+

+ The trance breaks. The night sky now holds a fifth star — a new planet that should + not exist, yet does. Other Channelers begin encountering the same menace. Every fight + in the mindscape, even a loss, creates another star in the night sky. +

+
+
+ +
+

Your Role

+ +
+

+ What began as survival becomes hope. The endless void can be undone. The sky can be + filled with worlds. The lost experiences beyond the Origin Stone can be restored. +

+
+ Every battle in the mindscape leaves a light in the sky. +
+

+ You are a Channeler. Channel the Archspirits. Shape the mindscape. Fight the menace. + Restore worlds to the sky. Turn every battle into a testament of will. +

+
+ Begin Channeling + Learn the Rules +
+
+
+ +
+
diff --git a/Server/src/SOR.Website/Pages/Story.cshtml.cs b/Server/src/SOR.Website/Pages/Story.cshtml.cs new file mode 100644 index 0000000..fc4f38d --- /dev/null +++ b/Server/src/SOR.Website/Pages/Story.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class StoryModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Support.cshtml b/Server/src/SOR.Website/Pages/Support.cshtml new file mode 100644 index 0000000..70776cd --- /dev/null +++ b/Server/src/SOR.Website/Pages/Support.cshtml @@ -0,0 +1,49 @@ +@page +@model SupportModel +@{ + ViewData["Title"] = "Support"; +} + + + +
+ +
+

Account Help

+
    +
  • Forgot your password? Reset it here.
  • +
  • Need to verify your email? Log in and check your account page.
  • +
  • Want to delete your account? Contact us at the address below.
  • +
+
+ +
+

Bug Reports

+

+ Found a bug? Please describe what happened, what you expected, and the steps to reproduce it. + Include your platform and any relevant error messages. +

+
+ +
+

Contact

+

+ Full support contact details will be listed here before public launch. + For now, reach out via community channels. +

+
+ +
+

AI Asset Reports

+

+ Noticed an asset that appears AI-generated but is not in our disclosure? + Review our AI asset policy and contact support. +

+
+ +
diff --git a/Server/src/SOR.Website/Pages/Support.cshtml.cs b/Server/src/SOR.Website/Pages/Support.cshtml.cs new file mode 100644 index 0000000..070d2de --- /dev/null +++ b/Server/src/SOR.Website/Pages/Support.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class SupportModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Terms.cshtml b/Server/src/SOR.Website/Pages/Terms.cshtml new file mode 100644 index 0000000..c80318c --- /dev/null +++ b/Server/src/SOR.Website/Pages/Terms.cshtml @@ -0,0 +1,75 @@ +@page +@model TermsModel +@{ + ViewData["Title"] = "Terms of Service"; +} + + + +
+ +
+

Acceptance

+

+ By creating an account or using Aeternalis, you agree to these Terms of Service. + If you do not agree, do not use the service. +

+
+ +
+

Accounts

+
    +
  • One account per person. Sharing accounts is not permitted.
  • +
  • You are responsible for maintaining the security of your credentials.
  • +
  • You must be at least 13 years old to create an account.
  • +
  • Accurate registration information is required.
  • +
+
+ +
+

Conduct

+
    +
  • No cheating, exploiting, or using unauthorized third-party software.
  • +
  • No harassment, hate speech, or abusive behaviour toward other players.
  • +
  • No activity that disrupts the service or other players' experience.
  • +
+
+ +
+

Intellectual Property

+

+ All game content, art, and systems are the property of Aeternalis Games. + Your account data is yours; game content remains ours. +

+
+ +
+

Termination

+

+ We reserve the right to suspend or terminate accounts that violate these terms, + with or without prior notice. +

+
+ +
+

Changes

+

+ We may update these terms. Continued use after changes constitutes acceptance. +

+
+ +
+

Contact

+

Questions about these terms? Visit the support page.

+
+ +

+ This is a placeholder terms document. Complete legal terms will be provided before public launch. +

+ +
diff --git a/Server/src/SOR.Website/Pages/Terms.cshtml.cs b/Server/src/SOR.Website/Pages/Terms.cshtml.cs new file mode 100644 index 0000000..8716e9e --- /dev/null +++ b/Server/src/SOR.Website/Pages/Terms.cshtml.cs @@ -0,0 +1,8 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc.RazorPages; + +public sealed class TermsModel : PageModel +{ + public void OnGet() { } +} diff --git a/Server/src/SOR.Website/Pages/Webclient.cshtml b/Server/src/SOR.Website/Pages/Webclient.cshtml new file mode 100644 index 0000000..0913728 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Webclient.cshtml @@ -0,0 +1,21 @@ +@page +@model WebclientModel +@{ + ViewData["Title"] = "Play"; +} + +
+
+

Enter the Mindscape

+

Sign in to your Channeler account to begin.

+ + + + +
+
diff --git a/Server/src/SOR.Website/Pages/Webclient.cshtml.cs b/Server/src/SOR.Website/Pages/Webclient.cshtml.cs new file mode 100644 index 0000000..852fc83 --- /dev/null +++ b/Server/src/SOR.Website/Pages/Webclient.cshtml.cs @@ -0,0 +1,30 @@ +namespace SOR.Website.Pages; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +/// +/// Canonical route for launching the game client. +/// +/// Security controls: +/// - Authenticated users are redirected directly (return URL preserved via cookie auth). +/// - Unauthenticated users see a login gate — not an automatic redirect to the webclient +/// URL, which prevents the webclient from being embedded without a session. +/// - No dynamic content injected from query string into the page (no XSS surface). +/// +public sealed class WebclientModel : PageModel +{ + // The actual webclient URL is configured separately and may live on a subdomain. + // For Phase 1 this is a placeholder. Replace with the real client URL when deployed. + public const string ClientUrl = "/webclient/app"; + + public bool IsAuthenticated => User.Identity?.IsAuthenticated == true; + + public IActionResult OnGet() + { + if (IsAuthenticated) + return Redirect(ClientUrl); + + return Page(); + } +} diff --git a/Server/src/SOR.Website/Pages/_ViewImports.cshtml b/Server/src/SOR.Website/Pages/_ViewImports.cshtml new file mode 100644 index 0000000..74ae92e --- /dev/null +++ b/Server/src/SOR.Website/Pages/_ViewImports.cshtml @@ -0,0 +1,5 @@ +@namespace SOR.Website.Pages +@using System.Security.Claims +@using SOR.Database.Entities.Identity +@using SOR.Database.Enums +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/Server/src/SOR.Website/Pages/_ViewStart.cshtml b/Server/src/SOR.Website/Pages/_ViewStart.cshtml new file mode 100644 index 0000000..820a2f6 --- /dev/null +++ b/Server/src/SOR.Website/Pages/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = "_Layout"; +} diff --git a/Server/src/SOR.Website/Program.cs b/Server/src/SOR.Website/Program.cs new file mode 100644 index 0000000..e889e87 --- /dev/null +++ b/Server/src/SOR.Website/Program.cs @@ -0,0 +1,267 @@ +// 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(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); + +// ── ASP.NET Core Identity ───────────────────────────────────────────────────── +// Registers UserManager, SignInManager, 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>(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() + .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(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( + "

An error occurred.

"); + })); + + // 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(); + +// 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(); diff --git a/Server/src/SOR.Website/SOR.Website.csproj b/Server/src/SOR.Website/SOR.Website.csproj new file mode 100644 index 0000000..5b08dcf --- /dev/null +++ b/Server/src/SOR.Website/SOR.Website.csproj @@ -0,0 +1,36 @@ + + + SOR.Website + Exe + + SOR.Website + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + diff --git a/Server/src/SOR.Website/SecurityHeadersMiddleware.cs b/Server/src/SOR.Website/SecurityHeadersMiddleware.cs new file mode 100644 index 0000000..b968797 --- /dev/null +++ b/Server/src/SOR.Website/SecurityHeadersMiddleware.cs @@ -0,0 +1,104 @@ +namespace SOR.Website; + +/// +/// Adds a strict suite of HTTP security response headers to every response. +/// +/// XSS prevention: +/// Content-Security-Policy: restricts which resources (scripts, styles, images, +/// frames) the browser may load. 'script-src self' means zero inline scripts are +/// executed — any injected <script> tag or javascript: URL is dead on arrival. +/// 'style-src self' blocks injected inline styles. 'object-src none' kills plug-in +/// vectors (Flash etc.). 'base-uri self' prevents <base> tag hijacking. +/// 'form-action self' prevents forms from being redirected to attacker-controlled +/// URLs even if an attacker injects a form into the page. +/// +/// Clickjacking prevention: +/// X-Frame-Options and frame-ancestors 'none' together ensure no page on this +/// site can be embedded in an iframe on another origin, defeating UI redress attacks. +/// +/// MIME confusion prevention: +/// X-Content-Type-Options: nosniff stops browsers from executing a response as a +/// different MIME type than declared (e.g., serving a .png that is actually JS). +/// +/// Information leakage prevention: +/// Referrer-Policy limits what URL is sent to third parties in the Referer header. +/// The header is added on every response so the browser always uses the strictest rule. +/// +public sealed class SecurityHeadersMiddleware(RequestDelegate next) +{ + public Task InvokeAsync(HttpContext context) + { + var h = context.Response.Headers; + + // ── Clickjacking ───────────────────────────────────────────────────────── + // Legacy header: understood by all browsers including old IE. + h["X-Frame-Options"] = "DENY"; + + // ── MIME confusion ─────────────────────────────────────────────────────── + h["X-Content-Type-Options"] = "nosniff"; + + // ── Referrer leakage ───────────────────────────────────────────────────── + // Sends origin only when navigating same-origin, full URL on same-site, + // and origin-only (no path) when crossing to a different origin over HTTPS. + h["Referrer-Policy"] = "strict-origin-when-cross-origin"; + + // ── Browser feature permissions ────────────────────────────────────────── + // Explicitly deny any feature the site does not need. + // Payment API denial is particularly important to prevent skimming attacks. + h["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()"; + + // ── Content Security Policy ────────────────────────────────────────────── + // + // default-src 'self' + // All resource types not listed below inherit this: same-origin only. + // + // script-src 'self' + // Scripts may only be loaded from this origin. No 'unsafe-inline' means + // zero inline