feat(auth): add trusted-device 30-day 2FA skip (backend)

Adds a "trust this device" option to the 2FA challenge: on success, mints a
random token (only its SHA-256 hash is stored), sets it as a new httpOnly,
Secure, SameSite=Strict cookie, and records a TrustedDevice row. AuthController
checks that cookie for the exact signing-in user before gating on 2FA -- a
mismatched user, expired, or revoked device falls through to the normal 2FA
prompt, never errors. TwoFactorController also exposes list/revoke/revoke-all
endpoints for managing trusted devices, scoped to the owning user.

Schema added via the existing raw-SQL reconciler (SQLite + MySQL dialects),
not EF migrations, matching this repo's established pattern.
This commit is contained in:
cesnimda
2026-07-13 01:02:35 +02:00
parent b85dc1ffb7
commit b914630657
10 changed files with 554 additions and 9 deletions
@@ -44,7 +44,8 @@ public sealed class TwoFactorController : ControllerBase
public sealed record VerifySetupResult(bool Enabled, IReadOnlyList<string> RecoveryCodes);
public sealed record StatusResult(bool Enabled, DateTimeOffset? EnabledAtUtc);
public sealed record RecoveryCodesResult(IReadOnlyList<string> RecoveryCodes);
public sealed record ChallengeRequest(string PendingToken, string Code);
public sealed record ChallengeRequest(string PendingToken, string Code, bool TrustDevice = false);
public sealed record TrustedDeviceDto(int Id, string? DeviceLabel, DateTimeOffset CreatedAtUtc, DateTimeOffset LastSeenAtUtc, DateTimeOffset ExpiresAtUtc, bool IsCurrentDevice);
[HttpPost("setup")]
[Authorize(AuthenticationSchemes = "local")]
@@ -202,9 +203,74 @@ public sealed class TwoFactorController : ControllerBase
_pending.Resolve(pendingToken, consume: true);
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, user, session.RememberMe, cancellationToken);
if (request.TrustDevice)
{
await TrustedDeviceService.IssueAsync(_db, Request, Response, user.Id, cancellationToken);
}
return Ok(new AuthController.AuthSessionResult(true, "local"));
}
[HttpGet("trusted-devices")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> ListTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
var devices = await _db.TrustedDevices
.Where(x => x.UserId == user.Id)
.OrderByDescending(x => x.LastSeenAtUtc)
.Select(x => new TrustedDeviceDto(x.Id, x.DeviceLabel, x.CreatedAtUtc, x.LastSeenAtUtc, x.ExpiresAtUtc, currentHash != null && x.TokenHash == currentHash))
.ToListAsync(cancellationToken);
return Ok(devices);
}
[HttpDelete("trusted-devices/{id:int}")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeTrustedDevice(int id, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var device = await _db.TrustedDevices.FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id, cancellationToken);
if (device is null) return NotFound();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
var isCurrentDevice = currentHash != null && string.Equals(device.TokenHash, currentHash, StringComparison.Ordinal);
_db.TrustedDevices.Remove(device);
await _db.SaveChangesAsync(cancellationToken);
if (isCurrentDevice)
{
TrustedDeviceService.ClearCookie(Request, Response);
}
return NoContent();
}
[HttpPost("trusted-devices/revoke-all")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeAllTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var devices = await _db.TrustedDevices.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);
if (devices.Count > 0)
{
_db.TrustedDevices.RemoveRange(devices);
await _db.SaveChangesAsync(cancellationToken);
}
TrustedDeviceService.ClearCookie(Request, Response);
return NoContent();
}
private static bool VerifyCode(string base32Secret, string? code)
{
code = (code ?? string.Empty).Trim();