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
+13
View File
@@ -29,6 +29,7 @@ namespace JobTrackerApi.Data
public DbSet<CvExtractionRun> CvExtractionRuns => Set<CvExtractionRun>();
public DbSet<TailoredCvDraft> TailoredCvDrafts => Set<TailoredCvDraft>();
public DbSet<TwoFactorRecoveryCode> TwoFactorRecoveryCodes => Set<TwoFactorRecoveryCode>();
public DbSet<TrustedDevice> TrustedDevices => Set<TrustedDevice>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -151,6 +152,18 @@ namespace JobTrackerApi.Data
modelBuilder.Entity<TwoFactorRecoveryCode>()
.HasIndex(x => new { x.UserId, x.UsedAtUtc });
// No FK to AspNetUsers: the login-time trusted-device check reads these rows before a
// session (and thus CurrentUserId) exists, via IgnoreQueryFilters() -- same convention
// as TwoFactorRecoveryCode above.
modelBuilder.Entity<TrustedDevice>()
.HasQueryFilter(x => CurrentUserId != null && x.UserId == CurrentUserId);
modelBuilder.Entity<TrustedDevice>()
.HasIndex(x => x.UserId);
modelBuilder.Entity<TrustedDevice>()
.HasIndex(x => x.TokenHash);
}
}
}