From a3401ceedf30c2eb6167f7ef6e4ae820883d2de2 Mon Sep 17 00:00:00 2001 From: Artemy <109195690+stalcker2288969@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:19:08 +0700 Subject: [PATCH] Add SRP password recovery and E2EE reset Add proof-based password registration, login, enrollment, and change flows, with rate limiting and encrypted recovery-key envelopes. Support explicit E2EE identity resets while preserving historical signer verification, and document and test the new recovery workflows. --- .../ConfigurationProgramExtensions.cs | 2 + .../Authentication/AuthController.cs | 105 +- Govor.API/Controllers/E2eeController.cs | 12 +- Govor.API/Program.cs | 10 +- .../Authentication/AuthService.cs | 19 +- .../Authentication/IAuthService.cs | 3 +- .../Authentication/PasswordAccountService.cs | 219 +++ .../Authentication/PasswordChallenges.cs | 35 + .../Authentication/PasswordProtocol.cs | 129 ++ .../E2ee/E2eeRecoveryProtocol.cs | 5 + Govor.Application/E2ee/E2eeService.cs | 38 +- Govor.Application/Govor.Application.csproj | 1 + .../AdminsStuff/UsersService.cs | 13 + .../Requests/RegistrationRequest.cs | 20 +- .../E2eeRecoveryVaultConfiguration.cs | 4 +- .../Configurations/UserConfiguration.cs | 6 +- Govor.Domain/GovorDbContext.cs | 9 + ...24105815_PasswordBasedRecovery.Designer.cs | 1472 ++++++++++++++++ .../20261024105815_PasswordBasedRecovery.cs | 131 ++ ...024114709_PreserveResetSigners.Designer.cs | 1479 +++++++++++++++++ .../20261024114709_PreserveResetSigners.cs | 40 + .../Migrations/GovorDbContextModelSnapshot.cs | 72 + .../Models/Users/Crypto/E2eeIdentityChange.cs | 12 + .../Models/Users/Crypto/E2eeRecoveryVault.cs | 4 + Govor.Domain/Models/Users/User.cs | 6 +- docs/e2ee.md | 35 +- docs/password-recovery.md | 147 ++ .../Api/PasswordAuthHttpTests.cs | 107 ++ .../Security/PasswordRecoveryTests.cs | 223 +++ 29 files changed, 4322 insertions(+), 36 deletions(-) create mode 100644 Govor.Application/Authentication/PasswordAccountService.cs create mode 100644 Govor.Application/Authentication/PasswordChallenges.cs create mode 100644 Govor.Application/Authentication/PasswordProtocol.cs create mode 100644 Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.Designer.cs create mode 100644 Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.cs create mode 100644 Govor.Domain/Migrations/20261024114709_PreserveResetSigners.Designer.cs create mode 100644 Govor.Domain/Migrations/20261024114709_PreserveResetSigners.cs create mode 100644 Govor.Domain/Models/Users/Crypto/E2eeIdentityChange.cs create mode 100644 docs/password-recovery.md create mode 100644 tests/Govor.Server.Tests/Api/PasswordAuthHttpTests.cs create mode 100644 tests/Govor.Server.Tests/Security/PasswordRecoveryTests.cs diff --git a/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs b/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs index c018f94..8b68d84 100644 --- a/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs +++ b/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs @@ -33,6 +33,8 @@ public static class ConfigurationProgramExtensions public static void AddServices(this IServiceCollection services) { services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/Govor.API/Controllers/Authentication/AuthController.cs b/Govor.API/Controllers/Authentication/AuthController.cs index efb6dd6..32029f5 100644 --- a/Govor.API/Controllers/Authentication/AuthController.cs +++ b/Govor.API/Controllers/Authentication/AuthController.cs @@ -6,11 +6,15 @@ using Govor.Contracts.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SmartRes; +using Govor.Application.Infrastructure.Extensions; +using Microsoft.AspNetCore.RateLimiting; +using System.Security.Cryptography; namespace Govor.API.Controllers.Authentication; [ApiController] -[AllowAnonymous] +[Authorize(Roles = "User,Admin")] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] [Route("api/[controller]")] public class AuthController : Controller { @@ -19,28 +23,46 @@ public class AuthController : Controller private IAccountService _accountService; private ILogger _logger; private readonly IChatNotificationService _notifier; + private readonly PasswordAccountService _passwords; + private readonly ICurrentUserService _current; + private readonly ICurrentUserSessionService _currentSession; public AuthController( IAccountService accountService, IInvitesService invitesService, IUserSessionOpener userSessionOpener, ILogger logger, - IChatNotificationService notifier) + IChatNotificationService notifier, + PasswordAccountService passwords = null, + ICurrentUserService current = null, + ICurrentUserSessionService currentSession = null) { _userSession = userSessionOpener; _accountService = accountService; _invitesService = invitesService; _logger = logger; _notifier = notifier; + _passwords = passwords; + _current = current; + _currentSession = currentSession; } - [HttpPost("register")] // api/auth/register + [AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("register")] // api/auth/register public async Task Register([FromBody] RegistrationRequest request) { _logger.LogInformation("Processing registration request for: {Name}", request.Name); + PasswordCredentials credentials = null; + if (request.SrpVerifier is not null) + { + credentials = new(1, request.SrpSalt, request.SrpIdentity, request.SrpVerifier); + try { PasswordProtocol.Validate(credentials); } + catch (CryptographicException) { return BadRequest("Invalid SRP credentials."); } + } var result = await _invitesService.ValidateAsync(request.InviteLink) - .BindAsync(invite => _accountService.RegistrationAsync(request.Name, request.Password, invite)) + .BindAsync(invite => credentials is null + ? _accountService.RegistrationAsync(request.Name, request.Password, invite) + : _accountService.RegistrationWithPasswordProofAsync(request.Name, credentials, invite)) .TapAsync(user => _logger.LogInformation("User {Username} ({Id}) registered successfully", user.Username, user.Id)) .BindAsync(async user => { @@ -62,7 +84,7 @@ public class AuthController : Controller return result.ToActionResult(); } - [HttpPost("login")] // api/auth/login + [AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("login")] // api/auth/login public async Task Login([FromBody] LoginRequest request) { _logger.LogInformation("Processing registration request for: {Name}", request.Name); @@ -83,4 +105,77 @@ public class AuthController : Controller return result.ToActionResult(); } + [AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("password/challenge")] + public Task Challenge(PasswordChallengeRequest request) => + Execute(async () => Ok(await _passwords.StartAsync(request))); + + [AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("password/login")] + public Task Login(PasswordProof proof) => Execute(async () => + { + return Ok(await _passwords.LoginAsync(proof, _userSession)); + }); + + [HttpGet("password")] + public Task Configuration() => + Execute(async () => Ok(await _passwords.GetAsync(_current.GetCurrentUserId()))); + + [HttpPut("password/enrollment")] + public Task Enroll(PasswordEnrollmentRequest request) => Execute(async () => + { + await _passwords.EnrollAsync(_current.GetCurrentUserId(), request); + return Ok(new { enrolled = true }); + }); + + [HttpPut("password/recovery")] + public Task SaveEnvelope(SavePasswordEnvelope request) => Execute(async () => + { + await _passwords.SaveEnvelopeAsync(_current.GetCurrentUserId(), request.Envelope); + return Ok(new { saved = true }); + }); + + [EnableRateLimiting("password-auth"), HttpPost("password/{purpose:regex(^(change|reset)$)}/challenge")] + public Task ActionChallenge(string purpose, PasswordChallengeRequest request) => Execute(async () => + Ok(await _passwords.StartAsync(request, purpose, _current.GetCurrentUserId(), _currentSession.GetUserSessionId()))); + + [EnableRateLimiting("password-auth"), HttpPost("password/{purpose:regex(^(change|reset)$)}/authorize")] + public Task AuthorizeAction(string purpose, PasswordProof proof) => Execute(async () => + Ok(await _passwords.AuthorizeAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), proof, + purpose))); + + [HttpPost("password/change")] + public Task Change(ChangePasswordRequest request) => Execute(async () => + { + await _passwords.ChangeAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), request); + return Ok(new { changed = true }); + }); + + [HttpPost("password/reset-encryption")] + [RequestSizeLimit(4_120_000)] + public Task Reset(ResetEncryptionRequest request) => Execute(async () => + Ok(await _passwords.ResetAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), request))); + + private async Task Execute(Func> action) + { + try + { + return await action(); + } + catch (UnauthorizedAccessException) + { + return Unauthorized("Password proof is incorrect or expired."); + } + catch (Microsoft.EntityFrameworkCore.DbUpdateException) + { + return Conflict("Account changed. Retry the operation."); + } + catch (InvalidOperationException ex) + { + return Conflict(ex.Message); + } + catch (Exception ex) when (ex is CryptographicException or ArgumentException or FormatException or + System.Text.Json.JsonException or KeyNotFoundException) + { + return BadRequest("Invalid password authentication data."); + } + } } diff --git a/Govor.API/Controllers/E2eeController.cs b/Govor.API/Controllers/E2eeController.cs index 58abc99..3b18e11 100644 --- a/Govor.API/Controllers/E2eeController.cs +++ b/Govor.API/Controllers/E2eeController.cs @@ -40,6 +40,13 @@ public sealed class E2eeController( [HttpGet("recovery")] public async Task Recovery() => Ok(await e2ee.GetRecoveryAsync(user.GetCurrentUserId())); + [HttpGet("identities/{peer:guid}/changes")] + public async Task IdentityChanges(Guid peer) + { + try { return Ok(await e2ee.GetIdentityChangesAsync(user.GetCurrentUserId(), peer)); } + catch (UnauthorizedAccessException) { return Forbid(); } + } + [HttpGet("devices")] public async Task Devices() => Ok(await e2ee.GetOwnDevicesAsync(user.GetCurrentUserId())); @@ -55,12 +62,13 @@ public sealed class E2eeController( } [HttpGet("conversations/{type:int}/{conversationId:guid}/signers/{deviceSession:guid}")] - public async Task HistoricalSigner(int type, Guid conversationId, Guid deviceSession) + public async Task HistoricalSigner(int type, Guid conversationId, Guid deviceSession, [FromQuery] string identityKey = null) { if (type is < 0 or > 1) return BadRequest(); try { - var key = await e2ee.GetHistoricalSignerAsync(user.GetCurrentUserId(), conversationId, (RecipientType)type, deviceSession); + if (identityKey?.Length > 1000) return BadRequest(); + var key = await e2ee.GetHistoricalSignerAsync(user.GetCurrentUserId(), conversationId, (RecipientType)type, deviceSession, identityKey); return key is null ? NotFound() : Ok(key); } catch (UnauthorizedAccessException) { return Forbid(); } diff --git a/Govor.API/Program.cs b/Govor.API/Program.cs index 1aca5d2..207b3a0 100644 --- a/Govor.API/Program.cs +++ b/Govor.API/Program.cs @@ -105,6 +105,13 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) }); builder.Services.AddAuthorization(); +builder.Services.AddRateLimiter(options => +{ + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.AddPolicy("password-auth", context => System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions + { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); +}); builder.Services.AddControllers(); @@ -175,6 +182,7 @@ app.UseSwaggerUI(); //app.UseHttpsRedirection(); app.UseRouting(); +app.UseRateLimiter(); app.UseCors("AllowFrontend"); app.UseAuthentication(); @@ -210,4 +218,4 @@ app.MapSwagger() app.Map("/", () => "Not for browsers"); -app.Run(); \ No newline at end of file +app.Run(); diff --git a/Govor.Application/Authentication/AuthService.cs b/Govor.Application/Authentication/AuthService.cs index c86bfad..0947414 100644 --- a/Govor.Application/Authentication/AuthService.cs +++ b/Govor.Application/Authentication/AuthService.cs @@ -33,7 +33,16 @@ public class AuthService : IAccountService _clock = clock; } - public async Task> RegistrationAsync(string name, string password, Invitation invitation) + public Task> RegistrationAsync(string name, string password, Invitation invitation) => + RegisterCoreAsync(name, password, invitation, null); + + public Task> RegistrationWithPasswordProofAsync(string name, PasswordCredentials credentials, Invitation invitation) + { + PasswordProtocol.Validate(credentials); + return RegisterCoreAsync(name, null, invitation, credentials); + } + + private async Task> RegisterCoreAsync(string name, string? password, Invitation invitation, PasswordCredentials? credentials) { var validationResult = _usernameValidator.Validate(name); if (validationResult.IsFailure) @@ -48,7 +57,7 @@ public class AuthService : IAccountService $"User with username '{name}' already exists.")); } - var passwordHash = _passwordHasher.Hash(password); + var passwordHash = credentials is null ? _passwordHasher.Hash(password!) : "srp-only"; var operationId = Guid.NewGuid(); return await _context.Database.CreateExecutionStrategy().ExecuteAsync(async () => @@ -81,7 +90,9 @@ public class AuthService : IAccountService var user = new User { Id = operationId, Username = name, PasswordHash = passwordHash, Description = string.Empty, - CreatedOn = DateOnly.FromDateTime(now), IconId = Guid.Empty, WasOnline = now, InviteId = invitation.Id + CreatedOn = DateOnly.FromDateTime(now), IconId = Guid.Empty, WasOnline = now, InviteId = invitation.Id, + SrpSalt = credentials?.Salt, SrpIdentity = credentials?.Identity, SrpVerifier = credentials?.Verifier, + CredentialVersion = credentials is null ? 0 : 1 }; await _context.Users.AddAsync(user); @@ -120,6 +131,8 @@ public class AuthService : IAccountService $"User '{name}' is not registered.")); } + if (user.SrpVerifier is not null) + return Result.Failure(Error.Unauthorized("Auth.PasswordProofRequired", "Use password proof authentication with an updated client.")); if (!_passwordHasher.Verify(password, user.PasswordHash)) { return Result.Failure(Error.Failure( diff --git a/Govor.Application/Authentication/IAuthService.cs b/Govor.Application/Authentication/IAuthService.cs index 1f508c4..0ab8f26 100644 --- a/Govor.Application/Authentication/IAuthService.cs +++ b/Govor.Application/Authentication/IAuthService.cs @@ -9,4 +9,5 @@ public interface IAccountService { public Task> RegistrationAsync(string name, string password, Invitation invitation); public Task> LoginAsync(string name, string password); -} \ No newline at end of file + public Task> RegistrationWithPasswordProofAsync(string name, PasswordCredentials credentials, Invitation invitation); +} diff --git a/Govor.Application/Authentication/PasswordAccountService.cs b/Govor.Application/Authentication/PasswordAccountService.cs new file mode 100644 index 0000000..a337aa7 --- /dev/null +++ b/Govor.Application/Authentication/PasswordAccountService.cs @@ -0,0 +1,219 @@ +using System.Security.Cryptography; +using Govor.Application.E2ee; +using Govor.Domain; +using Govor.Domain.Models.Users; +using Govor.Domain.Models.Users.Crypto; +using Microsoft.EntityFrameworkCore; + +namespace Govor.Application.Authentication; + +public sealed class PasswordAccountService(GovorDbContext db, PasswordChallenges challenges, IPasswordHasher legacyHasher) +{ + public static PasswordCredentials Credentials(User user) => user.SrpVerifier is null + ? throw new InvalidOperationException("This account needs a one-time password upgrade.") + : new(1, user.SrpSalt!, user.SrpIdentity!, user.SrpVerifier); + + public async Task StartAsync(PasswordChallengeRequest request, string purpose = "login", + Guid? user = null, Guid? session = null) + { + if (!PasswordProtocol.GroupElement(request.PublicEphemeral) || request.Name is null || request.Name.Length > 50 || + request.DeviceInfo is null || request.DeviceInfo.Length > 256) throw new ArgumentException("Invalid password challenge."); + var account = user.HasValue ? await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user) : + await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Username == request.Name); + if (account is { SrpVerifier: null }) + return new(Guid.Empty, "", "", "", account.CredentialVersion, true); + // Unknown names receive a normal-looking challenge and always fail proof verification. + var credentials = account is null ? FakeCredentials() : Credentials(account); + var ephemeral = PasswordProtocol.Server().GenerateEphemeral(credentials.Verifier); + var entry = new PasswordChallenges.Entry(account?.Id ?? Guid.Empty, session ?? Guid.Empty, purpose, + account?.CredentialVersion ?? 0, credentials, ephemeral.Secret, request.PublicEphemeral, + request.DeviceInfo, challenges.Now.AddMinutes(2)); + var id = challenges.Add(entry); + return new(id, credentials.Salt, credentials.Identity, ephemeral.Public, entry.CredentialVersion); + } + + public async Task<(User User, string ServerProof, string DeviceInfo)> VerifyAsync(PasswordProof proof, + string purpose = "login", Guid? user = null, Guid? session = null) + { + var entry = challenges.Consume(proof.ChallengeId, purpose, user, session); + if (!PasswordProtocol.Hex(proof.Proof, 128)) throw new UnauthorizedAccessException("Invalid password proof."); + string serverProof; + try + { + var result = PasswordProtocol.Server().DeriveSession(entry.SecretEphemeral, entry.PublicEphemeral, + entry.Credentials.Salt, entry.Credentials.Identity, entry.Credentials.Verifier, proof.Proof); + serverProof = result.Proof; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { throw new UnauthorizedAccessException("Incorrect password or invalid proof."); } + var account = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == entry.UserId); + if (account is null || account.CredentialVersion != entry.CredentialVersion || + account.SrpVerifier != entry.Credentials.Verifier) throw new UnauthorizedAccessException("Credentials changed. Sign in again."); + return (account, serverProof, entry.DeviceInfo); + } + + public async Task AuthorizeAsync(Guid user, Guid session, PasswordProof proof, string action) + { + var verified = await VerifyAsync(proof, action, user, session); + var grant = new PasswordChallenges.Entry(user, session, action + "-authorized", verified.User.CredentialVersion, + Credentials(verified.User), "", "", "", challenges.Now.AddMinutes(2)); + return new(challenges.Add(grant), verified.ServerProof, verified.User.CredentialVersion); + } + + public async Task LoginAsync(PasswordProof proof, Govor.Application.Users.UserSessions.IUserSessionOpener sessions) + { + var verified = await VerifyAsync(proof); + return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var tx = await db.Database.BeginTransactionAsync(); + if (await db.Users.Where(u => u.Id == verified.User.Id && u.CredentialVersion == verified.User.CredentialVersion) + .ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1) + throw new UnauthorizedAccessException("Credentials changed during login."); + var result = await sessions.OpenSessionAsync(verified.User, verified.DeviceInfo); + if (result.IsFailure) throw new InvalidOperationException("Unable to open the authenticated session."); + await tx.CommitAsync(); + return new PasswordLoginResult(result.Value.refreshToken, result.Value.accessToken, verified.ServerProof, verified.User.CredentialVersion); + }); + } + + public async Task GetAsync(Guid user) + { + var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user); + var credentials = Credentials(account); + var recovery = await db.E2eeRecoveryVaults.AsNoTracking().SingleOrDefaultAsync(v => v.UserId == user); + var envelope = recovery is { PasswordCiphertext: not null, PasswordSignature: not null } && + recovery.PasswordCredentialVersion == account.CredentialVersion + ? new PasswordEnvelope(recovery.IdentityKey, recovery.PasswordCredentialVersion, recovery.PasswordCiphertext, recovery.PasswordSignature) : null; + return new(credentials, account.CredentialVersion, envelope); + } + + public async Task EnrollAsync(Guid user, PasswordEnrollmentRequest request) + { + PasswordProtocol.Validate(request.Credentials); + var account = await db.Users.SingleAsync(u => u.Id == user); + if (account.SrpVerifier is not null) throw new InvalidOperationException("Password authentication is already upgraded."); + if (request.LegacyPassword is null || request.LegacyPassword.Length > 256 || !legacyHasher.Verify(request.LegacyPassword, account.PasswordHash)) + throw new UnauthorizedAccessException("Incorrect current password."); + if (request.LegacyPassword.Length >= 8) + { + var old = PasswordProtocol.Derive(request.LegacyPassword, request.Credentials.Salt, request.Credentials.Identity); + var client = PasswordProtocol.Client(); + if (client.DeriveVerifier(client.DerivePrivateKey(request.Credentials.Salt, request.Credentials.Identity, old.Secret)) == request.Credentials.Verifier) + throw new ArgumentException("The replacement password must differ from the former plaintext password."); + } + Apply(account, request.Credentials); + await db.SaveChangesAsync(); + } + + public async Task SaveEnvelopeAsync(Guid user, PasswordEnvelope envelope) + { + await db.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var tx = await db.Database.BeginTransactionAsync(); + if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == envelope.CredentialVersion) + .ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1) + throw new InvalidOperationException("Password changed. Retry."); + var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user); + PasswordProtocol.ValidateEnvelope(user, Credentials(account), envelope); + var recovery = await db.E2eeRecoveryVaults.SingleAsync(v => v.UserId == user); + if (recovery.IdentityKey != envelope.IdentityKey) throw new InvalidOperationException("Encryption identity changed. Retry."); + recovery.PasswordCredentialVersion = envelope.CredentialVersion; + recovery.PasswordCiphertext = envelope.Ciphertext; + recovery.PasswordSignature = envelope.Signature; + await db.SaveChangesAsync(); await tx.CommitAsync(); + }); + } + + public async Task ChangeAsync(Guid user, Guid session, ChangePasswordRequest request) + { + PasswordProtocol.Validate(request.Credentials); + var grant = challenges.Consume(request.AuthorizationId, "change-authorized", user, session); + await db.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var tx = await db.Database.BeginTransactionAsync(); + if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == grant.CredentialVersion) + .ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1) + throw new InvalidOperationException("Credentials changed. Retry."); + var account = await db.Users.SingleAsync(u => u.Id == user); + if (account.CredentialVersion != grant.CredentialVersion) throw new InvalidOperationException("Credentials changed. Retry."); + var recovery = await db.E2eeRecoveryVaults.SingleOrDefaultAsync(v => v.UserId == user); + if (recovery is not null) + { + if (request.Envelope is null || request.Envelope.IdentityKey != recovery.IdentityKey || + request.Envelope.CredentialVersion != account.CredentialVersion + 1) + throw new ArgumentException("Changing a known password must preserve the encrypted recovery key."); + PasswordProtocol.ValidateEnvelope(user, request.Credentials, request.Envelope); + recovery.PasswordCiphertext = request.Envelope.Ciphertext; + recovery.PasswordSignature = request.Envelope.Signature; + recovery.PasswordCredentialVersion = request.Envelope.CredentialVersion; + } + Apply(account, request.Credentials); + await RevokeOtherSessionsAsync(user, session); + await db.SaveChangesAsync(); await tx.CommitAsync(); + }); + } + + public async Task ResetAsync(Guid user, Guid session, ResetEncryptionRequest request) + { + var grant = challenges.Consume(request.AuthorizationId, "reset-authorized", user, session); + E2eeRecoveryProtocol.Validate(request.Vault); + PasswordProtocol.ValidateEnvelope(user, grant.Credentials, request.Envelope); + if (request.Vault.UserId != user || request.Vault.Revision != request.ExpectedRevision + 1 || + request.Envelope.IdentityKey != request.Vault.IdentityKey || request.Envelope.CredentialVersion != grant.CredentialVersion) + throw new ArgumentException("Invalid encryption reset context."); + AccountIdentityChange? change = null; + await db.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var tx = await db.Database.BeginTransactionAsync(); + if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == grant.CredentialVersion) + .ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1) + throw new InvalidOperationException("Credentials changed. Retry."); + var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user); + if (account.CredentialVersion != grant.CredentialVersion) throw new InvalidOperationException("Credentials changed. Retry."); + var recovery = await db.E2eeRecoveryVaults.SingleAsync(v => v.UserId == user); + if (recovery.IdentityKey != request.ExpectedIdentityKey || recovery.Revision != request.ExpectedRevision || + recovery.IdentityKey == request.Vault.IdentityKey) throw new InvalidOperationException("Encryption identity changed. Retry."); + change = new(user, recovery.Epoch + 1, recovery.IdentityKey, request.Vault.IdentityKey, + challenges.Now.ToUnixTimeMilliseconds()); + var previousDevice = (await new E2eeService(db).GetOwnDevicesAsync(user)).SingleOrDefault(d => d.SessionId == session); + db.E2eeIdentityChanges.Add(new() { UserId = user, Epoch = change.Epoch, PreviousIdentityKey = change.PreviousIdentityKey, + IdentityKey = change.IdentityKey, ChangedAt = change.ChangedAt, + PreviousSessionId = previousDevice?.SessionId, + PreviousDeviceKeyJson = previousDevice is null ? null : System.Text.Json.JsonSerializer.Serialize(previousDevice) }); + recovery.Epoch = change.Epoch; + recovery.Revision = request.Vault.Revision; + recovery.IdentityKey = request.Vault.IdentityKey; + recovery.Ciphertext = request.Vault.Ciphertext; + recovery.Signature = request.Vault.Signature; + recovery.PasswordCiphertext = request.Envelope.Ciphertext; + recovery.PasswordSignature = request.Envelope.Signature; + recovery.PasswordCredentialVersion = request.Envelope.CredentialVersion; + await RevokeOtherSessionsAsync(user, session); + // Keep historical public certificates, but remove the current + // session's former identity so it can register under the new root. + await db.UserCryptoSessions.Where(c => c.UserSessionId == session).ExecuteDeleteAsync(); + await db.SaveChangesAsync(); await tx.CommitAsync(); + }); + return change!; + } + + private async Task RevokeOtherSessionsAsync(Guid user, Guid currentSession) + { + await db.UserSessions.Where(s => s.UserId == user && s.Id != currentSession) + .ExecuteUpdateAsync(s => s.SetProperty(s => s.IsRevoked, true)); + await db.UserPushTokens.Where(t => t.UserId == user && t.UserSessionId != currentSession) + .ExecuteUpdateAsync(t => t.SetProperty(t => t.IsActive, false)); + } + private static void Apply(User user, PasswordCredentials credentials) + { + user.PasswordHash = "srp-only"; + user.SrpSalt = credentials.Salt; user.SrpIdentity = credentials.Identity; user.SrpVerifier = credentials.Verifier; + user.CredentialVersion++; + } + private static PasswordCredentials FakeCredentials() + { + var salt = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + var identity = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + return new(1, salt, identity, PasswordProtocol.Client().DeriveVerifier(Convert.ToHexString(RandomNumberGenerator.GetBytes(64)))); + } +} diff --git a/Govor.Application/Authentication/PasswordChallenges.cs b/Govor.Application/Authentication/PasswordChallenges.cs new file mode 100644 index 0000000..589ca76 --- /dev/null +++ b/Govor.Application/Authentication/PasswordChallenges.cs @@ -0,0 +1,35 @@ +namespace Govor.Application.Authentication; + +// Ephemeral proofs and authorizations are process-local, bounded and consumed +// exactly once. A restart invalidates pending handshakes, never long-term keys. +public sealed class PasswordChallenges(TimeProvider? clock = null) +{ + private readonly TimeProvider _clock = clock ?? TimeProvider.System; + private readonly object _gate = new(); + private readonly Dictionary _entries = []; + public sealed record Entry(Guid UserId, Guid SessionId, string Purpose, long CredentialVersion, + PasswordCredentials Credentials, string SecretEphemeral, string PublicEphemeral, + string DeviceInfo, DateTimeOffset ExpiresAt); + + public Guid Add(Entry entry) + { + lock (_gate) + { + foreach (var id in _entries.Where(p => p.Value.ExpiresAt <= _clock.GetUtcNow()).Select(p => p.Key).ToArray()) + _entries.Remove(id); + if (_entries.Count >= 1024) throw new InvalidOperationException("Too many pending password proofs. Retry shortly."); + var key = Guid.NewGuid(); _entries.Add(key, entry); return key; + } + } + public Entry Consume(Guid id, string purpose, Guid? user = null, Guid? session = null) + { + lock (_gate) + { + if (!_entries.Remove(id, out var value) || value.ExpiresAt <= _clock.GetUtcNow() || + value.Purpose != purpose || (user.HasValue && value.UserId != user) || + (session.HasValue && value.SessionId != session)) throw new UnauthorizedAccessException("Password proof is expired or invalid."); + return value; + } + } + public DateTimeOffset Now => _clock.GetUtcNow(); +} diff --git a/Govor.Application/Authentication/PasswordProtocol.cs b/Govor.Application/Authentication/PasswordProtocol.cs new file mode 100644 index 0000000..488efd8 --- /dev/null +++ b/Govor.Application/Authentication/PasswordProtocol.cs @@ -0,0 +1,129 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Numerics; +using Jose; +using SecureRemotePassword; +using Govor.Application.E2ee; + +namespace Govor.Application.Authentication; + +public sealed record PasswordCredentials(int Version, string Salt, string Identity, string Verifier); +public sealed record PasswordEnvelope(string IdentityKey, long CredentialVersion, string Ciphertext, string Signature); +public sealed record PasswordConfiguration(PasswordCredentials Credentials, long CredentialVersion, PasswordEnvelope? Envelope); +public sealed record PasswordChallengeRequest(string Name, string PublicEphemeral, string DeviceInfo = ""); +public sealed record PasswordChallenge(Guid ChallengeId, string Salt, string Identity, string PublicEphemeral, long CredentialVersion, bool Legacy = false); +public sealed record PasswordProof(Guid ChallengeId, string Proof); +public sealed record PasswordLoginResult(string RefreshToken, string AccessToken, string ServerProof, long CredentialVersion); +public sealed record PasswordActionResult(Guid AuthorizationId, string ServerProof, long CredentialVersion); +public sealed record PasswordEnrollmentRequest(PasswordCredentials Credentials, string? LegacyPassword = null); +public sealed record SavePasswordEnvelope(PasswordEnvelope Envelope); +public sealed record ChangePasswordRequest(Guid AuthorizationId, PasswordCredentials Credentials, PasswordEnvelope? Envelope); +public sealed record ResetEncryptionRequest(Guid AuthorizationId, string ExpectedIdentityKey, long ExpectedRevision, + RecoveryVault Vault, PasswordEnvelope Envelope); +public sealed record AccountIdentityChange(Guid UserId, long Epoch, string PreviousIdentityKey, string IdentityKey, long ChangedAt); + +// SRP-6a is supplied by srp.net, rather than implemented here. Fixed parameters +// and separate HKDF domains prevent the authentication verifier/session key from +// being used as the key that opens the recovery archive. +public static class PasswordProtocol +{ + public const int Iterations = 600_000; + public static SrpParameters Parameters() => SrpParameters.Create4096(); + public static SrpClient Client() => new(Parameters()); + public static SrpServer Server() => new(Parameters()); + + public static (PasswordCredentials Credentials, string ArchiveKey) Create(string password) + { + var salt = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + var identity = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + var (secret, archiveKey) = Derive(password, salt, identity); + var client = Client(); + return (new(1, salt, identity, client.DeriveVerifier(client.DerivePrivateKey(salt, identity, secret))), archiveKey); + } + + public static (string Secret, string ArchiveKey) Derive(string password, string salt, string identity) + { + if (password is null || password.Length is < 8 or > 256 || !Hex(salt, 64) || !Hex(identity, 64)) + throw new CryptographicException("Invalid password or password parameters."); + var master = Rfc2898DeriveBytes.Pbkdf2(password, Convert.FromHexString(salt), Iterations, HashAlgorithmName.SHA256, 32); + try + { + var auth = HKDF.DeriveKey(HashAlgorithmName.SHA256, master, 32, info: Encoding.UTF8.GetBytes("govor-auth-v1\n" + identity)); + var archive = HKDF.DeriveKey(HashAlgorithmName.SHA256, master, 32, info: Encoding.UTF8.GetBytes("govor-password-archive-v1\n" + identity)); + try { return (Base64Url.Encode(auth), Base64Url.Encode(archive)); } + finally { CryptographicOperations.ZeroMemory(auth); CryptographicOperations.ZeroMemory(archive); } + } + finally { CryptographicOperations.ZeroMemory(master); } + } + + public static void Validate(PasswordCredentials credentials) + { + if (credentials is null || credentials.Version != 1 || !Hex(credentials.Salt, 64) || + !Hex(credentials.Identity, 64) || !Hex(credentials.Verifier, 1024) || + !SrpUtility.IsValidVerifier(Parameters(), credentials.Verifier) || !GroupElement(credentials.Verifier)) + throw new CryptographicException("Invalid SRP credentials."); + } + + public static bool Hex(string? value, int length) => value?.Length == length && + value.All(c => c is >= '0' and <= '9' or >= 'A' and <= 'F' or >= 'a' and <= 'f'); + public static bool GroupElement(string? value) + { + if (!Hex(value, 1024)) return false; + var integer = new BigInteger(Convert.FromHexString(value!), isUnsigned: true, isBigEndian: true); + var prime = new BigInteger(Convert.FromHexString(Parameters().Prime.ToHex()), isUnsigned: true, isBigEndian: true); + return integer > 1 && integer < prime - 1; + } + + public static PasswordEnvelope Seal(Guid user, long version, PasswordCredentials credentials, + string privateIdentity, string code, string archiveKey) + { + Validate(credentials); + var root = E2eeRecoveryProtocol.PublicIdentity(privateIdentity); + var key = Base64Url.Decode(archiveKey); + try + { + if (key.Length != 32) throw new CryptographicException("Invalid archive key."); + var ciphertext = Jose.JWT.Encode(new KeyPayload(1, user, root, version, code), key, JweAlgorithm.DIR, JweEncryption.A256GCM); + var envelope = new PasswordEnvelope(root, version, ciphertext, ""); + return envelope with { Signature = E2eeRecoveryProtocol.SignAccountPayload(privateIdentity, Binding(user, credentials, envelope)) }; + } + finally { CryptographicOperations.ZeroMemory(key); } + } + + public static string Open(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope, string archiveKey) + { + ValidateEnvelope(user, credentials, envelope); + var key = Base64Url.Decode(archiveKey); + try + { + if (key.Length != 32) throw new CryptographicException("Invalid archive key."); + var payload = JsonSerializer.Deserialize(Jose.JWT.Decode(envelope.Ciphertext, key, + JweAlgorithm.DIR, JweEncryption.A256GCM), E2eeProtocol.Json) ?? throw new CryptographicException("Invalid password archive."); + if (payload.Version != 1 || payload.UserId != user || payload.IdentityKey != envelope.IdentityKey || + payload.CredentialVersion != envelope.CredentialVersion || Base64Url.Decode(payload.Code).Length != 32) + throw new CryptographicException("Password archive context mismatch."); + return payload.Code; + } + finally { CryptographicOperations.ZeroMemory(key); } + } + + public static void ValidateEnvelope(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope) + { + Validate(credentials); + if (user == Guid.Empty || envelope is null || envelope.CredentialVersion < 1 || envelope.Ciphertext is null || + envelope.Ciphertext.Length is < 50 or > 4096 || envelope.Signature is null) + throw new CryptographicException("Invalid password archive."); + var parts = envelope.Ciphertext.Split('.'); + if (parts.Length != 5 || parts[1].Length != 0) throw new CryptographicException("Invalid password archive JWE."); + using var header = JsonDocument.Parse(Base64Url.Decode(parts[0])); + if (header.RootElement.EnumerateObject().Count() != 2 || header.RootElement.GetProperty("alg").GetString() != "dir" || + header.RootElement.GetProperty("enc").GetString() != "A256GCM") throw new CryptographicException("Invalid archive algorithms."); + E2eeRecoveryProtocol.VerifyAccountPayload(envelope.IdentityKey, Binding(user, credentials, envelope), envelope.Signature); + } + + private static byte[] Binding(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope) => + JsonSerializer.SerializeToUtf8Bytes(new { purpose = "govor-password-recovery-v1", user, + credentials, envelope.IdentityKey, envelope.CredentialVersion, envelope.Ciphertext }); + private sealed record KeyPayload(int Version, Guid UserId, string IdentityKey, long CredentialVersion, string Code); +} diff --git a/Govor.Application/E2ee/E2eeRecoveryProtocol.cs b/Govor.Application/E2ee/E2eeRecoveryProtocol.cs index f8602ca..1ee057d 100644 --- a/Govor.Application/E2ee/E2eeRecoveryProtocol.cs +++ b/Govor.Application/E2ee/E2eeRecoveryProtocol.cs @@ -49,6 +49,11 @@ public static class E2eeRecoveryProtocol public static string AccountFingerprint(string identity) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("govor-account-v1\n" + identity))); + public static string SignAccountPayload(string privateIdentity, byte[] data) + { using var key = PrivateIdentity(privateIdentity); return Sign(key, data); } + public static void VerifyAccountPayload(string publicIdentity, byte[] data, string signature) + { using var key = PublicIdentityKey(publicIdentity); Verify(key, data, signature); } + public static DeviceKey Certify(DeviceKey device, string privateIdentity, long generation = 0, string? previousFingerprint = null) { diff --git a/Govor.Application/E2ee/E2eeService.cs b/Govor.Application/E2ee/E2eeService.cs index 28ea179..fb89c04 100644 --- a/Govor.Application/E2ee/E2eeService.cs +++ b/Govor.Application/E2ee/E2eeService.cs @@ -111,6 +111,19 @@ public sealed class E2eeService(GovorDbContext context) return new(value is null ? null : new(user, value.Revision, value.IdentityKey, value.Ciphertext, value.Signature)); } + public async Task GetIdentityChangesAsync(Guid user, Guid peer) + { + if (user != peer && !await context.PrivateChats.AnyAsync(c => + (c.UserAId == user && c.UserBId == peer) || (c.UserAId == peer && c.UserBId == user)) && + !await context.GroupMemberships.AnyAsync(m => m.UserId == user && !m.IsBanned && + (context.GroupMemberships.Any(p => p.GroupId == m.GroupId && p.UserId == peer && !p.IsBanned) || + context.Messages.Any(msg => msg.RecipientType == RecipientType.Group && msg.RecipientId == m.GroupId && msg.SenderId == peer)))) + throw new UnauthorizedAccessException(); + return await context.E2eeIdentityChanges.AsNoTracking().Where(c => c.UserId == peer).OrderBy(c => c.Epoch) + .Select(c => new Govor.Application.Authentication.AccountIdentityChange(c.UserId, c.Epoch, + c.PreviousIdentityKey, c.IdentityKey, c.ChangedAt)).ToArrayAsync(); + } + public async Task SaveRecoveryAsync(Guid user, SaveRecoveryVault request) { if (request.ExpectedRevision < 0 || request.ExpectedRevision == long.MaxValue) @@ -166,14 +179,31 @@ public sealed class E2eeService(GovorDbContext context) await context.SaveChangesAsync(); } - public async Task GetHistoricalSignerAsync(Guid user, Guid conversation, RecipientType type, Guid session) + public async Task GetHistoricalSignerAsync(Guid user, Guid conversation, RecipientType type, Guid session, string? identityKey = null) { if (!await context.HasChatAccessAsync(user, conversation, type)) throw new UnauthorizedAccessException(); var crypto = await context.UserCryptoSessions.AsNoTracking().Include(c => c.SignedPreKey).Include(c => c.UserSession) .SingleOrDefaultAsync(c => c.UserSessionId == session); - if (crypto is null || !await context.Messages.AnyAsync(m => m.RecipientId == conversation && - m.RecipientType == type && m.SenderId == crypto.UserSession.UserId)) return null; - return ToDeviceKey(crypto); + var owner = await context.UserSessions.AsNoTracking().Where(s => s.Id == session).Select(s => (Guid?)s.UserId).SingleOrDefaultAsync(); + if (owner is null || !await context.Messages.AnyAsync(m => m.RecipientId == conversation && + m.RecipientType == type && m.SenderId == owner.Value)) return null; + if (crypto is not null) + { + var current = ToDeviceKey(crypto); + if (identityKey is null || current.IdentityKey == identityKey) return current; + } + // A reset replaces this session's signing key, but v1 messages still need + // the former account certificate. Public history never reactivates a key. + var previous = await context.E2eeIdentityChanges.AsNoTracking().Where(c => c.UserId == owner.Value && + c.PreviousSessionId == session && c.PreviousDeviceKeyJson != null) + .OrderByDescending(c => c.Epoch).Select(c => c.PreviousDeviceKeyJson!).ToArrayAsync(); + foreach (var json in previous) + { + var key = System.Text.Json.JsonSerializer.Deserialize(json, E2eeProtocol.Json); + if (key is not null && key.SessionId == session && key.UserId == owner && + (identityKey is null || key.IdentityKey == identityKey)) return key; + } + return null; } public async Task ValidateAsync(string content, Guid sender, Guid conversation, diff --git a/Govor.Application/Govor.Application.csproj b/Govor.Application/Govor.Application.csproj index 4c4e975..7404fca 100644 --- a/Govor.Application/Govor.Application.csproj +++ b/Govor.Application/Govor.Application.csproj @@ -7,6 +7,7 @@ + diff --git a/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs b/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs index b3c222f..81fc865 100644 --- a/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs +++ b/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs @@ -33,6 +33,19 @@ public class UsersService : IUsersAdministration return; user.PasswordHash = _passwordHasher.Hash(password); + user.SrpVerifier = null; + user.SrpSalt = null; + user.SrpIdentity = null; + user.CredentialVersion++; + var recovery = await _context.E2eeRecoveryVaults.SingleOrDefaultAsync(v => v.UserId == userId); + if (recovery is not null) + { + // An administrator can reset authentication, but cannot rewrap an + // encryption key without knowing a client-side recovery secret. + recovery.PasswordCiphertext = null; + recovery.PasswordSignature = null; + recovery.PasswordCredentialVersion = 0; + } var sessions = await _context.UserSessions.Where(s => s.UserId == userId && !s.IsRevoked).ToListAsync(); foreach (var session in sessions) diff --git a/Govor.Contracts/Requests/RegistrationRequest.cs b/Govor.Contracts/Requests/RegistrationRequest.cs index afe6048..35b24a5 100644 --- a/Govor.Contracts/Requests/RegistrationRequest.cs +++ b/Govor.Contracts/Requests/RegistrationRequest.cs @@ -3,17 +3,31 @@ using Govor.Domain.Common.Constants; namespace Govor.Contracts.Requests; -public record RegistrationRequest +public record RegistrationRequest : IValidatableObject { [Required] [StringLength(UserConstants.MAX_LENGHT_OF_NAME, MinimumLength = UserConstants.MIN_LENGHT_OF_NAME, ErrorMessage = "Username must be between 4 and 44 characters.")] public string Name { get; init; } - [Required] [MinLength(8)] - public string Password { get; init; } + public string? Password { get; init; } + public string? SrpSalt { get; init; } + public string? SrpIdentity { get; init; } + public string? SrpVerifier { get; init; } [MinLength(InvitationConstants.MIN_INVITATION_LENGTH)] public string InviteLink { get; init; } public string DeviceInfo { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var proofRegistration = SrpSalt is not null || SrpIdentity is not null || SrpVerifier is not null; + if (proofRegistration) + { + if (Password is not null || SrpSalt is null || SrpIdentity is null || SrpVerifier is null) + yield return new ValidationResult("Provide complete SRP credentials without a plaintext password."); + } + else if (string.IsNullOrWhiteSpace(Password)) + yield return new ValidationResult("Password is required.", [nameof(Password)]); + } } diff --git a/Govor.Domain/Configurations/E2eeRecoveryVaultConfiguration.cs b/Govor.Domain/Configurations/E2eeRecoveryVaultConfiguration.cs index 71f1d7d..8769b56 100644 --- a/Govor.Domain/Configurations/E2eeRecoveryVaultConfiguration.cs +++ b/Govor.Domain/Configurations/E2eeRecoveryVaultConfiguration.cs @@ -15,6 +15,8 @@ public class E2eeRecoveryVaultConfiguration : IEntityTypeConfiguration v.IdentityKey).HasMaxLength(200); b.Property(v => v.Signature).HasMaxLength(100); b.Property(v => v.Ciphertext).HasMaxLength(4_000_000); + b.Property(v => v.PasswordCiphertext).HasMaxLength(4096); + b.Property(v => v.PasswordSignature).HasMaxLength(100); b.HasOne().WithOne().HasForeignKey(v => v.UserId).OnDelete(DeleteBehavior.Cascade); } -} \ No newline at end of file +} diff --git a/Govor.Domain/Configurations/UserConfiguration.cs b/Govor.Domain/Configurations/UserConfiguration.cs index 1a34014..f2e0695 100644 --- a/Govor.Domain/Configurations/UserConfiguration.cs +++ b/Govor.Domain/Configurations/UserConfiguration.cs @@ -9,6 +9,10 @@ public class UserConfiguration : IEntityTypeConfiguration public void Configure(EntityTypeBuilder builder) { builder.HasKey(x => x.Id); + builder.Property(u => u.SrpSalt).HasMaxLength(64); + builder.Property(u => u.SrpIdentity).HasMaxLength(64); + builder.Property(u => u.SrpVerifier).HasMaxLength(1024); + builder.Property(u => u.CredentialVersion).IsConcurrencyToken(); builder.HasIndex(u => u.Username).IsUnique(); builder.HasIndex(u => u.CreatedOn); @@ -32,4 +36,4 @@ public class UserConfiguration : IEntityTypeConfiguration .IsRequired() .HasMaxLength(128); } -} \ No newline at end of file +} diff --git a/Govor.Domain/GovorDbContext.cs b/Govor.Domain/GovorDbContext.cs index 0a070b2..a7223b9 100644 --- a/Govor.Domain/GovorDbContext.cs +++ b/Govor.Domain/GovorDbContext.cs @@ -15,6 +15,7 @@ public class GovorDbContext(DbContextOptions options) : DbContex public virtual DbSet UserPushTokens { get; set; } public virtual DbSet UserCryptoSessions { get; set; } public virtual DbSet E2eeRecoveryVaults { get; set; } + public DbSet E2eeIdentityChanges { get; set; } public virtual DbSet SignedPreKeys { get; set; } public virtual DbSet OneTimePreKeys { get; set; } public virtual DbSet Friendships { get; set; } @@ -42,6 +43,14 @@ public class GovorDbContext(DbContextOptions options) : DbContex protected override void OnModelCreating(ModelBuilder modelBuilder) { + modelBuilder.Entity(b => + { + b.HasKey(c => new { c.UserId, c.Epoch }); + b.Property(c => c.PreviousIdentityKey).HasMaxLength(200); + b.Property(c => c.IdentityKey).HasMaxLength(200); + b.Property(c => c.PreviousDeviceKeyJson).HasMaxLength(10000); + b.HasOne().WithMany().HasForeignKey(c => c.UserId).OnDelete(DeleteBehavior.Cascade); + }); modelBuilder.ApplyConfiguration(new E2eeRecoveryVaultConfiguration()); modelBuilder.ApplyConfiguration(new UserSessionConfiguration()); modelBuilder.ApplyConfiguration(new FriendshipConfiguration()); diff --git a/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.Designer.cs b/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.Designer.cs new file mode 100644 index 0000000..15805fb --- /dev/null +++ b/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.Designer.cs @@ -0,0 +1,1472 @@ +// +using System; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + [DbContext(typeof(GovorDbContext))] + [Migration("20261024105815_PasswordBasedRecovery")] + partial class PasswordBasedRecovery + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageId") + .HasColumnType("uuid"); + + b.Property("IsChannel") + .HasColumnType("boolean"); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("OwnerUserId") + .HasColumnType("uuid"); + + b.Property("ReactionMode") + .HasColumnType("integer"); + + b.Property("ReactionPolicyVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("OwnerUserId"); + + b.ToTable("ChatGroups"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddresseeId") + .HasColumnType("uuid"); + + b.Property("RequesterId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AddresseeId"); + + b.HasIndex("RequesterId"); + + b.ToTable("Friendships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupId", "UserId") + .IsUnique(); + + b.ToTable("GroupAdmins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationCode") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("UsedCount") + .HasColumnType("integer"); + + b.Property("UserMakerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.HasIndex("InvitationCode") + .IsUnique(); + + b.HasIndex("UserMakerId"); + + b.ToTable("GroupInvitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationId") + .HasColumnType("uuid"); + + b.Property("IsBanned") + .HasColumnType("boolean"); + + b.Property("MemberSince") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("InvitationId"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupId", "UserId") + .IsUnique(); + + b.ToTable("GroupMemberships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("Participants") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Invitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("MediaType") + .IsRequired() + .HasColumnType("text"); + + b.Property("MineType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OwnerId") + .HasColumnType("uuid"); + + b.Property("OwnerType") + .HasColumnType("integer"); + + b.Property("UploaderId") + .HasColumnType("uuid"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MessageId"); + + b.HasIndex("NextAttemptAt"); + + b.ToTable("ChatPushNotifications"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("MediaFileId"); + + b.HasIndex("MessageId"); + + b.ToTable("MediaAttachments"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedContent") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsEdited") + .HasColumnType("boolean"); + + b.Property("PrivateChatId") + .HasColumnType("uuid"); + + b.Property("ReactionsVersion") + .HasColumnType("bigint"); + + b.Property("RecipientId") + .HasColumnType("uuid"); + + b.Property("RecipientType") + .HasColumnType("integer"); + + b.Property("ReplyToMessageId") + .HasColumnType("uuid"); + + b.Property("SenderId") + .HasColumnType("uuid"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("PrivateChatId"); + + b.HasIndex("RecipientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("ReactedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReactionCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ReactionId"); + + b.HasIndex("UserId"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("ViewedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageViews"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("UserAId") + .HasColumnType("uuid"); + + b.Property("UserBId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.ToTable("PrivateChats"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "ReactionId"); + + b.HasIndex("ReactionId"); + + b.ToTable("ChannelAllowedReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationMilliseconds") + .HasColumnType("integer"); + + b.Property("Emoji") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.Property("SizeBytes") + .HasColumnType("integer"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.HasIndex("MediaFileId"); + + b.HasIndex("PackId"); + + b.ToTable("ReactionItems"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000001"), + Code = "👍", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👍", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👍", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000002"), + Code = "👎", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👎", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👎", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000003"), + Code = "❤️", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "❤️", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "❤️", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000004"), + Code = "🔥", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🔥", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🔥", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000005"), + Code = "🥰", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🥰", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🥰", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000006"), + Code = "👏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000007"), + Code = "😁", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😁", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😁", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000008"), + Code = "🤔", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤔", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤔", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000009"), + Code = "😢", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😢", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😢", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000010"), + Code = "🎉", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🎉", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🎉", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000011"), + Code = "🤯", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤯", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤯", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000012"), + Code = "🙏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🙏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🙏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ShareCode") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("IsDefault") + .IsUnique() + .HasFilter("\"IsDefault\" = TRUE"); + + b.HasIndex("ShareCode") + .IsUnique(); + + b.ToTable("ReactionPacks"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0000-000000000001"), + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Default public emoji reactions", + IsDefault = true, + IsEnabled = true, + Name = "Emoji", + ShareCode = "default" + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PackId"); + + b.HasIndex("PackId"); + + b.ToTable("UserReactionPacks"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b => + { + b.Property("Id") + .HasColumnType("integer"); + + b.Property("AllowLeave") + .HasColumnType("boolean"); + + b.Property("RequiredChannelId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RequiredChannelId"); + + b.ToTable("ServerCommunitySettings"); + + b.HasData( + new + { + Id = 1, + AllowLeave = true + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("UserId"); + + b.ToTable("Admins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Epoch") + .HasColumnType("bigint"); + + b.Property("ChangedAt") + .HasColumnType("bigint"); + + b.Property("IdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PreviousIdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("UserId", "Epoch"); + + b.ToTable("E2eeIdentityChanges"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Ciphertext") + .IsRequired() + .HasMaxLength(4000000) + .HasColumnType("character varying(4000000)"); + + b.Property("Epoch") + .HasColumnType("bigint"); + + b.Property("IdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PasswordCiphertext") + .HasMaxLength(4096) + .HasColumnType("character varying(4096)"); + + b.Property("PasswordCredentialVersion") + .HasColumnType("bigint"); + + b.Property("PasswordSignature") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("Signature") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.HasKey("UserId"); + + b.ToTable("E2eeRecoveryVaults"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("IsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("PublicKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UploadedAt"); + + b.HasIndex("UserCryptoSessionId", "IsUsed"); + + b.ToTable("OneTimePreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicSignedPreKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("SignedPreKeySignature") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserCryptoSessionId") + .IsUnique(); + + b.ToTable("SignedPreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountIdentityKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AccountSignature") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Generation") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("PreviousFingerprint") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PublicIdentityKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.ToTable("UserCryptoSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedOn") + .HasColumnType("date"); + + b.Property("CredentialVersion") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IconId") + .HasColumnType("uuid"); + + b.Property("InviteId") + .HasColumnType("uuid"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("SrpIdentity") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpSalt") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpVerifier") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("WasOnline") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatedOn"); + + b.HasIndex("InviteId"); + + b.HasIndex("Username") + .IsUnique(); + + b.HasIndex("WasOnline"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserPushToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.HasIndex("UserId", "IsActive"); + + b.ToTable("UserPushTokens"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceInfo") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("RefreshTokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RefreshTokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("UserSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "Addressee") + .WithMany("ReceivedFriendRequests") + .HasForeignKey("AddresseeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "Requester") + .WithMany("SentFriendRequests") + .HasForeignKey("RequesterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Addressee"); + + b.Navigation("Requester"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Admins") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("InviteCodes") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "UserMaker") + .WithMany() + .HasForeignKey("UserMakerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserMaker"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", "ChatGroup") + .WithMany("Members") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.GroupInvitation", null) + .WithMany() + .HasForeignKey("InvitationId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ChatGroup"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany() + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("MediaAttachments") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MediaFile"); + + b.Navigation("Message"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Messages") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.PrivateChat", null) + .WithMany("Messages") + .HasForeignKey("PrivateChatId"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("Reactions") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Message"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany("MessageViews") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", null) + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", "Pack") + .WithMany("Reactions") + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Pack"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", null) + .WithMany() + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("RequiredChannelId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Admin", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithMany("OneTimePreKeys") + .HasForeignKey("UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithOne("SignedPreKey") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.SignedPreKey", "UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.HasOne("Govor.Domain.Models.Users.UserSession", "UserSession") + .WithOne("CryptoSession") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.HasOne("Govor.Domain.Models.Invitation", "Invite") + .WithMany("Users") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invite"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Navigation("Admins"); + + b.Navigation("InviteCodes"); + + b.Navigation("Members"); + + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Navigation("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Navigation("MediaAttachments"); + + b.Navigation("MessageViews"); + + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Navigation("OneTimePreKeys"); + + b.Navigation("SignedPreKey") + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Navigation("ReceivedFriendRequests"); + + b.Navigation("SentFriendRequests"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Navigation("CryptoSession") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.cs b/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.cs new file mode 100644 index 0000000..fe711c1 --- /dev/null +++ b/Govor.Domain/Migrations/20261024105815_PasswordBasedRecovery.cs @@ -0,0 +1,131 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + /// + public partial class PasswordBasedRecovery : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CredentialVersion", + table: "Users", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.AddColumn( + name: "SrpIdentity", + table: "Users", + type: "character varying(64)", + maxLength: 64, + nullable: true); + + migrationBuilder.AddColumn( + name: "SrpSalt", + table: "Users", + type: "character varying(64)", + maxLength: 64, + nullable: true); + + migrationBuilder.AddColumn( + name: "SrpVerifier", + table: "Users", + type: "character varying(1024)", + maxLength: 1024, + nullable: true); + + migrationBuilder.AddColumn( + name: "Epoch", + table: "E2eeRecoveryVaults", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.AddColumn( + name: "PasswordCiphertext", + table: "E2eeRecoveryVaults", + type: "character varying(4096)", + maxLength: 4096, + nullable: true); + + migrationBuilder.AddColumn( + name: "PasswordCredentialVersion", + table: "E2eeRecoveryVaults", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.AddColumn( + name: "PasswordSignature", + table: "E2eeRecoveryVaults", + type: "character varying(100)", + maxLength: 100, + nullable: true); + + migrationBuilder.CreateTable( + name: "E2eeIdentityChanges", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + Epoch = table.Column(type: "bigint", nullable: false), + PreviousIdentityKey = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + IdentityKey = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + ChangedAt = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_E2eeIdentityChanges", x => new { x.UserId, x.Epoch }); + table.ForeignKey( + name: "FK_E2eeIdentityChanges_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "E2eeIdentityChanges"); + + migrationBuilder.DropColumn( + name: "CredentialVersion", + table: "Users"); + + migrationBuilder.DropColumn( + name: "SrpIdentity", + table: "Users"); + + migrationBuilder.DropColumn( + name: "SrpSalt", + table: "Users"); + + migrationBuilder.DropColumn( + name: "SrpVerifier", + table: "Users"); + + migrationBuilder.DropColumn( + name: "Epoch", + table: "E2eeRecoveryVaults"); + + migrationBuilder.DropColumn( + name: "PasswordCiphertext", + table: "E2eeRecoveryVaults"); + + migrationBuilder.DropColumn( + name: "PasswordCredentialVersion", + table: "E2eeRecoveryVaults"); + + migrationBuilder.DropColumn( + name: "PasswordSignature", + table: "E2eeRecoveryVaults"); + } + } +} diff --git a/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.Designer.cs b/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.Designer.cs new file mode 100644 index 0000000..4cea274 --- /dev/null +++ b/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.Designer.cs @@ -0,0 +1,1479 @@ +// +using System; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + [DbContext(typeof(GovorDbContext))] + [Migration("20261024114709_PreserveResetSigners")] + partial class PreserveResetSigners + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageId") + .HasColumnType("uuid"); + + b.Property("IsChannel") + .HasColumnType("boolean"); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("OwnerUserId") + .HasColumnType("uuid"); + + b.Property("ReactionMode") + .HasColumnType("integer"); + + b.Property("ReactionPolicyVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("OwnerUserId"); + + b.ToTable("ChatGroups"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddresseeId") + .HasColumnType("uuid"); + + b.Property("RequesterId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AddresseeId"); + + b.HasIndex("RequesterId"); + + b.ToTable("Friendships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupId", "UserId") + .IsUnique(); + + b.ToTable("GroupAdmins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationCode") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("UsedCount") + .HasColumnType("integer"); + + b.Property("UserMakerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.HasIndex("InvitationCode") + .IsUnique(); + + b.HasIndex("UserMakerId"); + + b.ToTable("GroupInvitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationId") + .HasColumnType("uuid"); + + b.Property("IsBanned") + .HasColumnType("boolean"); + + b.Property("MemberSince") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("InvitationId"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupId", "UserId") + .IsUnique(); + + b.ToTable("GroupMemberships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("Participants") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Invitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("MediaType") + .IsRequired() + .HasColumnType("text"); + + b.Property("MineType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OwnerId") + .HasColumnType("uuid"); + + b.Property("OwnerType") + .HasColumnType("integer"); + + b.Property("UploaderId") + .HasColumnType("uuid"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MessageId"); + + b.HasIndex("NextAttemptAt"); + + b.ToTable("ChatPushNotifications"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("MediaFileId"); + + b.HasIndex("MessageId"); + + b.ToTable("MediaAttachments"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedContent") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsEdited") + .HasColumnType("boolean"); + + b.Property("PrivateChatId") + .HasColumnType("uuid"); + + b.Property("ReactionsVersion") + .HasColumnType("bigint"); + + b.Property("RecipientId") + .HasColumnType("uuid"); + + b.Property("RecipientType") + .HasColumnType("integer"); + + b.Property("ReplyToMessageId") + .HasColumnType("uuid"); + + b.Property("SenderId") + .HasColumnType("uuid"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("PrivateChatId"); + + b.HasIndex("RecipientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("ReactedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReactionCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ReactionId"); + + b.HasIndex("UserId"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("ViewedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageViews"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("UserAId") + .HasColumnType("uuid"); + + b.Property("UserBId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.ToTable("PrivateChats"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "ReactionId"); + + b.HasIndex("ReactionId"); + + b.ToTable("ChannelAllowedReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationMilliseconds") + .HasColumnType("integer"); + + b.Property("Emoji") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.Property("SizeBytes") + .HasColumnType("integer"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.HasIndex("MediaFileId"); + + b.HasIndex("PackId"); + + b.ToTable("ReactionItems"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000001"), + Code = "👍", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👍", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👍", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000002"), + Code = "👎", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👎", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👎", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000003"), + Code = "❤️", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "❤️", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "❤️", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000004"), + Code = "🔥", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🔥", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🔥", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000005"), + Code = "🥰", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🥰", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🥰", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000006"), + Code = "👏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000007"), + Code = "😁", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😁", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😁", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000008"), + Code = "🤔", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤔", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤔", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000009"), + Code = "😢", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😢", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😢", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000010"), + Code = "🎉", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🎉", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🎉", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000011"), + Code = "🤯", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤯", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤯", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000012"), + Code = "🙏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🙏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🙏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ShareCode") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("IsDefault") + .IsUnique() + .HasFilter("\"IsDefault\" = TRUE"); + + b.HasIndex("ShareCode") + .IsUnique(); + + b.ToTable("ReactionPacks"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0000-000000000001"), + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Default public emoji reactions", + IsDefault = true, + IsEnabled = true, + Name = "Emoji", + ShareCode = "default" + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PackId"); + + b.HasIndex("PackId"); + + b.ToTable("UserReactionPacks"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b => + { + b.Property("Id") + .HasColumnType("integer"); + + b.Property("AllowLeave") + .HasColumnType("boolean"); + + b.Property("RequiredChannelId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RequiredChannelId"); + + b.ToTable("ServerCommunitySettings"); + + b.HasData( + new + { + Id = 1, + AllowLeave = true + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("UserId"); + + b.ToTable("Admins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Epoch") + .HasColumnType("bigint"); + + b.Property("ChangedAt") + .HasColumnType("bigint"); + + b.Property("IdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PreviousDeviceKeyJson") + .HasMaxLength(10000) + .HasColumnType("character varying(10000)"); + + b.Property("PreviousIdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PreviousSessionId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "Epoch"); + + b.ToTable("E2eeIdentityChanges"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Ciphertext") + .IsRequired() + .HasMaxLength(4000000) + .HasColumnType("character varying(4000000)"); + + b.Property("Epoch") + .HasColumnType("bigint"); + + b.Property("IdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PasswordCiphertext") + .HasMaxLength(4096) + .HasColumnType("character varying(4096)"); + + b.Property("PasswordCredentialVersion") + .HasColumnType("bigint"); + + b.Property("PasswordSignature") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("Signature") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.HasKey("UserId"); + + b.ToTable("E2eeRecoveryVaults"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("IsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("PublicKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UploadedAt"); + + b.HasIndex("UserCryptoSessionId", "IsUsed"); + + b.ToTable("OneTimePreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicSignedPreKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("SignedPreKeySignature") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserCryptoSessionId") + .IsUnique(); + + b.ToTable("SignedPreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountIdentityKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AccountSignature") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Generation") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("PreviousFingerprint") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PublicIdentityKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.ToTable("UserCryptoSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedOn") + .HasColumnType("date"); + + b.Property("CredentialVersion") + .IsConcurrencyToken() + .HasColumnType("bigint"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IconId") + .HasColumnType("uuid"); + + b.Property("InviteId") + .HasColumnType("uuid"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("SrpIdentity") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpSalt") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpVerifier") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("WasOnline") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatedOn"); + + b.HasIndex("InviteId"); + + b.HasIndex("Username") + .IsUnique(); + + b.HasIndex("WasOnline"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserPushToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.HasIndex("UserId", "IsActive"); + + b.ToTable("UserPushTokens"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceInfo") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("RefreshTokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RefreshTokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("UserSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "Addressee") + .WithMany("ReceivedFriendRequests") + .HasForeignKey("AddresseeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "Requester") + .WithMany("SentFriendRequests") + .HasForeignKey("RequesterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Addressee"); + + b.Navigation("Requester"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Admins") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("InviteCodes") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "UserMaker") + .WithMany() + .HasForeignKey("UserMakerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserMaker"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", "ChatGroup") + .WithMany("Members") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.GroupInvitation", null) + .WithMany() + .HasForeignKey("InvitationId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ChatGroup"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany() + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("MediaAttachments") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MediaFile"); + + b.Navigation("Message"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Messages") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.PrivateChat", null) + .WithMany("Messages") + .HasForeignKey("PrivateChatId"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("Reactions") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Message"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany("MessageViews") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", null) + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", "Pack") + .WithMany("Reactions") + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Pack"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", null) + .WithMany() + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("RequiredChannelId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Admin", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithMany("OneTimePreKeys") + .HasForeignKey("UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithOne("SignedPreKey") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.SignedPreKey", "UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.HasOne("Govor.Domain.Models.Users.UserSession", "UserSession") + .WithOne("CryptoSession") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.HasOne("Govor.Domain.Models.Invitation", "Invite") + .WithMany("Users") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invite"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Navigation("Admins"); + + b.Navigation("InviteCodes"); + + b.Navigation("Members"); + + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Navigation("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Navigation("MediaAttachments"); + + b.Navigation("MessageViews"); + + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Navigation("OneTimePreKeys"); + + b.Navigation("SignedPreKey") + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Navigation("ReceivedFriendRequests"); + + b.Navigation("SentFriendRequests"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Navigation("CryptoSession") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.cs b/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.cs new file mode 100644 index 0000000..225de29 --- /dev/null +++ b/Govor.Domain/Migrations/20261024114709_PreserveResetSigners.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + /// + public partial class PreserveResetSigners : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PreviousDeviceKeyJson", + table: "E2eeIdentityChanges", + type: "character varying(10000)", + maxLength: 10000, + nullable: true); + + migrationBuilder.AddColumn( + name: "PreviousSessionId", + table: "E2eeIdentityChanges", + type: "uuid", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PreviousDeviceKeyJson", + table: "E2eeIdentityChanges"); + + migrationBuilder.DropColumn( + name: "PreviousSessionId", + table: "E2eeIdentityChanges"); + } + } +} diff --git a/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs b/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs index f7f51db..438fff6 100644 --- a/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs +++ b/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs @@ -797,6 +797,39 @@ namespace Govor.Domain.Migrations b.ToTable("Admins"); }); + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Epoch") + .HasColumnType("bigint"); + + b.Property("ChangedAt") + .HasColumnType("bigint"); + + b.Property("IdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PreviousDeviceKeyJson") + .HasMaxLength(10000) + .HasColumnType("character varying(10000)"); + + b.Property("PreviousIdentityKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PreviousSessionId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "Epoch"); + + b.ToTable("E2eeIdentityChanges"); + }); + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => { b.Property("UserId") @@ -807,11 +840,25 @@ namespace Govor.Domain.Migrations .HasMaxLength(4000000) .HasColumnType("character varying(4000000)"); + b.Property("Epoch") + .HasColumnType("bigint"); + b.Property("IdentityKey") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); + b.Property("PasswordCiphertext") + .HasMaxLength(4096) + .HasColumnType("character varying(4096)"); + + b.Property("PasswordCredentialVersion") + .HasColumnType("bigint"); + + b.Property("PasswordSignature") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + b.Property("Revision") .IsConcurrencyToken() .HasColumnType("bigint"); @@ -927,6 +974,10 @@ namespace Govor.Domain.Migrations b.Property("CreatedOn") .HasColumnType("date"); + b.Property("CredentialVersion") + .IsConcurrencyToken() + .HasColumnType("bigint"); + b.Property("Description") .HasMaxLength(500) .HasColumnType("character varying(500)"); @@ -942,6 +993,18 @@ namespace Govor.Domain.Migrations .HasMaxLength(128) .HasColumnType("character varying(128)"); + b.Property("SrpIdentity") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpSalt") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SrpVerifier") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + b.Property("Username") .IsRequired() .HasMaxLength(50) @@ -1279,6 +1342,15 @@ namespace Govor.Domain.Migrations b.Navigation("User"); }); + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b => { b.HasOne("Govor.Domain.Models.Users.User", null) diff --git a/Govor.Domain/Models/Users/Crypto/E2eeIdentityChange.cs b/Govor.Domain/Models/Users/Crypto/E2eeIdentityChange.cs new file mode 100644 index 0000000..4529b62 --- /dev/null +++ b/Govor.Domain/Models/Users/Crypto/E2eeIdentityChange.cs @@ -0,0 +1,12 @@ +namespace Govor.Domain.Models.Users.Crypto; + +public sealed class E2eeIdentityChange +{ + public Guid UserId { get; set; } + public long Epoch { get; set; } + public string PreviousIdentityKey { get; set; } = ""; + public string IdentityKey { get; set; } = ""; + public long ChangedAt { get; set; } + public Guid? PreviousSessionId { get; set; } + public string? PreviousDeviceKeyJson { get; set; } +} diff --git a/Govor.Domain/Models/Users/Crypto/E2eeRecoveryVault.cs b/Govor.Domain/Models/Users/Crypto/E2eeRecoveryVault.cs index 7614467..c9ffe5a 100644 --- a/Govor.Domain/Models/Users/Crypto/E2eeRecoveryVault.cs +++ b/Govor.Domain/Models/Users/Crypto/E2eeRecoveryVault.cs @@ -7,4 +7,8 @@ public sealed class E2eeRecoveryVault public string IdentityKey { get; set; } = ""; public string Ciphertext { get; set; } = ""; public string Signature { get; set; } = ""; + public long Epoch { get; set; } + public long PasswordCredentialVersion { get; set; } + public string? PasswordCiphertext { get; set; } + public string? PasswordSignature { get; set; } } diff --git a/Govor.Domain/Models/Users/User.cs b/Govor.Domain/Models/Users/User.cs index acb595a..77a9e00 100644 --- a/Govor.Domain/Models/Users/User.cs +++ b/Govor.Domain/Models/Users/User.cs @@ -8,6 +8,10 @@ public class User public string Username {get; set;} public string Description {get; set;} public string PasswordHash {get; set;} + public string? SrpSalt { get; set; } + public string? SrpIdentity { get; set; } + public string? SrpVerifier { get; set; } + public long CredentialVersion { get; set; } public Guid IconId {get; set;} public DateOnly CreatedOn {get; set;} public DateTime WasOnline {get; set;} @@ -22,4 +26,4 @@ public class User return Id == user.Id; } -} \ No newline at end of file +} diff --git a/docs/e2ee.md b/docs/e2ee.md index d51f91e..c8cefab 100644 --- a/docs/e2ee.md +++ b/docs/e2ee.md @@ -5,11 +5,12 @@ После входа актуальный клиент автоматически создаёт ключи, публикует только публичные данные и регистрирует устройство. После добавления друга или вступления в группу сообщения и файлы шифруются без диалогов сверки ключей или состава чата. -На новом физическом устройстве нужно один раз ввести код с доверенного устройства -(Настройки → Перенос истории / резервный код) либо сохранённый резервный код. -После этого клиент скачивает зашифрованный архив и расшифровывает прежние сообщения -и ключи вложений. Передача кода выполняется пользователем между своими устройствами; -отдельного протокола QR-сопряжения или удалённого одобрения устройства пока нет. +На новом физическом устройстве обычный вход восстанавливает историю по паролю, +если парольная копия ключа уже настроена. Для прежнего архива без такой копии +нужен код с доверенного устройства (Настройки → Перенос истории / резервный код) +либо сохранённый резервный код. После восстановления копия настраивается автоматически. +Подробные сценарии входа, смены/сброса пароля и команды запуска описаны в +[password-recovery.md](password-recovery.md). QR-сопряжения пока нет. Это расширение существующего протокола JOSE, **не реализация Signal/MLS**. Ротация ограничивает использование отдельного украденного ключа шифрования после @@ -31,8 +32,9 @@ forward secrecy или post-compromise security. Восстанавливаем MAUI SecureStorage хранит приватные ключи устройств, резервный код, ключ аккаунта, архив ключей расшифровки и отпечатки известных аккаунтов. Область хранения разделена -по адресу сервера и пользователю. Пароль аккаунта сам по себе не восстанавливает -историю. При потере всех устройств и резервного кода восстановление невозможно. +по адресу сервера и пользователю. Производный парольный ключ открывает отдельную +зашифрованную копию резервного кода. Потеря прежнего пароля, всех устройств и кода +делает старую историю невосстановимой; явный сброс позволяет начать с новыми ключами. Сервер хранит публичные ключи, сертификаты, номера поколений и зашифрованный архив. В архив входят приватный ключ аккаунта, прежние RSA-ключи расшифровки с публичными @@ -46,8 +48,9 @@ MAUI SecureStorage хранит приватные ключи устройств связывает UserId, SessionId, отпечаток устройства, поколение и предыдущий отпечаток с этим ключом аккаунта. Новое устройство или ротация с тем же ключом аккаунта не требуют ручной сверки. Подмена уже известного ключа аккаунта блокирует отправку -и отображение новых неподтверждённых данных. Автоматического сброса доверия нет; -безопасный UX намеренной замены ключа аккаунта — отдельная будущая функция. +и отображение новых неподтверждённых данных. Явный сброс после потери доступа +публикует серверный журнал замены корневого ключа; клиент уведомляет собеседника +при первом использовании нового ключа. Журнал является частью доверия серверу. **Первая встреча доверяет каталогу сервера.** Прозрачности ключей нет. Состав группы и право вступления по-прежнему сообщает сервер; состав не подписывается участниками. @@ -80,8 +83,8 @@ MAUI SecureStorage хранит приватные ключи устройств Отзыв сессии исключает её из новых получателей, но не отзывает уже прочитанное, украденные секреты или ранее выгруженный архив. Резервный код и ключ аккаунта пока не ротируются автоматически. После компрометации всего устройства недостаточно -обычной недельной ротации RSA; это требует отдельной процедуры восстановления -доверия, отзыва сессий и замены секретов аккаунта. +обычной недельной ротации RSA; в настройках есть отдельный явный сброс ключей +аккаунта и кода с отзывом остальных сессий. Он не отменяет уже раскрытые данные. ## Архив и несколько устройств @@ -91,7 +94,8 @@ IdentityKey и шифротекст. Внутри JWE также проверя Обновление использует compare-and-swap по Revision. При конфликте клиент скачивает актуальную версию, объединяет ключи и известные аккаунты, затем повторяет запись -(не более четырёх попыток). Ключ аккаунта на сервере неизменяем. Известная локально +(не более четырёх попыток). Обычный маршрут архива не меняет ключ аккаунта; +для этого требуется отдельный сброс со свежим доказательством пароля. Известная локально версия запрещает откат архива; новое устройство без сохранённого номера версии не способно доказать полноту истории при сокрытии последнего архива сервером. Обычная синхронизация выполняется не чаще раза в минуту, а регистрация нового @@ -122,12 +126,15 @@ IdentityKey и шифротекст. Внутри JWE также проверя ## Обновление существующих установок -1. Применить миграцию `20261024084524_E2eeRecoveryAndRotation` до обновления клиентов. +1. Применить миграции `20261024084524_E2eeRecoveryAndRotation` и + `20261024105815_PasswordBasedRecovery`, `20261024114709_PreserveResetSigners` + до обновления клиентов. Сервер и клиенты должны обновляться согласованно. Старые клиенты не умеют сертифицировать устройства аккаунта с настроенным восстановлением. 2. Открыть обновлённый клиент на устройстве, где ещё есть прежние ключи. Они входят в архив до публикации нового ключа; сохранить предложенный резервный код. -3. На остальных устройствах ввести этот код и синхронизировать историю. Каждое +3. Выполнить обновлённый вход на устройстве с ключами для создания парольной копии. + На остальных устройствах войти по паролю; пока копии нет, нужен прежний код. Каждое старое устройство с уникальными, ещё не выгруженными ключами должно обновиться хотя бы один раз: отсутствующие приватные ключи сервер восстановить не может. 4. Перед использованием с реальными данными проверить новый вход, восстановление, diff --git a/docs/password-recovery.md b/docs/password-recovery.md new file mode 100644 index 0000000..c63ca17 --- /dev/null +++ b/docs/password-recovery.md @@ -0,0 +1,147 @@ +# Вход по паролю и восстановление E2EE + +## Пользовательские сценарии + +Регистрация остаётся на экране регистрации и использует единственный +`POST /api/auth/register` в `AuthController`. Отдельного контроллера регистрации нет. +Новый клиент передаёт SRP salt/identity/verifier вместо открытого пароля. +Существующие проверки имени, приглашения и обязательного канала сохранены. + +После настройки парольной копии ключа обычный вход на новом устройстве восстанавливает +зашифрованный архив истории автоматически. Пароль не хранится и не передаётся серверу +новым методом входа. Локально в SecureStorage сохраняется производный ключ архива. +Резервный код остаётся дополнительным способом переноса и восстановления. + +В настройках доступны: + +- **Сменить пароль с сохранением истории**: подтверждение прежнего пароля, новый + пароль с повтором, перешифрование копии кода; ключ аккаунта и история сохраняются. + Другие сессии и их push-токены отзываются. +- **Начать общение с новыми ключами**: подтверждение потери истории и текущего пароля; + создаются новый ключ аккаунта, код и ключи устройства, другие сессии отзываются. + Собеседник получает уведомление при первой обработке нового ключа. Сверять ключи + вручную не нужно. Необъявленная подмена закреплённого ключа по-прежнему блокируется. + +Если забыт пароль, администратор может сбросить доступ к аккаунту, но этим не +расшифровывает старую историю. После входа с выданным паролем пользователь задаёт +новый пароль и восстанавливает прежний архив резервным кодом/с доверенного устройства. +Без прежнего пароля, кода и доступного устройства старую историю восстановить нельзя; +можно явно начать общение с новыми ключами. Уже полученная собеседниками история +современных сертифицированных сообщений у них сохраняется. + +## Переход со старого входа + +Старый bcrypt-аккаунт один раз требует выбрать **другой** пароль. Только в этой +явной процедуре старый пароль проверяется прежним серверным методом; новый пароль +в сеть не отправляется. Сервер проверяет различие паролей, а не только UI. +Если на сервере уже был архив без парольной копии, для первого восстановления +всё ещё нужен прежний код либо устройство с ключами. Неизвестные секреты сервер +не может создать задним числом. Старая refresh-сессия без нового входа также не +имеет производного парольного ключа. + +Клиент запоминает успешный SRP-вход для адреса сервера и имени. Если сервер позже +предлагает старый вход, автоматической отправки пароля не происходит. На экране +появляется действие «Продолжить после сброса пароля» только после такой ошибки. +Обычная ссылка «Зарегистрируйтесь!» остаётся на месте. Первый вход с чистого +устройства всё ещё доверяет настоящему серверу и HTTPS, включая предложение миграции. + +## Протокол и хранение + +Используется SRP-6a из `srp` 1.0.7 / srp.net, группа 4096 бит и SHA-512. +Это не OPAQUE и не независимо проверенная реализация всего прикладного протокола. +PBKDF2-SHA256 (600 000 итераций, случайная соль 32 байта) и отдельные контексты +HKDF-SHA256 дают секрет аутентификации и ключ парольной копии. Они не совпадают; +восстановление не использует общий сеансовый SRP-ключ. + +Случайный резервный код шифрует основной архив. Парольный ключ шифрует копию кода +в JWE dir/A256GCM. Подпись ключа аккаунта связывает её с владельцем, текущими SRP +параметрами и версией учётных данных. Изменение пароля атомарно меняет verifier +и эту копию. Сброс забытого пароля очищает парольную копию, сохраняя основной архив. +В БД нет открытого пароля, кода или приватного ключа аккаунта. Однако кража БД +позволяет подбирать слабые пароли офлайн; восстановление по паролю зависит от +его стойкости. Получив пароль и архив, атакующий получает доступ к истории. + +Challenge и подтверждения действий одноразовые, действуют две минуты; подтверждения +смены пароля/сброса связаны с пользователем, сессией и назначением. Изменение версии +учётных данных инвалидирует начатые доказательства. На клиенте журналы смены пароля +и сброса ключей позволяют проверить серверный результат после потери ответа до +замены локальных секретов. Старый пароль при нормальном входе не отправляется. + +Замена ключа аккаунта публикуется в журнале `E2eeIdentityChanges` с последовательным +epoch. Журнал доступен самому аккаунту и собеседникам с доступом к переписке; +участник группы может проверить автора сохранённых сообщений после его выхода. +Сервер авторизует сброс по свежему доказательству пароля, а не по подписи утраченного +ключа. Это явная часть доверия серверу, не криптографическое доказательство +непрерывности старого ключа. Исторические сертифицированные сообщения до сброса +принимаются без отката текущего закреплённого ключа. + +Публичный сертификат прежнего ключа текущей сессии сохраняется отдельно в журнале +сброса: он нужен для проверки v1-сообщений, в которых ещё нет сертификата внутри. +Запрос исторического автора принимает `identityKey` и проверяет доступ к чату; +архивный сертификат не становится получателем новых сообщений и не возобновляет сессию. + +Хранилище challenge пока находится в памяти процесса (лимит 1024). Для нескольких +экземпляров нужны маршрутизация всего обмена на один экземпляр либо распределённое +одноразовое хранилище. Лимит регистрации, входа и доказательств действий — +30 запросов/минуту на RemoteIpAddress; фоновое чтение парольной копии в него не входит. +За reverse proxy необходимо настроить доверенные forwarded headers и подходящие +лимиты. HTTPS обязателен. Криптографический аудит и нагрузочная проверка нужны +перед публичным выпуском. Ограничения FS/PCS и доверия группам из [e2ee.md](e2ee.md) +сохраняются; парольное восстановление их не устраняет. + +## API + +Все маршруты находятся в `AuthController`. Регистрация и challenge/login анонимные; +остальные требуют access token и определяют владельца из JWT. + +| Метод | Маршрут | Назначение | +| --- | --- | --- | +| POST | /api/auth/register | Единая регистрация: SRP либо совместимый старый формат | +| POST | /api/auth/password/challenge | Начать вход | +| POST | /api/auth/password/login | Проверить доказательство; токены и серверное доказательство | +| GET | /api/auth/password | Собственные параметры и зашифрованная копия кода | +| PUT | /api/auth/password/enrollment | Однократное обновление старого входа | +| PUT | /api/auth/password/recovery | Создать подписанную парольную копию кода | +| POST | /api/auth/password/{change\|reset}/challenge | Начать подтверждение действия | +| POST | /api/auth/password/{change\|reset}/authorize | Получить одноразовое разрешение | +| POST | /api/auth/password/change | Атомарная смена пароля с сохранением архива | +| POST | /api/auth/password/reset-encryption | Явный сброс ключей, новый архив и запись журнала | +| GET | /api/e2ee/identities/{userId}/changes | История смены ключа доступного собеседника | + +## Локальная проверка + +Из корня серверного репозитория, с запущенной отдельной локальной PostgreSQL +и созданной БД `govor_dev` (подставьте собственные реквизиты): + +```powershell +$env:ASPNETCORE_ENVIRONMENT = 'Development' +$env:ConnectionStrings__GovorDbContext = 'Host=127.0.0.1;Port=5432;Database=govor_dev;Username=postgres;Password=YOUR_LOCAL_PASSWORD' +$env:Firebase__Enabled = 'false' +dotnet restore Govor.API/Govor.API.csproj +dotnet run --project Govor.API/Govor.API.csproj --no-launch-profile -- --migrate-only +dotnet run --project Govor.API/Govor.API.csproj --launch-profile http +``` + +Первый `run` применяет все миграции и завершается; второй запускает API на +`http://localhost:7155`. HTTP предназначен для локальной проверки. Для проверки +на устройстве настройте доступный устройству адрес и HTTPS. +Новые миграции — `20261024105815_PasswordBasedRecovery` и +`20261024114709_PreserveResetSigners`, после `20261024084524_E2eeRecoveryAndRotation`. +Пользовательская БД агентом не обновлялась. + +Проверить регистрацию, повторный вход с чистым SecureStorage без ввода кода, +смену пароля и вход новым паролем, восстановление кодом после административного +сброса, явный сброс ключей и уведомление на втором аккаунте. Отдельно проверить +потерю ответа при смене пароля/сбросе и повторный запуск клиента. + +```powershell +dotnet test Govor.Server.slnx +# Из корня мобильного репозитория: +dotnet test Govor.Mobile.Tests/Govor.Mobile.Tests.csproj +dotnet build Govor.Mobile/Govor.Mobile.csproj -f net10.0-android -p:TargetFrameworks=net10.0-android +``` + +Общие `PasswordProtocol` и `E2eeRecoveryProtocol` в двух репозиториях должны +совпадать за исключением namespace. Источники SRP: +[srp.net](https://github.com/secure-remote-password/srp.net), +[пакет srp](https://www.nuget.org/packages/srp/1.0.7). diff --git a/tests/Govor.Server.Tests/Api/PasswordAuthHttpTests.cs b/tests/Govor.Server.Tests/Api/PasswordAuthHttpTests.cs new file mode 100644 index 0000000..6fde773 --- /dev/null +++ b/tests/Govor.Server.Tests/Api/PasswordAuthHttpTests.cs @@ -0,0 +1,107 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Govor.Application.Authentication; +using Microsoft.EntityFrameworkCore; + +namespace Govor.Server.Tests; + +public partial class ReadApiTests +{ + [Test] + public async Task PasswordAttemptsAreRateLimitedWithoutThrottlingBackgroundRecoveryReads() + { + var created = PasswordProtocol.Create("http-rate-limit-password"); + var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Bob); + user.SrpSalt = created.Credentials.Salt; user.SrpIdentity = created.Credentials.Identity; + user.SrpVerifier = created.Credentials.Verifier; user.CredentialVersion = 1; + await _db.Context.SaveChangesAsync(); + Authorize(); + for (var attempt = 0; attempt < 31; attempt++) + { + using var read = await _client.GetAsync("/api/auth/password"); + Assert.That(read.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + } + _client.DefaultRequestHeaders.Authorization = null; + for (var attempt = 0; attempt < 31; attempt++) + { + using var proof = await _client.PostAsJsonAsync("/api/auth/password/challenge", + new PasswordChallengeRequest(user.Username, new string('0', 1024))); + Assert.That(proof.StatusCode, Is.EqualTo(attempt == 30 ? HttpStatusCode.TooManyRequests : HttpStatusCode.BadRequest)); + } + } + + [Test] + public async Task SingleRegistrationRouteAcceptsSrpAndReturnsTokensForProtectedPasswordConfiguration() + { + Assert.That((await _client.GetAsync("/api/auth/password")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + var created = PasswordProtocol.Create("http-registration-password"); + var invitation = await _db.Context.Invitations.SingleAsync(i => i.Code == "test"); + invitation.Code = Guid.NewGuid().ToString("N"); + await _db.Context.SaveChangesAsync(); + object Request(string? password = null) => new { name = "НовыйУчастник456", inviteLink = invitation.Code, + deviceInfo = "HTTP phone", srpSalt = created.Credentials.Salt, srpIdentity = created.Credentials.Identity, + srpVerifier = created.Credentials.Verifier, password }; + Assert.That((await _client.PostAsJsonAsync("/api/auth/register", Request("plaintext-password"))).StatusCode, + Is.EqualTo(HttpStatusCode.BadRequest)); + var registered = await _client.PostAsJsonAsync("/api/auth/register", Request()); + Assert.That(registered.StatusCode, Is.EqualTo(HttpStatusCode.OK), await registered.Content.ReadAsStringAsync()); + using var tokens = JsonDocument.Parse(await registered.Content.ReadAsStringAsync()); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens.RootElement.GetProperty("accessToken").GetString()); + var configResponse = await _client.GetAsync("/api/auth/password"); + Assert.That(configResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK), await configResponse.Content.ReadAsStringAsync()); + Assert.That(configResponse.Headers.CacheControl?.NoStore, Is.True); + var config = (await configResponse.Content.ReadFromJsonAsync())!; + Assert.That(config.Credentials, Is.EqualTo(created.Credentials)); + Assert.That(config.Envelope, Is.Null); + var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Username == "НовыйУчастник456"); + Assert.That(user.PasswordHash, Is.EqualTo("srp-only")); + Assert.That(user.CredentialVersion, Is.EqualTo(1)); + Assert.That((await _client.PostAsJsonAsync("/api/auth/login", new { name = user.Username, + password = "http-registration-password", deviceInfo = "legacy" })).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + [Test] + public async Task HttpPasswordProofOpensSessionAndChangeRoutesConsumeSessionBoundAuthorization() + { + const string password = "http-password-proof"; + var created = PasswordProtocol.Create(password); + var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Bob); + user.PasswordHash = "srp-only"; user.SrpSalt = created.Credentials.Salt; + user.SrpIdentity = created.Credentials.Identity; user.SrpVerifier = created.Credentials.Verifier; + user.CredentialVersion = 1; await _db.Context.SaveChangesAsync(); + + async Task<(PasswordProof Proof, SecureRemotePassword.SrpClient Client, string Public, SecureRemotePassword.SrpSession Session)> Prove(string purpose) + { + var client = PasswordProtocol.Client(); var ephemeral = client.GenerateEphemeral(); + var route = purpose == "login" ? "challenge" : $"{purpose}/challenge"; + var response = await _client.PostAsJsonAsync("/api/auth/password/" + route, new PasswordChallengeRequest(user.Username, ephemeral.Public, "test phone")); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), await response.Content.ReadAsStringAsync()); + var challenge = (await response.Content.ReadFromJsonAsync())!; + var derived = PasswordProtocol.Derive(password, challenge.Salt, challenge.Identity); + var session = client.DeriveSession(ephemeral.Secret, challenge.PublicEphemeral, challenge.Salt, challenge.Identity, + client.DerivePrivateKey(challenge.Salt, challenge.Identity, derived.Secret)); + return (new(challenge.ChallengeId, session.Proof), client, ephemeral.Public, session); + } + var login = await Prove("login"); + var response = await _client.PostAsJsonAsync("/api/auth/password/login", login.Proof); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), await response.Content.ReadAsStringAsync()); + var authenticated = (await response.Content.ReadFromJsonAsync())!; + login.Client.VerifySession(login.Public, login.Session, authenticated.ServerProof); + Assert.That((await _client.PostAsJsonAsync("/api/auth/password/login", login.Proof)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticated.AccessToken); + var action = await Prove("change"); + var grantResponse = await _client.PostAsJsonAsync("/api/auth/password/change/authorize", action.Proof); + Assert.That(grantResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK), await grantResponse.Content.ReadAsStringAsync()); + var grant = (await grantResponse.Content.ReadFromJsonAsync())!; + action.Client.VerifySession(action.Public, action.Session, grant.ServerProof); + var staleLogin = await Prove("login"); + var replacement = PasswordProtocol.Create("http-replacement-password"); + var request = new ChangePasswordRequest(grant.AuthorizationId, replacement.Credentials, null); + Assert.That((await _client.PostAsJsonAsync("/api/auth/password/change", request)).StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That((await _client.PostAsJsonAsync("/api/auth/password/change", request)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + Assert.That((await _client.PostAsJsonAsync("/api/auth/password/login", staleLogin.Proof)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + Assert.That((await _client.GetAsync("/api/auth/password")).StatusCode, Is.EqualTo(HttpStatusCode.OK)); + } +} diff --git a/tests/Govor.Server.Tests/Security/PasswordRecoveryTests.cs b/tests/Govor.Server.Tests/Security/PasswordRecoveryTests.cs new file mode 100644 index 0000000..178f08d --- /dev/null +++ b/tests/Govor.Server.Tests/Security/PasswordRecoveryTests.cs @@ -0,0 +1,223 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Govor.Application.Authentication; +using Govor.Application.E2ee; +using Govor.Application.Infrastructure.AdminsStuff; +using Govor.Domain.Models.Users; +using Microsoft.EntityFrameworkCore; +using SecureRemotePassword; + +namespace Govor.Server.Tests; + +[TestFixture] +public class PasswordRecoveryTests +{ + private const string Password = "correct-horse-2026"; + private TestDatabase _db = null!; + private PasswordAccountService _service = null!; + private PasswordChallenges _challenges = null!; + private PasswordCredentials _credentials = null!; + private string _archiveKey = null!, _root = null!, _code = null!, _name = null!; + private UserSession _session = null!; + [OneTimeSetUp] + public void Keys() + { + (_credentials, _archiveKey) = PasswordProtocol.Create(Password); + _root = E2eeRecoveryProtocol.GenerateIdentity(); _code = E2eeRecoveryProtocol.GenerateCode(); + } + [SetUp] + public async Task Setup() + { + _db = new(); _challenges = new(); _service = new(_db.Context, _challenges, new PasswordHasher()); + var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Alice); + user.SrpSalt = _credentials.Salt; user.SrpIdentity = _credentials.Identity; user.SrpVerifier = _credentials.Verifier; + user.PasswordHash = "srp-only"; user.CredentialVersion = 1; _name = user.Username; + _session = new() { UserId = user.Id, ExpiresAt = DateTime.UtcNow.AddDays(2), RefreshTokenHash = Guid.NewGuid().ToString() }; + _db.Context.UserSessions.Add(_session); + await _db.Context.SaveChangesAsync(); + var vault = E2eeRecoveryProtocol.Seal(user.Id, 1, _root, _code, "archived private keys"); + await new E2eeService(_db.Context).SaveRecoveryAsync(user.Id, new(0, vault.IdentityKey, vault.Ciphertext, vault.Signature)); + await _service.SaveEnvelopeAsync(user.Id, PasswordProtocol.Seal(user.Id, 1, _credentials, _root, _code, _archiveKey)); + } + [TearDown] public void Cleanup() => _db.Dispose(); + + private async Task<(PasswordProof Proof, SrpClient Client, string Public, SrpSession Session)> Proof(string action = "login", string password = Password) + { + var client = PasswordProtocol.Client(); var ephemeral = client.GenerateEphemeral(); + var challenge = await _service.StartAsync(new(_name, ephemeral.Public, "test device"), action, + action == "login" ? null : _db.Alice, action == "login" ? null : _session.Id); + var derived = PasswordProtocol.Derive(password, challenge.Salt, challenge.Identity); + var session = client.DeriveSession(ephemeral.Secret, challenge.PublicEphemeral, challenge.Salt, challenge.Identity, + client.DerivePrivateKey(challenge.Salt, challenge.Identity, derived.Secret)); + return (new(challenge.ChallengeId, session.Proof), client, ephemeral.Public, session); + } + private async Task Grant(string action) + { + var proof = await Proof(action); + var result = await _service.AuthorizeAsync(_db.Alice, _session.Id, proof.Proof, action); + proof.Client.VerifySession(proof.Public, proof.Session, result.ServerProof); + return result.AuthorizationId; + } + + [Test] + public async Task PasswordIsProvedWithoutBeingSentAndArchiveKeyIsIndependentOfSessionKey() + { + var proof = await Proof(); + var verified = await _service.VerifyAsync(proof.Proof); + proof.Client.VerifySession(proof.Public, proof.Session, verified.ServerProof); + Assert.That(verified.User.Id, Is.EqualTo(_db.Alice)); + Assert.That(JsonSerializer.Serialize(proof.Proof), Does.Not.Contain(Password).And.Not.Contain(_archiveKey)); + var config = await _service.GetAsync(_db.Alice); + Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(_code)); + Assert.Catch(() => PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, + Jose.Base64Url.Encode(SHA256.HashData(Convert.FromHexString(proof.Session.Key))))); + Assert.ThrowsAsync(() => _service.VerifyAsync(proof.Proof)); + } + + [Test] + public async Task IncorrectPasswordAndCrossPurposeProofAreRejected() + { + var wrong = await Proof(password: "incorrect-password"); + Assert.ThrowsAsync(() => _service.VerifyAsync(wrong.Proof)); + var action = await Proof("reset"); + Assert.ThrowsAsync(() => _service.VerifyAsync(action.Proof)); + var other = await Proof("change"); + Assert.ThrowsAsync(() => _service.AuthorizeAsync(_db.Bob, _session.Id, other.Proof, "change")); + } + + [Test] + public async Task UnknownAccountReceivesAProofChallengeRatherThanALegacyPasswordRequest() + { + var challenge = await _service.StartAsync(new("not-an-account", PasswordProtocol.Client().GenerateEphemeral().Public)); + Assert.That(challenge.Legacy, Is.False); + Assert.That(challenge.PublicEphemeral, Has.Length.EqualTo(1024)); + Assert.ThrowsAsync(() => _service.VerifyAsync(new(challenge.ChallengeId, new string('0', 128)))); + Assert.ThrowsAsync(() => _service.StartAsync(new(_name, new string('0', 1024)))); + } + + [Test] + public async Task KnownPasswordChangeRewrapsSameArchiveAndRevokesOtherSessions() + { + var other = new UserSession { UserId = _db.Alice, ExpiresAt = DateTime.UtcNow.AddDays(1), RefreshTokenHash = "another-session" }; + _db.Context.UserSessions.Add(other); await _db.Context.SaveChangesAsync(); + var replacement = PasswordProtocol.Create("replacement-password-2026"); + var envelope = PasswordProtocol.Seal(_db.Alice, 2, replacement.Credentials, _root, _code, replacement.ArchiveKey); + var grant = await Grant("change"); + await _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, envelope)); + var config = await _service.GetAsync(_db.Alice); + Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, replacement.ArchiveKey), Is.EqualTo(_code)); + Assert.That((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!.IdentityKey, Is.EqualTo(E2eeRecoveryProtocol.PublicIdentity(_root))); + Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == other.Id)).IsRevoked, Is.True); + Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == _session.Id)).IsRevoked, Is.False); + var old = await Proof(); Assert.ThrowsAsync(() => _service.VerifyAsync(old.Proof)); + var updated = await Proof(password: "replacement-password-2026"); await _service.VerifyAsync(updated.Proof); + Assert.ThrowsAsync(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, envelope))); + } + + [Test] + public async Task InvalidPasswordChangeRollsBackCredentialsAndPreservesHistory() + { + var replacement = PasswordProtocol.Create("replacement-password-2026"); + var grant = await Grant("change"); + Assert.ThrowsAsync(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, null))); + var config = await _service.GetAsync(_db.Alice); + Assert.That(config.CredentialVersion, Is.EqualTo(1)); + Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(_code)); + } + + [Test] + public async Task ForgottenPasswordResetDoesNotReencryptHistoryWithTheAdministratorsNewPassword() + { + await new UsersService(_db.Context, new PasswordHasher()).SetPasswordAsync(_db.Alice, "administrator-reset-password"); + var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Id == _db.Alice); + var vault = await _db.Context.E2eeRecoveryVaults.AsNoTracking().SingleAsync(); + Assert.That(user.SrpVerifier, Is.Null); + Assert.That(vault.PasswordCiphertext, Is.Null); + Assert.That(E2eeRecoveryProtocol.Open((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!, _db.Alice, _code), + Is.EqualTo("archived private keys")); + Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == _session.Id)).IsRevoked, Is.True); + } + + [Test] + public async Task ExplicitEncryptionResetPublishesIdentityChangeAndNewPasswordRecoveryEnvelope() + { + var e2ee = new E2eeService(_db.Context); + var formerKeys = E2eeProtocol.GenerateKeys(); + var formerDevice = E2eeRecoveryProtocol.Certify(E2eeProtocol.PublicKey(formerKeys, _db.Alice, _session.Id), _root); + await e2ee.RegisterAsync(_db.Alice, _session.Id, formerDevice); + _db.AddMessage(sender: _db.Alice); + var previous = (await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!; + var newRoot = E2eeRecoveryProtocol.GenerateIdentity(); var newCode = E2eeRecoveryProtocol.GenerateCode(); + var vault = E2eeRecoveryProtocol.Seal(_db.Alice, 2, newRoot, newCode, "new history only"); + var envelope = PasswordProtocol.Seal(_db.Alice, 1, _credentials, newRoot, newCode, _archiveKey); + var grant = await Grant("reset"); + var reset = new ResetEncryptionRequest(grant, previous.IdentityKey, previous.Revision, vault, envelope); + var change = await _service.ResetAsync(_db.Alice, _session.Id, reset); + _db.Context.ChangeTracker.Clear(); // Device enrollment is a subsequent HTTP request with a fresh context. + var newKeys = E2eeProtocol.GenerateKeys(); + await e2ee.RegisterAsync(_db.Alice, _session.Id, + E2eeRecoveryProtocol.Certify(E2eeProtocol.PublicKey(newKeys, _db.Alice, _session.Id), newRoot)); + var historical = await e2ee.GetHistoricalSignerAsync(_db.Bob, _db.ChatId, Govor.Domain.Models.Messages.RecipientType.User, + _session.Id, formerDevice.IdentityKey); + Assert.That(historical, Is.EqualTo(formerDevice)); + Assert.ThrowsAsync(() => e2ee.GetHistoricalSignerAsync(_db.Outsider, _db.ChatId, + Govor.Domain.Models.Messages.RecipientType.User, _session.Id, formerDevice.IdentityKey)); + Assert.That(change.PreviousIdentityKey, Is.EqualTo(previous.IdentityKey)); + Assert.That(change.Epoch, Is.EqualTo(1)); + Assert.That((await new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Bob, _db.Alice)), Has.Length.EqualTo(1)); + Assert.ThrowsAsync(() => new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice)); + var group = new Govor.Domain.Models.ChatGroup { Id = Guid.NewGuid(), Name = "Past author", Description = "" }; + var membership = new Govor.Domain.Models.GroupMembership { GroupId = group.Id, UserId = _db.Outsider, MemberSince = DateTime.UtcNow }; + _db.Context.ChatGroups.Add(group); _db.Context.GroupMemberships.Add(membership); + await _db.Context.SaveChangesAsync(); + _db.AddMessage(sender: _db.Alice, chat: group.Id, type: Govor.Domain.Models.Messages.RecipientType.Group); + Assert.That(await new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice), Has.Length.EqualTo(1)); + membership.IsBanned = true; await _db.Context.SaveChangesAsync(); + Assert.ThrowsAsync(() => new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice)); + var config = await _service.GetAsync(_db.Alice); + Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(newCode)); + var currentVault = (await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!; + Assert.Catch(() => E2eeRecoveryProtocol.Open(currentVault, _db.Alice, _code)); + Assert.ThrowsAsync(() => _service.ResetAsync(_db.Alice, _session.Id, reset)); + } + + [Test] + public async Task StaleEncryptionResetDoesNotReplaceTheExistingIdentity() + { + var root = E2eeRecoveryProtocol.GenerateIdentity(); var code = E2eeRecoveryProtocol.GenerateCode(); + var vault = E2eeRecoveryProtocol.Seal(_db.Alice, 3, root, code, "new history"); + var envelope = PasswordProtocol.Seal(_db.Alice, 1, _credentials, root, code, _archiveKey); + var grant = await Grant("reset"); + Assert.ThrowsAsync(() => _service.ResetAsync(_db.Alice, _session.Id, + new(grant, E2eeRecoveryProtocol.PublicIdentity(_root), 2, vault, envelope))); + Assert.That((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!.IdentityKey, Is.EqualTo(E2eeRecoveryProtocol.PublicIdentity(_root))); + } + + [Test] + public async Task LegacyEnrollmentChecksOldPasswordAndRequiresADifferentReplacement() + { + var account = await _db.Context.Users.SingleAsync(u => u.Id == _db.Alice); + account.SrpSalt = null; account.SrpIdentity = null; account.SrpVerifier = null; + account.PasswordHash = new PasswordHasher().Hash(Password); + await _db.Context.SaveChangesAsync(); + Assert.ThrowsAsync(() => _service.EnrollAsync(_db.Alice, new(_credentials, "wrong-password"))); + Assert.ThrowsAsync(() => _service.EnrollAsync(_db.Alice, new(_credentials, Password))); + var replacement = PasswordProtocol.Create("upgraded-password-2026"); + await _service.EnrollAsync(_db.Alice, new(replacement.Credentials, Password)); + Assert.That((await _service.GetAsync(_db.Alice)).Credentials, Is.EqualTo(replacement.Credentials)); + Assert.ThrowsAsync(() => _service.EnrollAsync(_db.Alice, new(replacement.Credentials, Password))); + } + + [Test] + public async Task ExpiredProofAndExpiredActionGrantCannotBeUsed() + { + var clock = new TestClock(); _challenges = new(clock); _service = new(_db.Context, _challenges, new PasswordHasher()); + var proof = await Proof(); clock.Now = clock.Now.AddMinutes(3); + Assert.ThrowsAsync(() => _service.VerifyAsync(proof.Proof)); + var grant = await Grant("change"); clock.Now = clock.Now.AddMinutes(3); + Assert.ThrowsAsync(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, _credentials, null))); + } + + private sealed class TestClock : TimeProvider + { public DateTimeOffset Now = DateTimeOffset.UtcNow; public override DateTimeOffset GetUtcNow() => Now; } +}