- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/ SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate limit and lockout, role/permission metadata on every endpoint, audit log, first-run administrator bootstrap. - Sequences with keyset paging, ETags and settings_version conflicts; sync manifest; frames, proxies, thumbnails and exports streamed with Range. - Chunked resumable uploads with hash short-circuit, quota and disk checks, staging on the archive volume, SHA-256 verification and IArchiveIngest. - Job engine host, jobs API, render nodes with heartbeat timeout and reassignment, WebSocket events, LAN discovery beacon, upload cleanup. - Windows service host over advapi32 (--service, --install-service, --uninstall-service); fails fast without the archive module services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
106 lines
5.3 KiB
C#
106 lines
5.3 KiB
C#
using System.Globalization;
|
|
using Titano.Core.Model;
|
|
using Titano.Data;
|
|
using Titano.Protocol;
|
|
using Titano.Server.Configuration;
|
|
using Titano.Server.Security;
|
|
|
|
namespace Titano.Server.Api;
|
|
|
|
/// <summary><c>/api/v1/auth</c>: sign-in (token or admin cookie), sign-out, password change, current account.</summary>
|
|
public static class AuthEndpoints
|
|
{
|
|
public static void Map(RouteGroupBuilder api)
|
|
{
|
|
api.MapPost("/auth/login", LoginAsync).AllowAnonymousCaller();
|
|
api.MapPost("/auth/logout", LogoutAsync).AllowDuringPasswordChange();
|
|
api.MapPost("/auth/password", ChangePasswordAsync).AllowDuringPasswordChange();
|
|
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
|
|
}
|
|
|
|
private static async Task<IResult> LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
|
|
AuditLog audit, TimeProvider time)
|
|
{
|
|
var ct = context.RequestAborted;
|
|
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
|
|
var account = Accounts.Key(request.Username);
|
|
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
|
|
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
|
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
|
|
if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required");
|
|
|
|
var user = await db.Users.GetByUsernameAsync(account, ct);
|
|
bool valid;
|
|
if (user is null)
|
|
{
|
|
PasswordHasher.VerifyDummy(request.Password);
|
|
valid = false;
|
|
}
|
|
else
|
|
{
|
|
valid = PasswordHasher.Verify(request.Password, user.PasswordHash) && !user.Disabled;
|
|
}
|
|
if (!valid)
|
|
{
|
|
guard.RecordFailure(account);
|
|
await audit.WriteAsync(user?.Id, account, context, "login_failed", "user", user?.Id.ToString());
|
|
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
|
}
|
|
|
|
guard.RecordSuccess(account);
|
|
var signedIn = user! with { LastLogin = time.GetUtcNow() };
|
|
if (PasswordHasher.NeedsRehash(signedIn.PasswordHash))
|
|
{
|
|
signedIn = signedIn with { PasswordHash = PasswordHasher.Hash(request.Password) };
|
|
await db.Users.UpdateAsync(signedIn, ct);
|
|
}
|
|
else
|
|
{
|
|
await db.Users.RecordLoginAsync(signedIn.Id, signedIn.LastLogin.Value, ct);
|
|
}
|
|
var issued = await tokens.IssueAsync(signedIn, request.ClientName, ct);
|
|
await audit.WriteAsync(signedIn.Id, signedIn.Username, context, "login", "user", signedIn.Id.ToString(), issued.Stored.ClientName);
|
|
|
|
string? secret = issued.Secret;
|
|
if (request.Cookie)
|
|
{
|
|
// The admin panel never sees the token itself; it travels only in the HttpOnly cookie.
|
|
SessionCookies.Issue(context, issued);
|
|
secret = null;
|
|
}
|
|
return Results.Json(new LoginResponse(secret, Dto.User(signedIn), signedIn.MustChangePassword, issued.Stored.Expires), ProtocolJson.Default.LoginResponse);
|
|
}
|
|
|
|
private static async Task<IResult> LogoutAsync(HttpContext context, Caller caller, TitanoDatabase db)
|
|
{
|
|
await db.Tokens.RevokeAsync(caller.TokenHash, context.RequestAborted);
|
|
if (caller.Source == CredentialSource.Cookie) SessionCookies.Clear(context);
|
|
return Results.NoContent();
|
|
}
|
|
|
|
private static async Task<IResult> ChangePasswordAsync(HttpContext context, Caller caller, ChangePasswordRequest request, TitanoDatabase db,
|
|
AuditLog audit, ServerOptions options)
|
|
{
|
|
var ct = context.RequestAborted;
|
|
if (string.IsNullOrEmpty(request.CurrentPassword) || !PasswordHasher.Verify(request.CurrentPassword, caller.User.PasswordHash))
|
|
return ApiErrors.BadRequest(context, "wrong_password");
|
|
if (!PasswordHasher.IsAcceptable(request.NewPassword))
|
|
return ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength);
|
|
if (request.NewPassword == request.CurrentPassword) return ApiErrors.BadRequest(context, "same_password");
|
|
|
|
var updated = caller.User with { PasswordHash = PasswordHasher.Hash(request.NewPassword), MustChangePassword = false };
|
|
await db.Users.UpdateAsync(updated, ct);
|
|
await db.Tokens.RevokeAllExceptAsync(caller.Id, caller.TokenHash, ct);
|
|
await audit.WriteAsync(caller, context, "password_changed", "user", caller.Id.ToString());
|
|
if (caller.User.Role == UserRole.Admin) AdminBootstrap.ForgetInitialPassword(options);
|
|
return Results.NoContent();
|
|
}
|
|
|
|
private static IResult TooMany(HttpContext context, string code, TimeSpan wait)
|
|
{
|
|
var seconds = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds));
|
|
context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture);
|
|
return ApiErrors.Result(context, StatusCodes.Status429TooManyRequests, code, seconds.ToString(CultureInfo.InvariantCulture));
|
|
}
|
|
}
|