Auth and sessions¶
Admin auth lives in server/Auth/ (hashing, sessions, guards), with its routes in server/Endpoints/Admin/ and the first-start owner in server/Hosting/OwnerSeeder.cs. This is the most security-sensitive
code in the project and the easiest to break by accident, so this page is
deliberately detailed. Everything below is about admin accounts, except the
player auth section at the end.
The shape of it¶
- Passwords are hashed with Argon2id; the encoded hash goes in
admin_users.pw_hash. - Login mints an opaque 32-byte random token. Only its SHA-256 is stored.
- The token goes to the browser as an
HttpOnlycookie, never in a response body. - A session dies at whichever comes first: 30 minutes idle or 12 hours absolute.
- Two roles,
OwnerandAdmin, enforced by a database check constraint as well as by code.
Password hashing¶
const int TimeCost = 2;
const int MemoryCostKib = 19456; // 19 MiB
const int Lanes = 1;
const int HashLength = 32;
public static string Hash(string password) => // Auth/PasswordHasher.cs
Argon2.Hash(password, TimeCost, MemoryCostKib, Lanes, Argon2Type.HybridAddressing, HashLength);
Those are OWASP's minimum recommended Argon2id parameters.
Argon2Type.HybridAddressing is Argon2id — the hybrid of Argon2i and Argon2d,
which is the variant you want for password storage.
Argon2.Hash returns an encoded string that already contains the salt and
the parameters, which is why there is no separate salt column and why
verification needs nothing but the stored string:
static bool VerifyPassword(string encodedHash, string password) =>
Argon2.Verify(encodedHash, password);
Raising the cost later is safe
Because the parameters live inside each hash, you can increase them for new passwords and old hashes keep verifying with their original settings.
The timing defence¶
If the username does not exist, login still runs a full verification — against that dummy hash:
var passwordOk = VerifyPassword(admin?.PwHash ?? DummyHash, request.Password);
if (admin is null || admin.DisabledAt is not null || !passwordOk)
return Results.Json(new { error = "invalid credentials" }, statusCode: 401);
Two properties fall out, and both are deliberate:
- Constant-ish timing. An unknown username costs the same ~tens of milliseconds as a wrong password, so response time does not reveal which usernames exist.
- One identical error. Wrong password, unknown username and disabled
account all return the same
401 {"error":"invalid credentials"}.
Do not 'improve' this with an early return
Returning as soon as the user lookup misses would reintroduce the timing leak, and splitting the error messages into "no such user" / "wrong password" would hand over a username oracle. The combined condition is the point.
Tokens and the cookie¶
32 bytes from a CSPRNG. The token carries no information — it is a lookup key, not a JWT. Nothing is encoded in it, so nothing can be forged out of it.
Only the hash is persisted:
public static byte[] Hash(string token) => // Auth/TokenHasher.cs
SHA256.HashData(Encoding.UTF8.GetBytes(token));
Why SHA-256 here, but Argon2id for passwords?
Different threat. Passwords are low-entropy and human-chosen, so they need a slow hash to make guessing expensive. A 32-byte random token has 256 bits of entropy — brute force is already impossible, so a fast hash is fine and desirable, since this runs on every authenticated request.
The cookie:
static CookieOptions SessionCookieOptions(HttpRequest request, DateTime expires) => new()
{
HttpOnly = true,
Secure = request.IsHttps,
SameSite = SameSiteMode.Strict,
Expires = expires,
Path = "/",
};
| Flag | Effect |
|---|---|
HttpOnly |
JavaScript cannot read it, so XSS cannot steal the session |
SameSite=Strict |
Never sent on cross-site requests — this is the CSRF defence |
Secure = request.IsHttps |
HTTPS-only in production; still works over plain HTTP locally and inside the SSH tunnel |
Expires |
Matches the session's absolute expiry |
Secure is conditional rather than always-on so local dev and the tunnel both
work. Inside the tunnel the hop is plain HTTP, which is fine — SSH already
encrypted it.
SameSite=Strict constrains the whole architecture
It is why the UI must be served from the same origin as the API. Put the UI
on a different host and the browser stops sending the cookie, so login
breaks with no error that points at the cause. This is the reason the
Dockerfile bakes the Vue build into wwwroot and the reason Vite proxies
/api in dev.
The two expiries¶
flowchart TD
login["Login<br/>issued_at = now"] --> set["expires_at = now + 12h<br/>idle_expires_at = now + 30m"]
set --> req{"Authenticated<br/>request?"}
req -->|"yes, and both expiries in the future"| push["idle_expires_at = min(now + 30m, expires_at)"]
push --> req
req -->|"past idle_expires_at"| dead["401 — forgotten tab died"]
req -->|"past expires_at"| dead2["401 — absolute lifetime reached"]
| Pushed forward? | Guards against | |
|---|---|---|
idle_expires_at (30 min) |
Yes, on every authenticated request | A forgotten tab staying logged in |
expires_at (12 h) |
Never | A stolen cookie being kept alive indefinitely |
The push is capped so idle can never outlive absolute:
var nextIdle = now.AddMinutes(IdleMinutes);
session.IdleExpiresAt = nextIdle < session.ExpiresAt ? nextIdle : session.ExpiresAt;
Never poll /api/admin/me on a timer
/me is an authenticated request, so it pushes the idle expiry forward like
any other. A 30-second keep-alive means the 30-minute idle timeout can
never fire, leaving only the 12-hour cap — you would have silently deleted
half the session policy.
Call /me on app load and on route changes. The frontend does exactly that,
with a comment saying why.
AdminSessionService.FindActiveSession¶
The method every authenticated request goes through. AdminSessionService is an injected service (it takes the Db and a TimeProvider, so tests can fake the clock):
public async Task<(AdminSession Session, AdminUser Admin)?> FindActiveSession(HttpContext http)
{
if (!http.Request.Cookies.TryGetValue(CookieName, out var token) || string.IsNullOrEmpty(token))
return null;
var tokenHash = TokenHasher.Hash(token);
var now = time.UtcNow();
var session = await db.AdminSessions.FirstOrDefaultAsync(s =>
s.TokenHash == tokenHash
&& s.RevokedAt == null
&& s.ExpiresAt > now
&& s.IdleExpiresAt > now);
if (session is null) return null;
var admin = await db.AdminUsers.FindAsync(session.AdminId);
if (admin is null || admin.DisabledAt is not null) return null;
var nextIdle = now.AddMinutes(IdleMinutes);
session.IdleExpiresAt = nextIdle < session.ExpiresAt ? nextIdle : session.ExpiresAt;
await db.SaveChangesAsync();
return (session, admin);
}
Four rejection reasons, all collapsing to the same null: no cookie, no
matching session, revoked or expired, or the admin is disabled.
That last check is what makes deactivation take effect. Setting
disabled_at alone is enough to lock someone out on their very next request —
revoking their sessions is defence in depth, not the mechanism.
It writes on every request
One UPDATE per authenticated call, to push the idle expiry. Fine at this
scale. If it ever matters, only push when the stored value is more than a
minute stale.
The two guards¶
.RequireAdmin() — owner or admin¶
A chainable endpoint filter, used like the framework's own extensions:
public static TBuilder RequireAdmin<TBuilder>(this TBuilder builder) where TBuilder : IEndpointConventionBuilder
{
builder.AddEndpointFilter(async (context, next) =>
{
var sessions = context.HttpContext.RequestServices.GetRequiredService<AdminSessionService>();
var found = await sessions.FindActiveSession(context.HttpContext);
if (found is null)
return Results.Json(new { error = "not logged in" }, statusCode: 401);
return await next(context);
});
return builder;
}
RequireOwner(http) — owner only¶
Called inside a handler, because it needs to distinguish 401 from 403:
It returns (AdminUser? Owner, IResult? Error) — 401 {"error":"not logged
in"} with no session, 403 {"error":"owner only"} for a non-owner admin.
| Guard | Lets through | Used by |
|---|---|---|
.RequireAdmin() |
Owner or admin | /api/players, /api/characters, /api/events |
sessions.RequireOwner(...) |
Owner only | all of /api/admin/admins |
Roles and the owner¶
Enforced in the database too, via ck_admin_users_role (role IN (0, 1)), so a
third role needs a migration — not just an enum edit. ToName() (an extension on AdminRole) maps them to
the strings "owner" and "admin" that the API emits.
Seeding¶
public async Task Seed() // Hosting/OwnerSeeder.cs, an injected service (Db, config, logger)
{
if (await db.AdminUsers.AnyAsync()) return;
// ... create username "admin" with Role = Owner
}
- Runs on every startup, but returns immediately unless
admin_usersis completely empty. - Password from
HAKUTAKU_ADMIN_PASSWORD, else generated and logged once as a warning. - There is exactly one owner, and the create endpoint cannot make another —
POST /api/admin/adminsalways setsRole = Admin.
Why the owner cannot be deactivated
DELETE /api/admin/admins/{id} returns 403 for the owner, whoever is
asking. That guard is load-bearing: the seeder only runs when there are
zero admins, and login rejects disabled accounts. Disable the sole
owner and there is no HTTP path back in — recovery would mean direct psql
access to the VM.
The endpoints¶
| Method | Path | Guard | Returns |
|---|---|---|---|
| POST | /api/admin/login |
None, rate-limited 5/min/IP | 204 + Set-Cookie |
| POST | /api/admin/logout |
Needs a session | 204, clears the cookie |
| GET | /api/admin/me |
Needs a session | 200 {username, email, role} |
| GET | /api/admin/admins |
Owner | 200 array, including deactivated |
| POST | /api/admin/admins |
Owner | 200 {id, username, role} |
| DELETE | /api/admin/admins/{id} |
Owner | 204 |
Full request/response detail in the API reference.
Behaviours worth knowing:
- Login returns
204with no body. Callingres.json()on it throws. - Logout returns
401when not logged in. Treat that as "already logged out", not an error — the frontend does. /meis how a client discovers whether it is signed in, since the cookie is unreadable from JS.- Usernames are matched case-insensitively and trimmed on login.
- Creating a duplicate username returns
409, caught from Postgres error23505on the unique index.
Deactivation¶
var now = DateTime.UtcNow;
target.DisabledAt = now;
await db.AdminSessions
.Where(s => s.AdminId == target.Id && s.RevokedAt == null)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.RevokedAt, now));
await db.SaveChangesAsync();
One-way. No restore endpoint, because nobody needed one.
It burns the username permanently
The unique index on lower(username) covers disabled rows, so that username
can never be used again. The admin UI says so in its confirmation prompt.
Things not to do¶
| Do not | Because |
|---|---|
Poll /me on a timer |
It defeats the idle timeout entirely |
| Try to read the cookie from JS | HttpOnly; call /me instead |
| Serve the UI from a different origin | SameSite=Strict stops sending the cookie |
| Add an early return when the username misses | Reintroduces the timing leak |
| Split the login error into distinct messages | Creates a username oracle |
| Return an entity directly from an admin endpoint | pw_hash would be serialised — project explicitly |
Publish the app's port on 0.0.0.0 |
Forwarded headers are trusted, so the rate limit becomes forgeable |
Known gaps¶
- No audit log.
admin_sessionsis login history, not an audit trail. ipis recorded, never checked. No session-pinning to an address.totp_secretis unused. The column exists; no code reads it.- Re-deactivating overwrites
disabled_at, losing the original time. - No
disabled_by. Who deactivated whom is not recorded. - No password change endpoint, and no minimum on login length (creation requires 8–256).
- Bearer equivalence. Anyone holding the cookie is the admin. There is no
second factor, which is what
totp_secretwas reserved for.
Server keys¶
A game server uses a server key, which is a third kind of credential next to
the admin cookie and the player token. It is sent in the X-Server-Key header and
opens the /api/server/* routes only.
- Made by the owner.
POST /api/admin/server-keys(owner only, the sameRequireOwnercheck asCreateAdmin) makes 32 random bytes, base64url. It is returned once. Only its SHA-256 is stored, inserver_keys.key_sha256, so a copy of the database can't be used as a server key, like session tokens. - Checked by a filter.
.RequireServerKey()(Auth/ServerKeyGuards.cs) addsRequireServerKeyFilter. It hashes the header and looks up a key with that hash that isn't revoked or expired. That is an indexed lookup by hash, which is fine for the same reason session lookups are: the key is 256 random bits, so there is nothing to guess and no timing to leak. - Refused by default. A missing, unknown, revoked or expired key gets
401 {error}, so with no keys in the table every server route is refused. So does one over 512 characters (Limits.ServerKeyMaxLength), which can't be a real 43-character key and isn't hashed. - Bookkeeping.
last_used_atis written at most once a minute per key. The lookup also readslast_used_at, so a key used under a minute ago costs one query and no write. Otherwise one conditionalUPDATErepeats the check, so two calls at once can't both write. The key's id is left on the request (HttpContext.Items["ServerKeyId"]) for handlers and logs. When a server call fails with a500, the exception handler (Hosting/ApiErrors.cs) logsServer key {id} made the request that failed, under theGameServercategory, right after the exception itself. - Kept apart from the admin routes. Admin routes read the cookie and nothing
else, so a server key never works on
/api/admin/*. In the same way, an admin cookie or a player token doesn't open/api/server/*. - Revoking sets
revoked_atand takes effect on the next call. It is one-way.
The filter sits on the whole /api/server group (Endpoints/GameServer/), so a
route added to that group is protected without anyone remembering to do it. Today
that group has ping and the player data routes (GET and POST
/api/server/players/{id}/data).
Player auth¶
The player routes are in server/Endpoints/PlayerAuth/, and their helpers in server/Services/. They reuse the shared helpers (PasswordHasher.Hash, PasswordHasher.Verify,
PasswordHasher.DummyHash, TokenHasher.Hash), so players get the same Argon2id
settings and the same hash-only token storage. The differences:
| Admin | Player | |
|---|---|---|
| Token transport | HttpOnly cookie |
Authorization: Bearer <token> header — the callers are game clients, not browsers |
| Lifetime | 30 min idle + 12 h absolute | one fixed 30 days, no idle timeout |
| Ways in | username + password | device token (login/device) while a guest, then email + password (login/email) |
| Rate limits | admin-login |
player-register, player-device-login, player-login, player-link and player-mail (verify, resend, forgot, reset), each its own allowance per IP: 5 a minute, except player-register (30) and player-device-login (60), which every copy of the game calls on launch, so a room behind one IP has to fit. display-name is limited per player instead: 5 tries an hour, counted in memory |
How a player gets in:
registermakes a new guest every time; nothing is looked up. The server mints a 32-byte device token, the guest's only credential, and returns it once. Only its SHA-256 (lowercase hex) is stored, as theplayer_identitiessubject. The request'shardwareIdis just recorded onPlayers.RegisteredHardwareId. It isn't secret, so nothing signs in with it. An optionaldisplayNameis stored too;display-name(needs the token) changes it later. A display name is never an identity either: it isn't unique.login/devicehashes the token and looks it up. An unknown token is a401, and never creates a player. That's the difference from the old find-or-createregister, which silently made a fresh, empty account whenever a client lost its ID.link/email(needs the token): adds an unverified email identity next to the device one and mails a code (see Email codes). The cheap existence checks run before the Argon2 hash, so the expensive work happens at most once per session. The database enforces one email per player and one player per email; the handler reads the violated constraint's name to tell the two409s apart. An unverified link only holds its address for 24 hours (LinkEmail.UnverifiedHold); after that the next player to link it replaces it, in one transaction. Otherwise a guest could link someone else's address, never verify it, and lock the real owner out for good. A verified link is never replaced.email/verifymarks the email verified and deletes the device token, in one transaction. The account is recoverable from then on, so a credential that never expires has no reason to stay on one phone. Waiting for verification rather than linking means a mistyped address can't strand a guest.login/emailwith email + password: the same rules as admin login. An unknown email still pays for a hash check againstDummyHash, and both failures give the identical401body.
So a verified player has no device token at all. Until refresh tokens exist, staying signed in between launches means the game keeps the 30-day session token, then asks for the password again when it expires.
Email codes¶
Verification and password reset share one mechanism (player_email_codes, with
a purpose of verify or reset):
- A code is 6 digits, lives 15 minutes, works once, and dies after
5 wrong guesses. A new code retires the older one, and a player can only be
mailed one per purpose per minute and 5 per purpose per 24 hours. The daily
count comes from the
player_email_codesrows themselves, since old codes are marked used and never deleted.forgotstays silent past either limit (so it can't give an account away), andresendsays which limit it hit. - Only a SHA-256 of the code (tied to the player and purpose) is stored.
- Six digits are weak on their own, so the guess cap does the real work.
RedeemCodecounts the attempt in the database before comparing, so parallel guesses can't get past the cap, and only one request can redeem a code. - Transactions. Redeeming a code and the write it unlocks (setting the
password and revoking sessions, or marking the email verified and dropping the
device token) run in one transaction (
RedeemCodeThen), so a failure can't burn the code or leave a half-finished change. A wrong guess commits instead of rolling back, because the attempt counter has to survive or the cap would stop working. Making a code takes a per-player lock, so parallel requests take turns and can't both pass the one-per-minute check. link/emailcreates the unverified email and mails a code. If the mail fails, the link is still saved and the response saysverificationSent: false.password/forgotanswers identically for every email, and a hit sends its mail in the background so it isn't measurably slower than a miss. Only verified emails get a code.password/resetredeems the code, sets the hash and revokes all of the player's sessions.- Login does not require a verified email. Verification only gates reset.
Mail goes through IEmailSender (server/SEmail/). With Smtp:Host set
(env SMTP_HOST, plus SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_FROM) it
sends over SMTP with TLS. With no host it uses LogEmailSender, which writes
the whole message, code included, to the app log. That is right for local dev
and wrong for anything real: anyone who can read the logs could take over an
account whose email they can request a reset for.
Known gaps, on purpose for now:
- Unverified emails are still claims. Someone can link an address that isn't
theirs and hold it before its owner does. Because
link/emailanswers the same for a taken email (so it can't be used to look up who has an account), the real owner just gets no code, plus a heads-up email. Nothing expires or reclaims these. verifyandresendstill behave differently after a link that hit a taken email: they say "no email is linked" where a real pending link says "invalid or expired code". So the lookup leak is closed onlink/emailitself but can still be inferred through those two routes.- Timing is only roughly equal. A taken email and a free one both pay for the password hash, but a real link also waits on the mail server. Locally (no smtp) the two are within noise; with a real mail server the free path is slower.
- A guest's device token never expires, and there's no way to revoke one short of verifying an email. A guest whose token leaks has no recourse until they link and verify one.
- Every register or login makes a new session, and nothing cleans up old or expired rows. There is no player logout and no way to revoke a single player token short of editing the database.
- Old codes pile up in
player_email_codestoo. - A player token only unlocks the email routes. Characters, events and the rest are admin-gated until the player API is designed.
- No way to change or remove a linked email, or change a password while signed in.