diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs new file mode 100644 index 00000000..601bc915 --- /dev/null +++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs @@ -0,0 +1,599 @@ +using StackExchange.Redis; +using System.Net; +using System.Text.Json; +using Microsoft.AspNetCore.Http.Connections; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; +using OpenShock.Common.Models.WebSocket.User; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.PublicShareAccess; +using OpenShock.Common.Services.Session; + +namespace OpenShock.API.IntegrationTests.Tests; + +public sealed class PublicSharePasswordTests +{ + private const string Password = "hunter22"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- Loading the share --- + + [Test] + public async Task ProtectedShare_HidesShockersUntilUnlocked() + { + var (_, shareId) = await CreateShareWithShocker("pwhide", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var locked = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(locked.GetProperty("passwordProtected").GetBoolean()).IsTrue(); + await Assert.That(locked.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + await Assert.That(locked.GetProperty("devices").GetArrayLength()).IsEqualTo(0); + await Assert.That(locked.GetProperty("name").GetString()).IsEqualTo("pw share"); + + var token = await Unlock(visitor, shareId, Password); + var unlocked = await GetShare(visitor, shareId, token); + await Assert.That(unlocked.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(unlocked.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ProtectedShare_BySlug_NeedsTheTokenToo() + { + var (owner, shareId) = await CreateShareWithShocker("pwslug", Password, slug: "locked"); + using var visitor = WebApplicationFactory.CreateClient(); + + var locked = await GetJson(visitor, $"/1/public/shares/links/by-slug/{owner.Username}/locked", unlockToken: null); + await Assert.That(locked.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + + var token = await Unlock(visitor, shareId, Password); + var unlocked = await GetJson(visitor, $"/1/public/shares/links/by-slug/{owner.Username}/locked", token); + await Assert.That(unlocked.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ProtectedShare_OwnerSeesItWithoutPassword() + { + var (owner, shareId) = await CreateShareWithShocker("pwowner", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var share = await GetShare(ownerClient, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + } + + [Test] + public async Task ShareWithoutPassword_IsOpen() + { + var (_, shareId) = await CreateShareWithShocker("pwnone", password: null); + using var visitor = WebApplicationFactory.CreateClient(); + + var share = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordProtected").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + await Assert.That(share.GetProperty("devices").GetArrayLength()).IsEqualTo(1); + + var unlock = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(unlock.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task OwnList_ShowsWhetherAShareHasAPassword() + { + var (owner, shareId) = await CreateShareWithShocker("pwlist", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var list = await GetJson(ownerClient, "/1/shares/links", unlockToken: null); + var entry = list.EnumerateArray().Single(x => x.GetProperty("id").GetGuid() == shareId); + await Assert.That(entry.GetProperty("hasPassword").GetBoolean()).IsTrue(); + } + + // --- Unlocking --- + + [Test] + public async Task Unlock_WithWrongPassword_Returns401() + { + var (_, shareId) = await CreateShareWithShocker("pwwrong", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = "nope-nope" })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + } + + [Test] + public async Task Unlock_AfterTooManyWrongPasswords_IsLockedOutEvenWithTheRightOne() + { + var (_, shareId) = await CreateShareWithShocker("pwlockout", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts; i++) + { + var wrong = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = "nope-nope" })); + await Assert.That(wrong.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + } + + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + } + + [Test] + public async Task Unlock_ParallelWrongPasswords_NeverGetPastTheLimit() + { + var (_, shareId) = await CreateShareWithShocker("pwparallel", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var responses = await Task.WhenAll(Enumerable.Range(0, PublicShareAccessService.MaxFailedAttempts + 10).Select(_ => + visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" })))); + + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Unauthorized)).IsEqualTo(PublicShareAccessService.MaxFailedAttempts); + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.TooManyRequests)).IsEqualTo(10); + } + + [Test] + public async Task Unlock_WrongPassword_StartsAnExpiringLockoutWindow() + { + var (_, shareId) = await CreateShareWithShocker("pwwindow", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" })); + + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var ttl = await redis.KeyTimeToLiveAsync($"public-share-unlock-failures:{shareId}"); + await Assert.That(ttl).IsNotNull(); + await Assert.That(ttl!.Value).IsLessThanOrEqualTo(PublicShareAccessService.FailedAttemptWindow); + } + + [Test] + public async Task Unlock_CorrectPasswords_DoNotCountTowardsTheLockout() + { + var (_, shareId) = await CreateShareWithShocker("pwnocount", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + for (var i = 0; i <= PublicShareAccessService.MaxFailedAttempts; i++) + { + var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + } + + [Test] + public async Task Unlock_WhitespacePassword_CanBeEntered() + { + const string spaces = " "; + var (_, shareId) = await CreateShareWithShocker("pwspaces", spaces); + using var visitor = WebApplicationFactory.CreateClient(); + + var token = await Unlock(visitor, shareId, spaces); + await Assert.That(token).IsNotEmpty(); + } + + [Test] + public async Task Lockout_RejectedAttempts_AreNotCounted() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var shareId = Guid.NewGuid(); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts - 1; i++) + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + + // The last attempt is a correct password still being checked when another one is rejected. + var inFlight = await access.TryReserveAttemptAsync(shareId); + await Assert.That(inFlight).IsNotNull(); + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNull(); + await access.ReleaseAttemptAsync(shareId, inFlight!); + + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + } + + [Test] + public async Task Lockout_ReleaseFromAnEndedWindow_DoesNotCountAgainstTheNextOne() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var shareId = Guid.NewGuid(); + + var stale = await access.TryReserveAttemptAsync(shareId); + await redis.KeyDeleteAsync($"public-share-unlock-failures:{shareId}"); + + for (var i = 0; i < PublicShareAccessService.MaxFailedAttempts; i++) + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNotNull(); + + await access.ReleaseAttemptAsync(shareId, stale!); + await Assert.That(await access.TryReserveAttemptAsync(shareId)).IsNull(); + } + + [Test] + public async Task Lockout_CorrectPassword_DoesNotStartTheWindow() + { + var access = WebApplicationFactory.Services.GetRequiredService(); + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + var shareId = Guid.NewGuid(); + var key = $"public-share-unlock-failures:{shareId}"; + + var correct = await access.TryReserveAttemptAsync(shareId); + await access.ReleaseAttemptAsync(shareId, correct!); + await Assert.That(await redis.KeyExistsAsync(key)).IsFalse(); + + // The first incorrect password starts a full window. + await access.TryReserveAttemptAsync(shareId); + var ttl = await redis.KeyTimeToLiveAsync(key); + await Assert.That(ttl).IsNotNull(); + await Assert.That(ttl!.Value).IsGreaterThan(PublicShareAccessService.FailedAttemptWindow - TimeSpan.FromMinutes(1)); + } + + [Test] + public async Task Unlock_TokenIsOnlyValidForItsShare() + { + var (_, shareId) = await CreateShareWithShocker("pwscope", Password); + var (_, otherShareId) = await CreateShareWithShocker("pwscopeo", Password); + using var visitor = WebApplicationFactory.CreateClient(); + + var token = await Unlock(visitor, shareId, Password); + var other = await GetShare(visitor, otherShareId, token); + await Assert.That(other.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + } + + // --- Changing the password --- + + [Test] + public async Task ChangingThePassword_InvalidatesEarlierTokens() + { + var (owner, shareId) = await CreateShareWithShocker("pwchange", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + + await SetPassword(owner, shareId, "another-one"); + + var share = await GetShare(visitor, shareId, token); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsTrue(); + + var wrongOld = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(wrongOld.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Unlock(visitor, shareId, "another-one"); + } + + [Test] + public async Task RemovingThePassword_OpensTheShare() + { + var (owner, shareId) = await CreateShareWithShocker("pwremove", Password); + + var updated = await SetPassword(owner, shareId, null); + await Assert.That(updated.GetProperty("hasPassword").GetBoolean()).IsFalse(); + + using var visitor = WebApplicationFactory.CreateClient(); + var share = await GetShare(visitor, shareId, unlockToken: null); + await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse(); + } + + [Test] + public async Task SettingAPassword_ThatIsTooShort_Returns400() + { + var (owner, shareId) = await CreateShareWithShocker("pwshort", password: null); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + + var response = await ownerClient.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password = "abc" })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task SettingThePassword_OfSomeoneElsesShare_Returns404() + { + var (_, shareId) = await CreateShareWithShocker("pwforeign", password: null); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("pwforeigno"), + TestHelper.UniqueEmail("pwforeigno"), "SecurePassword123#"); + using var otherClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); + + var response = await otherClient.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password = Password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + } + + [Test] + public async Task Profile_DefaultShare_SaysWhetherItIsPasswordProtected() + { + var (owner, shareId) = await CreateShareWithShocker("pwprofile", Password); + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var profile = await ownerClient.PutAsync("/1/account/profile", + TestHelper.JsonContent(new + { isPublic = true, socials = Array.Empty(), defaultPublicShareId = shareId })); + await Assert.That(profile.IsSuccessStatusCode).IsTrue(); + + using var visitor = WebApplicationFactory.CreateClient(); + var json = await GetJson(visitor, $"/1/public/users/{owner.Username}", unlockToken: null, unwrapData: false); + await Assert.That(json.GetProperty("defaultPublicShare").GetProperty("passwordProtected").GetBoolean()) + .IsTrue(); + } + + // --- The hub --- + + [Test] + public async Task Hub_WithoutToken_IsRejected() + { + var (_, shareId) = await CreateShareWithShocker("pwhubnone", Password); + + await AssertCannotConnectAsync(shareId, unlockToken: null); + await AssertCannotConnectAsync(shareId, unlockToken: "not-a-real-token-not-a-real-tok"); + + // The same route admits a valid token, so the rejections above came from the password check. + using var visitor = WebApplicationFactory.CreateClient(); + await using var connection = await ConnectAsync(shareId, await Unlock(visitor, shareId, Password)); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_WithToken_ConnectsAndCanCall() + { + var (_, shareId) = await CreateShareWithShocker("pwhubok", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + + await using var connection = await ConnectAsync(shareId, token); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_OwnerConnectsWithoutToken() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubowner", Password); + + await using var connection = await ConnectAsync(shareId, unlockToken: null, sessionToken: owner.SessionToken); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_ChangingThePassword_ClosesOpenConnections() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubchange", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + + await SetPassword(owner, shareId, "another-one"); + + await AssertConnectionClosesAsync(connection); + await AssertCannotConnectAsync(shareId, token); + } + + [Test] + public async Task Hub_SettingAPassword_ClosesGuestsWhoGotInWithout() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubset", password: null); + await using var connection = await ConnectAsync(shareId, unlockToken: null); + + await SetPassword(owner, shareId, Password); + + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_RemovingThePassword_KeepsConnectionsOpen() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubremove", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + + await SetPassword(owner, shareId, null); + + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + await connection.InvokeAsync("Control", Array.Empty()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Hub_DeletingTheShare_ClosesOpenConnections() + { + var (owner, shareId) = await CreateShareWithShocker("pwhubdelete", password: null); + await using var connection = await ConnectAsync(shareId, unlockToken: null); + + using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await ownerClient.DeleteAsync($"/1/shares/links/{shareId}"); + await Assert.That(response.IsSuccessStatusCode).IsTrue(); + + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_PasswordChangedWithoutAnnouncement_ClosesOnTheNextCheck() + { + var (_, shareId) = await CreateShareWithShocker("pwhubfallback", Password); + using var visitor = WebApplicationFactory.CreateClient(); + var token = await Unlock(visitor, shareId, Password); + await using var connection = await ConnectAsync(shareId, token); + // Checked once here, so the call below has to be a re-check. + await connection.InvokeAsync("Control", Array.Empty()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = Guid.CreateVersion7(); + await db.PublicShares.Where(x => x.Id == shareId) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordStamp, stamp)); + } + + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + Exception? failure = null; + try + { + await connection.InvokeAsync("Control", Array.Empty()); + } + catch (Exception ex) + { + failure = ex; + } + + await Assert.That(failure).IsNotNull(); + await AssertConnectionClosesAsync(connection); + } + + [Test] + public async Task Hub_LoggedInVisitor_IsClosedOnLogout() + { + var (_, shareId) = await CreateShareWithShocker("pwhublogout", password: null); + var visitor = await TestHelper.CreateAndLoginUser(WebApplicationFactory, + TestHelper.UniqueUsername("pwhublogoutv"), TestHelper.UniqueEmail("pwhublogoutv"), "SecurePassword123#"); + await using var connection = await ConnectAsync(shareId, unlockToken: null, sessionToken: visitor.SessionToken); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService() + .DeleteSessionByTokenAsync(visitor.SessionToken); + } + + await AssertConnectionClosesAsync(connection); + } + + // --- Helpers --- + + private async Task<(AuthenticatedUser Owner, Guid ShareId)> CreateShareWithShocker(string prefix, + string? password, string? slug = null) + { + var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), + TestHelper.UniqueEmail(prefix), "SecurePassword123#"); + var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "pw hub"); + + var shockerId = Guid.CreateVersion7(); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Shockers.Add(new Shocker + { + Id = shockerId, Name = "pw shocker", RfId = 1234, DeviceId = deviceId, + Model = ShockerModelType.CaiXianlin + }); + await db.SaveChangesAsync(); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var created = await client.PostAsync("/1/shares/links", + TestHelper.JsonContent(new { name = "pw share", password, slug })); + await Assert.That(created.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await created.Content.ReadAsStringAsync()); + var shareId = json.RootElement.GetProperty("data").GetGuid(); + + var added = await client.PostAsync($"/1/shares/links/{shareId}/{shockerId}", null); + await Assert.That(added.StatusCode).IsEqualTo(HttpStatusCode.OK); + + return (owner, shareId); + } + + private Task GetShare(HttpClient client, Guid shareId, string? unlockToken) + => GetJson(client, $"/1/public/shares/links/{shareId}", unlockToken); + + private static async Task GetJson(HttpClient client, string path, string? unlockToken, + bool unwrapData = true) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + if (unlockToken is not null) request.Headers.Add(AuthConstants.PublicShareUnlockHeaderName, unlockToken); + + var response = await client.SendAsync(request); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = unwrapData ? json.RootElement.GetProperty("data") : json.RootElement; + return root.Clone(); + } + + private static async Task Unlock(HttpClient client, Guid shareId, string password) + { + var response = await client.PostAsync($"/1/public/shares/links/{shareId}/unlock", + TestHelper.JsonContent(new { password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("token").GetString()!; + } + + private async Task SetPassword(AuthenticatedUser owner, Guid shareId, string? password) + { + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await client.PutAsync($"/1/shares/links/{shareId}/password", + TestHelper.JsonContent(new { password })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.Clone(); + } + + /// Connects and waits until the hub admitted the connection (it sends Welcome after its checks). + private async Task ConnectAsync(Guid shareId, string? unlockToken, string? sessionToken = null) + { + var (connection, welcomed) = BuildConnection(shareId, unlockToken, sessionToken); + try + { + await connection.StartAsync(); + await welcomed.WaitAsync(TimeSpan.FromSeconds(30)); + return connection; + } + catch + { + await connection.DisposeAsync(); + throw; + } + } + + private (HubConnection Connection, Task Welcomed) BuildConnection(Guid shareId, string? unlockToken, string? sessionToken = null) + { + var server = WebApplicationFactory.Server; + var path = $"/1/hubs/share/link/{shareId}?name=Guest"; + if (unlockToken is not null) path += $"&unlockToken={Uri.EscapeDataString(unlockToken)}"; + + var connection = new HubConnectionBuilder() + .WithUrl(new Uri(server.BaseAddress, path), options => + { + options.Transports = HttpTransportType.WebSockets; + options.SkipNegotiation = true; + options.WebSocketFactory = async (context, cancellationToken) => + { + var client = server.CreateWebSocketClient(); + if (sessionToken is not null) + client.ConfigureRequest = request => + request.Headers.Cookie = $"{AuthConstants.UserSessionCookieName}={sessionToken}"; + return await client.ConnectAsync(context.Uri, cancellationToken); + }; + }) + .Build(); + + var welcomed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + connection.On("Welcome", _ => welcomed.TrySetResult()); + return (connection, welcomed.Task); + } + + /// + /// The handshake succeeds, then the hub rejects the connection in its admission checks: it closes without + /// being welcomed. Any other failure, such as a broken route, fails the test. + /// + private async Task AssertCannotConnectAsync(Guid shareId, string? unlockToken) + { + var (connection, welcomed) = BuildConnection(shareId, unlockToken); + await using (connection) + { + await connection.StartAsync(); + await AssertConnectionClosesAsync(connection); + await Assert.That(welcomed.IsCompleted).IsFalse(); + } + } + + private static async Task AssertConnectionClosesAsync(HubConnection connection) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (connection.State != HubConnectionState.Disconnected && DateTime.UtcNow < deadline) + { + await Task.Delay(50); + } + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Disconnected); + } +} diff --git a/API/Controller/Public/GetUserProfile.cs b/API/Controller/Public/GetUserProfile.cs index 6acd2803..0d88b17f 100644 --- a/API/Controller/Public/GetUserProfile.cs +++ b/API/Controller/Public/GetUserProfile.cs @@ -48,7 +48,8 @@ public async Task GetUserProfile([FromRoute] string username, Can { Id = x.DefaultPublicShare.Id, Name = x.DefaultPublicShare.Name, - Slug = x.DefaultPublicShare.Slug + Slug = x.DefaultPublicShare.Slug, + PasswordProtected = x.DefaultPublicShare.PasswordHash != null } : null }) diff --git a/API/Controller/Public/PublicShareController.cs b/API/Controller/Public/PublicShareController.cs index 6a6a05fa..0b08ee6e 100644 --- a/API/Controller/Public/PublicShareController.cs +++ b/API/Controller/Public/PublicShareController.cs @@ -4,10 +4,13 @@ using OpenShock.API.Models.Response; using OpenShock.API.Utils; using OpenShock.Common.Utils; +using System.Security.Claims; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Constants; using OpenShock.Common.Errors; using OpenShock.Common.Extensions; using OpenShock.Common.Models; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Public; @@ -18,6 +21,7 @@ public sealed partial class PublicController /// Gets information about a public share. /// /// + /// The token from unlocking a password-protected share. /// /// The public share information was successfully retrieved. /// The public share does not exist. @@ -26,14 +30,16 @@ public sealed partial class PublicController [ApiVersion(1)] [ProducesResponseType>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public Task GetPublicShare([FromRoute] Guid publicShareId, CancellationToken cancellationToken) - => GetPublicShareResponse(_db.PublicShares.Where(x => x.Id == publicShareId), cancellationToken); + public Task GetPublicShare([FromRoute] Guid publicShareId, + [FromHeader(Name = AuthConstants.PublicShareUnlockHeaderName)] string? unlockToken, CancellationToken cancellationToken) + => GetPublicShareResponse(_db.PublicShares.Where(x => x.Id == publicShareId), unlockToken, cancellationToken); /// /// Gets information about a public share by its owner's username and custom slug. /// /// /// + /// The token from unlocking a password-protected share. /// /// The public share information was successfully retrieved. /// The public share does not exist. @@ -42,13 +48,14 @@ public Task GetPublicShare([FromRoute] Guid publicShareId, Cancel [ApiVersion(1)] [ProducesResponseType>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public Task GetPublicShareBySlug([FromRoute] string username, [FromRoute] string slug, CancellationToken cancellationToken) + public Task GetPublicShareBySlug([FromRoute] string username, [FromRoute] string slug, + [FromHeader(Name = AuthConstants.PublicShareUnlockHeaderName)] string? unlockToken, CancellationToken cancellationToken) { slug = slug.ToLowerInvariant(); - return GetPublicShareResponse(_db.PublicShares.Where(x => x.Owner.Name == username && x.Slug == slug), cancellationToken); + return GetPublicShareResponse(_db.PublicShares.Where(x => x.Owner.Name == username && x.Slug == slug), unlockToken, cancellationToken); } - private async Task GetPublicShareResponse(IQueryable query, CancellationToken cancellationToken) + private async Task GetPublicShareResponse(IQueryable query, string? unlockToken, CancellationToken cancellationToken) { var publicShare = await query .Where(x => x.Owner.UserDeactivation == null) @@ -73,6 +80,8 @@ private async Task GetPublicShareResponse(IQueryable new { DeviceId = y.Shocker.Device.Id, @@ -99,8 +108,9 @@ private async Task GetPublicShareResponse(IQueryable GetPublicShareResponse(IQueryable x.Id != shocker.DeviceId)) @@ -125,4 +139,14 @@ private async Task GetPublicShareResponse(IQueryableThe owner always gets in; anyone else needs a token from entering the current password. + private async Task IsUnlocked(Guid publicShareId, Guid ownerId, Guid? passwordStamp, string? unlockToken) + { + var userId = User.TryGetOpenShockUserIdentity()?.GetClaimValueAsGuid(ClaimTypes.NameIdentifier); + if (userId == ownerId) return true; + + return passwordStamp is { } stamp && await HttpContext.RequestServices.GetRequiredService() + .IsTokenValidAsync(publicShareId, stamp, unlockToken); + } } diff --git a/API/Controller/Public/UnlockPublicShare.cs b/API/Controller/Public/UnlockPublicShare.cs new file mode 100644 index 00000000..12d43fe4 --- /dev/null +++ b/API/Controller/Public/UnlockPublicShare.cs @@ -0,0 +1,62 @@ +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; +using OpenShock.API.Models.Requests; +using OpenShock.API.Models.Response; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Errors; +using OpenShock.Common.Services.PublicShareAccess; +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Public; + +public sealed partial class PublicController +{ + /// + /// Unlocks a password-protected public share. + /// + /// + /// + /// + /// + /// The password was correct. + /// The public share has no password. + /// The password was incorrect. + /// The public share does not exist. + /// Too many incorrect passwords were entered for this public share. + [Tags("Public Shocker Shares")] + [HttpPost("shares/links/{publicShareId}/unlock")] + [ApiVersion(1)] + [EnableRateLimiting("auth")] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // NotPasswordProtected + [ProducesResponseType(StatusCodes.Status401Unauthorized, MediaTypeNames.Application.ProblemJson)] // PasswordIncorrect + [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound + [ProducesResponseType(StatusCodes.Status429TooManyRequests, MediaTypeNames.Application.ProblemJson)] // TooManyPasswordAttempts + public async Task UnlockPublicShare([FromRoute] Guid publicShareId, [FromBody] PublicShareUnlock body, + [FromServices] IPublicShareAccessService publicShareAccess, CancellationToken cancellationToken) + { + var share = await _db.PublicShares + .Where(x => x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null) + .Select(x => new { x.PasswordHash, x.PasswordStamp }) + .FirstOrDefaultAsync(cancellationToken); + if (share is null) return Problem(PublicShareError.PublicShareNotFound); + if (share.PasswordHash is null || share.PasswordStamp is not { } stamp) return Problem(PublicShareError.NotPasswordProtected); + + if (await publicShareAccess.TryReserveAttemptAsync(publicShareId) is not { } reservation) return Problem(PublicShareError.TooManyPasswordAttempts); + + if (!HashingUtils.VerifyPassword(body.Password, share.PasswordHash).Verified) return Problem(PublicShareError.PasswordIncorrect); + + await publicShareAccess.ReleaseAttemptAsync(publicShareId, reservation); + + var token = await publicShareAccess.IssueTokenAsync(publicShareId, stamp); + return Ok(new PublicShareUnlockResponse + { + Token = token, + ExpiresOn = DateTime.UtcNow + PublicShareAccessService.TokenLifetime + }); + } +} diff --git a/API/Controller/Shares/Links/CreatePublicShare.cs b/API/Controller/Shares/Links/CreatePublicShare.cs index 96f50324..d9c42a75 100644 --- a/API/Controller/Shares/Links/CreatePublicShare.cs +++ b/API/Controller/Shares/Links/CreatePublicShare.cs @@ -8,6 +8,7 @@ using OpenShock.Common.Errors; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Shares.Links; @@ -49,6 +50,8 @@ public async Task CreatePublicShare([FromBody] PublicShareCreate OwnerId = CurrentUser.Id, Name = body.Name, Slug = slug, + PasswordHash = body.Password is null ? null : HashingUtils.HashPassword(body.Password), + PasswordStamp = body.Password is null ? null : Guid.CreateVersion7(), ExpiresAt = body.ExpiresOn is null ? null : DateTime.SpecifyKind(body.ExpiresOn.Value, DateTimeKind.Utc) }; _db.PublicShares.Add(entity); diff --git a/API/Controller/Shares/Links/DeletePublicShare.cs b/API/Controller/Shares/Links/DeletePublicShare.cs index 4d1f4224..5927c9c9 100644 --- a/API/Controller/Shares/Links/DeletePublicShare.cs +++ b/API/Controller/Shares/Links/DeletePublicShare.cs @@ -8,6 +8,7 @@ using OpenShock.Common.Extensions; using OpenShock.Common.Models; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Shares.Links; @@ -27,7 +28,7 @@ public sealed partial class ShareLinksController [TokenPermission(PermissionType.Publicshares_Edit)] [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound - public async Task DeletePublicShare([FromRoute] Guid publicShareId, [FromServices] IDeviceUpdateService deviceUpdateService, CancellationToken cancellationToken) + public async Task DeletePublicShare([FromRoute] Guid publicShareId, [FromServices] IDeviceUpdateService deviceUpdateService, [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) { var result = await _db.PublicShares .Where(x => x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow)) @@ -37,6 +38,7 @@ public async Task DeletePublicShare([FromRoute] Guid publicShareI if (result <= 0) return Problem(PublicShareError.PublicShareNotFound); await deviceUpdateService.UpdatePublicShare(publicShareId); + await redisPubService.SendPublicShareAccessRevoked(publicShareId); return LegacyEmptyOk("Deleted public share"); } } diff --git a/API/Controller/Shares/Links/SetPublicSharePassword.cs b/API/Controller/Shares/Links/SetPublicSharePassword.cs new file mode 100644 index 00000000..37f72b63 --- /dev/null +++ b/API/Controller/Shares/Links/SetPublicSharePassword.cs @@ -0,0 +1,54 @@ +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using OpenShock.API.Models.Requests; +using OpenShock.API.Models.Response; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.Errors; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Shares.Links; + +public sealed partial class ShareLinksController +{ + /// + /// Set, change or remove the password of a public share + /// + /// + /// Setting or changing the password disconnects everyone currently using the share; they have to enter the + /// new one. Removing it keeps them connected. + /// + /// The updated public share + /// Public share not found or does not belong to you + [HttpPut("{publicShareId}/password")] + [ApiVersion(1)] + [TokenPermission(PermissionType.Publicshares_Edit)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // PublicShareNotFound + public async Task SetPublicSharePassword([FromRoute] Guid publicShareId, [FromBody] PublicSharePasswordSet body, + [FromServices] IRedisPubService redisPubService, CancellationToken cancellationToken) + { + var share = await _db.PublicShares.FirstOrDefaultAsync(x => x.OwnerId == CurrentUser.Id && x.Id == publicShareId && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow), cancellationToken); + if (share is null) return Problem(PublicShareError.PublicShareNotFound); + + if (body.Password is null) + { + // The stamp stays, so connections that got in with the old password are not closed. + share.PasswordHash = null; + await _db.SaveChangesAsync(cancellationToken); + return Ok(OwnPublicShareResponse.GetFromEf(share)); + } + + share.PasswordHash = HashingUtils.HashPassword(body.Password); + share.PasswordStamp = Guid.CreateVersion7(); + await _db.SaveChangesAsync(cancellationToken); + + await redisPubService.SendPublicShareAccessRevoked(publicShareId); + return Ok(OwnPublicShareResponse.GetFromEf(share)); + } +} diff --git a/API/Models/Requests/PublicShareCreate.cs b/API/Models/Requests/PublicShareCreate.cs index 21a90738..66385081 100644 --- a/API/Models/Requests/PublicShareCreate.cs +++ b/API/Models/Requests/PublicShareCreate.cs @@ -16,4 +16,10 @@ public sealed class PublicShareCreate /// [StringLength(ApiHardLimits.PublicShareSlugMaxLength, MinimumLength = ApiHardLimits.PublicShareSlugMinLength)] public string? Slug { get; init; } = null; + + /// + /// Optional password visitors must enter before they can see or control the shockers. + /// + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = ApiHardLimits.PublicSharePasswordMinLength)] + public string? Password { get; init; } = null; } diff --git a/API/Models/Requests/PublicSharePasswordSet.cs b/API/Models/Requests/PublicSharePasswordSet.cs new file mode 100644 index 00000000..4bc93dd5 --- /dev/null +++ b/API/Models/Requests/PublicSharePasswordSet.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; +using OpenShock.Common.Constants; + +namespace OpenShock.API.Models.Requests; + +public sealed class PublicSharePasswordSet +{ + /// + /// The new password, or null to remove it. Setting or changing it disconnects everyone currently using the share. + /// + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = ApiHardLimits.PublicSharePasswordMinLength)] + public required string? Password { get; init; } +} diff --git a/API/Models/Requests/PublicShareUnlock.cs b/API/Models/Requests/PublicShareUnlock.cs new file mode 100644 index 00000000..05e9c3a8 --- /dev/null +++ b/API/Models/Requests/PublicShareUnlock.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; +using OpenShock.Common.Constants; + +namespace OpenShock.API.Models.Requests; + +public sealed class PublicShareUnlock +{ + // Whitespace is allowed: share passwords may consist of spaces. + [Required(AllowEmptyStrings = true)] + [StringLength(ApiHardLimits.PublicSharePasswordMaxLength, MinimumLength = 1)] + public required string Password { get; init; } +} diff --git a/API/Models/Response/OwnPublicShareResponse.cs b/API/Models/Response/OwnPublicShareResponse.cs index 17589cc3..41b9bf95 100644 --- a/API/Models/Response/OwnPublicShareResponse.cs +++ b/API/Models/Response/OwnPublicShareResponse.cs @@ -9,6 +9,7 @@ public sealed class OwnPublicShareResponse public required string? Slug { get; init; } public required DateTime CreatedOn { get; init; } public DateTime? ExpiresOn { get; init; } + public required bool HasPassword { get; init; } public static OwnPublicShareResponse GetFromEf(PublicShare x) => new() { @@ -16,6 +17,7 @@ public sealed class OwnPublicShareResponse Name = x.Name, Slug = x.Slug, CreatedOn = x.CreatedAt, - ExpiresOn = x.ExpiresAt + ExpiresOn = x.ExpiresAt, + HasPassword = x.PasswordHash != null }; } diff --git a/API/Models/Response/PublicShareResponse.cs b/API/Models/Response/PublicShareResponse.cs index 45babb1e..21ee7b7c 100644 --- a/API/Models/Response/PublicShareResponse.cs +++ b/API/Models/Response/PublicShareResponse.cs @@ -10,6 +10,16 @@ public sealed class PublicShareResponse public DateTime? ExpiresOn { get; init; } public required PublicShareAuthor Author { get; init; } + /// + /// Visitors have to enter a password before they can see or control the shockers. + /// + public required bool PasswordProtected { get; init; } + + /// + /// The share is password protected and this request did not unlock it: is empty. + /// + public required bool PasswordRequired { get; init; } + public IList Devices { get; init; } = new List(); } diff --git a/API/Models/Response/PublicShareUnlockResponse.cs b/API/Models/Response/PublicShareUnlockResponse.cs new file mode 100644 index 00000000..0eb68448 --- /dev/null +++ b/API/Models/Response/PublicShareUnlockResponse.cs @@ -0,0 +1,12 @@ +namespace OpenShock.API.Models.Response; + +public sealed class PublicShareUnlockResponse +{ + /// + /// Send it in the OpenShockPublicShareUnlock header when loading the share, and as the unlockToken query + /// parameter when connecting to its hub. Invalid once the password is changed. + /// + public required string Token { get; init; } + + public required DateTime ExpiresOn { get; init; } +} diff --git a/API/Models/Response/PublicUserProfileResponse.cs b/API/Models/Response/PublicUserProfileResponse.cs index 1753fe42..9664d54b 100644 --- a/API/Models/Response/PublicUserProfileResponse.cs +++ b/API/Models/Response/PublicUserProfileResponse.cs @@ -14,6 +14,7 @@ public sealed class PublicUserProfilePublicShare public required Guid Id { get; init; } public required string Name { get; init; } public required string? Slug { get; init; } + public required bool PasswordProtected { get; init; } } public sealed class PublicUserProfileDetails diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 7ff90748..a1c1914b 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -59,6 +59,7 @@ public async Task StartAsync(CancellationToken cancellationToken) await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); + await _subscriber.SubscribeAsync(RedisChannels.PublicShareAccessRevoked, HandlePublicShareAccessRevoked); } private void HandleSessionRevoked(RedisChannel _, RedisValue message) @@ -78,6 +79,14 @@ private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of user [{UserId}]", closed, userId); } + private void HandlePublicShareAccessRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var publicShareId)) return; + + var closed = _hubConnections.AbortPublicShare(publicShareId); + if (closed > 0) _logger.LogDebug("Closed {Count} connection(s) to public share [{PublicShareId}]", closed, publicShareId); + } + private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) { var channelName = (string?)channel; diff --git a/Common/Constants/ApiHardLimits.cs b/Common/Constants/ApiHardLimits.cs index 1717fc7a..e15e72cc 100644 --- a/Common/Constants/ApiHardLimits.cs +++ b/Common/Constants/ApiHardLimits.cs @@ -41,6 +41,8 @@ public static class ApiHardLimits public const int PublicShareSlugMinLength = 2; public const int PublicShareSlugMaxLength = 32; + public const int PublicSharePasswordMinLength = 4; + public const int PublicSharePasswordMaxLength = 128; public const int UserProfilePronounsMaxLength = 32; public const int UserProfileBioMaxLength = 1000; diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 3fdb5c6a..9f3dd031 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -7,6 +7,7 @@ public static class AuthConstants public const string UserSessionHeaderName = "OpenShockSession"; public const string ApiTokenHeaderName = "OpenShockToken"; public const string HubTokenHeaderName = "DeviceToken"; + public const string PublicShareUnlockHeaderName = "OpenShockPublicShareUnlock"; public const string AutomationTokenHeaderName = "X-OpenShock-Automation-Token"; public const int GeneratedTokenLength = 32; diff --git a/Common/Errors/PublicShareError.cs b/Common/Errors/PublicShareError.cs index 11c1c879..2cbf07a1 100644 --- a/Common/Errors/PublicShareError.cs +++ b/Common/Errors/PublicShareError.cs @@ -18,5 +18,10 @@ public static class PublicShareError public static OpenShockProblem PublicShareExpiryDateInPast => new("ShareLink.ExpiryDateInPast", "Expiry date cannot be in the past", HttpStatusCode.BadRequest); public static OpenShockProblem SlugInvalid => new("ShareLink.SlugInvalid", "Invalid public share slug", HttpStatusCode.BadRequest, $"Slugs must be {ApiHardLimits.PublicShareSlugMinLength}-{ApiHardLimits.PublicShareSlugMaxLength} characters of lowercase letters, digits and single hyphens, and cannot start or end with a hyphen"); public static OpenShockProblem SlugTaken => new("ShareLink.SlugTaken", "You already have a public share with this slug", HttpStatusCode.Conflict); + // Password errors + public static OpenShockProblem NotPasswordProtected => new("ShareLink.NotPasswordProtected", "This public share has no password", HttpStatusCode.BadRequest); + public static OpenShockProblem PasswordIncorrect => new("ShareLink.PasswordIncorrect", "Incorrect password", HttpStatusCode.Unauthorized); + public static OpenShockProblem TooManyPasswordAttempts => new("ShareLink.TooManyPasswordAttempts", "Too many incorrect passwords", HttpStatusCode.TooManyRequests, "Too many incorrect passwords were entered for this public share. Try again later."); + public static OpenShockProblem TooManyPublicShares => new("ShareLink.TooManyShareLinks", "You have too many public shares", HttpStatusCode.Conflict, $"You have reached the maximum number of public shares ({ApiHardLimits.MaxPublicSharesPerUser})"); } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs index 40b4bd45..81a888d9 100644 --- a/Common/Hubs/HubConnectionTracker.cs +++ b/Common/Hubs/HubConnectionTracker.cs @@ -50,8 +50,35 @@ public sealed class HubConnectionTracker return null; } + /// + /// Starts tracking a public share connection, or marks an already tracked (logged in) one as such, so it is + /// closed when the share's access changes. + /// + /// The share's password stamp the visitor got in with, null when it had no password. + public TrackedHubConnection TrackPublicShare(HubCallerContext context, Guid publicShareId, Guid? passwordStamp) + { + var tracked = _connections.GetOrAdd(context.ConnectionId, _ => new TrackedHubConnection(context, userId: null, sessionId: null, apiTokenId: null)); + tracked.AttachPublicShare(publicShareId, passwordStamp); + // A logged in connection was already checked, but not against the share: the next call has to. + tracked.ResetValidation(); + // Kept on the connection too, so a call that arrives after a revocation untracked it can be told apart + // from an anonymous connection that was never tracked. + context.Items[PublicShareConnectionKey] = tracked; + return tracked; + } + + /// The public share connection as it was tracked, also after it was untracked. + public static TrackedHubConnection? GetPublicShareConnection(HubCallerContext context) + => context.Items.TryGetValue(PublicShareConnectionKey, out var tracked) ? tracked as TrackedHubConnection : null; + + private static readonly object PublicShareConnectionKey = new(); + public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); + /// Closes the connections to this public share. + /// How many connections were closed. + public int AbortPublicShare(Guid publicShareId) => Abort(c => c.PublicShareId == publicShareId); + /// Closes the connections that authenticated with this session. /// The id the session is stored under, see . /// How many connections were closed. @@ -104,6 +131,18 @@ public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sess public string? SessionId { get; } public Guid? ApiTokenId { get; } + /// The public share this connection controls, null for other hubs. + public Guid? PublicShareId { get; private set; } + + /// The share's password stamp when this connection was let in, null when it had no password. + public Guid? PasswordStamp { get; private set; } + + public void AttachPublicShare(Guid publicShareId, Guid? passwordStamp) + { + PublicShareId = publicShareId; + PasswordStamp = passwordStamp; + } + public bool WasValidatedWithin(TimeSpan interval) { var lastValidated = Interlocked.Read(ref _lastValidated); @@ -111,4 +150,7 @@ public bool WasValidatedWithin(TimeSpan interval) } public void MarkValidated() => Interlocked.Exchange(ref _lastValidated, Stopwatch.GetTimestamp()); + + /// Makes the next call check the connection again. + public void ResetValidation() => Interlocked.Exchange(ref _lastValidated, 0); } diff --git a/Common/Hubs/PublicShareHub.cs b/Common/Hubs/PublicShareHub.cs index 0da2b361..a2f41eb4 100644 --- a/Common/Hubs/PublicShareHub.cs +++ b/Common/Hubs/PublicShareHub.cs @@ -5,6 +5,7 @@ using OpenShock.Common.Models.WebSocket.User; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Common.Services.Session; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Constants; @@ -17,6 +18,8 @@ public sealed class PublicShareHub : Hub private readonly IHubContext _userHub; private readonly ISessionService _sessionService; private readonly IControlSender _controlSender; + private readonly HubConnectionTracker _connectionTracker; + private readonly IPublicShareAccessService _publicShareAccess; private readonly ILogger _logger; /// /// Permissions of the API token this connection authenticated with, or null for a session @@ -26,8 +29,14 @@ public sealed class PublicShareHub : Hub ? Context.User.GetApiTokenPermissions() : null; - public PublicShareHub(OpenShockContext db, IHubContext userHub, ISessionService sessionService, IControlSender controlSender, ILogger logger) + /// Query parameter carrying the unlock token of a password-protected share. + public const string UnlockTokenQueryName = "unlockToken"; + + public PublicShareHub(OpenShockContext db, IHubContext userHub, ISessionService sessionService, IControlSender controlSender, + HubConnectionTracker connectionTracker, IPublicShareAccessService publicShareAccess, ILogger logger) { + _connectionTracker = connectionTracker; + _publicShareAccess = publicShareAccess; _db = db; _userHub = userHub; _sessionService = sessionService; @@ -58,13 +67,27 @@ public override async Task OnConnectedAsync() } } - var exists = await _db.PublicShares.AnyAsync(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null); - if (!exists) + var share = await _db.PublicShares + .Where(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.UtcNow) && x.Owner.UserDeactivation == null) + .Select(x => new { x.OwnerId, HasPassword = x.PasswordHash != null, x.PasswordStamp }) + .FirstOrDefaultAsync(); + if (share is null) { _logger.LogDebug("Aborting connection... public share not found"); Context.Abort(); return; } + + if (share.HasPassword && user?.Id != share.OwnerId) + { + var unlockToken = httpContext.Request.Query[UnlockTokenQueryName].FirstOrDefault(); + if (share.PasswordStamp is not { } stamp || !await _publicShareAccess.IsTokenValidAsync(id, stamp, unlockToken)) + { + _logger.LogDebug("Aborting connection... public share is password protected and was not unlocked"); + Context.Abort(); + return; + } + } // TODO: Add token auth @@ -114,6 +137,10 @@ public override async Task OnConnectedAsync() AdditionalItems = additionalItems } }; + // Closed when the share's password is set or changed, or the share is deleted. Left unvalidated so the + // first call checks the share again, covering a change made since it was read above. + _connectionTracker.TrackPublicShare(Context, id, share.PasswordStamp); + await Groups.AddToGroupAsync(Context.ConnectionId, GroupName(id)); await Clients.Caller.Welcome(user is null ? AuthType.Guest : AuthType.Authenticated); } diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index 69cbc6e8..019e2934 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -83,6 +83,13 @@ public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception // queued calls are still draining: the check below turns those away. var tracked = _tracker.Get(context.ConnectionId); + // A public share connection only leaves the tracker when it is being closed, so there is nothing to check. + if (tracked is null && HubConnectionTracker.GetPublicShareConnection(context) is not null) + { + context.Abort(); + throw new HubException("Access to this public share is no longer valid"); + } + if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) { if (!await ValidateAsync(context, tracked, invocationContext.ServiceProvider)) @@ -100,10 +107,27 @@ private static async Task ValidateAsync(HubCallerContext context, TrackedH { if (!await IsStillAuthenticated(context, services)) return false; + if (tracked?.PublicShareId is { } publicShareId && !await IsPublicShareStillAccessible(publicShareId, tracked.PasswordStamp, context, services)) return false; + tracked?.MarkValidated(); return true; } + /// + /// A public share connection may go on while the share exists, has not expired, its owner is active and its + /// password was not set or changed since the visitor got in. Covers what the Redis message can miss. + /// + private static Task IsPublicShareStillAccessible(Guid publicShareId, Guid? passwordStamp, HubCallerContext context, IServiceProvider services) + { + var db = services.GetRequiredService(); + var now = DateTime.UtcNow; + return db.PublicShares.AnyAsync(x => + x.Id == publicShareId && + (x.ExpiresAt == null || x.ExpiresAt > now) && + x.Owner.UserDeactivation == null && + x.PasswordStamp == passwordStamp, context.ConnectionAborted); + } + private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) { var user = context.User; diff --git a/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs b/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs new file mode 100644 index 00000000..4842081a --- /dev/null +++ b/Common/Migrations/20261203012615_PublicSharePasswords.Designer.cs @@ -0,0 +1,2000 @@ +// +using System; +using System.Collections.Generic; +using System.Net; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenShock.Common.OpenShockDb; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +[DbContext(typeof(MigrationOpenShockContext))] +[Migration("20261203012615_PublicSharePasswords")] +partial class _20261203012615_PublicSharePasswords +{ + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:CollationDefinition:public.ndcoll", "und-u-ks-level2,und-u-ks-level2,icu,False") + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "audit_action", new[] { "login", "logout", "password_changed", "email_change_requested", "email_changed", "username_changed", "api_token_created", "api_token_deleted", "oauth_connected", "oauth_disconnected", "account_deactivated", "account_reactivated", "account_deleted", "automation_token_created", "automation_token_updated", "automation_token_rotated", "automation_token_deleted", "automation_token_used" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "automation_token_type", new[] { "turnstile", "rate_limit", "control_stats_read" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "configuration_value_type", new[] { "string", "bool", "int", "float", "json" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_limit_mode", new[] { "clamp", "lerp" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_type", new[] { "stop", "shock", "vibrate", "sound" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_status", new[] { "pending", "sending", "sent", "failed", "skipped" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_type", new[] { "account_activation", "password_reset", "email_verification", "email_change_notice" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "match_type_enum", new[] { "exact", "contains" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "ota_update_status", new[] { "started", "running", "finished", "error", "timeout" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "password_encryption_type", new[] { "bcrypt_enhanced", "pbkdf2" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "permission_type", new[] { "shockers.use", "shockers.edit", "shockers.pause", "devices.edit", "devices.auth", "usershares.edit", "usershares.pause", "publicshares.pause", "publicshares.edit" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "role_type", new[] { "support", "staff", "admin", "system" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "shocker_model_type", new[] { "cai_xianlin", "petrainer", "petrainer_998dr", "wellturn_t330" }); + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "timescaledb"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("FriendlyName") + .HasColumnType("text"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AdminUsersView", b => + { + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("ApiTokenCount") + .HasColumnType("integer") + .HasColumnName("api_token_count"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("DeactivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deactivated_at"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeviceCount") + .HasColumnType("integer") + .HasColumnName("device_count"); + + b.Property("Email") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("email"); + + b.Property("EmailChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("email_change_request_count"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("name"); + + b.Property("NameChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("name_change_request_count"); + + b.Property("PasswordHashType") + .HasColumnType("character varying") + .HasColumnName("password_hash_type"); + + b.Property("PasswordResetCount") + .HasColumnType("integer") + .HasColumnName("password_reset_count"); + + b.Property("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("ShockerControlLogCount") + .HasColumnType("integer") + .HasColumnName("shocker_control_log_count"); + + b.Property("ShockerCount") + .HasColumnType("integer") + .HasColumnName("shocker_count"); + + b.Property("ShockerPublicShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_public_share_count"); + + b.Property("ShockerUserShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_user_share_count"); + + b.ToTable((string)null); + + b.ToView("admin_users_view", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByIp") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("created_by_ip"); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property>("Permissions") + .IsRequired() + .HasColumnType("permission_type[]") + .HasColumnName("permissions"); + + b.Property("ShockerControlDurationMax") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(65535) + .HasColumnName("shocker_control_duration_max"); + + b.Property("ShockerControlDurationMin") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(300) + .HasColumnName("shocker_control_duration_min"); + + b.Property("ShockerControlDurationMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_duration_mode"); + + b.Property("ShockerControlIntensityMax") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)100) + .HasColumnName("shocker_control_intensity_max"); + + b.Property("ShockerControlIntensityMin") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)0) + .HasColumnName("shocker_control_intensity_min"); + + b.Property("ShockerControlIntensityMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_intensity_mode"); + + b.Property("ShockerControlPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("shocker_control_paused"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ValidUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("valid_until"); + + b.HasKey("Id") + .HasName("api_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.HasIndex("ValidUntil"); + + b.ToTable("api_tokens", t => + { + t.HasCheckConstraint("ck_api_tokens_shocker_control_duration", "shocker_control_duration_min >= 300 AND shocker_control_duration_max <= 65535 AND shocker_control_duration_min <= shocker_control_duration_max"); + + t.HasCheckConstraint("ck_api_tokens_shocker_control_intensity", "shocker_control_intensity_min >= 0 AND shocker_control_intensity_max <= 100 AND shocker_control_intensity_min <= shocker_control_intensity_max"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AffectedCount") + .HasColumnType("integer") + .HasColumnName("affected_count"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("IpCountry") + .HasMaxLength(4) + .HasColumnType("character varying(4)") + .HasColumnName("ip_country"); + + b.Property("SubmittedCount") + .HasColumnType("integer") + .HasColumnName("submitted_count"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("api_token_reports_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("api_token_reports"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AutoCleanupAfter") + .HasColumnType("interval") + .HasColumnName("auto_cleanup_after"); + + b.Property("AutoCleanupUsers") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("auto_cleanup_users"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("LastRotatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_rotated_at"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property>("Types") + .IsRequired() + .HasColumnType("automation_token_type[]") + .HasColumnName("types"); + + b.Property("UseCount") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("use_count"); + + b.HasKey("Id") + .HasName("automation_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("automation_tokens"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ConfigurationItem", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name") + .UseCollation("C"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.Property("Type") + .HasColumnType("configuration_value_type") + .HasColumnName("type"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("value"); + + b.HasKey("Name") + .HasName("configuration_pkey"); + + b.ToTable("configuration"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ControlStat", b => + { + b.Property("Bucket") + .HasColumnType("timestamp with time zone") + .HasColumnName("bucket"); + + b.Property("ControllerUserId") + .HasColumnType("uuid") + .HasColumnName("controller_user_id"); + + b.Property("Count") + .HasColumnType("bigint") + .HasColumnName("count"); + + b.Property("DurationMs") + .HasColumnType("bigint") + .HasColumnName("duration_ms"); + + b.Property("IntensityMs") + .HasColumnType("bigint") + .HasColumnName("intensity_ms"); + + b.Property("Live") + .HasColumnType("boolean") + .HasColumnName("live"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.ToTable((string)null); + + b.ToView("control_stats", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)") + .HasColumnName("token") + .UseCollation("C"); + + b.HasKey("Id") + .HasName("devices_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("devices"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("UpdateId") + .HasColumnType("integer") + .HasColumnName("update_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Message") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("message"); + + b.Property("Status") + .HasColumnType("ota_update_status") + .HasColumnName("status"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("version"); + + b.HasKey("DeviceId", "UpdateId") + .HasName("device_ota_updates_pkey"); + + b.HasIndex(new[] { "CreatedAt" }, "device_ota_updates_created_at_idx"); + + b.ToTable("device_ota_updates"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DiscordWebhook", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("WebhookId") + .HasColumnType("bigint") + .HasColumnName("webhook_id"); + + b.Property("WebhookToken") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("webhook_token"); + + b.HasKey("Name") + .HasName("discord_webhooks_pkey"); + + b.ToTable("discord_webhooks"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailOutboxMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttemptCount") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0) + .HasColumnName("attempt_count"); + + b.Property("CoalesceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("coalesce_key"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("FailedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("failed_at"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("last_error"); + + b.Property("NextAttemptAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property>("Payload") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("recipient"); + + b.Property("RecipientName") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("recipient_name"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("sent_at"); + + b.Property("Status") + .HasColumnType("email_status") + .HasColumnName("status"); + + b.Property("Type") + .HasColumnType("email_type") + .HasColumnName("type"); + + b.HasKey("Id") + .HasName("email_outbox_pkey"); + + b.HasIndex("CoalesceKey") + .HasFilter("coalesce_key IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasFilter("status IN ('pending', 'sending')"); + + b.HasIndex("Recipient"); + + b.ToTable("email_outbox"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailProviderBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Domain") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("domain") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("email_provider_blacklist_pkey"); + + var index = b.HasIndex("Domain") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("email_provider_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("PasswordStamp") + .HasColumnType("uuid") + .HasColumnName("password_stamp"); + + b.Property("Slug") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("slug") + .UseCollation("C"); + + b.HasKey("Id") + .HasName("public_shares_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("OwnerId", "Slug") + .IsUnique() + .HasFilter("slug IS NOT NULL"); + + b.ToTable("public_shares", t => + { + t.HasCheckConstraint("ck_public_shares_slug", "slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.Property("PublicShareId") + .HasColumnType("uuid") + .HasColumnName("public_share_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("Cooldown") + .HasColumnType("integer") + .HasColumnName("cooldown"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("PublicShareId", "ShockerId") + .HasName("public_share_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("public_share_shockers", t => + { + t.HasCheckConstraint("ck_public_share_shockers_cooldown", "cooldown >= 0"); + + t.HasCheckConstraint("ck_public_share_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_public_share_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("Model") + .HasColumnType("shocker_model_type") + .HasColumnName("model"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("RfId") + .HasColumnType("integer") + .HasColumnName("rf_id"); + + b.HasKey("Id") + .HasName("shockers_pkey"); + + b.HasIndex("DeviceId"); + + b.ToTable("shockers", t => + { + t.HasCheckConstraint("ck_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + + t.HasCheckConstraint("ck_shockers_rf_id", "rf_id BETWEEN 0 AND 65535"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ControlledByUserId") + .HasColumnType("uuid") + .HasColumnName("controlled_by_user_id"); + + b.Property("CustomName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("custom_name"); + + b.Property("Duration") + .HasColumnType("bigint") + .HasColumnName("duration"); + + b.Property("InsertedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("inserted_at") + .HasDefaultValueSql("now()"); + + b.Property("Intensity") + .HasColumnType("smallint") + .HasColumnName("intensity"); + + b.Property("LiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("live_control"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.HasKey("Id", "CreatedAt") + .HasName("shocker_control_logs_pkey"); + + b.HasIndex("ControlledByUserId"); + + b.HasIndex("OwnerUserId", "CreatedAt"); + + b.HasIndex("ShockerId", "CreatedAt"); + + b.ToTable("shocker_control_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.HasKey("Id") + .HasName("shocker_share_codes_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("shocker_share_codes", t => + { + t.HasCheckConstraint("ck_shocker_share_codes_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_shocker_share_codes_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email") + .UseCollation("ndcoll"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("name") + .UseCollation("ndcoll"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property>("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("SecurityStamp") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("security_stamp") + .HasDefaultValueSql("gen_random_uuid()"); + + b.HasKey("Id") + .HasName("users_pkey"); + + b.HasIndex("CreatedByAutomationTokenId"); + + var index = b.HasIndex("Email") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + var index0 = b.HasIndex("Name") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index0, new[] { "ndcoll" }); + + b.ToTable("users"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("EmailSendAttempts") + .HasColumnType("integer") + .HasColumnName("email_send_attempts"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.HasKey("UserId") + .HasName("user_activation_requests_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("user_activation_requests"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Action") + .HasColumnType("audit_action") + .HasColumnName("action"); + + b.Property("ActorId") + .HasColumnType("uuid") + .HasColumnName("actor_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("Metadata") + .HasColumnType("jsonb") + .HasColumnName("metadata"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasColumnName("reason"); + + b.Property("UserAgent") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("user_agent"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_audit_logs_pkey"); + + b.HasIndex("ActorId"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_audit_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.Property("DeactivatedUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_user_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeleteLater") + .HasColumnType("boolean") + .HasColumnName("delete_later"); + + b.Property("UserModerationId") + .HasColumnType("uuid") + .HasColumnName("user_moderation_id"); + + b.HasKey("DeactivatedUserId") + .HasName("user_deactivations_pkey"); + + b.HasIndex("DeactivatedByUserId"); + + b.ToTable("user_deactivations"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("NewEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_new"); + + b.Property("OldEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_old"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_email_changes_pkey"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UsedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_email_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("MatchType") + .HasColumnType("match_type_enum") + .HasColumnName("match_type"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("value") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("user_name_blacklist_pkey"); + + var index = b.HasIndex("Value") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("user_name_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(id); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OldName") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("old_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_name_changes_pkey"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("user_name_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.Property("ProviderKey") + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasColumnName("provider_key") + .UseCollation("C"); + + b.Property("ExternalId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("external_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DisplayName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("display_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ProviderKey", "ExternalId") + .HasName("user_oauth_connections_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_oauth_connections"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_password_resets_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_password_resets"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserProfile", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("Bio") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)") + .HasColumnName("bio"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DefaultPublicShareId") + .HasColumnType("uuid") + .HasColumnName("default_public_share_id"); + + b.Property("IsPublic") + .HasColumnType("boolean") + .HasColumnName("is_public"); + + b.Property("Pronouns") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("pronouns"); + + b.Property("Socials") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("socials"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("UserId") + .HasName("user_profiles_pkey"); + + b.HasIndex("DefaultPublicShareId"); + + b.ToTable("user_profiles"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.Property("SharedWithUserId") + .HasColumnType("uuid") + .HasColumnName("shared_with_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("SharedWithUserId", "ShockerId") + .HasName("user_shares_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_shares", t => + { + t.HasCheckConstraint("ck_user_shares_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_shares_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("RecipientUserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_share_invites_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("RecipientUserId"); + + b.ToTable("user_share_invites"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.Property("InviteId") + .HasColumnType("uuid") + .HasColumnName("invite_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("InviteId", "ShockerId") + .HasName("user_share_invite_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_share_invite_shockers", t => + { + t.HasCheckConstraint("ck_user_share_invite_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_share_invite_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("ApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_tokens_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "ReportedByUser") + .WithMany("ReportedApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_token_reports_reported_by_user_id"); + + b.Navigation("ReportedByUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("Devices") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_devices_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("OtaUpdates") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_device_ota_updates_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OwnedPublicShares") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_shares_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.PublicShare", "PublicShare") + .WithMany("ShockerMappings") + .HasForeignKey("PublicShareId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_public_share_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("PublicShareMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_shocker_id"); + + b.Navigation("PublicShare"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("Shockers") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shockers_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_control_logs_owner_user_id"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("ShockerShareCodes") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_share_codes_shocker_id"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.AutomationToken", "CreatedByAutomationToken") + .WithMany("CreatedUsers") + .HasForeignKey("CreatedByAutomationTokenId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_users_created_by_automation_token_id"); + + b.Navigation("CreatedByAutomationToken"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithOne("UserActivationRequest") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserActivationRequest", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_activation_requests_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Actor") + .WithMany("ActorAuditLogs") + .HasForeignKey("ActorId") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("fk_user_audit_logs_actor_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("AuditLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_audit_logs_user_id"); + + b.Navigation("Actor"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedByUser") + .WithMany() + .HasForeignKey("DeactivatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_by_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedUser") + .WithOne("UserDeactivation") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserDeactivation", "DeactivatedUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_user_id"); + + b.Navigation("DeactivatedByUser"); + + b.Navigation("DeactivatedUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("EmailChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_email_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("NameChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_name_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("OAuthConnections") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_oauth_connections_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("PasswordResets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_password_resets_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserProfile", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.PublicShare", "DefaultPublicShare") + .WithMany() + .HasForeignKey("DefaultPublicShareId") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("fk_user_profiles_default_public_share_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithOne("Profile") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_profiles_user_id"); + + b.Navigation("DefaultPublicShare"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "SharedWithUser") + .WithMany("IncomingUserShares") + .HasForeignKey("SharedWithUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shared_with_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShares") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shocker_id"); + + b.Navigation("SharedWithUser"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OutgoingUserShareInvites") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invites_owner_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "RecipientUser") + .WithMany("IncomingUserShareInvites") + .HasForeignKey("RecipientUserId") + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_user_share_invites_recipient_user_id"); + + b.Navigation("Owner"); + + b.Navigation("RecipientUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.UserShareInvite", "Invite") + .WithMany("ShockerMappings") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_invite_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShareInviteShockerMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_shocker_id"); + + b.Navigation("Invite"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Navigation("CreatedUsers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Navigation("OtaUpdates"); + + b.Navigation("Shockers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Navigation("ShockerMappings"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Navigation("PublicShareMappings"); + + b.Navigation("ShockerShareCodes"); + + b.Navigation("UserShareInviteShockerMappings"); + + b.Navigation("UserShares"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Navigation("ActorAuditLogs"); + + b.Navigation("ApiTokens"); + + b.Navigation("AuditLogs"); + + b.Navigation("Devices"); + + b.Navigation("EmailChanges"); + + b.Navigation("IncomingUserShareInvites"); + + b.Navigation("IncomingUserShares"); + + b.Navigation("NameChanges"); + + b.Navigation("OAuthConnections"); + + b.Navigation("OutgoingUserShareInvites"); + + b.Navigation("OwnedPublicShares"); + + b.Navigation("PasswordResets"); + + b.Navigation("Profile"); + + b.Navigation("ReportedApiTokens"); + + b.Navigation("UserActivationRequest"); + + b.Navigation("UserDeactivation"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Navigation("ShockerMappings"); + }); +#pragma warning restore 612, 618 + } +} diff --git a/Common/Migrations/20261203012615_PublicSharePasswords.cs b/Common/Migrations/20261203012615_PublicSharePasswords.cs new file mode 100644 index 00000000..3279c035 --- /dev/null +++ b/Common/Migrations/20261203012615_PublicSharePasswords.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +/// +public partial class _20261203012615_PublicSharePasswords : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "password_hash", + table: "public_shares", + type: "character varying(100)", + maxLength: 100, + nullable: true, + collation: "C"); + + migrationBuilder.AddColumn( + name: "password_stamp", + table: "public_shares", + type: "uuid", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "password_hash", + table: "public_shares"); + + migrationBuilder.DropColumn( + name: "password_stamp", + table: "public_shares"); + } +} diff --git a/Common/Migrations/OpenShockContextModelSnapshot.cs b/Common/Migrations/OpenShockContextModelSnapshot.cs index 6c528ded..1e92348b 100644 --- a/Common/Migrations/OpenShockContextModelSnapshot.cs +++ b/Common/Migrations/OpenShockContextModelSnapshot.cs @@ -18,7 +18,7 @@ partial class OpenShockContextModelSnapshot : ModelSnapshot // If you encounter a merge conflict in the line below, it means you need to // discard one of the migration branches and recreate its migrations on top of // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. - public override string LastMigrationId => "20261201014156_ShareLinkSlugsAndUserProfiles"; + public override string LastMigrationId => "20261203012615_PublicSharePasswords"; protected override void BuildModel(ModelBuilder modelBuilder) { @@ -704,6 +704,16 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("uuid") .HasColumnName("owner_id"); + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("PasswordStamp") + .HasColumnType("uuid") + .HasColumnName("password_stamp"); + b.Property("Slug") .HasMaxLength(32) .HasColumnType("character varying(32)") diff --git a/Common/OpenShockDb/Models/PublicShare.cs b/Common/OpenShockDb/Models/PublicShare.cs index c8fe8701..5bde2201 100644 --- a/Common/OpenShockDb/Models/PublicShare.cs +++ b/Common/OpenShockDb/Models/PublicShare.cs @@ -15,6 +15,16 @@ public sealed class PublicShare public DateTime? ExpiresAt { get; set; } + /// + /// Optional password visitors must enter before they can see or control the shockers. + /// + public string? PasswordHash { get; set; } + + /// + /// Changes whenever the password is set or changed, invalidating every unlock issued before. + /// + public Guid? PasswordStamp { get; set; } + public DateTime CreatedAt { get; init; } // Navigations diff --git a/Common/OpenShockDb/OpenShockContext.cs b/Common/OpenShockDb/OpenShockContext.cs index a5885a60..b3ecc5dc 100644 --- a/Common/OpenShockDb/OpenShockContext.cs +++ b/Common/OpenShockDb/OpenShockContext.cs @@ -558,6 +558,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .UseCollation("C") .HasMaxLength(ApiHardLimits.PublicShareSlugMaxLength) .HasColumnName("slug"); + entity.Property(e => e.PasswordHash) + .UseCollation("C") + .HasMaxLength(ApiHardLimits.PasswordHashMaxLength) + .HasColumnName("password_hash"); + entity.Property(e => e.PasswordStamp).HasColumnName("password_stamp"); entity.Property(e => e.OwnerId).HasColumnName("owner_id"); entity.HasOne(d => d.Owner).WithMany(p => p.OwnedPublicShares) diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 43d2158a..8b59ce42 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -31,6 +31,7 @@ using OpenShock.Common.Services.Configuration; using OpenShock.Common.Services.Geo; using OpenShock.Common.Services.RedisPubSub; +using OpenShock.Common.Services.PublicShareAccess; using OpenShock.Common.Services.Session; using OpenShock.Common.Services.Webhook; using OpenShock.Common.Utils; @@ -316,6 +317,7 @@ public static IServiceCollection AddOpenShockServices(this IServiceCollection se services.AddSingleton(); services.AddScoped(); services.AddScoped(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); diff --git a/Common/Services/PublicShareAccess/PublicShareAccessService.cs b/Common/Services/PublicShareAccess/PublicShareAccessService.cs new file mode 100644 index 00000000..6dd2105b --- /dev/null +++ b/Common/Services/PublicShareAccess/PublicShareAccessService.cs @@ -0,0 +1,106 @@ +using OpenShock.Common.Utils; +using OpenShock.Internal.Common.Utils; +using StackExchange.Redis; + +namespace OpenShock.Common.Services.PublicShareAccess; + +/// +/// Unlock tokens for password-protected public shares. A visitor who entered the password gets a token, +/// which they send along when they load the share and when they connect to its hub. A token is tied to the +/// share's password stamp, so setting or changing the password invalidates every token issued before. +/// +public interface IPublicShareAccessService +{ + /// Issues a token for a visitor who entered the correct password. + Task IssueTokenAsync(Guid publicShareId, Guid passwordStamp); + + /// Whether the token unlocks this share at its current password stamp. + Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp, string? token); + + /// + /// Counts a password attempt towards the share's lockout, before the password is checked, so parallel + /// guesses cannot get past the limit. + /// + /// + /// The reservation, to hand to , or null when too many incorrect passwords were + /// entered for this share recently. A rejected attempt is not counted. + /// + Task TryReserveAttemptAsync(Guid publicShareId); + + /// + /// Gives a reserved attempt back once the password turned out correct: only incorrect ones count. Does nothing + /// when the window it was reserved in has ended. + /// + Task ReleaseAttemptAsync(Guid publicShareId, string reservation); +} + +public sealed class PublicShareAccessService : IPublicShareAccessService +{ + public static readonly TimeSpan TokenLifetime = TimeSpan.FromHours(12); + + /// + /// Incorrect passwords allowed per share within , from any visitor. + /// Per-IP limits alone would let a botnet guess indefinitely. + /// + public const int MaxFailedAttempts = 20; + public static readonly TimeSpan FailedAttemptWindow = TimeSpan.FromMinutes(15); + + private const int TokenLength = 32; + + private readonly IDatabase _redis; + + public PublicShareAccessService(IConnectionMultiplexer connectionMultiplexer) + { + _redis = connectionMultiplexer.GetDatabase(); + } + + public async Task IssueTokenAsync(Guid publicShareId, Guid passwordStamp) + { + var token = CryptoUtils.RandomString(TokenLength); + await _redis.StringSetAsync(TokenKey(token), TokenValue(publicShareId, passwordStamp), TokenLifetime); + return token; + } + + public async Task IsTokenValidAsync(Guid publicShareId, Guid passwordStamp, string? token) + { + if (string.IsNullOrEmpty(token) || token.Length != TokenLength) return false; + + var value = await _redis.StringGetAsync(TokenKey(token)); + return value.HasValue && (string?)value == TokenValue(publicShareId, passwordStamp); + } + + public async Task TryReserveAttemptAsync(Guid publicShareId) + { + var result = await _redis.ScriptEvaluateAsync(ReserveAttemptScript, [FailedAttemptsKey(publicShareId)], + [(long)FailedAttemptWindow.TotalMilliseconds, MaxFailedAttempts, Guid.NewGuid().ToString("N")]); + return result.IsNull ? null : (string?)result; + } + + public Task ReleaseAttemptAsync(Guid publicShareId, string reservation) + => _redis.ScriptEvaluateAsync(ReleaseAttemptScript, [FailedAttemptsKey(publicShareId)], [reservation]); + + // The counter is a hash of the attempt count and the id of its window. The window starts with the first attempt + // and is not extended by later ones; it gets its expiry in the same operation that creates it. The reservation + // is the window id, so a release only counts against the window it was reserved in. + private const string ReserveAttemptScript = """ + local count = tonumber(redis.call('HGET', KEYS[1], 'count') or '0') + if count >= tonumber(ARGV[2]) then return false end + if redis.call('EXISTS', KEYS[1]) == 0 then + redis.call('HSET', KEYS[1], 'window', ARGV[3]) + redis.call('PEXPIRE', KEYS[1], ARGV[1]) + end + redis.call('HINCRBY', KEYS[1], 'count', 1) + return redis.call('HGET', KEYS[1], 'window') + """; + + // A window holding no incorrect password is dropped, so the window starts with the first incorrect one. + private const string ReleaseAttemptScript = """ + if redis.call('HGET', KEYS[1], 'window') ~= ARGV[1] then return 0 end + if redis.call('HINCRBY', KEYS[1], 'count', -1) <= 0 then redis.call('DEL', KEYS[1]) end + return 0 + """; + + private static RedisKey TokenKey(string token) => $"public-share-unlock:{HashingUtils.HashToken(token)}"; + private static string TokenValue(Guid publicShareId, Guid passwordStamp) => $"{publicShareId}:{passwordStamp}"; + private static RedisKey FailedAttemptsKey(Guid publicShareId) => $"public-share-unlock-failures:{publicShareId}"; +} diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 3a9dcb92..69fc76e2 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -33,6 +33,13 @@ public interface IRedisPubService /// Task SendUserAuthRevoked(Guid userId); + /// + /// Who may use a public share changed. Notifies every instance so open connections to it are closed. + /// Best-effort: a connection that misses it is checked on its first hub call once the revalidation interval + /// has passed since its last check. An idle connection is not checked, but cannot control anything either. + /// + Task SendPublicShareAccessRevoked(Guid publicShareId); + /// /// Notifies the email outbox consumer that one or more messages were just enqueued, so it drains /// them without waiting for its next safety-net poll. Best-effort: a lost notification only delays diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index 53de95e7..515bab26 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -23,6 +23,12 @@ public static class RedisChannels /// public static readonly RedisChannel SessionRevoked = new("session-revoked", RedisChannel.PatternMode.Literal); + /// + /// Fired when who may use a public share changed (its password was set or changed, or it was deleted). The + /// payload is the share id. Open connections to it are closed; visitors have to get in again. + /// + public static readonly RedisChannel PublicShareAccessRevoked = new("public-share-access-revoked", RedisChannel.PatternMode.Literal); + /// /// Fired when an account may no longer be used at all (deactivated or deleted). The payload is the user /// id. Every open connection of that user is closed, whatever it authenticated with. diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 0e55f96a..9d5a442d 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -38,6 +38,11 @@ public Task SendUserAuthRevoked(Guid userId) return _subscriber.PublishAsync(RedisChannels.UserAuthRevoked, userId.ToString()); } + public Task SendPublicShareAccessRevoked(Guid publicShareId) + { + return _subscriber.PublishAsync(RedisChannels.PublicShareAccessRevoked, publicShareId.ToString()); + } + public Task SendEmailOutboxPending() { // Payload-less wake-up nudge; the consumer reads the actual rows from the database.