From e6251fe6d2884b2d306d64a5db02d932f8bb1ffd Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 12 Nov 2026 16:28:54 +1100 Subject: [PATCH 1/2] feat(discord): add validated webhook delivery groundwork Keep the component non-packable until a supported subscription integration is authorized. Document beta.4 contracts and full-stream consumer limitations; add offline payload/client tests and CI coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 2 + CONTRIBUTING.md | 5 + LANCommander.Community.slnx | 2 + plugins/Server.DiscordWebhook/README.md | 135 ++++++++ .../DiscordMessage.cs | 94 ++++++ .../DiscordWebhookClient.cs | 147 +++++++++ .../DiscordWebhookEndpoint.cs | 39 +++ ...der.Community.Server.DiscordWebhook.csproj | 9 + .../DiscordWebhookTests.cs | 290 ++++++++++++++++++ ...mmunity.Server.DiscordWebhook.Tests.csproj | 14 + 10 files changed, 737 insertions(+) create mode 100644 plugins/Server.DiscordWebhook/README.md create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordMessage.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookEndpoint.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj create mode 100644 plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs create mode 100644 plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8134002..f096224 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,8 @@ jobs: ./eng/Test-GitHubPackages.ps1 - name: Validate Quake core safety tests run: dotnet test plugins/Server.Quake3/LANCommander.Community.Server.Quake3.Tests/LANCommander.Community.Server.Quake3.Tests.csproj -c Release --nologo + - name: Validate Discord webhook groundwork (not an installable plugin) + run: dotnet test plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj -c Release --nologo validate: runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 967e4ab..4d63de7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,5 +29,10 @@ procedures. Repository-local agent guidance is under [release preparation](.github/skills/plugin-release/SKILL.md), and [authoring more skills](.github/skills/repository-skill-authoring/SKILL.md). +The [Discord webhook groundwork](plugins/Server.DiscordWebhook/README.md) is +non-packable while its subscription-action host integration is blocked. Run its +focused `dotnet test` command from that README; do not add it to release +selection or claim it is an installable plugin before integration is verified. + Do not create or push release tags, publish releases, or change deployed identities without explicit maintainer authorization. diff --git a/LANCommander.Community.slnx b/LANCommander.Community.slnx index 23f1a05..56864a8 100644 --- a/LANCommander.Community.slnx +++ b/LANCommander.Community.slnx @@ -1,4 +1,6 @@ + + diff --git a/plugins/Server.DiscordWebhook/README.md b/plugins/Server.DiscordWebhook/README.md new file mode 100644 index 0000000..c4d7193 --- /dev/null +++ b/plugins/Server.DiscordWebhook/README.md @@ -0,0 +1,135 @@ +# Discord webhook action groundwork + +**Not an installable LANCommander plugin yet.** This directory contains a +non-packable Discord payload and single-attempt delivery library, with offline +tests. It deliberately has no plugin registration, event consumer, subscription +store, background worker, configuration page, or release-registry entry. +No existing plugin or generic webhook behavior is changed. + +## Host contract findings + +Inspected the official repository at +[`d5fe374e11e46479c848dd89523ae6963b4e7e8f`](https://github.com/LANCommander/LANCommander/tree/d5fe374e11e46479c848dd89523ae6963b4e7e8f) +(main, 2026-11-12) and the published +[`v2.2.0-beta.4`](https://github.com/LANCommander/LANCommander/releases/tag/v2.2.0-beta.4) +contracts (source `675befe0673c03aded2b45995694661ce454ba95`). +The public NuGet `LANCommander.Server.Plugins` feed's latest version at +inspection was `2.2.0-beta.4`; no newer package supplies the missing action API. +This library itself has no host dependency and makes no host compatibility +claim for an integrated plugin. + +The public +[`ServerEventContracts.cs`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Plugins/Messaging/ServerEventContracts.cs) +contains: + +- `IServerEventConsumer.HandleAsync(ServerEvent, CancellationToken)`, registered + in `IPlugin.ConfigureServices`. Every consumer receives every published event. +- `IServerEventTransport.ConfigureTransport(StandardConfigurer, string)` + and `ConfigureSubscriptions(StandardConfigurer)`, + also registered in `ConfigureServices`. The first registered transport replaces + the in-memory **Rebus broker transport**; it is not an outbound webhook target. + Implementing it as a Discord HTTP sender would not provide broker semantics. + +[`AddServerEvents`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/EventServiceCollectionExtensions.cs) +registers the concrete generic webhook consumer/handler and subscribes the bus to +`ServerEvent`. The +[`publisher`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/ServerEventPublisher.cs) +publishes independently of generic webhook subscriptions, after saving built-in +outboxes. The +[`dispatcher`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/ServerEventDispatcher.cs) +fans out to all consumers with the host's application-stopping token. +Consumer failures are logged by type and dropped, not retried. The default event +transport is in-memory. Durable generic webhook recovery does not replay events +to other consumers; `IServerEventOutbox` is in host Services, not the public +plugin contracts. + +The built-in +[`WebhookSubscription`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Data/Models/WebhookSubscription.cs) +has endpoint, signing secret, event filter, enabled, timeout and attempt settings, +but no provider/action identifier or action-specific configuration. Its +[`handler`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/WebhookDeliveryHandler.cs) +posts stored event-envelope JSON directly, with no plugin transformation or +delivery callback. Settings and APIs are administrator-only; saved signing +secrets are protected and not returned, but endpoint URLs are returned unchanged. +A Discord URL token cannot safely be treated as an ordinary visible endpoint. + +Therefore a Discord action **inside the host's existing subscription system** +requires a public action-provider registry/discovery contract, provider ID and +secret-aware configuration schema/persistence/UI on subscriptions, and a +host-selected delivery callback with cancellation, status and retry-after +semantics. Those APIs do not exist in beta.4 or inspected main. No fake action, +reflection, internal API dependency, or host change is included here. + +A separate plugin-owned Discord subscriptions UI could instead use +`IServerEventConsumer`, but that changes the product boundary: the plugin would +own filtering, protected credentials, storage, administration, queueing and +retries. Its durability could begin only after consumer receipt; event loss +before receipt or on enqueue failure would remain possible. That alternative +requires explicit approval before implementation. + +## Reusable Discord behavior + +`DiscordWebhookEndpoint.Parse` permits canonical HTTPS incoming webhook URLs on +`discord.com` and `discordapp.com`, using `/api/webhooks/{id}/{token}` or +`/api/v10/webhooks/{id}/{token}`. It rejects credentials, queries, fragments, +custom ports, encoded/normalized paths and arbitrary hosts. The endpoint object's +string representation is redacted; validation errors never echo the input. +Do not log, serialize or display raw endpoint input. + +`DiscordPayload.Serialize` creates Discord JSON, not a LANCommander envelope. +Supported fields are content, optional username, and rich embeds containing +title, description, RGB color, fields, footer text and author name. All mention +parsing is disabled, including user/role/everyone mentions. JSON serialization +handles quoting, escaping and Unicode without string interpolation. + +Validation rejects rather than truncates: content 2,000; username 80; at most +10 embeds; title/author 256; description 4,096; footer 2,048; at most 25 fields +per embed; field name 256 and value 1,024; combined embed text 6,000. Lengths +use UTF-16 code units (conservative for supplementary characters). Content or +a nonempty text embed is required. No attachment, forum/thread, component, +avatar, bot token, Discord SDK or arbitrary JSON support is included. + +`DiscordWebhookClient.SendAsync` performs exactly one POST, adds controlled +`wait=true` so Discord confirms the message was saved, and accepts a 1-30 second +timeout (default 10). Cancellation propagates; timeouts and transport errors +become bounded typed results. Responses, reason phrases and exception messages +are never logged or returned. Redirects, proxies, cookies and trace-header +propagation are disabled on the default handler. There is no HTTP-client-factory +request logger. The injectable handler is for trusted implementations/tests only. +Host-installed HTTP tracing/profilers can still observe URLs: disable or redact +webhook paths in that instrumentation before integrating a credentialed client. + +2xx is delivered, 408/5xx/network errors are transient, other failures +(including redirects and missing/deleted webhooks) are rejected. HTTP 429 +returns a rate-limit result and the greater valid delay from `Retry-After` +(seconds or HTTP date) and JSON `retry_after` (fractional seconds). Untrusted +rate-limit bodies are limited to 4 KiB. Invalid/missing delay remains explicitly +unknown (`null`), not success. There is **no automatic retry, sleep, rate-limit +bucket coordinator, persistent delivery history or restart recovery**. A future +adapter must schedule retries without shortening supplied delays, coordinate +per-webhook/global limits, and avoid retrying permanent failures. An ambiguous +network timeout may follow a successful send; retrying can duplicate messages. +Do not use the single-attempt client as a complete notification service. + +Discord references: +[execute webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook), +[embed limits](https://docs.discord.com/developers/resources/message#embed-object-embed-limits), +[rate limits](https://docs.discord.com/developers/topics/rate-limits). + +## Development + +Requires .NET 10 SDK. All delivery tests use an in-process fake handler and +synthetic endpoints; no network messages or real credentials are used. + +```powershell +dotnet test .\plugins\Server.DiscordWebhook\tests\LANCommander.Community.Server.DiscordWebhook.Tests\LANCommander.Community.Server.DiscordWebhook.Tests.csproj -c Release --nologo +pwsh .\eng\Test-ReleaseSelection.ps1 +pwsh .\eng\Test-Repository.ps1 +``` + +CI runs the independent tests. Host registration/discovery, permissions/UI, +installation, delivery persistence and real Discord delivery are not exercised +or claimed. The reserved future project/package/assembly identity is +`LANCommander.Community.Server.DiscordWebhook`. It remains non-packable until a +supported integration is implemented and verified; no version, changelog, +package types, registry entry, release allowlist or publication claim is added. diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordMessage.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordMessage.cs new file mode 100644 index 0000000..979d9b1 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordMessage.cs @@ -0,0 +1,94 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed record DiscordMessage( + string? Content = null, + IReadOnlyList? Embeds = null, + string? Username = null); + +public sealed record DiscordEmbed( + string? Title = null, + string? Description = null, + int? Color = null, + IReadOnlyList? Fields = null, + string? Footer = null, + string? Author = null); + +public sealed record DiscordEmbedField(string Name, string Value, bool Inline = false); + +public static class DiscordPayload +{ + private static readonly JsonSerializerOptions Options = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + public static byte[] Serialize(DiscordMessage message) + { + ArgumentNullException.ThrowIfNull(message); + CheckText(message.Content, 2000, "Content"); + CheckText(message.Username, 80, "Username"); + var embeds = message.Embeds?.ToArray() ?? []; + if (embeds.Length > 10) + throw new ArgumentException("At most 10 embeds are allowed."); + if (string.IsNullOrWhiteSpace(message.Content) && embeds.Length == 0) + throw new ArgumentException("Content or at least one embed is required."); + + var total = 0; + var payloadEmbeds = embeds.Select(embed => + { + if (embed is null) + throw new ArgumentException("Embeds cannot contain null."); + CheckText(embed.Title, 256, "Embed title"); + CheckText(embed.Description, 4096, "Embed description"); + CheckText(embed.Footer, 2048, "Embed footer"); + CheckText(embed.Author, 256, "Embed author"); + if (embed.Color is < 0 or > 0xFFFFFF) + throw new ArgumentException("Embed color must be a 24-bit RGB value."); + var fields = embed.Fields?.ToArray() ?? []; + if (fields.Length > 25) + throw new ArgumentException("At most 25 fields per embed are allowed."); + var textLength = (embed.Title?.Length ?? 0) + (embed.Description?.Length ?? 0) + + (embed.Footer?.Length ?? 0) + (embed.Author?.Length ?? 0); + var payloadFields = fields.Select(field => + { + if (field is null || string.IsNullOrWhiteSpace(field.Name) || string.IsNullOrWhiteSpace(field.Value)) + throw new ArgumentException("Embed fields require a name and value."); + CheckText(field.Name, 256, "Embed field name"); + CheckText(field.Value, 1024, "Embed field value"); + textLength += field.Name.Length + field.Value.Length; + return new { name = field.Name, value = field.Value, inline = field.Inline }; + }).ToArray(); + if (textLength == 0) + throw new ArgumentException("Each embed must contain text."); + total += textLength; + return new + { + title = embed.Title, + description = embed.Description, + color = embed.Color, + fields = payloadFields.Length == 0 ? null : payloadFields, + footer = embed.Footer is null ? null : new { text = embed.Footer }, + author = embed.Author is null ? null : new { name = embed.Author } + }; + }).ToArray(); + if (total > 6000) + throw new ArgumentException("Combined embed text must not exceed 6000 characters."); + + return JsonSerializer.SerializeToUtf8Bytes(new + { + content = message.Content, + username = message.Username, + embeds = payloadEmbeds.Length == 0 ? null : payloadEmbeds, + allowed_mentions = new { parse = Array.Empty() } + }, Options); + } + + private static void CheckText(string? value, int maximum, string field) + { + if (value is not null && (value.Length == 0 || value.Length > maximum)) + throw new ArgumentException($"{field} must contain 1-{maximum} characters when supplied."); + } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs new file mode 100644 index 0000000..ba3d623 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs @@ -0,0 +1,147 @@ +using System.Globalization; +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; + +namespace LANCommander.Community.Server.DiscordWebhook; + +public enum DiscordDeliveryStatus +{ + Delivered, + Rejected, + RateLimited, + TransientFailure, + TimedOut +} + +public sealed record DiscordDeliveryResult( + DiscordDeliveryStatus Status, + int? HttpStatusCode = null, + TimeSpan? RetryAfter = null); + +/// One attempt only; a future host action adapter must own durable scheduling. +public sealed class DiscordWebhookClient : IDisposable +{ + private readonly HttpClient _client; + + public DiscordWebhookClient() : this(new SocketsHttpHandler + { + AllowAutoRedirect = false, + UseCookies = false, + UseProxy = false, + ActivityHeadersPropagator = null, + PooledConnectionLifetime = TimeSpan.FromMinutes(2) + }) { } + + /// + /// Takes ownership of the handler. For tests or trusted handlers only; custom handlers + /// must not redirect, log request URIs, attach credentials or retry automatically. + /// + public DiscordWebhookClient(HttpMessageHandler handler) + { + ArgumentNullException.ThrowIfNull(handler); + _client = new HttpClient(handler, disposeHandler: true) { Timeout = Timeout.InfiniteTimeSpan }; + } + + public async Task SendAsync( + DiscordWebhookEndpoint endpoint, + DiscordMessage message, + int timeoutSeconds = 10, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ArgumentNullException.ThrowIfNull(endpoint); + if (timeoutSeconds is < 1 or > 30) + throw new ArgumentOutOfRangeException(nameof(timeoutSeconds), "Timeout must be 1-30 seconds."); + var body = DiscordPayload.Serialize(message); + // Discord's default wait=false can acknowledge a message that was never saved. + var address = new UriBuilder(endpoint.Address) { Query = "wait=true" }.Uri; + using var request = new HttpRequestMessage(HttpMethod.Post, address); + request.Content = new ByteArrayContent(body); + request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); + + try + { + using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + var code = (int)response.StatusCode; + if (response.IsSuccessStatusCode) + return new(DiscordDeliveryStatus.Delivered, code); + if (response.StatusCode == HttpStatusCode.TooManyRequests) + { + var headerDelay = ReadRetryAfter(response); + var bodyDelay = await ReadBodyRetryAfterAsync(response, timeout.Token); + var delay = headerDelay is null ? bodyDelay : + bodyDelay is null || headerDelay >= bodyDelay ? headerDelay : bodyDelay; + return new(DiscordDeliveryStatus.RateLimited, code, delay); + } + return new(code >= 500 || code == 408 + ? DiscordDeliveryStatus.TransientFailure : DiscordDeliveryStatus.Rejected, code); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (OperationCanceledException) + { + return new(DiscordDeliveryStatus.TimedOut); + } + catch (HttpRequestException) + { + return new(DiscordDeliveryStatus.TransientFailure); + } + catch (IOException) + { + return new(DiscordDeliveryStatus.TransientFailure); + } + } + + private static TimeSpan? ReadRetryAfter(HttpResponseMessage response) + { + if (!response.Headers.TryGetValues("Retry-After", out var values)) + return null; + var value = values.FirstOrDefault(); + if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var seconds)) + return Delay(seconds); + if (DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date)) + return Delay(Math.Max(0, (date - DateTimeOffset.UtcNow).TotalSeconds)); + return null; + } + + private static async Task ReadBodyRetryAfterAsync( + HttpResponseMessage response, CancellationToken cancellationToken) + { + // Discord returns retry_after in seconds, potentially fractional. Bound untrusted bodies. + using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + var buffer = new byte[4097]; + var length = 0; + while (length < buffer.Length) + { + var read = await stream.ReadAsync(buffer.AsMemory(length), cancellationToken); + if (read == 0) + break; + length += read; + } + if (length > 4096) + return null; + try + { + using var json = JsonDocument.Parse(buffer.AsMemory(0, length)); + return json.RootElement.ValueKind == JsonValueKind.Object && + json.RootElement.TryGetProperty("retry_after", out var value) && + value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var seconds) + ? Delay(seconds) : null; + } + catch (JsonException) + { + return null; + } + } + + private static TimeSpan? Delay(double seconds) => + double.IsFinite(seconds) && seconds >= 0 && seconds < TimeSpan.MaxValue.TotalSeconds - 1 + ? TimeSpan.FromSeconds(seconds) : null; + + public void Dispose() => _client.Dispose(); +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookEndpoint.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookEndpoint.cs new file mode 100644 index 0000000..8624e53 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookEndpoint.cs @@ -0,0 +1,39 @@ +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed class DiscordWebhookEndpoint +{ + internal Uri Address { get; } + + private DiscordWebhookEndpoint(Uri address) => Address = address; + + public static DiscordWebhookEndpoint Parse(string value) + { + const string error = "Use an HTTPS Discord incoming webhook URL without query, fragment or credentials."; + if (string.IsNullOrEmpty(value) || value.Length > 2048 || + value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)) || + value.Contains('%') || value.Contains('\\') || + !Uri.TryCreate(value, UriKind.Absolute, out var address) || + address.Scheme != Uri.UriSchemeHttps || !address.IsDefaultPort || + address.Host is not ("discord.com" or "discordapp.com") || + address.UserInfo.Length != 0 || address.Query.Length != 0 || address.Fragment.Length != 0) + throw new ArgumentException(error); + + var parts = address.AbsolutePath.Split('/'); + var offset = parts.Length == 6 && parts[2] == "v10" ? 1 : 0; + if (parts.Length != 5 + offset || parts[0] != "" || parts[1] != "api" || + parts[2 + offset] != "webhooks" || + parts[3 + offset].Length is < 1 or > 20 || + !parts[3 + offset].All(char.IsAsciiDigit) || + parts[4 + offset].Length is < 1 or > 256 || + !parts[4 + offset].All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-')) + throw new ArgumentException(error); + + // Reject normalization such as /../ rather than accepting a different path. + if (value != address.GetLeftPart(UriPartial.Authority) + address.AbsolutePath) + throw new ArgumentException(error); + + return new DiscordWebhookEndpoint(address); + } + + public override string ToString() => "[Discord webhook endpoint redacted]"; +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj new file mode 100644 index 0000000..d672694 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj @@ -0,0 +1,9 @@ + + + LANCommander.Community.Server.DiscordWebhook + LANCommander.Community.Server.DiscordWebhook + LANCommander.Community.Server.DiscordWebhook + + false + + diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs new file mode 100644 index 0000000..06f1307 --- /dev/null +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs @@ -0,0 +1,290 @@ +using System.Net; +using System.Text.Json; +using Xunit; + +namespace LANCommander.Community.Server.DiscordWebhook.Tests; + +public sealed class DiscordWebhookTests +{ + // Synthetic credentials; every request is intercepted by FakeHandler. + private const string Endpoint = "https://discord.com/api/webhooks/123456789012345678/synthetic-token"; + + [Theory] + [InlineData(Endpoint)] + [InlineData("https://discordapp.com/api/webhooks/123/synthetic_token")] + [InlineData("https://discord.com/api/v10/webhooks/123/synthetic-token")] + public void AcceptsSupportedIncomingWebhookEndpoints(string value) + { + Assert.Equal("[Discord webhook endpoint redacted]", DiscordWebhookEndpoint.Parse(value).ToString()); + } + + [Theory] + [InlineData("")] + [InlineData("http://discord.com/api/webhooks/123/synthetic-token")] + [InlineData("https://discord.com.evil.example/api/webhooks/123/synthetic-token")] + [InlineData("https://127.0.0.1/api/webhooks/123/synthetic-token")] + [InlineData("https://discord.com:444/api/webhooks/123/synthetic-token")] + [InlineData("https://user:password@discord.com/api/webhooks/123/synthetic-token")] + [InlineData(Endpoint + "?wait=true")] + [InlineData(Endpoint + "#fragment")] + [InlineData(Endpoint + "/messages/123")] + [InlineData(Endpoint + "/")] + [InlineData("https://discord.com/api/webhooks/id/synthetic-token")] + [InlineData("https://discord.com/api/webhooks/123/")] + [InlineData("https://discord.com/api/webhooks/123/%73ynthetic-token")] + [InlineData("https://discord.com/api/webhooks/123/../123/synthetic-token")] + [InlineData("https://discord.com\\api\\webhooks\\123\\synthetic-token")] + [InlineData(" " + Endpoint)] + public void RejectsUnsafeOrUnsupportedEndpointsWithoutEchoingInput(string value) + { + var exception = Assert.Throws(() => DiscordWebhookEndpoint.Parse(value)); + Assert.DoesNotContain("synthetic", exception.ToString()); + Assert.DoesNotContain("password", exception.ToString()); + Assert.DoesNotContain("https://", exception.ToString()); + } + + [Fact] + public void SerializesDiscordShapeAndEscapesUserContentWithoutEnablingMentions() + { + const string text = "Quote \" slash \\ newline\n @everyone <@123> \U0001F3AE"; + var message = new DiscordMessage(text, + [new(Title: "Game", Description: text, Color: 0x123456, + Fields: [new("Name", text, true)], Footer: "Footer", Author: "LANCommander")], + Username: "Community"); + using var json = JsonDocument.Parse(DiscordPayload.Serialize(message)); + var root = json.RootElement; + Assert.Equal(text, root.GetProperty("content").GetString()); + Assert.Equal("Community", root.GetProperty("username").GetString()); + Assert.Empty(root.GetProperty("allowed_mentions").GetProperty("parse").EnumerateArray()); + var embed = root.GetProperty("embeds")[0]; + Assert.Equal(text, embed.GetProperty("description").GetString()); + Assert.Equal(0x123456, embed.GetProperty("color").GetInt32()); + Assert.Equal("Footer", embed.GetProperty("footer").GetProperty("text").GetString()); + Assert.Equal("LANCommander", embed.GetProperty("author").GetProperty("name").GetString()); + Assert.Equal(text, embed.GetProperty("fields")[0].GetProperty("value").GetString()); + Assert.True(embed.GetProperty("fields")[0].GetProperty("inline").GetBoolean()); + Assert.False(root.TryGetProperty("payload", out _)); + } + + [Fact] + public void SupportsContentOnlyOrEmbedOnlyAndOmitsUnsetFields() + { + using var content = JsonDocument.Parse(DiscordPayload.Serialize(new("Hello"))); + Assert.False(content.RootElement.TryGetProperty("embeds", out _)); + Assert.False(content.RootElement.TryGetProperty("username", out _)); + using var embed = JsonDocument.Parse(DiscordPayload.Serialize(new(Embeds: [new(Description: "Hello")]))); + Assert.False(embed.RootElement.TryGetProperty("content", out _)); + Assert.False(embed.RootElement.GetProperty("embeds")[0].TryGetProperty("fields", out _)); + } + + public static IEnumerable InvalidMessages() + { + yield return [new DiscordMessage()]; + yield return [new DiscordMessage(" ")]; + yield return [new DiscordMessage(new string('x', 2001))]; + yield return [new DiscordMessage("OK", Username: new string('x', 81))]; + yield return [new DiscordMessage(Embeds: Enumerable.Repeat(new DiscordEmbed(Title: "x"), 11).ToArray())]; + yield return [new DiscordMessage(Embeds: [new()])]; + yield return [new DiscordMessage(Embeds: [new(Title: new string('x', 257))])]; + yield return [new DiscordMessage(Embeds: [new(Description: new string('x', 4097))])]; + yield return [new DiscordMessage(Embeds: [new(Footer: new string('x', 2049))])]; + yield return [new DiscordMessage(Embeds: [new(Author: new string('x', 257))])]; + yield return [new DiscordMessage(Embeds: [new(Title: "x", Color: -1)])]; + yield return [new DiscordMessage(Embeds: [new(Title: "x", Color: 0x1000000)])]; + yield return [new DiscordMessage(Embeds: [new(Fields: [new("", "x")])])]; + yield return [new DiscordMessage(Embeds: [new(Fields: [new("x", " ")])])]; + yield return [new DiscordMessage(Embeds: [new(Fields: [new(new string('x', 257), "x")])])]; + yield return [new DiscordMessage(Embeds: [new(Fields: [new("x", new string('x', 1025))])])]; + yield return [new DiscordMessage(Embeds: [new(Fields: Enumerable.Repeat(new DiscordEmbedField("x", "x"), 26).ToArray())])]; + yield return [new DiscordMessage(Embeds: [new(Description: new string('x', 3000)), new(Description: new string('x', 3001))])]; + } + + [Theory] + [MemberData(nameof(InvalidMessages))] + public void RejectsInvalidPayloadsBeforeSending(DiscordMessage message) + { + Assert.Throws(() => DiscordPayload.Serialize(message)); + } + + [Fact] + public void AcceptsExactContentAndCombinedEmbedBounds() + { + var message = new DiscordMessage(new string('x', 2000), + [new(Description: new string('x', 4096), Footer: new string('x', 1904))], + new string('x', 80)); + using var json = JsonDocument.Parse(DiscordPayload.Serialize(message)); + Assert.Equal(2000, json.RootElement.GetProperty("content").GetString()!.Length); + } + + [Theory] + [InlineData(200, DiscordDeliveryStatus.Delivered)] + [InlineData(204, DiscordDeliveryStatus.Delivered)] + [InlineData(302, DiscordDeliveryStatus.Rejected)] + [InlineData(400, DiscordDeliveryStatus.Rejected)] + [InlineData(401, DiscordDeliveryStatus.Rejected)] + [InlineData(404, DiscordDeliveryStatus.Rejected)] + [InlineData(408, DiscordDeliveryStatus.TransientFailure)] + [InlineData(500, DiscordDeliveryStatus.TransientFailure)] + [InlineData(503, DiscordDeliveryStatus.TransientFailure)] + public async Task MapsHttpStatusWithoutReturningReceiverContent(int code, DiscordDeliveryStatus expected) + { + var handler = new FakeHandler(async (request, ct) => + { + Assert.Equal(HttpMethod.Post, request.Method); + Assert.Equal(Endpoint + "?wait=true", request.RequestUri!.AbsoluteUri); + Assert.Equal("application/json", request.Content!.Headers.ContentType!.MediaType); + using var json = JsonDocument.Parse(await request.Content.ReadAsByteArrayAsync(ct)); + Assert.Equal("Hello", json.RootElement.GetProperty("content").GetString()); + return new((HttpStatusCode)code) + { + ReasonPhrase = Endpoint, + Content = new StringContent(Endpoint) + }; + }); + using var client = new DiscordWebhookClient(handler); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(expected, result.Status); + Assert.Equal(code, result.HttpStatusCode); + Assert.DoesNotContain("synthetic", result.ToString()); + Assert.Equal(1, handler.Calls); + } + + [Theory] + [InlineData("2.5", "{\"retry_after\":1.25}", 2.5)] + [InlineData("1", "{\"retry_after\":2.75,\"global\":true}", 2.75)] + [InlineData(null, "{\"retry_after\":0.125}", 0.125)] + [InlineData(null, "untrusted response", null)] + [InlineData(null, "{\"retry_after\":-1}", null)] + [InlineData(null, "{\"retry_after\":1e300}", null)] + [InlineData(null, "{\"retry_after\":\"5\"}", null)] + [InlineData(null, "[]", null)] + public async Task SurfacesRateLimitDelayWithoutRetrying(string? header, string body, double? seconds) + { + var handler = new FakeHandler((_, _) => + { + var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests) { Content = new StringContent(body) }; + if (header is not null) + response.Headers.TryAddWithoutValidation("Retry-After", header); + return Task.FromResult(response); + }); + using var client = new DiscordWebhookClient(handler); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(DiscordDeliveryStatus.RateLimited, result.Status); + Assert.Equal(seconds, result.RetryAfter?.TotalSeconds); + Assert.Equal(429, result.HttpStatusCode); + Assert.Equal(1, handler.Calls); + } + + [Fact] + public async Task BoundsRateLimitResponseBody() + { + var handler = new FakeHandler((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.TooManyRequests) + { + Content = new StringContent("{\"retry_after\":2,\"padding\":\"" + new string('x', 5000) + "\"}") + })); + using var client = new DiscordWebhookClient(handler); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(DiscordDeliveryStatus.RateLimited, result.Status); + Assert.Null(result.RetryAfter); + } + + [Fact] + public async Task ParsesHttpDateRetryAfter() + { + var date = DateTimeOffset.UtcNow.AddMinutes(2); + using var client = new DiscordWebhookClient(new FakeHandler((_, _) => + { + var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests) + { + Content = new StringContent("{}") + }; + response.Headers.RetryAfter = new(date); + return Task.FromResult(response); + })); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(DiscordDeliveryStatus.RateLimited, result.Status); + Assert.InRange(result.RetryAfter!.Value.TotalSeconds, 100, 120); + } + + [Fact] + public async Task RejectsInvalidMessageWithoutInvokingHandlerOrEchoingContent() + { + var handler = new FakeHandler((_, _) => throw new InvalidOperationException("Should not send")); + using var client = new DiscordWebhookClient(handler); + var exception = await Assert.ThrowsAsync(() => + client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new(new string('x', 2001)))); + Assert.DoesNotContain(new string('x', 100), exception.ToString()); + Assert.Equal(0, handler.Calls); + } + + [Fact] + public async Task RedactsTransportExceptionRatherThanRetainingIt() + { + using var client = new DiscordWebhookClient(new FakeHandler((_, _) => + throw new HttpRequestException("Failed at " + Endpoint, new IOException(Endpoint)))); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(DiscordDeliveryStatus.TransientFailure, result.Status); + Assert.DoesNotContain("synthetic", result.ToString()); + Assert.Null(result.HttpStatusCode); + } + + [Fact] + public async Task CallerCancellationPropagatesAndDoesNotBecomeRetryableFailure() + { + using var cts = new CancellationTokenSource(); + using var client = new DiscordWebhookClient(new FakeHandler(async (_, ct) => + { + await cts.CancelAsync(); + await Task.Delay(Timeout.Infinite, ct); + return new(HttpStatusCode.NoContent); + })); + await Assert.ThrowsAnyAsync(() => + client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello"), cancellationToken: cts.Token)); + } + + [Fact] + public async Task PreCanceledCallDoesNotSend() + { + var handler = new FakeHandler((_, _) => throw new InvalidOperationException("Should not send")); + using var client = new DiscordWebhookClient(handler); + await Assert.ThrowsAnyAsync(() => + client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello"), cancellationToken: new(true))); + Assert.Equal(0, handler.Calls); + } + + [Fact] + public async Task EnforcesTimeoutOnPendingNetworkOperation() + { + using var client = new DiscordWebhookClient(new FakeHandler(async (_, ct) => + { + await Task.Delay(Timeout.Infinite, ct); + return new(HttpStatusCode.NoContent); + })); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello"), timeoutSeconds: 1); + Assert.Equal(DiscordDeliveryStatus.TimedOut, result.Status); + } + + [Theory] + [InlineData(0)] + [InlineData(31)] + public async Task RejectsInvalidTimeoutBeforeSending(int timeout) + { + var handler = new FakeHandler((_, _) => throw new InvalidOperationException("Should not send")); + using var client = new DiscordWebhookClient(handler); + await Assert.ThrowsAsync(() => + client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello"), timeout)); + Assert.Equal(0, handler.Calls); + } + + private sealed class FakeHandler( + Func> send) : HttpMessageHandler + { + public int Calls { get; private set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Calls++; + return send(request, cancellationToken); + } + } +} diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj new file mode 100644 index 0000000..ca30039 --- /dev/null +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj @@ -0,0 +1,14 @@ + + + LANCommander.Community.Server.DiscordWebhook.Tests + LANCommander.Community.Server.DiscordWebhook.Tests + false + true + + + + + + + + From 14bd262636551e61bc9520c2599faac60085182e Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 19 Nov 2026 10:44:54 +1100 Subject: [PATCH 2/2] feat(discord): add standalone admin subscriptions and delivery queue Use the published beta.4 full-stream event consumer with protected plugin-owned subscriptions, native administrator management, bounded persistent retries and safe Discord embeds. Preserve generic host webhooks and document best-effort receipt and single-host delivery limits. Register independent packaging/releases, cover rendered UI and emitted-package loading, and align publication guards with the transferred canonical repository without changing existing plugin artifacts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 17 + CONTRIBUTING.md | 8 +- README.md | 3 +- RELEASES.md | 14 +- eng/Build-Plugin.ps1 | 5 +- eng/PluginRelease.psm1 | 2 +- eng/Publish-GitHubPackage.ps1 | 2 +- eng/Publish-NuGetPackage.ps1 | 2 +- eng/Publish-Release.ps1 | 2 +- eng/Test-GitHubPackages.ps1 | 3 + eng/Test-NuGetPackage.ps1 | 2 +- eng/Test-ReleaseSelection.ps1 | 5 +- eng/Validate-Plugin.ps1 | 2 +- eng/plugins.json | 22 + plugins/Server.DiscordWebhook/CHANGELOG.md | 13 + plugins/Server.DiscordWebhook/README.md | 290 ++++++----- .../eng/Test-Package.ps1 | 42 ++ .../DiscordAdministration.cs | 39 ++ .../DiscordModels.cs | 64 +++ .../DiscordPlugin.cs | 85 ++++ .../DiscordStore.cs | 352 +++++++++++++ .../DiscordWebhookClient.cs | 7 +- ...der.Community.Server.DiscordWebhook.csproj | 25 +- .../Pages/Index.razor | 164 ++++++ .../_Imports.razor | 6 + .../DiscordWebhookTests.cs | 25 + .../HostIntegrationTests.cs | 192 +++++++ ...mmunity.Server.DiscordWebhook.Tests.csproj | 6 + .../SubscriptionTests.cs | 479 ++++++++++++++++++ plugins/Server.DiscordWebhook/version.txt | 1 + 31 files changed, 1730 insertions(+), 153 deletions(-) create mode 100644 plugins/Server.DiscordWebhook/CHANGELOG.md create mode 100644 plugins/Server.DiscordWebhook/eng/Test-Package.ps1 create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordAdministration.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordModels.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordPlugin.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordStore.cs create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/Pages/Index.razor create mode 100644 plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/_Imports.razor create mode 100644 plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/HostIntegrationTests.cs create mode 100644 plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/SubscriptionTests.cs create mode 100644 plugins/Server.DiscordWebhook/version.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f096224..4432ce8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,15 +26,13 @@ jobs: ./eng/Test-GitHubPackages.ps1 - name: Validate Quake core safety tests run: dotnet test plugins/Server.Quake3/LANCommander.Community.Server.Quake3.Tests/LANCommander.Community.Server.Quake3.Tests.csproj -c Release --nologo - - name: Validate Discord webhook groundwork (not an installable plugin) - run: dotnet test plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj -c Release --nologo validate: runs-on: ubuntu-latest strategy: fail-fast: false matrix: - plugin: [Server.Mcp, Server.RecompCatalog, Launcher.MQTT, Server.Quake3] + plugin: [Server.Mcp, Server.RecompCatalog, Launcher.MQTT, Server.Quake3, Server.DiscordWebhook] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b05bb6f..d8e969c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,6 +7,7 @@ on: - server-recompcatalog-v* - launcher-mqtt-v* - server-quake3-v* + - server-discordwebhook-v* workflow_dispatch: inputs: tag: @@ -127,6 +128,22 @@ jobs: secrets: nuget_api_key: ${{ secrets.NUGET_API_KEY }} + server-discordwebhook: + needs: plan + if: needs.plan.outputs.plugin == 'Server.DiscordWebhook' + permissions: + actions: read + contents: write + packages: write + uses: ./.github/workflows/release-plugin.yml + with: + plugin: Server.DiscordWebhook + tag: ${{ needs.plan.outputs.tag }} + artifact_run_id: ${{ needs.plan.outputs.artifact_run_id }} + artifact_run_attempt: ${{ needs.plan.outputs.artifact_run_attempt }} + secrets: + nuget_api_key: ${{ secrets.NUGET_API_KEY }} + server-recompcatalog: needs: plan if: needs.plan.outputs.plugin == 'Server.RecompCatalog' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4d63de7..5e51211 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,6 +11,7 @@ Current component roots are: - `LANCommander.Community.Server.RecompCatalog` - `LANCommander.Community.Server.Quake3` and its `.Core` / test projects - `LANCommander.Community.Launcher.MQTT` +- `LANCommander.Community.Server.DiscordWebhook` and its test project Keep semantic plugin IDs, data IDs, configuration keys and protocol identities stable. A package/assembly rename is a new feed identity and needs a new version @@ -29,10 +30,9 @@ procedures. Repository-local agent guidance is under [release preparation](.github/skills/plugin-release/SKILL.md), and [authoring more skills](.github/skills/repository-skill-authoring/SKILL.md). -The [Discord webhook groundwork](plugins/Server.DiscordWebhook/README.md) is -non-packable while its subscription-action host integration is blocked. Run its -focused `dotnet test` command from that README; do not add it to release -selection or claim it is an installable plugin before integration is verified. +The [Discord webhook plugin](plugins/Server.DiscordWebhook/README.md) owns a +separate administrator UI and subscription queue. Tests must use fake HTTP +handlers and synthetic credentials, never external Discord deliveries. Do not create or push release tags, publish releases, or change deployed identities without explicit maintainer authorization. diff --git a/README.md b/README.md index 676619d..2f05f18 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ projects and releases. - [Server.Mcp](plugins/Server.Mcp/README.md) - [Server.RecompCatalog](plugins/Server.RecompCatalog/README.md) - [Server.Quake3](plugins/Server.Quake3/README.md) +- [Server.DiscordWebhook](plugins/Server.DiscordWebhook/README.md) - [Launcher.MQTT](plugins/Launcher.MQTT/README.md) Each child README is the canonical guide for its plugin's requirements, @@ -39,7 +40,7 @@ Validate a single plugin and create its local install artifact with `eng/Validate-Plugin.ps1`, selecting a component from the registry: ```powershell -pwsh .\eng\Validate-Plugin.ps1 -Plugin -OutputDirectory +pwsh .\eng\Validate-Plugin.ps1 -Plugin -OutputDirectory ``` The output directory must not already exist. See each plugin README for its diff --git a/RELEASES.md b/RELEASES.md index 52fd89d..41fc5d1 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -21,6 +21,7 @@ metadata when changing a component. | `Server.RecompCatalog` | `plugins/Server.RecompCatalog/version.txt` | `plugins/Server.RecompCatalog/CHANGELOG.md` | `server-recompcatalog-v` | `LANCommander.Community.Server.RecompCatalog..nupkg` | GitHub Packages; NuGet.org if `NUGET_API_KEY` is set | | `Server.Quake3` | `plugins/Server.Quake3/version.txt` | `plugins/Server.Quake3/CHANGELOG.md` | `server-quake3-v` | `LANCommander.Community.Server.Quake3..nupkg` | GitHub Packages; NuGet.org if `NUGET_API_KEY` is set | | `Launcher.MQTT` | `plugins/Launcher.MQTT/version.txt` | `plugins/Launcher.MQTT/CHANGELOG.md` | `launcher-mqtt-v` | `LANCommander.Community.Launcher.MQTT..nupkg` | GitHub Packages; NuGet.org if `NUGET_API_KEY` is set | +| `Server.DiscordWebhook` | `plugins/Server.DiscordWebhook/version.txt` | `plugins/Server.DiscordWebhook/CHANGELOG.md` | `server-discordwebhook-v` | `LANCommander.Community.Server.DiscordWebhook..nupkg` | GitHub Packages; NuGet.org if `NUGET_API_KEY` is set | Use complete SemVer in `version.txt`, including prerelease identifiers when applicable. The tag must contain that exact version, and the changelog must @@ -186,7 +187,7 @@ There is one release process: the component tag workflow creates the GitHub Release and publishes eligible `.nupkg` components to package feeds. There are no separate manual feed-dispatch workflows. -`eng/plugins.json` explicitly identifies feed-eligible components. All four +`eng/plugins.json` explicitly identifies feed-eligible components. All five `.nupkg` components publish to GitHub Packages on every successful component release. NuGet.org publication is automatically attempted for those same components only when the repository Actions secret `NUGET_API_KEY` is @@ -206,6 +207,7 @@ IDs, give it an expiry, and store it as the repository Actions secret named - `LANCommander.Community.Server.RecompCatalog` - `LANCommander.Community.Server.Quake3` - `LANCommander.Community.Launcher.MQTT` +- `LANCommander.Community.Server.DiscordWebhook` Do not use a personal account-wide key or commit the secret. No API key, NuGet.org account, trusted publisher, or external service is configured by @@ -224,10 +226,12 @@ The NuGet.org publisher has GitHub Release job has `contents: write`. `RepositoryUrl` in the plugin packages points to `https://github.com/LANCommander/LANCommander.Community`, linking packages to -the repository. After a first authorized GitHub Packages publication, -maintainers should review package visibility and repository access settings; -new packages may default to private, and public distribution must be -intentionally enabled in GitHub's package settings. +the repository. Existing package metadata and released artifacts remain +unchanged. Publication guards target only the canonical `LANCommander` owner. +After a first authorized GitHub Packages publication, maintainers should +review package visibility and repository access settings; new packages may +default to private, and public distribution must be intentionally enabled in +GitHub's package settings. ### Package discovery and eligibility diff --git a/eng/Build-Plugin.ps1 b/eng/Build-Plugin.ps1 index 6f5c6a3..2c01638 100644 --- a/eng/Build-Plugin.ps1 +++ b/eng/Build-Plugin.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3', 'Server.DiscordWebhook')] [string] $Plugin, [switch] $Package, [string] $OutputDirectory @@ -74,6 +74,9 @@ else { elseif ($Plugin -eq 'Server.Quake3') { & (Join-Path $repositoryRoot 'plugins/Server.Quake3/eng/Test-Package.ps1') -PackagePath $asset -ExpectedVersion $version } + elseif ($Plugin -eq 'Server.DiscordWebhook') { + & (Join-Path $repositoryRoot 'plugins/Server.DiscordWebhook/eng/Test-Package.ps1') -PackagePath $asset -ExpectedVersion $version + } else { & (Join-Path $PSScriptRoot 'Test-Recomp-Package.ps1') -PackagePath $asset -ExpectedVersion $version } diff --git a/eng/PluginRelease.psm1 b/eng/PluginRelease.psm1 index 155633d..32a2356 100644 --- a/eng/PluginRelease.psm1 +++ b/eng/PluginRelease.psm1 @@ -14,7 +14,7 @@ function Assert-PluginComponentIdentity { function Get-PluginRegistry { $path = Join-Path (Split-Path $PSScriptRoot -Parent) 'eng\plugins.json' $registry = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json - if ($registry.schemaVersion -ne 1 -or @($registry.plugins).Count -ne 4) { + if ($registry.schemaVersion -ne 1 -or @($registry.plugins).Count -ne 5) { throw "Unsupported or incomplete plugin registry: $path" } diff --git a/eng/Publish-GitHubPackage.ps1 b/eng/Publish-GitHubPackage.ps1 index 9c90bc6..46b01d3 100644 --- a/eng/Publish-GitHubPackage.ps1 +++ b/eng/Publish-GitHubPackage.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT', 'Server.DiscordWebhook')] [string] $Plugin, [Parameter(Mandatory)][string] $Tag, [Parameter(Mandatory)][string] $ArtifactDirectory, diff --git a/eng/Publish-NuGetPackage.ps1 b/eng/Publish-NuGetPackage.ps1 index b2f14e3..8aba19c 100644 --- a/eng/Publish-NuGetPackage.ps1 +++ b/eng/Publish-NuGetPackage.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT', 'Server.DiscordWebhook')] [string] $Plugin, [Parameter(Mandatory)][string] $Tag, [Parameter(Mandatory)][string] $ArtifactDirectory, diff --git a/eng/Publish-Release.ps1 b/eng/Publish-Release.ps1 index eed06d3..c0ad021 100644 --- a/eng/Publish-Release.ps1 +++ b/eng/Publish-Release.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3', 'Server.DiscordWebhook')] [string] $Plugin, [Parameter(Mandatory)][string] $Tag, [Parameter(Mandatory)][string] $ArtifactDirectory, diff --git a/eng/Test-GitHubPackages.ps1 b/eng/Test-GitHubPackages.ps1 index 60bfad4..ded3640 100644 --- a/eng/Test-GitHubPackages.ps1 +++ b/eng/Test-GitHubPackages.ps1 @@ -208,6 +208,9 @@ try { Assert-Fails { & (Join-Path $PSScriptRoot 'Publish-GitHubPackage.ps1') -Plugin Server.Mcp -Tag $testTag -ArtifactDirectory $artifactDirectory -Owner someone-else -Repository someone-else/LANCommander.Community -Publish -PlanOnly } 'restricted to the canonical' 'Repository/owner guard' + Assert-Fails { + & (Join-Path $PSScriptRoot 'Publish-GitHubPackage.ps1') -Plugin Server.Mcp -Tag $testTag -ArtifactDirectory $artifactDirectory -Owner aaronpowell -Repository aaronpowell/LANCommander.Community -Publish -PlanOnly + } 'restricted to the canonical' 'Former owner cannot publish after transfer' $equivalentPath = Join-Path $testRoot 'equivalent.nupkg' New-RepackedPackage -SourcePath $packagePath -DestinationPath $equivalentPath diff --git a/eng/Test-NuGetPackage.ps1 b/eng/Test-NuGetPackage.ps1 index a50f068..2f547ee 100644 --- a/eng/Test-NuGetPackage.ps1 +++ b/eng/Test-NuGetPackage.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Server.Quake3', 'Launcher.MQTT', 'Server.DiscordWebhook')] [string] $Plugin, [Parameter(Mandatory)][string] $PackagePath, [Parameter(Mandatory)][string] $ExpectedVersion, diff --git a/eng/Test-ReleaseSelection.ps1 b/eng/Test-ReleaseSelection.ps1 index e828fe2..245271e 100644 --- a/eng/Test-ReleaseSelection.ps1 +++ b/eng/Test-ReleaseSelection.ps1 @@ -25,7 +25,10 @@ Assert-Equal '0.2.2' $tag[0].version 'Component-tag SemVer' $quake = @(Resolve-PluginSelection -Tag 'server-quake3-v0.1.0-beta.2') Assert-Equal 'Server.Quake3' $quake[0].key 'Quake component-tag selection' Assert-Equal '0.1.0-beta.2' $quake[0].version 'Quake independent prerelease' -Assert-Equal 4 @(Get-PluginRegistry).Count 'Complete component registry' +Assert-Equal 5 @(Get-PluginRegistry).Count 'Complete component registry' +$discord = @(Resolve-PluginSelection -Tag 'server-discordwebhook-v0.1.0-beta.1') +Assert-Equal 'Server.DiscordWebhook' $discord[0].key 'Discord independent component selection' +Assert-Equal '0.1.0-beta.1' $discord[0].version 'Discord prerelease version' $batch = @(Resolve-PluginSelection -Plugins @('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT')) Assert-Equal @('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT') @($batch | ForEach-Object key) 'Coordinated LC batch' diff --git a/eng/Validate-Plugin.ps1 b/eng/Validate-Plugin.ps1 index c8a7e19..7e9bf19 100644 --- a/eng/Validate-Plugin.ps1 +++ b/eng/Validate-Plugin.ps1 @@ -1,7 +1,7 @@ [CmdletBinding()] param( [Parameter(Mandatory)] - [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3')] + [ValidateSet('Server.Mcp', 'Server.RecompCatalog', 'Launcher.MQTT', 'Server.Quake3', 'Server.DiscordWebhook')] [string] $Plugin, [string] $OutputDirectory ) diff --git a/eng/plugins.json b/eng/plugins.json index 2d8a8c7..4e62caf 100644 --- a/eng/plugins.json +++ b/eng/plugins.json @@ -1,6 +1,28 @@ { "schemaVersion": 1, "plugins": [ + { + "key": "Server.DiscordWebhook", + "tagPrefix": "server-discordwebhook", + "versionFile": "plugins/Server.DiscordWebhook/version.txt", + "project": "plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj", + "tests": [ + "plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj" + ], + "rootNamespace": "LANCommander.Community.Server.DiscordWebhook", + "packageId": "LANCommander.Community.Server.DiscordWebhook", + "assemblyName": "LANCommander.Community.Server.DiscordWebhook", + "packageTypes": ["LANCommander.Plugin", "LANCommander.Plugin.Server"], + "packageTags": ["LANCommander", "plugin", "server", "discord", "webhook"], + "host": "Server", + "minimumHostVersion": "2.2.0-beta.4", + "maximumHostVersion": null, + "hostPackageVersion": "2.2.0-beta.4", + "hostSourceCommit": "675befe0673c03aded2b45995694661ce454ba95", + "artifactFormat": "nupkg", + "githubPackagesEligible": true, + "nugetOrgEligible": true + }, { "key": "Server.Quake3", "tagPrefix": "server-quake3", diff --git a/plugins/Server.DiscordWebhook/CHANGELOG.md b/plugins/Server.DiscordWebhook/CHANGELOG.md new file mode 100644 index 0000000..3738298 --- /dev/null +++ b/plugins/Server.DiscordWebhook/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 0.1.0-beta.1 + +- Add a separate administrator-only Discord webhook management page. +- Consume beta.4 server events with plugin-owned filters, enabled subscriptions, + protected webhook credentials, safe message embeds and synthetic test delivery. +- Persist accepted work and bounded retries in host-preserved plugin Data storage. + Expose delivery history, capacity warnings, secret failures and HTTP status. +- Add offline payload, transport, persistence, retry, authorization, rendered UI, + registration and extracted-package loader tests. +- Document best-effort receipt, restart recovery, duplicate delivery, single-host + storage and operational limits. Generic webhook management is unchanged. diff --git a/plugins/Server.DiscordWebhook/README.md b/plugins/Server.DiscordWebhook/README.md index c4d7193..8876dc9 100644 --- a/plugins/Server.DiscordWebhook/README.md +++ b/plugins/Server.DiscordWebhook/README.md @@ -1,135 +1,171 @@ -# Discord webhook action groundwork - -**Not an installable LANCommander plugin yet.** This directory contains a -non-packable Discord payload and single-attempt delivery library, with offline -tests. It deliberately has no plugin registration, event consumer, subscription -store, background worker, configuration page, or release-registry entry. -No existing plugin or generic webhook behavior is changed. - -## Host contract findings - -Inspected the official repository at -[`d5fe374e11e46479c848dd89523ae6963b4e7e8f`](https://github.com/LANCommander/LANCommander/tree/d5fe374e11e46479c848dd89523ae6963b4e7e8f) -(main, 2026-11-12) and the published -[`v2.2.0-beta.4`](https://github.com/LANCommander/LANCommander/releases/tag/v2.2.0-beta.4) -contracts (source `675befe0673c03aded2b45995694661ce454ba95`). -The public NuGet `LANCommander.Server.Plugins` feed's latest version at -inspection was `2.2.0-beta.4`; no newer package supplies the missing action API. -This library itself has no host dependency and makes no host compatibility -claim for an integrated plugin. - -The public -[`ServerEventContracts.cs`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Plugins/Messaging/ServerEventContracts.cs) -contains: - -- `IServerEventConsumer.HandleAsync(ServerEvent, CancellationToken)`, registered - in `IPlugin.ConfigureServices`. Every consumer receives every published event. -- `IServerEventTransport.ConfigureTransport(StandardConfigurer, string)` - and `ConfigureSubscriptions(StandardConfigurer)`, - also registered in `ConfigureServices`. The first registered transport replaces - the in-memory **Rebus broker transport**; it is not an outbound webhook target. - Implementing it as a Discord HTTP sender would not provide broker semantics. - -[`AddServerEvents`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/EventServiceCollectionExtensions.cs) -registers the concrete generic webhook consumer/handler and subscribes the bus to -`ServerEvent`. The -[`publisher`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/ServerEventPublisher.cs) -publishes independently of generic webhook subscriptions, after saving built-in -outboxes. The -[`dispatcher`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/ServerEventDispatcher.cs) -fans out to all consumers with the host's application-stopping token. -Consumer failures are logged by type and dropped, not retried. The default event -transport is in-memory. Durable generic webhook recovery does not replay events -to other consumers; `IServerEventOutbox` is in host Services, not the public -plugin contracts. - -The built-in -[`WebhookSubscription`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Data/Models/WebhookSubscription.cs) -has endpoint, signing secret, event filter, enabled, timeout and attempt settings, -but no provider/action identifier or action-specific configuration. Its -[`handler`](https://github.com/LANCommander/LANCommander/blob/d5fe374e11e46479c848dd89523ae6963b4e7e8f/LANCommander.Server.Services/Events/WebhookDeliveryHandler.cs) -posts stored event-envelope JSON directly, with no plugin transformation or -delivery callback. Settings and APIs are administrator-only; saved signing -secrets are protected and not returned, but endpoint URLs are returned unchanged. -A Discord URL token cannot safely be treated as an ordinary visible endpoint. - -Therefore a Discord action **inside the host's existing subscription system** -requires a public action-provider registry/discovery contract, provider ID and -secret-aware configuration schema/persistence/UI on subscriptions, and a -host-selected delivery callback with cancellation, status and retry-after -semantics. Those APIs do not exist in beta.4 or inspected main. No fake action, -reflection, internal API dependency, or host change is included here. - -A separate plugin-owned Discord subscriptions UI could instead use -`IServerEventConsumer`, but that changes the product boundary: the plugin would -own filtering, protected credentials, storage, administration, queueing and -retries. Its durability could begin only after consumer receipt; event loss -before receipt or on enqueue failure would remain possible. That alternative -requires explicit approval before implementation. - -## Reusable Discord behavior - -`DiscordWebhookEndpoint.Parse` permits canonical HTTPS incoming webhook URLs on -`discord.com` and `discordapp.com`, using `/api/webhooks/{id}/{token}` or -`/api/v10/webhooks/{id}/{token}`. It rejects credentials, queries, fragments, -custom ports, encoded/normalized paths and arbitrary hosts. The endpoint object's -string representation is redacted; validation errors never echo the input. -Do not log, serialize or display raw endpoint input. - -`DiscordPayload.Serialize` creates Discord JSON, not a LANCommander envelope. -Supported fields are content, optional username, and rich embeds containing -title, description, RGB color, fields, footer text and author name. All mention -parsing is disabled, including user/role/everyone mentions. JSON serialization -handles quoting, escaping and Unicode without string interpolation. - -Validation rejects rather than truncates: content 2,000; username 80; at most -10 embeds; title/author 256; description 4,096; footer 2,048; at most 25 fields -per embed; field name 256 and value 1,024; combined embed text 6,000. Lengths -use UTF-16 code units (conservative for supplementary characters). Content or -a nonempty text embed is required. No attachment, forum/thread, component, -avatar, bot token, Discord SDK or arbitrary JSON support is included. - -`DiscordWebhookClient.SendAsync` performs exactly one POST, adds controlled -`wait=true` so Discord confirms the message was saved, and accepts a 1-30 second -timeout (default 10). Cancellation propagates; timeouts and transport errors -become bounded typed results. Responses, reason phrases and exception messages -are never logged or returned. Redirects, proxies, cookies and trace-header -propagation are disabled on the default handler. There is no HTTP-client-factory -request logger. The injectable handler is for trusted implementations/tests only. +# Discord webhooks + +A separate administrator-only page at **`/Plugins/DiscordWebhooks`**, linked in +the server sidebar as **Discord webhooks**. This plugin receives LANCommander's +published server events, selects its own enabled subscriptions, and sends +Discord-compatible messages. It does not replace the event transport, poll for +events, or modify the built-in generic webhook settings, subscriptions or UI. + +## Requirements and installation + +Requires **LANCommander Server 2.2.0-beta.4 or later** and .NET 10. Compiled and +loader-tested against published `LANCommander.SDK`, `LANCommander.Server.Plugins` +and `LANCommander.Server.UI` **2.2.0-beta.4**, corresponding to upstream source +`675befe0673c03aded2b45995694661ce454ba95`. A compile-time package restore does +not upgrade the host. Newer hosts are not live-tested. + +The package and assembly identity is +`LANCommander.Community.Server.DiscordWebhook`; its stable plugin ID is +`io.github.lancommander.community.discordwebhook`. The independent initial +version is **0.1.0-beta.1**, not a claim that it has been published. +Package types are `LANCommander.Plugin` and `LANCommander.Plugin.Server`. +Only the plugin DLL is bundled; host/framework dependencies are never bundled. +No Discord SDK, bot account or bot token is required. + +Build the local `.nupkg` with the validation command below. Install an +authorized published package through LANCommander's server plugin management, +or extract the contents of `lib/net10.0` from the locally built package to a +dedicated server `Plugins` subdirectory while the host is stopped. Restart +the server for discovery. Do not copy test output or host dependency DLLs. +This PR does not publish a package, create release tags, or install anything. + +## Management + +Sign in as a LANCommander administrator and open **Discord webhooks**. +The host page access attribute, navigation policy and every administration +service operation require the host's administrator policy. There are no +unauthenticated plugin HTTP endpoints. + +Choose **New subscription**, then supply: + +- A name (1-100 characters) and an incoming Discord webhook URL. +- One or more exact event types from the published host event catalogue. +- Enabled/disabled state, optional fixed message content (up to 1,000 characters), + timeout (1-30 seconds, default 10), and total attempt budget (1-5, default 3). + +Use **Save subscription** to create or update. Editing shows a blank password +field, never the existing URL; leave it blank to preserve the saved credential. +Saving cancels pending/in-flight records for that subscription so old queued +events do not unexpectedly use changed destinations or settings. An HTTP +request already sent cannot be recalled. Concurrent edits/deletes are rejected +using revision checks rather than silently overwriting another administrator. +Delete requires confirmation and removes the subscription and its history. + +**Send test** explicitly queues a synthetic `server.webhook.test` message for +only that enabled subscription, regardless of its event filter. It does not +change host resources, but **does send a real message** if used on a running +installation. Tests in this repository never invoke real Discord endpoints. +Refresh the page to see pending, in-flight, canceled, delivered, failed or +secret-unavailable status, attempts, last outcome, HTTP code and next retry. +Receiver text, exception messages and webhook URLs never appear in history. + +## Messages and endpoint safety + +Messages contain optional fixed content and a safe embed with the event type, +target type/ID, status, UTC timestamp and event ID. Arbitrary host payloads, +actor identity, usernames, issue descriptions, credentials and other free-form +event data are **not** forwarded. Administrators must still consider target IDs, +event types/times, status and fixed content sensitive when choosing a channel. +All Discord mention parsing is disabled, including user, role and everyone +mentions. Formatting/escaping uses JSON serialization, not interpolation. + +Only canonical HTTPS incoming webhook URLs on `discord.com` or `discordapp.com` +are accepted, at `/api/webhooks/{id}/{token}` or +`/api/v10/webhooks/{id}/{token}`. Queries, fragments, credentials, custom ports, +encoded/normalized paths and arbitrary hosts are rejected without echoing input. +The client adds controlled `wait=true` for server-confirmed message creation. +Forum/media thread destinations, attachments, avatars, components, arbitrary +JSON and custom templates are not supported. + +The reusable payload serializer enforces Discord's content (2,000), embed count +(10), title/author (256), description (4,096), footer (2,048), field count (25), +field name/value (256/1,024) and combined embed text (6,000) limits. It rejects +oversized messages rather than truncating, using conservative UTF-16 lengths. +The UI deliberately exposes a smaller, predictable message shape. + +URLs are protected with the host's ASP.NET Core data-protection provider and a +plugin-specific purpose; they are not returned to the browser. The URL input is +cleared after submission, including validation failure. The default HTTP handler +disables redirects, cookies, proxies and trace-header propagation; no +HTTP-client-factory request logger is used. HTTP status and fixed classifications +are recorded, not bodies/reason phrases or exception text. Host-installed HTTP tracing/profilers can still observe URLs: disable or redact -webhook paths in that instrumentation before integrating a credentialed client. - -2xx is delivered, 408/5xx/network errors are transient, other failures -(including redirects and missing/deleted webhooks) are rejected. HTTP 429 -returns a rate-limit result and the greater valid delay from `Retry-After` -(seconds or HTTP date) and JSON `retry_after` (fractional seconds). Untrusted -rate-limit bodies are limited to 4 KiB. Invalid/missing delay remains explicitly -unknown (`null`), not success. There is **no automatic retry, sleep, rate-limit -bucket coordinator, persistent delivery history or restart recovery**. A future -adapter must schedule retries without shortening supplied delays, coordinate -per-webhook/global limits, and avoid retrying permanent failures. An ambiguous -network timeout may follow a successful send; retrying can duplicate messages. -Do not use the single-attempt client as a complete notification service. - -Discord references: -[execute webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook), -[embed limits](https://docs.discord.com/developers/resources/message#embed-object-embed-limits), -[rate limits](https://docs.discord.com/developers/topics/rate-limits). - -## Development - -Requires .NET 10 SDK. All delivery tests use an in-process fake handler and -synthetic endpoints; no network messages or real credentials are used. +webhook paths in that instrumentation. Restrict outbound access and plugin Data +directory permissions at the OS/container level. Discord execution tokens are +credentials; never put them in logs, examples, fixed message content or commits. + +## Delivery guarantees and limits + +The public beta.4 +[`IServerEventConsumer`](https://github.com/LANCommander/LANCommander/blob/675befe0673c03aded2b45995694661ce454ba95/LANCommander.Server.Plugins/Messaging/ServerEventContracts.cs) +receives every event independently of built-in webhook filters. The plugin +filters that stream; it does not duplicate host event publication. +The host's default Rebus transport is in-memory, and the host dispatcher logs +and drops consumer failures. **Events may be lost before plugin receipt or if +enqueue fails.** The built-in generic webhook outbox does not replay events to +this plugin. There is no claim of end-to-end guaranteed delivery. + +Once queued and committed locally, work survives normal host restarts. +A single worker claims and persists each attempt before HTTP. Interrupted +attempts consume budget and are recovered after their saved timeout lease +expires; the final interrupted attempt is marked failed rather than sent again. +Caller/host cancellation propagates. Crashes, timeouts or failed result commits +after Discord accepted a message can lead to duplicates. Delivery is not +exactly-once or ordered. Event-ID deduplication covers only retained entries. + +2xx is delivered; HTTP 408/5xx, network errors and timeouts retry within the +attempt budget with 5/10/20/40-second backoff (maximum 60 seconds). +Other HTTP failures, including redirects, 400, 401 and deleted webhooks, fail +without retry. Missing data-protection keys produce `SecretUnavailable`. +HTTP 429 honors the greater valid `Retry-After` header (seconds/date) and JSON +`retry_after` (fractional seconds); invalid/missing delay uses 60 seconds. +The bounded 4-KiB response parser never exposes receiver content. The entire +plugin pauses conservatively after any 429, so even global limits are respected +across subscriptions and restarts. The worker starts at most one attempt each +second; there is no hardcoded Discord route quota or cross-process rate broker. + +Storage is one atomic JSON-replacement file in **`PluginContext.DataDirectory`**, +with an exclusive lifetime lock, serialized operations and disk flush before +replacement. Limits are 32 subscriptions, 256 pending/in-flight deliveries, +128 retained terminal entries and 4 MiB total state. Capacity overflow rejects +the new event atomically (without evicting accepted work), records a persistent +warning and logs a credential-free error. That warning describes past loss and +remains until operator repair. Invalid/unreadable state is an explicit error, +never reset to empty. Mutable state is never stored in the install directory. + +This is **single-server local storage**, not a clustered outbox. Do not share its +Data directory across processes or network filesystems. When scaling the host, +Rebus consumers may run on different instances and local subscriptions/queues +are not synchronized. Keep one receiving instance for this plugin. +Back up the plugin Data directory **and the host's persistent data-protection +key ring** before upgrades. Losing keys prevents decrypting saved URLs; edit +and resupply credentials to recover. Preserve Data during upgrades. +Storage/permission failures require operator repair; do not delete state as an +automatic recovery. A process/power failure can have an ambiguous final commit. + +## Validation and release + +Requires .NET 10 SDK and PowerShell 7: ```powershell dotnet test .\plugins\Server.DiscordWebhook\tests\LANCommander.Community.Server.DiscordWebhook.Tests\LANCommander.Community.Server.DiscordWebhook.Tests.csproj -c Release --nologo pwsh .\eng\Test-ReleaseSelection.ps1 pwsh .\eng\Test-Repository.ps1 +pwsh .\eng\Validate-Plugin.ps1 -Plugin Server.DiscordWebhook -OutputDirectory .\artifacts\validation-discord-new ``` -CI runs the independent tests. Host registration/discovery, permissions/UI, -installation, delivery persistence and real Discord delivery are not exercised -or claimed. The reserved future project/package/assembly identity is -`LANCommander.Community.Server.DiscordWebhook`. It remains non-packable until a -supported integration is implemented and verified; no version, changelog, -package types, registry entry, release allowlist or publication claim is added. +Use a fresh output directory. Validation runs unit/integration/rendered UI tests, +NuGet metadata/private-only inventory checks and shared-host-type discovery +against the DLL extracted from the package. All HTTP tests use in-process fake +handlers and synthetic credentials. These are not live LANCommander install, +browser screenshots, real Discord delivery or live-host upgrade tests. + +CI and the independent registry/release selection include `Server.DiscordWebhook`. +Future authorized tag format: `server-discordwebhook-v`. See the child +changelog and [repository release procedure](../../RELEASES.md). No release, +package-feed publication or merge is performed by validation. + +Discord references: +[execute webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook), +[embed limits](https://docs.discord.com/developers/resources/message#embed-object-embed-limits), +[rate limits](https://docs.discord.com/developers/topics/rate-limits). diff --git a/plugins/Server.DiscordWebhook/eng/Test-Package.ps1 b/plugins/Server.DiscordWebhook/eng/Test-Package.ps1 new file mode 100644 index 0000000..d3c6bc7 --- /dev/null +++ b/plugins/Server.DiscordWebhook/eng/Test-Package.ps1 @@ -0,0 +1,42 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][string] $PackagePath, + [Parameter(Mandatory)][string] $ExpectedVersion +) + +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.IO.Compression +$zip = [IO.Compression.ZipFile]::OpenRead([IO.Path]::GetFullPath($PackagePath)) +try { + $dlls = @($zip.Entries | Where-Object FullName -like '*.dll' | ForEach-Object FullName) + if ($dlls.Count -ne 1 -or $dlls[0] -cne 'lib/net10.0/LANCommander.Community.Server.DiscordWebhook.dll') { + throw "Discord package must bundle only its private plugin assembly; found $($dlls -join ', ')." + } + $specEntry = @($zip.Entries | Where-Object FullName -like '*.nuspec') + if ($specEntry.Count -ne 1) { throw 'Expected one Discord nuspec.' } + $reader = [IO.StreamReader]::new($specEntry[0].Open()) + try { [xml] $spec = $reader.ReadToEnd() } finally { $reader.Dispose() } + $ns = [Xml.XmlNamespaceManager]::new($spec.NameTable) + $ns.AddNamespace('n', $spec.DocumentElement.NamespaceURI) + if ($spec.SelectNodes('//n:dependency', $ns).Count -ne 0) { + throw 'Host dependencies must not be declared as private runtime dependencies.' + } + $metadata = $spec.SelectSingleNode('/n:package/n:metadata', $ns) + if ($metadata.id -cne 'LANCommander.Community.Server.DiscordWebhook' -or + $metadata.version -cne $ExpectedVersion -or + $metadata.repository.url -cne 'https://github.com/LANCommander/LANCommander.Community') { + throw 'Discord package identity, version or canonical repository mismatch.' + } + if (-not $zip.GetEntry('README.md')) { throw 'Discord package README is missing.' } +} +finally { $zip.Dispose() } + +$previous = $env:DISCORD_TEST_PACKAGE +try { + $env:DISCORD_TEST_PACKAGE = [IO.Path]::GetFullPath($PackagePath) + & dotnet test (Join-Path $PSScriptRoot '../tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj') ` + -c Release --no-build --no-restore --nologo --filter 'FullyQualifiedName~PackagedPluginLoads' + if ($LASTEXITCODE -ne 0) { throw 'Packaged Discord host-contract loader check failed.' } +} +finally { $env:DISCORD_TEST_PACKAGE = $previous } +Write-Output "Discord private-only package and loader verified: $ExpectedVersion" diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordAdministration.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordAdministration.cs new file mode 100644 index 0000000..91f94b3 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordAdministration.cs @@ -0,0 +1,39 @@ +using LANCommander.Server.Plugins; +using Microsoft.AspNetCore.Components.Authorization; + +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed class DiscordAdministration(DiscordStore store, AuthenticationStateProvider authentication) +{ + private async Task AuthorizeAsync(CancellationToken token) + { + token.ThrowIfCancellationRequested(); + var state = await authentication.GetAuthenticationStateAsync().WaitAsync(token); + if (!PluginAccessPolicy.Administrator.IsSatisfiedBy(state.User)) + throw new UnauthorizedAccessException("LANCommander administrator access is required."); + } + + public async Task GetAsync(CancellationToken token = default) + { + await AuthorizeAsync(token); + return await store.GetAsync(token); + } + + public async Task SaveAsync(DiscordSubscriptionEdit edit, long? expectedRevision, CancellationToken token = default) + { + await AuthorizeAsync(token); + await store.SaveAsync(edit, expectedRevision, token); + } + + public async Task DeleteAsync(Guid id, long revision, CancellationToken token = default) + { + await AuthorizeAsync(token); + await store.DeleteAsync(id, revision, token); + } + + public async Task TestAsync(Guid id, CancellationToken token = default) + { + await AuthorizeAsync(token); + await store.QueueTestAsync(id, token); + } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordModels.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordModels.cs new file mode 100644 index 0000000..3dbc023 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordModels.cs @@ -0,0 +1,64 @@ +using LANCommander.SDK.Events; + +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed record DiscordSubscriptionEdit( + Guid Id, string Name, string? WebhookUrl, string[] EventTypes, + bool Enabled = true, string? Content = null, int TimeoutSeconds = 10, int MaxAttempts = 3) +{ + public override string ToString() => $"Discord subscription edit {Id:D} (credentials redacted)"; +} + +public sealed record DiscordSubscriptionView( + Guid Id, string Name, string[] EventTypes, bool Enabled, string? Content, + int TimeoutSeconds, int MaxAttempts, long Revision); + +public sealed record DiscordDeliveryView( + Guid Id, Guid SubscriptionId, Guid EventId, string EventType, string Status, + int Attempts, int? HttpStatusCode, DateTimeOffset NextAttemptOn, string? LastOutcome); + +public sealed record DiscordSnapshot( + IReadOnlyList Subscriptions, + IReadOnlyList Deliveries, string? Warning); + +public sealed class DiscordStateException(string message) : Exception(message); + +internal sealed class DiscordState +{ + public int SchemaVersion { get; set; } = 1; + public List Subscriptions { get; set; } = []; + public List Deliveries { get; set; } = []; + public DateTimeOffset NotBefore { get; set; } + public string? Warning { get; set; } +} + +internal sealed record SavedDiscordSubscription( + Guid Id, string Name, string ProtectedEndpoint, string[] EventTypes, + bool Enabled, string? Content, int TimeoutSeconds, int MaxAttempts, long Revision); + +internal sealed record SavedDiscordDelivery( + Guid Id, Guid SubscriptionId, Guid EventId, string EventType, DiscordMessage Message, + string Status, int Attempts, int? HttpStatusCode, DateTimeOffset NextAttemptOn, string? LastOutcome = null); + +internal static class DiscordEventMessage +{ + public static DiscordMessage Create(ServerEvent value, string? content) + { + // Deliberately omit arbitrary payloads, actor identifiers and issue/user text. + // Events can contain user-controlled or sensitive data. + var type = value.EventType.Length <= 256 ? value.EventType : "Unknown event"; + var target = value.TargetType.Length <= 128 ? value.TargetType : "resource"; + var status = value.Status.Length <= 128 ? value.Status : "unknown"; + return new(content, + [ + new(Title: type, Color: status == "failed" ? 0xD73A49 : 0x5865F2, + Fields: + [ + new("Target", $"{target}: {value.TargetId:D}"), + new("Status", status), + new("Occurred (UTC)", value.OccurredAt.ToUniversalTime().ToString("O")), + new("Event ID", value.EventId.ToString("D")) + ]) + ]); + } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordPlugin.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordPlugin.cs new file mode 100644 index 0000000..ed38a36 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordPlugin.cs @@ -0,0 +1,85 @@ +using System.Reflection; +using LANCommander.SDK.Events; +using LANCommander.SDK.Plugins; +using LANCommander.Server.Plugins; +using LANCommander.Server.Plugins.Messaging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +[assembly: LANCommanderPlugin(typeof(LANCommander.Community.Server.DiscordWebhook.DiscordPlugin), + Id = LANCommander.Community.Server.DiscordWebhook.DiscordPlugin.PluginId, + MinHostVersion = "2.2.0-beta.4", Hosts = PluginHost.Server)] + +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed class DiscordPlugin : IPlugin +{ + public const string PluginId = "io.github.lancommander.community.discordwebhook"; + public string Id => PluginId; + public string Name => "Discord webhooks"; + public string Author => "LANCommander Community contributors"; + public string Version => typeof(DiscordPlugin).Assembly + .GetCustomAttribute()!.InformationalVersion; + + public void ConfigureServices(IServiceCollection services) + { + services.AddDataProtection(); + services.AddSingleton(new DiscordRoutes(typeof(DiscordPlugin).Assembly)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(_ => new DiscordWebhookClient()); + services.AddSingleton(); + services.AddHostedService(); + services.AddScoped(); + } + + public Task InitializeAsync(PluginContext context, CancellationToken cancellationToken) => + context.Services.GetRequiredService().InitializeAsync(context.DataDirectory, cancellationToken); +} + +internal sealed record DiscordRoutes(Assembly Assembly) : IServerRouteAssemblyExtension; + +internal sealed class DiscordNavigation : IServerNavigationExtension +{ + public string Id => DiscordPlugin.PluginId; + public string Label => "Discord webhooks"; + public string Href => "/Plugins/DiscordWebhooks"; + public string? Icon => "ChatCircle"; + public int Order => 120; + public PluginAccessPolicy Access => PluginAccessPolicy.Administrator; +} + +public sealed class DiscordEventConsumer(DiscordStore store, ILogger logger) : IServerEventConsumer +{ + public async Task HandleAsync(ServerEvent serverEvent, CancellationToken cancellationToken) + { + try { await store.EnqueueAsync(serverEvent, null, cancellationToken); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (DiscordStateException) + { + logger.LogError("Discord event enqueue failed; notification may be lost. Check Discord administration storage health."); + throw; + } + } +} + +internal sealed class DiscordDeliveryWorker(DiscordStore store, DiscordWebhookClient client, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await store.Ready.WaitAsync(stoppingToken); + while (!stoppingToken.IsCancellationRequested) + { + try { await store.DeliverNextAsync(client, DateTimeOffset.UtcNow, stoppingToken); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { return; } + catch (Exception ex) when (ex is DiscordStateException or ArgumentException or System.Security.Cryptography.CryptographicException) + { + // Never pass exceptions to the logger: the source may contain credentials. + logger.LogError("Discord delivery processing failed ({FailureType}); check storage and data-protection keys.", ex.GetType().Name); + } + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); + } + } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordStore.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordStore.cs new file mode 100644 index 0000000..86b9809 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordStore.cs @@ -0,0 +1,352 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization; +using LANCommander.SDK.Events; +using Microsoft.AspNetCore.DataProtection; + +namespace LANCommander.Community.Server.DiscordWebhook; + +public sealed class DiscordStore(IDataProtectionProvider protection) : IDisposable +{ + internal const int MaximumPending = 256; + internal const int MaximumHistory = 128; + private const int MaximumBytes = 4 * 1024 * 1024; + private readonly IDataProtector _protector = protection.CreateProtector(DiscordPlugin.PluginId, "endpoint-v1"); + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly SemaphoreSlim _deliveryGate = new(1, 1); + private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private static readonly JsonSerializerOptions JsonOptions = new() + { + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + RespectRequiredConstructorParameters = true, + MaxDepth = 32 + }; + private string? _path; + private FileStream? _lease; + private bool _hasSavedState; + private string? _health; + internal Task Ready => _ready.Task; + + public async Task InitializeAsync(string dataDirectory, CancellationToken token = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + await _gate.WaitAsync(token); + try + { + if (_path is not null) + return; + Directory.CreateDirectory(dataDirectory); + _lease = new FileStream(Path.Combine(dataDirectory, "discord.lock"), + FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + var path = Path.Combine(Path.GetFullPath(dataDirectory), "discord.json"); + await ReadAsync(path, token); + _hasSavedState = File.Exists(path); + _path = path; + _ready.TrySetResult(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or DiscordStateException) + { + _lease?.Dispose(); + _lease = null; + _health = "Discord storage is unavailable or invalid; no state was replaced."; + throw new DiscordStateException(_health); + } + finally { _gate.Release(); } + } + + public Task GetAsync(CancellationToken token = default) => + AccessAsync(state => new DiscordSnapshot( + state.Subscriptions.Select(s => new DiscordSubscriptionView(s.Id, s.Name, s.EventTypes.ToArray(), + s.Enabled, s.Content, s.TimeoutSeconds, s.MaxAttempts, s.Revision)).ToArray(), + state.Deliveries.OrderByDescending(d => d.NextAttemptOn) + .Select(d => new DiscordDeliveryView(d.Id, d.SubscriptionId, d.EventId, d.EventType, + d.Status, d.Attempts, d.HttpStatusCode, d.NextAttemptOn, d.LastOutcome)).ToArray(), + _health ?? state.Warning), false, token); + + public Task SaveAsync(DiscordSubscriptionEdit edit, long? expectedRevision, CancellationToken token = default) + { + ValidateEdit(edit); + var endpoint = string.IsNullOrEmpty(edit.WebhookUrl) ? null : DiscordWebhookEndpoint.Parse(edit.WebhookUrl); + return AccessAsync(state => + { + var existing = state.Subscriptions.SingleOrDefault(s => s.Id == edit.Id); + if (existing is null && (edit.Id != Guid.Empty || expectedRevision is not null)) + throw new InvalidOperationException("Subscription no longer exists. Refresh before editing."); + if (existing is not null && existing.Revision != expectedRevision) + throw new InvalidOperationException("Subscription changed in another session. Refresh before editing."); + if (existing is null && state.Subscriptions.Count >= 32) + throw new ArgumentException("At most 32 Discord subscriptions are supported."); + if (existing is null && endpoint is null) + throw new ArgumentException("A Discord webhook URL is required for a new subscription."); + var secret = endpoint is null ? existing!.ProtectedEndpoint : _protector.Protect(edit.WebhookUrl!); + var id = existing?.Id ?? Guid.NewGuid(); + var saved = new SavedDiscordSubscription(id, edit.Name.Trim(), secret, + edit.EventTypes.Distinct(StringComparer.Ordinal).ToArray(), edit.Enabled, + string.IsNullOrEmpty(edit.Content) ? null : edit.Content, + edit.TimeoutSeconds, edit.MaxAttempts, (existing?.Revision ?? 0) + 1); + state.Subscriptions.RemoveAll(s => s.Id == id); + state.Subscriptions.Add(saved); + // A save cancels queued work so old notifications cannot unexpectedly use new settings. + CancelPending(state, id); + return id; + }, true, token); + } + + public Task DeleteAsync(Guid id, long revision, CancellationToken token = default) => + AccessAsync(state => + { + var existing = state.Subscriptions.SingleOrDefault(s => s.Id == id) + ?? throw new InvalidOperationException("Subscription no longer exists."); + if (existing.Revision != revision) + throw new InvalidOperationException("Subscription changed in another session. Refresh before deleting."); + state.Subscriptions.Remove(existing); + state.Deliveries.RemoveAll(d => d.SubscriptionId == id); + return true; + }, true, token); + + public Task QueueTestAsync(Guid subscriptionId, CancellationToken token = default) => + EnqueueAsync(new ServerEvent(Guid.NewGuid(), ServerEventTypes.Test, DateTime.UtcNow, "server", + null, "webhook", subscriptionId, "completed", null, JsonSerializer.SerializeToElement(new { })), + subscriptionId, token); + + public async Task EnqueueAsync(ServerEvent serverEvent, Guid? testSubscription, CancellationToken token = default) + { + ArgumentNullException.ThrowIfNull(serverEvent); + var overflow = await AccessAsync(state => + { + var matches = state.Subscriptions.Where(s => s.Enabled && + (testSubscription is { } id ? s.Id == id : s.EventTypes.Contains(serverEvent.EventType, StringComparer.Ordinal))) + .Where(s => !state.Deliveries.Any(d => d.SubscriptionId == s.Id && d.EventId == serverEvent.EventId)) + .ToArray(); + if (testSubscription is not null && matches.Length == 0) + throw new InvalidOperationException("Test requires an existing enabled subscription."); + if (state.Deliveries.Count(IsPending) + matches.Length > MaximumPending) + { + state.Warning = "Discord queue capacity reached. At least one notification was dropped; narrow event filters or repair delivery."; + return true; + } + foreach (var s in matches) + { + var message = DiscordEventMessage.Create(serverEvent, s.Content); + DiscordPayload.Serialize(message); + state.Deliveries.Add(new(Guid.NewGuid(), s.Id, serverEvent.EventId, serverEvent.EventType, + message, "Pending", 0, null, DateTimeOffset.UtcNow)); + } + return false; + }, true, token); + if (overflow) + throw new DiscordStateException("Discord queue capacity reached; notification was not queued."); + } + + public async Task DeliverNextAsync(DiscordWebhookClient client, DateTimeOffset now, CancellationToken token = default) + { + await _deliveryGate.WaitAsync(token); + try + { + var claim = await AccessAsync<(SavedDiscordDelivery Delivery, SavedDiscordSubscription Subscription)?>(state => + { + if (state.NotBefore > now) + return null; + var delivery = state.Deliveries.Where(d => IsPending(d) && d.NextAttemptOn <= now) + .OrderBy(d => d.NextAttemptOn).FirstOrDefault(); + if (delivery is null) + return null; + var subscription = state.Subscriptions.SingleOrDefault(s => s.Id == delivery.SubscriptionId && s.Enabled); + if (subscription is null || delivery.Attempts >= subscription.MaxAttempts) + { + Replace(state, delivery with + { + Status = subscription is null ? "Canceled" : "Failed", + LastOutcome = "Attempt interrupted; budget exhausted", NextAttemptOn = now + }); + return null; + } + var claimed = delivery with + { + Status = "InFlight", Attempts = delivery.Attempts + 1, + NextAttemptOn = now.AddSeconds(subscription.TimeoutSeconds + 5), HttpStatusCode = null + }; + Replace(state, claimed); + return (Delivery: claimed, Subscription: subscription); + }, true, token); + if (claim is null) + return false; + + var (work, settings) = claim.Value; + DiscordDeliveryResult result; + try + { + var endpoint = DiscordWebhookEndpoint.Parse(_protector.Unprotect(settings.ProtectedEndpoint)); + result = await client.SendAsync(endpoint, work.Message, settings.TimeoutSeconds, token); + } + catch (CryptographicException) + { + await CompleteAsync(work, new(DiscordDeliveryStatus.Rejected), now, settings.MaxAttempts, + "SecretUnavailable", token); + return true; + } + // On shutdown the persisted InFlight attempt is recovered after its lease expires. + await CompleteAsync(work, result, now, settings.MaxAttempts, null, token); + return true; + } + finally { _deliveryGate.Release(); } + } + + private Task CompleteAsync(SavedDiscordDelivery work, DiscordDeliveryResult result, DateTimeOffset started, + int maxAttempts, string? failure, CancellationToken token) => + AccessAsync(state => + { + var current = state.Deliveries.SingleOrDefault(d => d.Id == work.Id); + var delay = result.Status == DiscordDeliveryStatus.RateLimited + ? result.RetryAfter ?? TimeSpan.FromSeconds(60) + : TimeSpan.FromSeconds(Math.Min(60, 5 * Math.Pow(2, work.Attempts - 1))); + // Measure from completion, not request start, so Retry-After is never shortened. + var completed = DateTimeOffset.UtcNow > started ? DateTimeOffset.UtcNow : started; + var next = delay > DateTimeOffset.MaxValue - completed ? DateTimeOffset.MaxValue : completed + delay; + if (result.Status == DiscordDeliveryStatus.RateLimited) + state.NotBefore = next; // Conservatively honor global and per-webhook 429s alike. + if (current?.Status != "InFlight") + return true; // Subscription changed/deleted while the HTTP attempt was running. + var retry = result.Status is DiscordDeliveryStatus.RateLimited or DiscordDeliveryStatus.TransientFailure + or DiscordDeliveryStatus.TimedOut; + var status = failure ?? (result.Status == DiscordDeliveryStatus.Delivered ? "Delivered" : + retry && work.Attempts < maxAttempts ? "Pending" : "Failed"); + Replace(state, work with + { + Status = status, HttpStatusCode = result.HttpStatusCode, LastOutcome = failure ?? result.Status.ToString(), + NextAttemptOn = status == "Pending" ? next : completed + }); + return true; + }, true, token); + + private async Task AccessAsync(Func operation, bool write, CancellationToken token) + { + if (_path is null) + throw new DiscordStateException(_health ?? "Discord plugin storage is not initialized."); + await _gate.WaitAsync(token); + string? pending = null; + try + { + var state = await ReadAsync(_path, token); + if (_hasSavedState && !File.Exists(_path)) + throw new DiscordStateException("Discord saved state is missing; refusing to replace it."); + var original = write ? JsonSerializer.SerializeToUtf8Bytes(state, JsonOptions) : null; + var result = operation(state); + if (write) + { + var history = state.Deliveries.Where(d => !IsPending(d)).ToArray(); + foreach (var old in history.Take(Math.Max(0, history.Length - MaximumHistory))) + state.Deliveries.Remove(old); + var bytes = JsonSerializer.SerializeToUtf8Bytes(state, JsonOptions); + if (bytes.Length > MaximumBytes) + throw new DiscordStateException("Discord state exceeds the storage size limit."); + if (original is not null && bytes.AsSpan().SequenceEqual(original)) + return result; + pending = _path + ".pending"; + await using (var stream = new FileStream(pending, FileMode.Create, FileAccess.Write, FileShare.None, + 8192, FileOptions.Asynchronous | FileOptions.WriteThrough)) + { + await stream.WriteAsync(bytes, token); + await stream.FlushAsync(token); + stream.Flush(true); + } + token.ThrowIfCancellationRequested(); + File.Move(pending, _path, true); + _hasSavedState = true; + _health = null; + } + return result; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or DiscordStateException) + { + _health = "Discord storage could not be read or committed. Notifications may be lost; check disk and permissions."; + throw new DiscordStateException(_health); + } + finally + { + try + { + if (pending is not null) + { + try { File.Delete(pending); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _health = "Discord staged state cleanup failed; an operation may already have committed. Refresh before retrying."; + throw new DiscordStateException(_health); + } + } + } + finally { _gate.Release(); } + } + } + + private static async Task ReadAsync(string path, CancellationToken token) + { + try + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, true); + if (stream.Length > MaximumBytes) + throw new DiscordStateException("Discord storage exceeds its size limit."); + var bytes = new byte[(int)stream.Length]; + await stream.ReadExactlyAsync(bytes, token); + var state = JsonSerializer.Deserialize(bytes, JsonOptions); + if (state is null || state.SchemaVersion != 1 || state.Subscriptions is null || state.Deliveries is null || + state.Subscriptions.Count > 32 || state.Subscriptions.Any(s => s is null || s.Id == Guid.Empty || + string.IsNullOrEmpty(s.ProtectedEndpoint) || s.Revision < 1) || + state.Subscriptions.Select(s => s.Id).Distinct().Count() != state.Subscriptions.Count || + state.Deliveries.Count > MaximumPending + MaximumHistory || + state.Deliveries.Any(d => d is null || d.Id == Guid.Empty || d.Attempts is < 0 or > 5 || + d.Message is null || d.EventType is null || + d.Status is not ("Pending" or "InFlight" or "Delivered" or "Failed" or "Canceled" or "SecretUnavailable")) || + state.Deliveries.Select(d => d.Id).Distinct().Count() != state.Deliveries.Count || + state.Deliveries.Count(IsPending) > MaximumPending) + throw new DiscordStateException("Discord storage is invalid."); + try + { + foreach (var s in state.Subscriptions) + ValidateEdit(new(s.Id, s.Name, null, s.EventTypes, s.Enabled, s.Content, s.TimeoutSeconds, s.MaxAttempts)); + foreach (var d in state.Deliveries) + DiscordPayload.Serialize(d.Message); + } + catch (ArgumentException) { throw new DiscordStateException("Discord saved configuration is invalid."); } + return state; + } + catch (FileNotFoundException) { return new(); } + } + + private static void ValidateEdit(DiscordSubscriptionEdit edit) + { + ArgumentNullException.ThrowIfNull(edit); + if (string.IsNullOrWhiteSpace(edit.Name) || edit.Name.Length > 100) + throw new ArgumentException("A subscription name of 1-100 characters is required."); + if (edit.EventTypes is null || edit.EventTypes.Length is < 1 or > 64 || + edit.EventTypes.Any(t => !ServerEventTypes.All.Contains(t))) + throw new ArgumentException("Select at least one supported event type."); + if (edit.TimeoutSeconds is < 1 or > 30 || edit.MaxAttempts is < 1 or > 5) + throw new ArgumentException("Timeout must be 1-30 seconds and attempts must be 1-5."); + if (edit.Content?.Length > 1000) + throw new ArgumentException("Optional message content must not exceed 1000 characters."); + } + + private static bool IsPending(SavedDiscordDelivery delivery) => delivery.Status is "Pending" or "InFlight"; + private static void Replace(DiscordState state, SavedDiscordDelivery delivery) + { + var index = state.Deliveries.FindIndex(d => d.Id == delivery.Id); + state.Deliveries[index] = delivery; + } + private static void CancelPending(DiscordState state, Guid id) + { + foreach (var delivery in state.Deliveries.Where(d => d.SubscriptionId == id && IsPending(d)).ToArray()) + Replace(state, delivery with + { + Status = "Canceled", LastOutcome = "Subscription settings changed", NextAttemptOn = DateTimeOffset.UtcNow + }); + } + + public void Dispose() + { + _lease?.Dispose(); + _gate.Dispose(); + _deliveryGate.Dispose(); + } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs index ba3d623..e7b0123 100644 --- a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/DiscordWebhookClient.cs @@ -19,7 +19,7 @@ public sealed record DiscordDeliveryResult( int? HttpStatusCode = null, TimeSpan? RetryAfter = null); -/// One attempt only; a future host action adapter must own durable scheduling. +/// One attempt only; the plugin delivery store owns durable scheduling. public sealed class DiscordWebhookClient : IDisposable { private readonly HttpClient _client; @@ -71,7 +71,10 @@ public async Task SendAsync( if (response.StatusCode == HttpStatusCode.TooManyRequests) { var headerDelay = ReadRetryAfter(response); - var bodyDelay = await ReadBodyRetryAfterAsync(response, timeout.Token); + TimeSpan? bodyDelay; + try { bodyDelay = await ReadBodyRetryAfterAsync(response, timeout.Token); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { bodyDelay = null; } + catch (Exception ex) when (ex is HttpRequestException or IOException) { bodyDelay = null; } var delay = headerDelay is null ? bodyDelay : bodyDelay is null || headerDelay >= bodyDelay ? headerDelay : bodyDelay; return new(DiscordDeliveryStatus.RateLimited, code, delay); diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj index d672694..b4c501c 100644 --- a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/LANCommander.Community.Server.DiscordWebhook.csproj @@ -1,9 +1,28 @@ - + LANCommander.Community.Server.DiscordWebhook LANCommander.Community.Server.DiscordWebhook LANCommander.Community.Server.DiscordWebhook - - false + true + $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)..\..\version.txt').Trim()) + Administrator-managed Discord event notifications for LANCommander servers. + README.md + MIT + https://github.com/LANCommander/LANCommander.Community + https://github.com/LANCommander/LANCommander.Community/tree/main/plugins/Server.DiscordWebhook + LANCommander.Plugin;LANCommander.Plugin.Server + LANCommander;plugin;server;discord;webhook + true + $(NoWarn);NU5128 + false + + + + + + + + + diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/Pages/Index.razor b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/Pages/Index.razor new file mode 100644 index 0000000..9204228 --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/Pages/Index.razor @@ -0,0 +1,164 @@ +@page "/Plugins/DiscordWebhooks" +@attribute [PluginAccess(PluginAccessLevel.Administrator)] +@implements IDisposable +@inject DiscordAdministration Administration +@inject ILogger Logger + +Discord webhooks + + + + Events are best-effort until received by this plugin. Queued notifications survive restarts; + retries may duplicate messages. No raw event payloads are sent. Test sends a real Discord message. + + @if (_error is not null) { @_error } + @if (_message is not null) { @_message } + @if (_snapshot?.Warning is { } warning) { @warning } + + + + @if (_snapshot is not null) + { + @if (_snapshot.Subscriptions.Count == 0) {

No Discord subscriptions configured.

} + @foreach (var item in _snapshot.Subscriptions) + { +
+ @item.Name - @(item.Enabled ? "Enabled" : "Disabled") + + + +
+ } + } + @if (_delete is { } deleting) + { +

Delete @deleting.Name and its delivery history? A request already in progress cannot be recalled.

+ + + } +
+ @if (_editing) + { + +
+ + + + +

@(_id == Guid.Empty ? "Paste an HTTPS Discord incoming webhook URL." : "Leave blank to keep the saved URL. Saved URLs are never returned.")

+ + + +

A safe embed adds the event type, target, status, UTC time and event ID. Mentions are disabled.

+ + + + +

Events

+ @foreach (var eventType in LANCommander.SDK.Events.ServerEventTypes.All) + { + + } +
+

Saving cancels pending deliveries for this subscription. An in-progress HTTP request may still complete.

+ + +
+ } + +

Refresh to update. Pending and in-flight work plus the latest 128 completed entries are retained.

+ @if (_snapshot is not null) + { + + + + @foreach (var delivery in _snapshot.Deliveries) + { + + + + + + } + +
SubscriptionEventStatusOutcomeAttemptsHTTPNext attempt / completion
@(_snapshot.Subscriptions.FirstOrDefault(s => s.Id == delivery.SubscriptionId)?.Name ?? "Deleted")@delivery.EventType@delivery.Status@delivery.LastOutcome@delivery.Attempts@delivery.HttpStatusCode@delivery.NextAttemptOn.ToString("u")
+ } +
+
+ +@code { + private readonly CancellationTokenSource _lifetime = new(); + private DiscordSnapshot? _snapshot; + private DiscordSubscriptionView? _delete; + private bool _busy, _editing, _enabled = true; + private Guid _id; + private long? _revision; + private string _name = "", _url = "", _content = ""; + private string? _error, _message; + private int _timeout = 10, _attempts = 3; + private HashSet _events = []; + + protected override Task OnInitializedAsync() => RefreshAsync(); + private Task RefreshAsync() => RunAsync(async () => _snapshot = await Administration.GetAsync(_lifetime.Token)); + private void New() + { + _id = Guid.Empty; _revision = null; _name = ""; _url = ""; _content = ""; + _enabled = true; _timeout = 10; _attempts = 3; _events = []; _editing = true; + } + private void Edit(DiscordSubscriptionView item) + { + _id = item.Id; _revision = item.Revision; _name = item.Name; _url = ""; _content = item.Content ?? ""; + _enabled = item.Enabled; _timeout = item.TimeoutSeconds; _attempts = item.MaxAttempts; + _events = item.EventTypes.ToHashSet(StringComparer.Ordinal); _editing = true; + } + private void Cancel() { _editing = false; _url = ""; } + private void SelectEvent(string eventType, ChangeEventArgs args) + { + if (args.Value is true) _events.Add(eventType); else _events.Remove(eventType); + } + private void ConfirmDelete(DiscordSubscriptionView item) => _delete = item; + private Task SaveAsync() => RunAsync(async () => + { + var edit = new DiscordSubscriptionEdit(_id, _name, _url, _events.ToArray(), _enabled, _content, _timeout, _attempts); + _url = ""; // Do not retain credentials on validation/storage failures. + await Administration.SaveAsync(edit, _revision, _lifetime.Token); + _editing = false; + _snapshot = await Administration.GetAsync(_lifetime.Token); + _message = "Subscription saved. Pending work for it was canceled."; + }); + private Task DeleteAsync() => RunAsync(async () => + { + if (_delete is not { } item) return; + await Administration.DeleteAsync(item.Id, item.Revision, _lifetime.Token); + _delete = null; Cancel(); + _snapshot = await Administration.GetAsync(_lifetime.Token); + _message = "Subscription and delivery history deleted."; + }); + private Task TestAsync(Guid id) => RunAsync(async () => + { + await Administration.TestAsync(id, _lifetime.Token); + _snapshot = await Administration.GetAsync(_lifetime.Token); + _message = "Synthetic test queued. Refresh deliveries to see its outcome."; + }); + private async Task RunAsync(Func action) + { + if (_busy) return; + _busy = true; _error = null; _message = null; + try { await action(); } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or UnauthorizedAccessException or DiscordStateException) + { + _error = ex.Message; + } + catch (Exception ex) + { + Logger.LogError("Discord administration failed ({FailureType})", ex.GetType().Name); + _error = "Discord operation could not be confirmed. Refresh before retrying."; + } + finally { _busy = false; } + } + public void Dispose() { _url = ""; _lifetime.Cancel(); _lifetime.Dispose(); } +} diff --git a/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/_Imports.razor b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/_Imports.razor new file mode 100644 index 0000000..f049cae --- /dev/null +++ b/plugins/Server.DiscordWebhook/src/LANCommander.Community.Server.DiscordWebhook/_Imports.razor @@ -0,0 +1,6 @@ +@using Microsoft.AspNetCore.Components +@using Microsoft.AspNetCore.Components.Web +@using Microsoft.Extensions.Logging +@using LANCommander.Community.Server.DiscordWebhook +@using LANCommander.Server.Plugins +@using LANCommander.Server.UI.Controls diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs index 06f1307..da3a4b5 100644 --- a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/DiscordWebhookTests.cs @@ -206,6 +206,23 @@ public async Task ParsesHttpDateRetryAfter() Assert.InRange(result.RetryAfter!.Value.TotalSeconds, 100, 120); } + [Fact] + public async Task BrokenRateLimitBodyDoesNotDiscardKnownRetryAfterHeader() + { + using var client = new DiscordWebhookClient(new FakeHandler((_, _) => + { + var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests) + { + Content = new BrokenContent() + }; + response.Headers.TryAddWithoutValidation("Retry-After", "120.5"); + return Task.FromResult(response); + })); + var result = await client.SendAsync(DiscordWebhookEndpoint.Parse(Endpoint), new("Hello")); + Assert.Equal(DiscordDeliveryStatus.RateLimited, result.Status); + Assert.Equal(120.5, result.RetryAfter!.Value.TotalSeconds); + } + [Fact] public async Task RejectsInvalidMessageWithoutInvokingHandlerOrEchoingContent() { @@ -286,5 +303,13 @@ protected override Task SendAsync(HttpRequestMessage reques Calls++; return send(request, cancellationToken); } + + } + + private sealed class BrokenContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => + throw new IOException("Untrusted body read failed"); + protected override bool TryComputeLength(out long length) { length = 0; return false; } } } diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/HostIntegrationTests.cs b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/HostIntegrationTests.cs new file mode 100644 index 0000000..af6143c --- /dev/null +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/HostIntegrationTests.cs @@ -0,0 +1,192 @@ +using System.IO.Compression; +using System.Reflection; +using System.Runtime.Loader; +using Bunit; +using LANCommander.SDK.Plugins; +using LANCommander.Server.Plugins; +using LANCommander.Server.Plugins.Messaging; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; +using DiscordPage = LANCommander.Community.Server.DiscordWebhook.Pages.Index; + +namespace LANCommander.Community.Server.DiscordWebhook.Tests; + +public sealed class HostIntegrationTests +{ + [Fact] + public async Task AdminPageCreatesEditsTestsAndDeletesWithoutRenderingSavedSecret() + { + using var fixture = new StoreFixture(); + await using var context = new BunitContext(); + context.Services.AddLogging(); + context.Services.AddSingleton(fixture.Store); + context.Services.AddSingleton(new TestAuthentication(true, "Administrator")); + context.Services.AddScoped(); + var page = context.Render(); + page.WaitForAssertion(() => Assert.Contains("No Discord subscriptions configured", page.Markup)); + Button(page, "New subscription").Click(); + page.Find("#discord-name").Change("Release alerts"); + page.Find("#discord-url").Change(StoreFixture.Endpoint); + var eventBox = page.FindAll("label").Single(label => label.TextContent.Trim() == "server.game.created") + .QuerySelector("input")!; + eventBox.Change(true); + Button(page, "Save subscription").Click(); + page.WaitForAssertion(() => Assert.Contains("Subscription saved", page.Markup)); + Assert.DoesNotContain("synthetic-token", page.Markup); + Assert.Empty(page.FindAll("iframe")); + Button(page, "Edit").Click(); + Assert.Equal("", page.Find("#discord-url").GetAttribute("value") ?? ""); + Assert.Equal("password", page.Find("#discord-url").GetAttribute("type")); + page.Find("#discord-name").Change("Updated alerts"); + Button(page, "Save subscription").Click(); + page.WaitForAssertion(() => + { + Assert.Contains("Updated alerts", page.Markup); + Assert.Empty(page.FindAll("#discord-name")); + Assert.False(Button(page, "Send test").HasAttribute("disabled")); + }); + Button(page, "Send test").Click(); + page.WaitForAssertion(() => Assert.Contains("Synthetic test queued", page.Markup)); + Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Button(page, "Delete").Click(); + Assert.Contains("Confirm delete", page.Markup); + Button(page, "Confirm delete").Click(); + page.WaitForAssertion(() => Assert.Contains("No Discord subscriptions configured", page.Markup)); + Assert.Empty((await fixture.Store.GetAsync()).Deliveries); + } + + [Fact] + public async Task ValidationErrorsAreVisibleAndDoNotEchoSubmittedSecret() + { + using var fixture = new StoreFixture(); + await using var context = new BunitContext(); + context.Services.AddLogging(); + context.Services.AddSingleton(fixture.Store); + context.Services.AddSingleton(new TestAuthentication(true, "Administrator")); + context.Services.AddScoped(); + var page = context.Render(); + Button(page, "New subscription").Click(); + page.Find("#discord-name").Change("Bad URL"); + page.Find("#discord-url").Change("https://evil.example/synthetic-token"); + page.FindAll("label").Single(label => label.TextContent.Trim() == "server.game.created") + .QuerySelector("input")!.Change(true); + Button(page, "Save subscription").Click(); + page.WaitForAssertion(() => Assert.Contains("Operation failed", page.Markup)); + Assert.DoesNotContain("evil.example", page.Markup); + Assert.DoesNotContain("synthetic-token", page.Markup); + Assert.Empty((await fixture.Store.GetAsync()).Subscriptions); + } + + [Fact] + public async Task PageDoesNotExposeSubscriptionsWhenAuthorizationFailsEvenWithoutRouter() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit() with { Name = "Private administration" }, null); + await using var context = new BunitContext(); + context.Services.AddLogging(); + context.Services.AddSingleton(fixture.Store); + context.Services.AddSingleton(new TestAuthentication(true, "User")); + context.Services.AddScoped(); + var page = context.Render(); + page.WaitForAssertion(() => Assert.Contains("administrator access is required", page.Markup)); + Assert.DoesNotContain("Private administration", page.Markup); + Assert.DoesNotContain("synthetic-token", page.Markup); + } + + [Fact] + public async Task PluginRegistersFullStreamConsumerAndInitializesHostProvidedDataDirectory() + { + var root = Path.Combine(Path.GetTempPath(), "discord-registration-" + Guid.NewGuid().ToString("N")); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(new EphemeralDataProtectionProvider()); + var plugin = new DiscordPlugin(); + plugin.ConfigureServices(services); + await using (var provider = services.BuildServiceProvider()) + { + await plugin.InitializeAsync(new PluginContext + { + Services = provider, DataDirectory = root, Host = PluginHost.Server, + Logger = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance + }, default); + var store = provider.GetRequiredService(); + await store.SaveAsync(StoreFixture.Edit(), null); + var consumer = Assert.Single(provider.GetServices()); + Assert.IsType(consumer); + await consumer.HandleAsync(StoreFixture.Event(), default); + Assert.Single((await store.GetAsync()).Deliveries); + Assert.Single(provider.GetServices(), service => service is DiscordDeliveryWorker); + Assert.Single(provider.GetServices()); + } + foreach (var file in Directory.GetFiles(root)) File.Delete(file); + Directory.Delete(root); + } + + [Fact] + public async Task HostedWorkerDeliversAcceptedWorkAndStopsOnCancellation() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + using var client = StoreFixture.Client((_, _) => Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK))); + using var worker = new DiscordDeliveryWorker(fixture.Store, client, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + await worker.StartAsync(default); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + try + { + while (Assert.Single((await fixture.Store.GetAsync(timeout.Token)).Deliveries).Status != "Delivered") + await Task.Delay(20, timeout.Token); + } + finally { await worker.StopAsync(default); } + Assert.True(worker.ExecuteTask!.IsCompleted); + } + + [Fact] + public void PackagedPluginLoadsWithSharedHostContractsAndAdminPageDiscovery() + { + var context = new SharedHostLoader(); + try + { + var package = Environment.GetEnvironmentVariable("DISCORD_TEST_PACKAGE"); + using var archive = package is null ? null : ZipFile.OpenRead(package); + using var stream = archive is null + ? File.OpenRead(typeof(DiscordPlugin).Assembly.Location) + : archive.GetEntry("lib/net10.0/LANCommander.Community.Server.DiscordWebhook.dll")!.Open(); + using var extracted = new MemoryStream(); + stream.CopyTo(extracted); + extracted.Position = 0; + var assembly = context.LoadFromStream(extracted); + var attribute = assembly.GetCustomAttribute()!; + Assert.Equal(DiscordPlugin.PluginId, attribute.Id); + Assert.Equal("2.2.0-beta.4", attribute.MinHostVersion); + Assert.Equal(PluginHost.Server, attribute.Hosts); + var type = Assert.Single(assembly.GetTypes(), t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsAbstract); + var plugin = Assert.IsAssignableFrom(Activator.CreateInstance(type)); + Assert.Equal("Discord webhooks", plugin.Name); + var page = Assert.Single(assembly.GetTypes(), t => t.GetCustomAttribute()?.Template == "/Plugins/DiscordWebhooks"); + Assert.Equal(PluginAccessPolicy.Administrator, page.GetCustomAttribute()!.Policy); + var services = new ServiceCollection(); + plugin.ConfigureServices(services); + using var provider = services.BuildServiceProvider(); + var nav = Assert.Single(provider.GetServices()); + Assert.Equal(PluginAccessPolicy.Administrator, nav.Access); + Assert.Equal("/Plugins/DiscordWebhooks", nav.Href); + Assert.Equal(nameof(LANCommander.Server.UI.Controls.IconType.ChatCircle), nav.Icon); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(IServerEventConsumer)); + Assert.DoesNotContain(services, descriptor => descriptor.ServiceType == typeof(IServerEventTransport)); + } + finally { context.Unload(); } + } + + private static AngleSharp.Dom.IElement Button(IRenderedComponent page, string text) => + page.FindAll("button").Single(button => button.TextContent.Trim() == text); + + private sealed class SharedHostLoader() : AssemblyLoadContext(isCollectible: true) + { + protected override Assembly? Load(AssemblyName assemblyName) => Default.LoadFromAssemblyName(assemblyName); + } +} diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj index ca30039..5a221b5 100644 --- a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/LANCommander.Community.Server.DiscordWebhook.Tests.csproj @@ -6,9 +6,15 @@ true + + + + + +
diff --git a/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/SubscriptionTests.cs b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/SubscriptionTests.cs new file mode 100644 index 0000000..2d8addd --- /dev/null +++ b/plugins/Server.DiscordWebhook/tests/LANCommander.Community.Server.DiscordWebhook.Tests/SubscriptionTests.cs @@ -0,0 +1,479 @@ +using System.Net; +using System.Security.Claims; +using System.Text.Json; +using LANCommander.SDK.Events; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LANCommander.Community.Server.DiscordWebhook.Tests; + +public sealed class SubscriptionTests +{ + [Fact] + public async Task CrudPersistsAcrossRestartWithoutReturningOrStoringPlaintextEndpoint() + { + using var fixture = new StoreFixture(); + var id = await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + var snapshot = await fixture.Store.GetAsync(); + var view = Assert.Single(snapshot.Subscriptions); + Assert.Equal(id, view.Id); + Assert.Equal(1, view.Revision); + Assert.DoesNotContain("synthetic-token", JsonSerializer.Serialize(snapshot)); + Assert.DoesNotContain("synthetic-token", await File.ReadAllTextAsync(fixture.StatePath)); + fixture.Restart(); + Assert.Equal(id, Assert.Single((await fixture.Store.GetAsync()).Subscriptions).Id); + await fixture.Store.SaveAsync(StoreFixture.Edit(id, url: "") with { Name = "Renamed", Enabled = false }, view.Revision); + view = Assert.Single((await fixture.Store.GetAsync()).Subscriptions); + Assert.Equal(2, view.Revision); + Assert.False(view.Enabled); + await fixture.Store.DeleteAsync(id, view.Revision); + Assert.Empty((await fixture.Store.GetAsync()).Subscriptions); + } + + [Theory] + [InlineData("", 10, 3)] + [InlineData("Name", 0, 3)] + [InlineData("Name", 31, 3)] + [InlineData("Name", 10, 0)] + [InlineData("Name", 10, 6)] + public async Task InvalidSubscriptionSettingsDoNotCommit(string name, int timeout, int attempts) + { + using var fixture = new StoreFixture(); + await Assert.ThrowsAsync(() => fixture.Store.SaveAsync( + StoreFixture.Edit() with { Name = name, TimeoutSeconds = timeout, MaxAttempts = attempts }, null)); + Assert.Empty((await fixture.Store.GetAsync()).Subscriptions); + } + + [Fact] + public async Task ValidatesEventsContentAndRequiredNewSecret() + { + using var fixture = new StoreFixture(); + foreach (var edit in new[] + { + StoreFixture.Edit(url: ""), StoreFixture.Edit() with { EventTypes = [] }, + StoreFixture.Edit() with { EventTypes = ["unknown.event"] }, + StoreFixture.Edit() with { Content = new string('x', 1001) }, + StoreFixture.Edit() with { WebhookUrl = "https://evil.example/secret" } + }) + await Assert.ThrowsAsync(() => fixture.Store.SaveAsync(edit, null)); + Assert.Empty((await fixture.Store.GetAsync()).Subscriptions); + } + + [Fact] + public async Task OptimisticRevisionPreventsLostUpdatesAndDeletes() + { + using var fixture = new StoreFixture(); + var id = await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + await fixture.Store.SaveAsync(StoreFixture.Edit(id, "") with { Name = "Latest" }, 1); + await Assert.ThrowsAsync(() => fixture.Store.SaveAsync(StoreFixture.Edit(id, ""), 1)); + await Assert.ThrowsAsync(() => fixture.Store.DeleteAsync(id, 1)); + Assert.Equal("Latest", Assert.Single((await fixture.Store.GetAsync()).Subscriptions).Name); + } + + [Fact] + public async Task ConsumerFiltersAllStreamByEnabledSubscriptionsAndDeduplicatesRetainedEventIds() + { + using var fixture = new StoreFixture(); + var selected = await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + await fixture.Store.SaveAsync(StoreFixture.Edit() with { Name = "Disabled", Enabled = false }, null); + await fixture.Store.SaveAsync(StoreFixture.Edit() with { Name = "Other", EventTypes = [ServerEventTypes.UserLogin] }, null); + var consumer = new DiscordEventConsumer(fixture.Store, NullLogger.Instance); + await consumer.HandleAsync(StoreFixture.Event(ServerEventTypes.UserLogout), default); + Assert.Empty((await fixture.Store.GetAsync()).Deliveries); + var value = StoreFixture.Event(); + await consumer.HandleAsync(value, default); + await consumer.HandleAsync(value, default); + var delivery = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal(selected, delivery.SubscriptionId); + Assert.Equal(value.EventId, delivery.EventId); + } + + [Fact] + public async Task TestTargetsOnlySelectedEnabledSubscriptionDespiteItsFilter() + { + using var fixture = new StoreFixture(); + var selected = await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + await fixture.Store.QueueTestAsync(selected); + var delivery = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal(selected, delivery.SubscriptionId); + Assert.Equal(ServerEventTypes.Test, delivery.EventType); + await fixture.Store.SaveAsync(StoreFixture.Edit(selected, "") with { Enabled = false }, 1); + await Assert.ThrowsAsync(() => fixture.Store.QueueTestAsync(selected)); + await Assert.ThrowsAsync(() => fixture.Store.QueueTestAsync(Guid.NewGuid())); + } + + [Fact] + public async Task EventFormattingDoesNotForwardArbitraryPayloadOrActorIdentity() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit() with { Content = "Community news" }, null); + var value = StoreFixture.Event() with + { + ActorId = Guid.NewGuid(), + Payload = JsonSerializer.SerializeToElement(new { password = "do-not-forward", description = "@everyone private" }) + }; + await fixture.Store.EnqueueAsync(value, null); + string? body = null; + using var client = StoreFixture.Client(async (request, token) => + { + body = await request.Content!.ReadAsStringAsync(token); + return new(HttpStatusCode.OK); + }); + await fixture.Store.DeliverNextAsync(client, DateTimeOffset.UtcNow.AddSeconds(1)); + Assert.NotNull(body); + Assert.Contains("Community news", body); + Assert.DoesNotContain("do-not-forward", body); + Assert.DoesNotContain(value.ActorId.Value.ToString(), body); + Assert.DoesNotContain("private", body); + Assert.Contains(value.TargetId.ToString(), body); + Assert.Contains(value.EventId.ToString(), body); + } + + [Theory] + [InlineData(204, "Delivered", false)] + [InlineData(400, "Failed", false)] + [InlineData(404, "Failed", false)] + [InlineData(500, "Pending", true)] + [InlineData(408, "Pending", true)] + public async Task CompletionDistinguishesPermanentAndRetryableFailures(int status, string expected, bool retry) + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + var calls = 0; + using var client = StoreFixture.Client((_, _) => + { + calls++; + return Task.FromResult(new HttpResponseMessage((HttpStatusCode)status)); + }); + var now = DateTimeOffset.UtcNow.AddSeconds(1); + Assert.True(await fixture.Store.DeliverNextAsync(client, now)); + var view = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal(expected, view.Status); + Assert.Equal(1, view.Attempts); + Assert.Equal(status, view.HttpStatusCode); + Assert.False(await fixture.Store.DeliverNextAsync(client, now)); + if (retry) + { + Assert.True(view.NextAttemptOn >= now.AddSeconds(5)); + await fixture.Store.DeliverNextAsync(client, view.NextAttemptOn); + view = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + await fixture.Store.DeliverNextAsync(client, view.NextAttemptOn); + view = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal("Failed", view.Status); + Assert.Equal(3, view.Attempts); + Assert.False(await fixture.Store.DeliverNextAsync(client, now.AddHours(1))); + } + Assert.Equal(retry ? 3 : 1, calls); + } + + [Fact] + public async Task RateLimitSurvivesRestartAndPausesOtherSubscriptionsWithoutShorteningDelay() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + await fixture.Store.EnqueueAsync(StoreFixture.Event(), null); + var calls = 0; + using var client = StoreFixture.Client((_, _) => + { + calls++; + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.TooManyRequests) + { + Content = new StringContent("{\"retry_after\":120.5,\"global\":true}") + }); + }); + var now = DateTimeOffset.UtcNow.AddSeconds(1); + Assert.True(await fixture.Store.DeliverNextAsync(client, now)); + fixture.Restart(); + Assert.False(await fixture.Store.DeliverNextAsync(client, now.AddSeconds(120))); + Assert.Equal(1, calls); + Assert.True(await fixture.Store.DeliverNextAsync(client, now.AddSeconds(121))); + } + + [Fact] + public async Task UnknownRateLimitDelayUsesConservativeMinuteNotImmediateRetry() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + using var client = StoreFixture.Client((_, _) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.TooManyRequests) { Content = new StringContent("bad json") })); + var now = DateTimeOffset.UtcNow.AddSeconds(1); + await fixture.Store.DeliverNextAsync(client, now); + var next = Assert.Single((await fixture.Store.GetAsync()).Deliveries).NextAttemptOn; + Assert.True(next >= now.AddSeconds(60)); + } + + [Fact] + public async Task InterruptedFinalAttemptRecoversAsFailedWithoutExceedingBudget() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(attempts: 1); + using var cts = new CancellationTokenSource(); + using var client = StoreFixture.Client(async (_, token) => + { + await cts.CancelAsync(); + await Task.Delay(Timeout.Infinite, token); + return new(HttpStatusCode.OK); + }); + var now = DateTimeOffset.UtcNow.AddSeconds(1); + await Assert.ThrowsAnyAsync(() => + fixture.Store.DeliverNextAsync(client, now, cts.Token)); + Assert.Equal("InFlight", Assert.Single((await fixture.Store.GetAsync()).Deliveries).Status); + fixture.Restart(); + using var noSend = StoreFixture.Client((_, _) => throw new InvalidOperationException("Must not send")); + Assert.False(await fixture.Store.DeliverNextAsync(noSend, now.AddMinutes(1))); + var view = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal("Failed", view.Status); + Assert.Equal(1, view.Attempts); + } + + [Fact] + public async Task PersistedPendingAttemptResumesAfterRestartWithProtectedSecret() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + fixture.Restart(); + using var client = StoreFixture.Client((request, _) => + { + Assert.EndsWith("synthetic-token?wait=true", request.RequestUri!.AbsoluteUri); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); + }); + await fixture.Store.DeliverNextAsync(client, DateTimeOffset.UtcNow.AddSeconds(1)); + Assert.Equal("Delivered", Assert.Single((await fixture.Store.GetAsync()).Deliveries).Status); + } + + [Fact] + public async Task LostProtectionKeyMarksSecretUnavailableWithoutMakingRequest() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + fixture.Restart(new EphemeralDataProtectionProvider()); + using var noSend = StoreFixture.Client((_, _) => throw new InvalidOperationException("Must not send")); + Assert.True(await fixture.Store.DeliverNextAsync(noSend, DateTimeOffset.UtcNow.AddSeconds(1))); + var view = Assert.Single((await fixture.Store.GetAsync()).Deliveries); + Assert.Equal("SecretUnavailable", view.Status); + Assert.DoesNotContain("synthetic-token", JsonSerializer.Serialize(view)); + } + + [Fact] + public async Task SavingDisablingOrDeletingCancelsQueuedWork() + { + using var fixture = new StoreFixture(); + var id = await fixture.QueueAsync(); + await fixture.Store.SaveAsync(StoreFixture.Edit(id, "") with { Enabled = false }, 1); + Assert.Equal("Canceled", Assert.Single((await fixture.Store.GetAsync()).Deliveries).Status); + using var noSend = StoreFixture.Client((_, _) => throw new InvalidOperationException("Must not send")); + Assert.False(await fixture.Store.DeliverNextAsync(noSend, DateTimeOffset.UtcNow.AddDays(1))); + await fixture.Store.DeleteAsync(id, 2); + Assert.Empty((await fixture.Store.GetAsync()).Deliveries); + } + + [Fact] + public async Task ConcurrentDeliveryCallsClaimOneAttempt() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + var calls = 0; + using var client = StoreFixture.Client((_, _) => + { + Interlocked.Increment(ref calls); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); + }); + var now = DateTimeOffset.UtcNow.AddSeconds(1); + var results = await Task.WhenAll(Enumerable.Range(0, 4) + .Select(_ => fixture.Store.DeliverNextAsync(client, now))); + Assert.Single(results, value => value); + Assert.Equal(1, calls); + } + + [Fact] + public async Task QueueOverflowIsVisibleAndDoesNotEvictPreviouslyAcceptedWork() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + for (var i = 0; i < DiscordStore.MaximumPending; i++) + await fixture.Store.EnqueueAsync(StoreFixture.Event(), null); + await Assert.ThrowsAsync(() => fixture.Store.EnqueueAsync(StoreFixture.Event(), null)); + var snapshot = await fixture.Store.GetAsync(); + Assert.Equal(DiscordStore.MaximumPending, snapshot.Deliveries.Count); + Assert.Contains("dropped", snapshot.Warning); + fixture.Restart(); + Assert.Contains("dropped", (await fixture.Store.GetAsync()).Warning); + } + + [Fact] + public async Task CorruptStateIsNeverReplacedWithAnEmptyConfiguration() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + const string corrupt = "{\"secret\":\"synthetic-token\"}"; + await File.WriteAllTextAsync(fixture.StatePath, corrupt); + var exception = await Assert.ThrowsAsync(() => fixture.Store.GetAsync()); + Assert.DoesNotContain("synthetic-token", exception.ToString()); + await Assert.ThrowsAsync(() => fixture.Store.SaveAsync(StoreFixture.Edit(), null)); + Assert.Equal(corrupt, await File.ReadAllTextAsync(fixture.StatePath)); + } + + [Fact] + public async Task MissingPreviouslySavedStateIsAnErrorRatherThanAnEmptyReset() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + File.Delete(fixture.StatePath); + await Assert.ThrowsAsync(() => fixture.Store.GetAsync()); + await Assert.ThrowsAsync(() => fixture.Store.SaveAsync(StoreFixture.Edit(), null)); + Assert.False(File.Exists(fixture.StatePath)); + } + + [Fact] + public async Task FailedClaimCommitDoesNotSendAndPreservesAcceptedWork() + { + using var fixture = new StoreFixture(); + await fixture.QueueAsync(); + var saved = await File.ReadAllTextAsync(fixture.StatePath); + // A directory at the exact staging path forces a real filesystem write failure. + var staging = fixture.StatePath + ".pending"; + Directory.CreateDirectory(staging); + using var noSend = StoreFixture.Client((_, _) => throw new InvalidOperationException("Must not send")); + try + { + var failure = await Assert.ThrowsAsync(() => + fixture.Store.DeliverNextAsync(noSend, DateTimeOffset.UtcNow.AddSeconds(1))); + Assert.DoesNotContain("synthetic-token", failure.ToString()); + Assert.Equal(saved, await File.ReadAllTextAsync(fixture.StatePath)); + } + finally { Directory.Delete(staging); } + Assert.Equal(0, Assert.Single((await fixture.Store.GetAsync()).Deliveries).Attempts); + } + + [Fact] + public async Task EditingDuringHttpDoesNotResurrectCanceledWork() + { + using var fixture = new StoreFixture(); + var id = await fixture.QueueAsync(); + using var client = StoreFixture.Client(async (_, _) => + { + await fixture.Store.SaveAsync(StoreFixture.Edit(id, "") with { Enabled = false }, 1); + return new(HttpStatusCode.ServiceUnavailable); + }); + await fixture.Store.DeliverNextAsync(client, DateTimeOffset.UtcNow.AddSeconds(1)); + Assert.Equal("Canceled", Assert.Single((await fixture.Store.GetAsync()).Deliveries).Status); + } + + [Fact] + public async Task RejectedDeliveryHistoryIsBoundedWithoutDroppingPendingEntries() + { + using var fixture = new StoreFixture(); + await fixture.Store.SaveAsync(StoreFixture.Edit(), null); + using var client = StoreFixture.Client((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest))); + for (var i = 0; i < DiscordStore.MaximumHistory + 2; i++) + { + await fixture.Store.EnqueueAsync(StoreFixture.Event(), null); + await fixture.Store.DeliverNextAsync(client, DateTimeOffset.UtcNow.AddMinutes(1)); + } + await fixture.Store.EnqueueAsync(StoreFixture.Event(), null); + var entries = (await fixture.Store.GetAsync()).Deliveries; + Assert.Equal(DiscordStore.MaximumHistory + 1, entries.Count); + Assert.Single(entries, d => d.Status == "Pending"); + } + + [Fact] + public async Task SecondStoreCannotShareTheSameDataDirectory() + { + using var fixture = new StoreFixture(); + using var second = new DiscordStore(fixture.Protection); + await Assert.ThrowsAsync(() => second.InitializeAsync(fixture.Root)); + } + + [Theory] + [InlineData(false, "Administrator")] + [InlineData(true, "User")] + [InlineData(true, "Moderator")] + public async Task UnauthorizedAdministrationCannotReadOrMutateAnyState(bool authenticated, string role) + { + using var fixture = new StoreFixture(); + var administration = new DiscordAdministration(fixture.Store, new TestAuthentication(authenticated, role)); + await Assert.ThrowsAsync(() => administration.GetAsync()); + await Assert.ThrowsAsync(() => administration.SaveAsync(StoreFixture.Edit(), null)); + await Assert.ThrowsAsync(() => administration.DeleteAsync(Guid.NewGuid(), 1)); + await Assert.ThrowsAsync(() => administration.TestAsync(Guid.NewGuid())); + Assert.Empty((await fixture.Store.GetAsync()).Subscriptions); + } + + [Fact] + public async Task AdministratorCanManageAndTestSubscription() + { + using var fixture = new StoreFixture(); + var administration = new DiscordAdministration(fixture.Store, new TestAuthentication(true, "Administrator")); + await administration.SaveAsync(StoreFixture.Edit(), null); + var id = Assert.Single((await administration.GetAsync()).Subscriptions).Id; + await administration.TestAsync(id); + Assert.Single((await administration.GetAsync()).Deliveries); + await administration.DeleteAsync(id, 1); + Assert.Empty((await administration.GetAsync()).Subscriptions); + } + + [Fact] + public void EditStringRepresentationNeverIncludesSubmittedCredential() + { + Assert.DoesNotContain("synthetic-token", StoreFixture.Edit().ToString()); + } +} + +internal sealed class StoreFixture : IDisposable +{ + public const string Endpoint = "https://discord.com/api/webhooks/123456789012345678/synthetic-token"; + public string Root { get; } = Path.Combine(Path.GetTempPath(), "discord-tests-" + Guid.NewGuid().ToString("N")); + public string StatePath => Path.Combine(Root, "discord.json"); + public IDataProtectionProvider Protection { get; private set; } = new EphemeralDataProtectionProvider(); + public DiscordStore Store { get; private set; } + + public StoreFixture() + { + Store = new(Protection); + Store.InitializeAsync(Root).GetAwaiter().GetResult(); + } + public void Restart(IDataProtectionProvider? protection = null) + { + Store.Dispose(); + Protection = protection ?? Protection; + Store = new(Protection); + Store.InitializeAsync(Root).GetAwaiter().GetResult(); + } + public async Task QueueAsync(int attempts = 3) + { + var id = await Store.SaveAsync(Edit() with { MaxAttempts = attempts }, null); + await Store.EnqueueAsync(Event(), null); + return id; + } + public static DiscordSubscriptionEdit Edit(Guid id = default, string url = Endpoint) => + new(id, "Community", url, [ServerEventTypes.GameCreated]); + public static ServerEvent Event(string type = ServerEventTypes.GameCreated) => + new(Guid.NewGuid(), type, DateTime.UtcNow, ServerEventTypes.GetSource(type), null, "game", + Guid.NewGuid(), "completed", null, JsonSerializer.SerializeToElement(new { })); + public static DiscordWebhookClient Client(Func> send) => + new(new Handler(send)); + public void Dispose() + { + Store.Dispose(); + // The fixture owns this unique test-only directory, never a shared plugin directory. + foreach (var file in Directory.GetFiles(Root)) + File.Delete(file); + Directory.Delete(Root); + } + private sealed class Handler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + send(request, cancellationToken); + } +} + +internal sealed class TestAuthentication(bool authenticated, string role) : AuthenticationStateProvider +{ + public override Task GetAuthenticationStateAsync() => + Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.Role, role)], authenticated ? "test" : null)))); +} diff --git a/plugins/Server.DiscordWebhook/version.txt b/plugins/Server.DiscordWebhook/version.txt new file mode 100644 index 0000000..4ab2ff6 --- /dev/null +++ b/plugins/Server.DiscordWebhook/version.txt @@ -0,0 +1 @@ +0.1.0-beta.1