Add Heimdall patron support intake

This commit is contained in:
Meta Vens 2026-06-09 17:16:27 +01:00
commit bb1b1056be
21 changed files with 625 additions and 13 deletions

View file

@ -14,6 +14,10 @@ public sealed class HeimdallOptions
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
public bool EnablePatronSupportIntake { get; init; } = true;
public bool IsConfigured =>
!string.IsNullOrWhiteSpace(BaseUrl) &&
!string.IsNullOrWhiteSpace(AppSlug);
@ -26,4 +30,9 @@ public sealed class HeimdallOptions
public bool IsPatreonConfigured =>
IsConfigured &&
!string.IsNullOrWhiteSpace(PatreonTierTitle);
public bool IsPatronSupportIntakeConfigured =>
IsConfigured &&
EnablePatronSupportIntake &&
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
}

View file

@ -334,10 +334,17 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
modelBuilder.Entity<PatronSupportEvent>(entity =>
{
entity.Property(x => x.Kind).HasConversion<string>();
entity.Property(x => x.Provider).HasConversion<string>();
entity.Property(x => x.Amount).HasPrecision(18, 2);
entity.Property(x => x.ExternalSupportId).HasMaxLength(240);
entity.Property(x => x.ProviderEventId).HasMaxLength(240);
entity.Property(x => x.ProviderPayerId).HasMaxLength(240);
entity.Property(x => x.ProviderSubscriptionId).HasMaxLength(240);
entity.Property(x => x.CurrencyCode).HasMaxLength(12);
entity.HasIndex(x => new { x.UserAccountId, x.Kind, x.IsCurrentRecurringSupport });
entity.HasIndex(x => new { x.Provider, x.ProviderEventId })
.IsUnique()
.HasFilter("\"ProviderEventId\" <> ''");
entity.HasOne(x => x.UserAccount)
.WithMany(x => x.PatronSupportEvents)
.HasForeignKey(x => x.UserAccountId)

View file

@ -0,0 +1,75 @@
using Bifrost.Web.Domain;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
[Migration("20260609160000_AddExternalPatronProviderIntake")]
public partial class AddExternalPatronProviderIntake : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Provider",
table: "PatronSupportEvents",
type: "text",
nullable: false,
defaultValue: nameof(ExternalPatronProvider.Manual));
migrationBuilder.AddColumn<string>(
name: "ProviderEventId",
table: "PatronSupportEvents",
type: "character varying(240)",
maxLength: 240,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "ProviderPayerId",
table: "PatronSupportEvents",
type: "character varying(240)",
maxLength: 240,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "ProviderSubscriptionId",
table: "PatronSupportEvents",
type: "character varying(240)",
maxLength: 240,
nullable: false,
defaultValue: "");
migrationBuilder.CreateIndex(
name: "IX_PatronSupportEvents_Provider_ProviderEventId",
table: "PatronSupportEvents",
columns: new[] { "Provider", "ProviderEventId" },
unique: true,
filter: "\"ProviderEventId\" <> ''");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_PatronSupportEvents_Provider_ProviderEventId",
table: "PatronSupportEvents");
migrationBuilder.DropColumn(
name: "Provider",
table: "PatronSupportEvents");
migrationBuilder.DropColumn(
name: "ProviderEventId",
table: "PatronSupportEvents");
migrationBuilder.DropColumn(
name: "ProviderPayerId",
table: "PatronSupportEvents");
migrationBuilder.DropColumn(
name: "ProviderSubscriptionId",
table: "PatronSupportEvents");
}
}
}

View file

@ -500,6 +500,25 @@ namespace Bifrost.Web.Data.Migrations
b.Property<DateTimeOffset>("RecordedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Provider")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ProviderEventId")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("ProviderPayerId")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("ProviderSubscriptionId")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("SupportedAtUtc")
.HasColumnType("timestamp with time zone");
@ -512,6 +531,10 @@ namespace Bifrost.Web.Data.Migrations
b.HasIndex("UserAccountId", "Kind", "IsCurrentRecurringSupport");
b.HasIndex("Provider", "ProviderEventId")
.IsUnique()
.HasFilter("\"ProviderEventId\" <> ''");
b.ToTable("PatronSupportEvents");
});

View file

@ -163,7 +163,15 @@ public enum PointTransactionType
public enum PatronSupportEventKind
{
OneTimeDonation,
RecurringSupportSnapshot
RecurringSupportSnapshot,
SupportAdjustment
}
public enum ExternalPatronProvider
{
Manual,
Patreon,
PayPal
}
public sealed class UserAccount
@ -717,6 +725,14 @@ public sealed class PatronSupportEvent
public string ExternalSupportId { get; set; } = string.Empty;
public ExternalPatronProvider Provider { get; set; } = ExternalPatronProvider.Manual;
public string ProviderEventId { get; set; } = string.Empty;
public string ProviderPayerId { get; set; } = string.Empty;
public string ProviderSubscriptionId { get; set; } = string.Empty;
public PatronSupportEventKind Kind { get; set; } = PatronSupportEventKind.OneTimeDonation;
public decimal Amount { get; set; }

View file

@ -0,0 +1,166 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Patronage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Features.Heimdall;
public sealed class HeimdallPatronSupportIntakeService(
BifrostDbContext dbContext,
PatronageService patronageService,
IOptions<HeimdallOptions> heimdallOptions)
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter() }
};
public async Task<HeimdallPatronSupportIntakeResult> ProcessAsync(
string signature,
string payload,
CancellationToken cancellationToken)
{
if (!heimdallOptions.Value.IsPatronSupportIntakeConfigured)
{
return HeimdallPatronSupportIntakeResult.NotConfigured("Heimdall patron support intake is not configured.");
}
if (!VerifySignature(heimdallOptions.Value.PatronSupportIntakeSecret, payload, signature))
{
return HeimdallPatronSupportIntakeResult.Unauthorized("Invalid Heimdall patron support intake signature.");
}
var request = JsonSerializer.Deserialize<HeimdallPatronSupportEventRequest>(payload, JsonOptions);
if (request is null)
{
return HeimdallPatronSupportIntakeResult.BadRequest("Patron support payload was empty.");
}
if (request.Provider is ExternalPatronProvider.Manual)
{
return HeimdallPatronSupportIntakeResult.BadRequest("Heimdall patron support intake requires an external provider.");
}
if (string.IsNullOrWhiteSpace(request.HeimdallAccountId))
{
return HeimdallPatronSupportIntakeResult.BadRequest("Patron support payload omitted Heimdall account id.");
}
if (string.IsNullOrWhiteSpace(request.ProviderEventId))
{
return HeimdallPatronSupportIntakeResult.BadRequest("Patron support payload omitted provider event id.");
}
var existingEvent = await dbContext.PatronSupportEvents
.AsNoTracking()
.SingleOrDefaultAsync(
x => x.Provider == request.Provider &&
x.ProviderEventId == request.ProviderEventId.Trim(),
cancellationToken);
if (existingEvent is not null)
{
return HeimdallPatronSupportIntakeResult.Processed(
$"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
existingEvent.Id);
}
var user = await dbContext.UserAccounts
.AsNoTracking()
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
if (user is null)
{
return HeimdallPatronSupportIntakeResult.BadRequest(
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
}
var supportEvent = await patronageService.RecordSupportEventAsync(
actorUserAccountId: null,
userAccountId: user.Id,
request.Kind,
request.Amount,
request.CurrencyCode,
request.ExternalSupportId,
request.Provider,
request.ProviderEventId,
request.ProviderPayerId,
request.ProviderSubscriptionId,
request.SupportedAtUtc,
request.IsCurrentRecurringSupport,
request.Notes,
cancellationToken);
return HeimdallPatronSupportIntakeResult.Processed(
$"Processed {request.Provider} patron support event {request.ProviderEventId}.",
supportEvent.Id);
}
private static bool VerifySignature(string secret, string payload, string signature)
{
if (string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(signature))
{
return false;
}
var normalizedSignature = signature.Trim();
if (normalizedSignature.StartsWith("sha256=", StringComparison.OrdinalIgnoreCase))
{
normalizedSignature = normalizedSignature["sha256=".Length..];
}
using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var expectedBytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(payload));
var expectedHex = Convert.ToHexString(expectedBytes).ToLowerInvariant();
return CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(expectedHex),
Encoding.ASCII.GetBytes(normalizedSignature.ToLowerInvariant()));
}
}
public sealed record HeimdallPatronSupportEventRequest(
string HeimdallAccountId,
ExternalPatronProvider Provider,
string ProviderEventId,
PatronSupportEventKind Kind,
decimal Amount,
string CurrencyCode,
string ExternalSupportId,
DateTimeOffset SupportedAtUtc,
bool IsCurrentRecurringSupport,
string ProviderPayerId = "",
string ProviderSubscriptionId = "",
string Notes = "");
public sealed record HeimdallPatronSupportIntakeResult(
HeimdallPatronSupportIntakeStatus Status,
string Message,
Guid? PatronSupportEventId)
{
public static HeimdallPatronSupportIntakeResult Processed(string message, Guid patronSupportEventId) =>
new(HeimdallPatronSupportIntakeStatus.Processed, message, patronSupportEventId);
public static HeimdallPatronSupportIntakeResult BadRequest(string message) =>
new(HeimdallPatronSupportIntakeStatus.BadRequest, message, null);
public static HeimdallPatronSupportIntakeResult Unauthorized(string message) =>
new(HeimdallPatronSupportIntakeStatus.Unauthorized, message, null);
public static HeimdallPatronSupportIntakeResult NotConfigured(string message) =>
new(HeimdallPatronSupportIntakeStatus.NotConfigured, message, null);
}
public enum HeimdallPatronSupportIntakeStatus
{
Processed,
BadRequest,
Unauthorized,
NotConfigured
}

View file

@ -35,6 +35,11 @@ public static class PatronTierPolicy
return Math.Max(0m, supportEvent.Amount);
}
if (supportEvent.Kind == PatronSupportEventKind.SupportAdjustment)
{
return supportEvent.Amount;
}
var amount = Math.Max(0m, supportEvent.Amount);
var age = nowUtc - supportEvent.SupportedAtUtc.ToUniversalTime();
if (age < TimeSpan.FromDays(30))

View file

@ -11,12 +11,16 @@ public sealed class PatronageService(
TimeProvider timeProvider)
{
public async Task<PatronSupportEvent> RecordSupportEventAsync(
Guid actorUserAccountId,
Guid? actorUserAccountId,
Guid userAccountId,
PatronSupportEventKind kind,
decimal amount,
string currencyCode,
string externalSupportId,
ExternalPatronProvider provider,
string providerEventId,
string providerPayerId,
string providerSubscriptionId,
DateTimeOffset supportedAtUtc,
bool isCurrentRecurringSupport,
string notes,
@ -31,11 +35,37 @@ public sealed class PatronageService(
throw new InvalidOperationException("Patron support can only be recorded for an active member.");
}
if (amount <= 0)
if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment)
{
throw new InvalidOperationException("Patron support amount must be greater than zero.");
}
if (amount == 0)
{
throw new InvalidOperationException("Patron support amount must not be zero.");
}
if (kind == PatronSupportEventKind.SupportAdjustment && amount > 0)
{
throw new InvalidOperationException("Patron support adjustments must reduce support.");
}
var normalizedProviderEventId = providerEventId.Trim();
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
{
throw new InvalidOperationException("External patron provider events require a provider event id.");
}
var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
? null
: await dbContext.PatronSupportEvents
.SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
if (existingProviderEvent is not null)
{
return existingProviderEvent;
}
var now = timeProvider.GetUtcNow();
var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
? "USD"
@ -60,6 +90,10 @@ public sealed class PatronageService(
UserAccountId = userAccountId,
Kind = kind,
ExternalSupportId = externalSupportId.Trim(),
Provider = provider,
ProviderEventId = normalizedProviderEventId,
ProviderPayerId = providerPayerId.Trim(),
ProviderSubscriptionId = providerSubscriptionId.Trim(),
Amount = amount,
CurrencyCode = normalizedCurrency,
IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport,
@ -74,9 +108,9 @@ public sealed class PatronageService(
UserAccountId = userAccountId,
Type = PointTransactionType.PatronSupport,
Amount = amount,
IsDecaying = kind != PatronSupportEventKind.RecurringSupportSnapshot,
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
CreatedAtUtc = now,
Note = $"Recorded {kind} patron support event {supportEvent.ExternalSupportId}."
Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}."
});
await dbContext.SaveChangesAsync(cancellationToken);
@ -85,7 +119,7 @@ public sealed class PatronageService(
nameof(PatronSupportEvent),
supportEvent.Id,
"patron-support.recorded",
$"Recorded {amount:0.##} {normalizedCurrency} {kind} patron support for {user.DisplayName}.",
$"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.",
cancellationToken);
await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
@ -93,7 +127,7 @@ public sealed class PatronageService(
}
public async Task<PatronPointSummary> RefreshPatronTierSnapshotAsync(
Guid actorUserAccountId,
Guid? actorUserAccountId,
Guid userAccountId,
CancellationToken cancellationToken)
{

View file

@ -8,6 +8,7 @@ public sealed class StartupConfigurationValidator(
IHostEnvironment hostEnvironment,
IOptions<GitHubOAuthOptions> gitHubOAuthOptions,
IOptions<GitHubAppOptions> gitHubAppOptions,
IOptions<HeimdallOptions> heimdallOptions,
IOptions<BifrostHostOptions> hostOptions)
{
public void Validate()
@ -34,6 +35,12 @@ public sealed class StartupConfigurationValidator(
failures.Add("Host:PublicBaseUrl and Host:ExpectedHost must be configured.");
}
if (heimdallOptions.Value.EnablePatronSupportIntake &&
!heimdallOptions.Value.IsPatronSupportIntakeConfigured)
{
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
}
var allowedHosts = configuration["AllowedHosts"] ?? string.Empty;
if (hostOptions.Value.RequireStrictHostValidation &&
(string.IsNullOrWhiteSpace(allowedHosts) || allowedHosts.Contains('*')))

View file

@ -206,6 +206,7 @@
<tr>
<td>@support.MemberName</td>
<td>
<span class="pill">@support.Provider</span>
<span class="pill">@support.Kind</span><br />
@support.Amount.ToString("0.##") @support.CurrencyCode
@if (support.IsCurrentRecurringSupport)

View file

@ -111,6 +111,10 @@ public sealed class IndexModel(
PatronSupport.Amount,
PatronSupport.CurrencyCode,
PatronSupport.ExternalSupportId ?? string.Empty,
ExternalPatronProvider.Manual,
string.Empty,
string.Empty,
string.Empty,
PatronSupport.SupportedAtUtc,
PatronSupport.IsCurrentRecurringSupport,
PatronSupport.Notes ?? string.Empty,
@ -181,6 +185,7 @@ public sealed class IndexModel(
return new PatronSupportListItem(
x.UserAccountId,
x.UserAccount.DisplayName,
x.Provider,
x.Kind,
x.Amount,
x.CurrencyCode,
@ -244,7 +249,7 @@ public sealed class IndexModel(
[Display(Name = "Support kind")]
public PatronSupportEventKind Kind { get; set; } = PatronSupportEventKind.OneTimeDonation;
[Range(0.01, 100000000)]
[Range(-100000000, 100000000)]
public decimal Amount { get; set; }
[Display(Name = "Currency")]
@ -270,6 +275,7 @@ public sealed class IndexModel(
public sealed record PatronSupportListItem(
Guid UserAccountId,
string MemberName,
ExternalPatronProvider Provider,
PatronSupportEventKind Kind,
decimal Amount,
string CurrencyCode,

View file

@ -70,6 +70,7 @@ builder.Services.AddScoped<DashboardSnapshotService>();
builder.Services.AddScoped<MembershipSynchronizationService>();
builder.Services.AddScoped<GitHubWebhookService>();
builder.Services.AddScoped<PatronageService>();
builder.Services.AddScoped<HeimdallPatronSupportIntakeService>();
builder.Services.AddScoped<ReadinessService>();
builder.Services.AddScoped<ApplicationBootstrapper>();
builder.Services.AddSingleton<StartupConfigurationValidator>();
@ -284,6 +285,29 @@ app.MapPost("/auth/heimdall/callback", (
}
}).AllowAnonymous();
app.MapPost("/heimdall/patron-support/events", async (
HttpRequest request,
HeimdallPatronSupportIntakeService intakeService,
CancellationToken cancellationToken) =>
{
using var reader = new StreamReader(request.Body);
var payload = await reader.ReadToEndAsync(cancellationToken);
var signature = request.Headers["X-Heimdall-Signature-256"].ToString();
var result = await intakeService.ProcessAsync(signature, payload, cancellationToken);
return result.Status switch
{
HeimdallPatronSupportIntakeStatus.Processed => Results.Text(
result.Message,
statusCode: StatusCodes.Status202Accepted),
HeimdallPatronSupportIntakeStatus.BadRequest => Results.BadRequest(result.Message),
HeimdallPatronSupportIntakeStatus.NotConfigured => Results.Text(
result.Message,
statusCode: StatusCodes.Status503ServiceUnavailable),
_ => Results.Text(result.Message, statusCode: StatusCodes.Status401Unauthorized)
};
}).AllowAnonymous();
app.MapGet("/auth/heimdall/wait", async (
HttpContext httpContext,
HeimdallAuthService heimdallAuthService,

View file

@ -29,7 +29,9 @@
"AppSlug": "bifrost",
"DiscordGuildId": "",
"DiscordAllowedRoleIds": [],
"PatreonTierTitle": "Inner Sanctum"
"PatreonTierTitle": "Inner Sanctum",
"PatronSupportIntakeSecret": "",
"EnablePatronSupportIntake": true
},
"Logging": {
"LogLevel": {