feat(website): Keycloak SSO auth, leaderboard tabs, HowToPlay CMS, webclient redirect

- SOR.Website now uses Keycloak OIDC (same realm as webclient) for SSO;
  clicking Play no longer re-prompts for login
- /webclient redirects directly to webclient.aeternalisgames.com (no auth gate)
- Leaderboard: 4 ranked tabs — Rank Score, Games Played, Games Won, Win Rate
  (Win Rate requires min 10 games; active column highlighted)
- HowToPlay page reads body HTML from catalog.website_contents (key=howtoplay);
  falls back to built-in static content when no DB entry exists
- Admin: HowToPlayEditor at /website/how-to-play with live HTML preview + clear
- Admin NavMenu: How To Play link added under Website section
- WebsiteContent entity + EF migration (catalog schema)
- appsettings.json: added Keycloak config skeleton (values from k8s secrets)
- Index page: branding corrected to "Origin: Stone of Revival" / Aeternalis Games;
  hero image sourced from CDN

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>
This commit is contained in:
dingo
2026-04-25 16:58:07 -04:00
co-authored by Claude Happy
parent f58a976745
commit 88695149d2
18 changed files with 1228 additions and 275 deletions
@@ -205,6 +205,11 @@
<i class="bi bi-newspaper me-2"></i>News Posts
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/website/how-to-play">
<i class="bi bi-book me-2"></i>How To Play
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
@@ -0,0 +1,145 @@
@page "/website/how-to-play"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Entities.Catalog
@inject CatalogDbContext Catalog
@attribute [Authorize]
<PageTitle>How To Play — SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">How To Play</h1>
<a href="https://aeternalisgames.com/how-to-play" target="_blank" class="btn btn-outline-secondary btn-sm">
<i class="bi bi-box-arrow-up-right me-1"></i>View live page
</a>
</div>
@if (!string.IsNullOrEmpty(_saveMessage))
{
<div class="alert alert-success alert-dismissible">
@_saveMessage
<button type="button" class="btn-close" @onclick="() => _saveMessage = null"></button>
</div>
}
@if (!string.IsNullOrEmpty(_errorMessage))
{
<div class="alert alert-danger alert-dismissible">
@_errorMessage
<button type="button" class="btn-close" @onclick="() => _errorMessage = null"></button>
</div>
}
<div class="card mb-3">
<div class="card-header d-flex justify-content-between align-items-center">
<span class="fw-semibold">Page Content (HTML)</span>
<div class="btn-group btn-group-sm" role="group">
<button type="button"
class="btn @(_showPreview ? "btn-outline-secondary" : "btn-secondary")"
@onclick="() => _showPreview = false">Edit</button>
<button type="button"
class="btn @(_showPreview ? "btn-secondary" : "btn-outline-secondary")"
@onclick="() => _showPreview = true">Preview</button>
</div>
</div>
<div class="card-body">
@if (_showPreview)
{
<div class="border rounded p-3 bg-white howto-preview" style="min-height:300px">
@((MarkupString)_bodyHtml)
</div>
}
else
{
<textarea class="form-control font-monospace"
rows="30"
placeholder="Enter full page HTML…"
@bind="_bodyHtml"></textarea>
<div class="form-text">
Full HTML for the <code>/how-to-play</code> page body.
Leave empty to fall back to the built-in static content.
</div>
}
</div>
</div>
<div class="d-flex gap-2">
<button class="btn btn-primary" @onclick="SaveAsync" disabled="@_saving">
@if (_saving)
{
<span class="spinner-border spinner-border-sm me-1"></span>
}
Save
</button>
@if (!string.IsNullOrWhiteSpace(_bodyHtml))
{
<button class="btn btn-outline-danger" @onclick="ClearAsync" disabled="@_saving">
Clear (revert to static)
</button>
}
</div>
@code {
private string _bodyHtml = string.Empty;
private bool _showPreview = false;
private bool _saving = false;
private string? _saveMessage;
private string? _errorMessage;
private WebsiteContent? _entry;
protected override async Task OnInitializedAsync()
{
_entry = await Catalog.WebsiteContents
.FirstOrDefaultAsync(w => w.Key == "howtoplay");
_bodyHtml = _entry?.BodyHtml ?? string.Empty;
}
private async Task SaveAsync()
{
_saving = true;
_saveMessage = null;
_errorMessage = null;
try
{
if (_entry is null)
{
_entry = new WebsiteContent
{
Key = "howtoplay",
Label = "How To Play",
BodyHtml = _bodyHtml,
UpdatedAt = DateTimeOffset.UtcNow,
};
Catalog.WebsiteContents.Add(_entry);
}
else
{
_entry.BodyHtml = _bodyHtml;
_entry.UpdatedAt = DateTimeOffset.UtcNow;
Catalog.WebsiteContents.Update(_entry);
}
await Catalog.SaveChangesAsync();
_saveMessage = "Saved successfully.";
}
catch (Exception ex)
{
_errorMessage = $"Save failed: {ex.Message}";
}
finally
{
_saving = false;
}
}
private async Task ClearAsync()
{
if (_entry is not null)
{
Catalog.WebsiteContents.Remove(_entry);
await Catalog.SaveChangesAsync();
_entry = null;
_bodyHtml = string.Empty;
_saveMessage = "Content cleared — page will show built-in static content.";
}
}
}
@@ -22,6 +22,7 @@ public sealed class CatalogDbContext : DbContext
: base(options) { }
public DbSet<NewsPost> NewsPosts => Set<NewsPost>();
public DbSet<WebsiteContent> WebsiteContents => Set<WebsiteContent>();
public DbSet<CardSet> CardSets => Set<CardSet>();
public DbSet<CardDefinition> CardDefinitions => Set<CardDefinition>();
public DbSet<CardAsset> CardAssets => Set<CardAsset>();
@@ -0,0 +1,23 @@
namespace SOR.Database.Entities.Catalog;
/// <summary>
/// A named block of HTML content for the public website, editable via the admin portal.
/// Used for pages like How To Play where the content is fully managed by staff.
///
/// Key examples: "howtoplay"
/// </summary>
public sealed class WebsiteContent
{
public Guid Id { get; set; } = Guid.NewGuid();
/// <summary>Stable lookup key, e.g. "howtoplay". Must be unique and lowercase.</summary>
public string Key { get; set; } = string.Empty;
/// <summary>Optional human-friendly label for the admin UI.</summary>
public string Label { get; set; } = string.Empty;
/// <summary>Full page body as HTML. Rendered directly — admin is trusted.</summary>
public string BodyHtml { get; set; } = string.Empty;
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}
@@ -0,0 +1,681 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Catalog
{
[DbContext(typeof(CatalogDbContext))]
[Migration("20260425201722_AddWebsiteContent")]
partial class AddWebsiteContent
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("catalog")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAnimationBinding", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("AnimationCdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<string>("AnimationTrackName")
.HasColumnType("text");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CastSoundCdnUrl")
.HasColumnType("text");
b.Property<string>("ImpactSoundCdnUrl")
.HasColumnType("text");
b.Property<bool>("IsAiGenerated")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("CardDefinitionId", "ActionName")
.IsUnique();
b.ToTable("card_animation_bindings", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAsset", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssetType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentETag")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsAiGenerated")
.HasColumnType("boolean");
b.Property<string>("MimeType")
.HasColumnType("text");
b.Property<string>("ModelFacingDirection")
.HasColumnType("text");
b.Property<string>("ModelTintMaskUrl")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CardDefinitionId", "AssetType");
b.ToTable("card_assets", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AbilitiesJson")
.HasColumnType("jsonb")
.HasColumnName("abilities");
b.Property<string>("Affinity")
.IsRequired()
.HasColumnType("text");
b.Property<string>("AttackSoundUrl")
.HasColumnType("text");
b.Property<string>("AttackType")
.HasColumnType("text");
b.Property<string>("BlockedSoundUrl")
.HasColumnType("text");
b.Property<bool?>("CanAttack")
.HasColumnType("boolean");
b.Property<bool?>("CanBeAttacked")
.HasColumnType("boolean");
b.Property<bool?>("CanBeBlocked")
.HasColumnType("boolean");
b.Property<bool?>("CanBeObstructed")
.HasColumnType("boolean");
b.Property<bool?>("CanBeSacrificed")
.HasColumnType("boolean");
b.Property<bool?>("CanDefend")
.HasColumnType("boolean");
b.Property<bool?>("CanMove")
.HasColumnType("boolean");
b.Property<bool?>("CanUseAbility")
.HasColumnType("boolean");
b.Property<string>("CardType")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("CollectorNumber")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("Damage")
.HasColumnType("integer");
b.Property<string>("DamagedSoundUrl")
.HasColumnType("text");
b.Property<string>("DeathSoundUrl")
.HasColumnType("text");
b.Property<long>("DefinitionVersion")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasDefaultValue(0L);
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string[]>("Genus")
.HasColumnType("text[]");
b.Property<bool>("IsPublished")
.HasColumnType("boolean");
b.Property<bool>("IsRetired")
.HasColumnType("boolean");
b.Property<int?>("MaxAttackRange")
.HasColumnType("integer");
b.Property<int?>("MaxChannelRange")
.HasColumnType("integer");
b.Property<int?>("MaxDefense")
.HasColumnType("integer");
b.Property<int?>("MaxHealth")
.HasColumnType("integer");
b.Property<int?>("MinAttackRange")
.HasColumnType("integer");
b.Property<int?>("MinChannelRange")
.HasColumnType("integer");
b.Property<float?>("ModelScale")
.HasColumnType("real");
b.Property<string>("ModelTintColor")
.HasColumnType("text");
b.Property<string>("MoveSoundUrl")
.HasColumnType("text");
b.Property<int?>("MovementPoints")
.HasColumnType("integer");
b.Property<string>("MovementType")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("OtherCostsJson")
.HasColumnType("jsonb")
.HasColumnName("other_costs");
b.Property<Guid?>("PreviousTierId")
.HasColumnType("uuid");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.Property<bool?>("RequiresLos")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("RetiredAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("SetId")
.HasColumnType("uuid");
b.Property<int>("SpCost")
.HasColumnType("integer");
b.Property<int>("StCost")
.HasColumnType("integer");
b.Property<string>("TerramorphaMode")
.HasColumnType("text");
b.Property<int?>("Tier")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Affinity");
b.HasIndex("CardType");
b.HasIndex("DefinitionVersion");
b.HasIndex("Name");
b.HasIndex("PreviousTierId");
b.HasIndex("Rarity");
b.HasIndex("SetId");
b.HasIndex("IsPublished", "SetId");
b.ToTable("card_definitions", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateOnly?>("ReleaseDate")
.HasColumnType("date");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.ToTable("card_sets", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CdnUploadRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ContentType")
.HasColumnType("text");
b.Property<bool>("IsAiGenerated")
.HasColumnType("boolean");
b.Property<string>("ObjectKey")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Prefix")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PublicUrl")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UploadedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("IsAiGenerated");
b.HasIndex("ObjectKey")
.IsUnique();
b.HasIndex("Prefix");
b.ToTable("cdn_upload_records", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.GameAudioConfig", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Context")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("TrackCdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TrackName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Context");
b.HasIndex("IsActive");
b.ToTable("game_audio_configs", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.HighlightConfig", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CdnPath")
.IsRequired()
.HasColumnType("text");
b.Property<string>("FallbackHex")
.IsRequired()
.HasColumnType("text");
b.Property<float>("Fps")
.HasColumnType("real");
b.Property<int>("FrameCount")
.HasColumnType("integer");
b.Property<string>("HighlightType")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAnimated")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("HighlightType")
.IsUnique();
b.ToTable("highlight_configs", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.NewsPost", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AuthorName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("BodyHtml")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("HeroImageUrl")
.HasColumnType("text");
b.Property<bool>("IsPublished")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("PublishedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Slug")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Summary")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Slug")
.IsUnique();
b.HasIndex("IsPublished", "PublishedAt");
b.ToTable("news_posts", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.SkyboxDefinition", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CdnPath")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("CubeNxUrl")
.HasColumnType("text")
.HasColumnName("cube_nx_url");
b.Property<string>("CubeNyUrl")
.HasColumnType("text")
.HasColumnName("cube_ny_url");
b.Property<string>("CubeNzUrl")
.HasColumnType("text")
.HasColumnName("cube_nz_url");
b.Property<string>("CubePxUrl")
.HasColumnType("text")
.HasColumnName("cube_px_url");
b.Property<string>("CubePyUrl")
.HasColumnType("text")
.HasColumnName("cube_py_url");
b.Property<string>("CubePzUrl")
.HasColumnType("text")
.HasColumnName("cube_pz_url");
b.Property<float>("Fps")
.HasColumnType("real");
b.Property<int>("FrameCount")
.HasColumnType("integer");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<bool>("IsAnimated")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SkyboxType")
.HasColumnType("text")
.HasColumnName("skybox_type");
b.HasKey("Id");
b.HasIndex("IsActive");
b.ToTable("skybox_definitions", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.TileBottomModel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CdnKey")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("PublicUrl")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Shape")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Shape", "IsActive");
b.ToTable("tile_bottom_models", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.TileModelBinding", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Affinity")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ModelCdnKey")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ModelPublicUrl")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Shape")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TexturePublicUrl")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Affinity", "Shape")
.IsUnique();
b.ToTable("tile_model_bindings", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.WebsiteContent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("BodyHtml")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Label")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("WebsiteContents", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAnimationBinding", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "CardDefinition")
.WithMany("AnimationBindings")
.HasForeignKey("CardDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CardDefinition");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAsset", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "CardDefinition")
.WithMany("Assets")
.HasForeignKey("CardDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CardDefinition");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "PreviousTier")
.WithMany()
.HasForeignKey("PreviousTierId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SOR.Database.Entities.Catalog.CardSet", "Set")
.WithMany("Cards")
.HasForeignKey("SetId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("PreviousTier");
b.Navigation("Set");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardDefinition", b =>
{
b.Navigation("AnimationBindings");
b.Navigation("Assets");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardSet", b =>
{
b.Navigation("Cards");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,39 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Catalog
{
/// <inheritdoc />
public partial class AddWebsiteContent : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "WebsiteContents",
schema: "catalog",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Key = table.Column<string>(type: "text", nullable: false),
Label = table.Column<string>(type: "text", nullable: false),
BodyHtml = table.Column<string>(type: "text", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_WebsiteContents", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "WebsiteContents",
schema: "catalog");
}
}
}
@@ -596,6 +596,32 @@ namespace SOR.Database.Migrations.Catalog
b.ToTable("tile_model_bindings", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.WebsiteContent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("BodyHtml")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Label")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("WebsiteContents", "catalog");
});
modelBuilder.Entity("SOR.Database.Entities.Catalog.CardAnimationBinding", b =>
{
b.HasOne("SOR.Database.Entities.Catalog.CardDefinition", "CardDefinition")
@@ -1,33 +1,28 @@
namespace SOR.Website.Pages.Auth;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SOR.Database.Entities.Identity;
/// <summary>
/// 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., &lt;img src="/auth/logout"&gt; 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.
/// Signs the player out of both the local website cookie and the Keycloak SSO session.
/// Keycloak sign-out ensures they are also prompted to authenticate on the webclient next visit.
/// </summary>
public sealed class LogoutModel(SignInManager<Account> signInManager) : PageModel
public sealed class LogoutModel : 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<IActionResult> 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.
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// Sign out of Keycloak SSO — redirects to Keycloak's end_session_endpoint,
// which then redirects back to "/" on this site.
await HttpContext.SignOutAsync("Keycloak",
new AuthenticationProperties { RedirectUri = "/" });
// SignOutAsync("Keycloak") issues the redirect itself; returning Page() here
// is a fallback for environments where Keycloak is not configured.
return RedirectToPage("/Index");
}
}
@@ -29,6 +29,13 @@
<div class="howto-content">
@if (Model.CustomBodyHtml is not null)
{
@Html.Raw(Model.CustomBodyHtml)
}
else
{
<section id="what-is-aeternalis" class="howto-section">
<h2>What is Aeternalis?</h2>
<p>
@@ -166,5 +173,6 @@
<a href="/cards" class="btn btn-ghost">Browse Cards</a>
</div>
}
</div>
</div>
@@ -1,8 +1,24 @@
namespace SOR.Website.Pages;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
public sealed class HowToPlayModel : PageModel
public sealed class HowToPlayModel(CatalogDbContext catalog) : PageModel
{
public void OnGet() { }
/// <summary>
/// HTML body from the database. Null means no entry yet — the view falls
/// back to the static content embedded in HowToPlay.cshtml.
/// </summary>
public string? CustomBodyHtml { get; private set; }
public async Task OnGetAsync()
{
var entry = await catalog.WebsiteContents
.AsNoTracking()
.FirstOrDefaultAsync(w => w.Key == "howtoplay");
if (!string.IsNullOrWhiteSpace(entry?.BodyHtml))
CustomBodyHtml = entry.BodyHtml;
}
}
+3 -3
View File
@@ -2,8 +2,8 @@
@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["MetaDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars. Origin: Stone of Revival is a tactical strategy card game by Aeternalis Games.";
ViewData["OgTitle"] = "Origin: Stone of Revival";
ViewData["OgDescription"] = "Channel the Archspirits. Shape the mindscape. Fill the void with stars.";
}
@@ -18,7 +18,7 @@
loading="eager">
}
<div class="hero-content">
<h1 class="hero-title">Aeternalis</h1>
<h1 class="hero-title">Origin: Stone of Revival</h1>
<p class="hero-tagline">Channel the Archspirits. Shape the mindscape. Fill the void with stars.</p>
<div class="hero-actions">
<a href="/webclient" class="btn btn-primary btn-lg">Play Now</a>
+33 -16
View File
@@ -2,7 +2,10 @@
@model LeaderboardModel
@{
ViewData["Title"] = "Leaderboard";
ViewData["MetaDescription"] = "Top Channelers ranked by score. Who has filled the most stars?";
ViewData["MetaDescription"] = "Top Channelers in Origin: Stone of Revival — ranked by score, games played, wins, and win rate.";
string Tab(string name) => Model.ActiveTab == name ? "lb-tab lb-tab-active" : "lb-tab";
string Col(string tab) => Model.ActiveTab == tab ? "stat-cell stat-cell-active" : "stat-cell";
}
<div class="page-header">
@@ -13,10 +16,27 @@
</div>
<div class="container">
<nav class="lb-tabs" aria-label="Leaderboard categories">
<a href="?by=rank" class="@Tab("rank")">Rank Score</a>
<a href="?by=played" class="@Tab("played")">Games Played</a>
<a href="?by=won" class="@Tab("won")">Games Won</a>
<a href="?by=rate" class="@Tab("rate")">Win Rate <span class="lb-tab-note">(min 10 games)</span></a>
</nav>
@if (!Model.Entries.Any())
{
<div class="empty-state">
<p>No ranked games have been played yet. Be the first Channeler.</p>
<p>
@if (Model.ActiveTab == "rate")
{
<text>No players have completed 10 or more ranked games yet.</text>
}
else
{
<text>No ranked games have been played yet. Be the first Channeler.</text>
}
</p>
<a href="/webclient" class="btn btn-primary">Play Now</a>
</div>
}
@@ -27,17 +47,17 @@
<tr>
<th scope="col">#</th>
<th scope="col">Channeler</th>
<th scope="col">Rank Score</th>
<th scope="col">Games Played</th>
<th scope="col">Games Won</th>
<th scope="col">Win Rate</th>
<th scope="col" class="@Col("rank")">Rank Score</th>
<th scope="col" class="@Col("played")">Played</th>
<th scope="col" class="@Col("won")">Won</th>
<th scope="col" class="@Col("rate")">Win Rate</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Entries.Count; i++)
{
var entry = Model.Entries[i];
var rank = i + 1;
var entry = Model.Entries[i];
var rank = i + 1;
var isSelf = Model.CurrentUserDisplayName is not null
&& entry.DisplayName == Model.CurrentUserDisplayName;
@@ -47,19 +67,16 @@
{
<span class="rank-badge rank-badge-@rank" aria-label="Rank @rank">@rank</span>
}
else
{
@rank
}
else { @rank }
</td>
<td class="name-cell">
@entry.DisplayName
@if (isSelf) { <span class="self-tag" aria-label="You">(you)</span> }
</td>
<td class="score-cell">@entry.RankScore</td>
<td class="stat-cell">@entry.GamesPlayed</td>
<td class="stat-cell">@entry.GamesWon</td>
<td class="stat-cell">@entry.WinRateDisplay</td>
<td class="@Col("rank")">@entry.RankScore</td>
<td class="@Col("played")">@entry.GamesPlayed</td>
<td class="@Col("won")">@entry.GamesWon</td>
<td class="@Col("rate")">@entry.WinRateDisplay</td>
</tr>
}
</tbody>
@@ -5,46 +5,32 @@ using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Enums;
/// <summary>
/// Public leaderboard showing top ranked players with win/loss stats.
///
/// Security controls:
/// - Only exposes: DisplayName, RankScore, GamesPlayed, GamesWon.
/// Never: Email, AccountId, or internal fields.
/// - AI accounts and accounts hidden from leaderboard are excluded at query level.
/// - Pagination limits response size.
/// </summary>
public sealed class LeaderboardModel(
SorIdentityDbContext identity,
GameDbContext game) : PageModel
{
public const int PageSize = 50;
public string ActiveTab { get; private set; } = "rank";
public IReadOnlyList<LeaderboardEntry> Entries { get; private set; } = [];
public string? CurrentUserDisplayName { get; private set; }
public async Task OnGetAsync()
public async Task OnGetAsync(string? by)
{
// Step 1 — pull the top-ranked accounts (identity schema).
ActiveTab = by is "played" or "won" or "rate" ? by : "rank";
// Pull the top accounts from identity with all stats we might need.
var accounts = await identity.Users
.Where(a => !a.IsAi && !a.IsHiddenFromLeaderboard)
.OrderByDescending(a => a.RankScore)
.Take(PageSize)
.Select(a => new { a.Id, a.DisplayName, a.RankScore })
.AsNoTracking()
.ToListAsync();
if (accounts.Count == 0)
{
Entries = [];
return;
}
if (accounts.Count == 0) return;
var accountIds = accounts.Select(a => a.Id).ToHashSet();
// Step 2 — pull completed game sessions for those accounts (game schema).
// A session counts for a player if they appear in any seat.
// WinnerAccountId being in the set means they won that session.
var sessions = await game.GameSessions
.Where(s => s.Status == GameSessionStatus.Completed
&& (accountIds.Contains(s.PlayerOneAccountId)
@@ -58,7 +44,6 @@ public sealed class LeaderboardModel(
.AsNoTracking()
.ToListAsync();
// Step 3 — aggregate wins and plays per account in memory.
var plays = new Dictionary<Guid, int>();
var wins = new Dictionary<Guid, int>();
@@ -67,32 +52,33 @@ public sealed class LeaderboardModel(
foreach (var id in new[] { s.PlayerOneAccountId, s.PlayerTwoAccountId }
.Where(accountIds.Contains))
{
plays.TryGetValue(id, out var p);
plays[id] = p + 1;
if (s.WinnerAccountId == id)
{
wins.TryGetValue(id, out var w);
wins[id] = w + 1;
}
plays.TryGetValue(id, out var p); plays[id] = p + 1;
if (s.WinnerAccountId == id) { wins.TryGetValue(id, out var w); wins[id] = w + 1; }
}
}
Entries = accounts
.Select(a =>
var all = accounts.Select(a =>
{
var played = plays.GetValueOrDefault(a.Id);
var won = wins.GetValueOrDefault(a.Id);
return new LeaderboardEntry
{
var played = plays.GetValueOrDefault(a.Id);
var won = wins.GetValueOrDefault(a.Id);
return new LeaderboardEntry
{
DisplayName = a.DisplayName ?? "Channeler",
RankScore = a.RankScore,
GamesPlayed = played,
GamesWon = won,
WinRate = played > 0 ? (double)won / played : 0,
};
})
.ToList();
DisplayName = a.DisplayName ?? "Channeler",
RankScore = a.RankScore,
GamesPlayed = played,
GamesWon = won,
WinRate = played > 0 ? (double)won / played : 0,
};
});
Entries = ActiveTab switch
{
"played" => all.OrderByDescending(e => e.GamesPlayed).Take(PageSize).ToList(),
"won" => all.OrderByDescending(e => e.GamesWon).Take(PageSize).ToList(),
"rate" => all.Where(e => e.GamesPlayed >= 10)
.OrderByDescending(e => e.WinRate).Take(PageSize).ToList(),
_ => all.OrderByDescending(e => e.RankScore).Take(PageSize).ToList(),
};
if (User.Identity?.IsAuthenticated == true)
CurrentUserDisplayName = User.FindFirst("display_name")?.Value;
@@ -105,8 +91,6 @@ public sealed class LeaderboardModel(
public int GamesPlayed { get; init; }
public int GamesWon { get; init; }
public double WinRate { get; init; }
public string WinRateDisplay =>
GamesPlayed == 0 ? "—" : $"{WinRate:P0}";
public string WinRateDisplay => GamesPlayed == 0 ? "—" : $"{WinRate:P0}";
}
}
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@(ViewData["Title"] != null ? ViewData["Title"] + " — " : "")Aeternalis</title>
<title>@(ViewData["Title"] != null ? ViewData["Title"] + " — " : "")Origin: Stone of Revival</title>
@if (ViewData["MetaDescription"] != null)
{
@@ -30,8 +30,8 @@
<header class="site-header">
<nav class="site-nav" aria-label="Main navigation">
<a href="/" class="nav-brand" aria-label="Aeternalis home">
<span class="brand-name">Aeternalis</span>
<a href="/" class="nav-brand" aria-label="Origin: Stone of Revival home">
<span class="brand-name">Origin</span><span class="brand-sub">Stone of Revival</span>
</a>
<button class="nav-toggle" aria-expanded="false" aria-controls="nav-links" aria-label="Open navigation">
@@ -56,14 +56,14 @@
var displayName = User.FindFirstValue("display_name") ?? User.Identity.Name ?? "Account";
<a href="/account" class="nav-account-name" aria-label="Your account">@displayName</a>
@* Logout is a POST to prevent CSRF logout via GET request. *@
<form method="post" asp-page="/Auth/Logout" class="nav-logout-form">
<form method="post" action="/auth/logout" class="nav-logout-form">
<button type="submit" class="nav-btn-ghost">Sign Out</button>
</form>
}
else
{
<a href="/auth/login" class="nav-btn-ghost">Log In</a>
<a href="/auth/register" class="nav-btn-primary">Create Account</a>
<a href="/auth/challenge" class="nav-btn-ghost">Log In</a>
<a href="/auth/challenge" class="nav-btn-primary">Create Account</a>
}
</div>
</nav>
@@ -4,26 +4,14 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
/// <summary>
/// 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).
/// Passes the player directly to the game client.
/// Auth is handled by Keycloak at the webclient level — if the player is already
/// signed in on the website (same Keycloak realm), the webclient opens without
/// a second login prompt (SSO).
/// </summary>
public sealed class WebclientModel : PageModel
{
// Hosted on its own subdomain so the game client can be updated independently.
public const string ClientUrl = "https://webclient.aeternalisgames.com";
public bool IsAuthenticated => User.Identity?.IsAuthenticated == true;
public IActionResult OnGet()
{
if (IsAuthenticated)
return Redirect(ClientUrl);
return Page();
}
public IActionResult OnGet() => Redirect(ClientUrl);
}
+180 -165
View File
@@ -1,29 +1,36 @@
// SOR.Website — Public game website and player account portal
// SOR.Website — Public game website for Origin: Stone of Revival
//
// 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.
// Authentication is delegated entirely to Keycloak (same realm as the game client).
// This gives the player a single SSO session: logging in on the website means
// clicking "Play" opens the webclient without a second auth prompt.
//
// 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.
// Auth flow:
// 1. Unauthenticated request → cookie middleware redirects to /auth/challenge
// 2. /auth/challenge initiates Keycloak OIDC code flow
// 3. Keycloak callback → OnTicketReceived finds/creates local Account by email
// and adds display_name claim to the cookie
// 4. Local cookie session set — user is signed in on the website
// 5. User clicks Play → https://webclient.aeternalisgames.com
// Keycloak recognises the existing SSO session → no second login prompt
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using StackExchange.Redis;
using SOR.Database;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using SOR.Website;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
@@ -31,8 +38,13 @@ var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, cfg) =>
cfg.ReadFrom.Configuration(ctx.Configuration));
// ── Keycloak config (fail fast) ───────────────────────────────────────────────
var keycloakAuthority = builder.Configuration["Keycloak:Authority"]
?? throw new InvalidOperationException("Keycloak:Authority is required.");
var keycloakClientId = builder.Configuration["Keycloak:ClientId"]
?? throw new InvalidOperationException("Keycloak:ClientId is required.");
// ── 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;
@@ -40,81 +52,120 @@ 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 ────────────────────────────────────────────────────────
// ── 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 =>
// ── Identity (UserManager only — sign-in is Keycloak's job) ──────────────────
// AddIdentityCore gives us UserManager<Account> for profile lookups (display name,
// rank score, etc.) without registering SignInManager or Identity cookie auth.
builder.Services.AddIdentityCore<Account>(opts =>
{
// 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;
opts.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<SorIdentityDbContext>()
.AddDefaultTokenProviders();
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<SorIdentityDbContext>();
// ── 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
// ── Keycloak OIDC authentication ──────────────────────────────────────────────
builder.Services
.AddAuthentication(opts =>
{
opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = "Keycloak";
})
.AddCookie(opts =>
{
// Unauthenticated requests to /Account/* are redirected here.
// /auth/challenge immediately triggers the Keycloak OIDC flow.
opts.LoginPath = "/auth/challenge";
opts.Cookie.Name = "__Host-sor-web-session";
opts.Cookie.HttpOnly = true;
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opts.Cookie.SameSite = SameSiteMode.Lax; // Lax required: OIDC callback is a cross-site POST
opts.Cookie.Path = "/";
opts.SlidingExpiration = true;
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
})
.AddOpenIdConnect("Keycloak", opts =>
{
opts.Authority = keycloakAuthority;
opts.ClientId = keycloakClientId;
opts.ClientSecret = builder.Configuration["Keycloak:ClientSecret"];
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=...
// If the public Keycloak URL isn't reachable from inside the cluster (DNS /
// network policy), point MetadataAddress at the internal k8s service URL.
// Authority is still used for issuer validation in token claims.
var meta = builder.Configuration["Keycloak:MetadataAddress"];
if (!string.IsNullOrEmpty(meta))
{
opts.MetadataAddress = meta;
opts.RequireHttpsMetadata = false;
}
opts.SlidingExpiration = true;
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
opts.ResponseType = "code";
opts.SaveTokens = true;
opts.GetClaimsFromUserInfoEndpoint = false; // token already contains all we need
opts.MapInboundClaims = false;
// 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.
});
opts.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "preferred_username",
ValidateAudience = false,
};
opts.Events = new OpenIdConnectEvents
{
OnTicketReceived = async ctx =>
{
if (ctx.Principal?.Identity is not ClaimsIdentity identity) return;
// ── Extract identity from the Keycloak access token ──────────
var accessToken = ctx.Properties?.GetTokenValue("access_token");
string? email = identity.FindFirst("email")?.Value;
string? preferredUsername = identity.FindFirst("preferred_username")?.Value;
string? displayName = identity.FindFirst("name")?.Value
?? preferredUsername;
// ── Find or provision the local Account record ───────────────
// Account records are keyed by email (same email the player uses
// in Keycloak). If this is their first website login, a stub account
// is created so pages that query identity (leaderboard, profile) work.
if (!string.IsNullOrEmpty(email))
{
var userManager = ctx.HttpContext.RequestServices
.GetRequiredService<UserManager<Account>>();
var account = await userManager.FindByEmailAsync(email);
if (account is null)
{
account = new Account
{
UserName = email,
Email = email,
DisplayName = displayName?.Trim() ?? email,
CreatedAt = DateTimeOffset.UtcNow,
RankScore = 1000,
};
await userManager.CreateAsync(account);
}
// Use the stored DisplayName (player may have changed it in-game).
displayName = account.DisplayName ?? displayName ?? email;
}
// ── Add display_name claim so nav bar renders without a DB hit ──
if (!string.IsNullOrEmpty(displayName))
identity.AddClaim(new Claim("display_name", displayName));
},
};
});
// ── 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";
@@ -126,68 +177,14 @@ builder.Services.AddAntiforgery(opts =>
});
// ── 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.
// Pod runs plain HTTP behind TLS-terminating ingress. Without this the OIDC
// middleware builds the redirect_uri as "http://..." which Keycloak rejects.
builder.Services.Configure<ForwardedHeadersOptions>(opts =>
{
opts.ForwardedHeaders =
@@ -202,20 +199,12 @@ builder.Services.Configure<ForwardedHeadersOptions>(opts =>
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;
@@ -223,46 +212,72 @@ if (!app.Environment.IsDevelopment())
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();
// ── Auth endpoints ────────────────────────────────────────────────────────────
// Challenge: triggers the Keycloak OIDC flow. The cookie middleware redirects
// here automatically when a request is unauthenticated.
app.MapGet("/auth/challenge", async (HttpContext ctx,
[Microsoft.AspNetCore.Mvc.FromQuery] string? returnUrl) =>
{
await ctx.ChallengeAsync("Keycloak",
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
}).AllowAnonymous();
// Logout: signs out of the local cookie AND the Keycloak SSO session so the
// player must re-authenticate on both the website and the webclient.
app.MapPost("/auth/logout", async (HttpContext ctx) =>
{
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await ctx.SignOutAsync("Keycloak",
new AuthenticationProperties { RedirectUri = "/" });
}).AllowAnonymous();
// ── Endpoints ─────────────────────────────────────────────────────────────────
app.MapRazorPages();
// Health check: AllowAnonymous so Kubernetes probes work before any session exists.
app.MapHealthChecks("/health").AllowAnonymous();
// ── RUN ───────────────────────────────────────────────────────────────────────
// ── Eager OIDC discovery ──────────────────────────────────────────────────────
await CheckOidcDiscoveryAsync(app);
Log.Information("SOR.Website starting");
await app.RunAsync();
// ── Helpers ───────────────────────────────────────────────────────────────────
static async Task CheckOidcDiscoveryAsync(WebApplication app)
{
var opts = app.Services
.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<OpenIdConnectOptions>>()
.Get("Keycloak");
var url = opts.MetadataAddress ?? $"{opts.Authority}/.well-known/openid-configuration";
try
{
var config = await opts.ConfigurationManager!.GetConfigurationAsync(CancellationToken.None);
opts.ConfigurationManager = new FixedConfigurationManager(config);
app.Logger.LogInformation("Keycloak OIDC discovery OK: {AuthEndpoint}", config.AuthorizationEndpoint);
}
catch (Exception ex)
{
app.Logger.LogError(ex,
"Keycloak OIDC discovery FAILED from {Url}. " +
"Set Keycloak__MetadataAddress to the internal k8s service URL if the " +
"public auth domain is not reachable from the pod.", url);
}
}
sealed class FixedConfigurationManager(OpenIdConnectConfiguration config)
: IConfigurationManager<OpenIdConnectConfiguration>
{
public Task<OpenIdConnectConfiguration> GetConfigurationAsync(CancellationToken cancel)
=> Task.FromResult(config);
public void RequestRefresh() { }
}
+6 -1
View File
@@ -7,9 +7,14 @@
</PropertyGroup>
<ItemGroup>
<!-- ASP.NET Core Identity: UserManager, SignInManager, password hashing -->
<!-- ASP.NET Core Identity: UserManager for profile lookups (sign-in delegated to Keycloak) -->
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
<!-- Keycloak OIDC authentication -->
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" />
<!-- Data Protection keys stored in Redis so all pods share the same key ring.
Without this, cookies set by pod A cannot be decrypted by pod B. -->
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" />
+5
View File
@@ -17,5 +17,10 @@
"Cdn": {
"PublicBaseUrl": "https://cdn.aeternalisgames.com"
},
"Keycloak": {
"Authority": "",
"ClientId": "",
"MetadataAddress": ""
},
"AllowedHosts": "*"
}