Sealed-ballot motions: commit-reveal over typed gamecult.sealed_ballot.v0 documents

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-09 20:24:49 +00:00
commit d5a71eb639
11 changed files with 878 additions and 2 deletions

View file

@ -41,6 +41,8 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
public DbSet<Vote> Votes => Set<Vote>();
public DbSet<SealedBallot> SealedBallots => Set<SealedBallot>();
public DbSet<LedgerEntry> LedgerEntries => Set<LedgerEntry>();
public DbSet<PayoutProposalBatch> PayoutProposalBatches => Set<PayoutProposalBatch>();
@ -275,6 +277,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
entity.Property(x => x.Category).HasConversion<string>();
entity.Property(x => x.Status).HasConversion<string>();
entity.Property(x => x.ApprovalThreshold).HasPrecision(6, 3);
entity.Property(x => x.Kind).HasConversion<string>();
entity.HasOne(x => x.Project)
.WithMany(x => x.Motions)
.HasForeignKey(x => x.ProjectId)
@ -299,6 +302,18 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<SealedBallot>(entity =>
{
entity.HasIndex(x => new { x.MotionId, x.UserAccountId }).IsUnique();
entity.HasOne(x => x.Motion)
.WithMany(x => x.SealedBallots)
.HasForeignKey(x => x.MotionId);
entity.HasOne(x => x.UserAccount)
.WithMany()
.HasForeignKey(x => x.UserAccountId)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<LedgerEntry>(entity =>
{
entity.Property(x => x.EntryType).HasConversion<string>();

View file

@ -0,0 +1,59 @@
using System;
using Bifrost.Web.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
// Hand-written: no dotnet-ef on the authoring host. The snapshot was edited to match; BuildTargetModel is left to the base no-op.
[DbContext(typeof(BifrostDbContext))]
[Migration("20261109200000_AddSealedBallotMotions")]
public partial class AddSealedBallotMotions : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(name: "Candidates", table: "Motions", type: "text", nullable: false, defaultValue: "");
migrationBuilder.AddColumn<DateTimeOffset>(name: "CommitClosesAtUtc", table: "Motions", type: "timestamp with time zone", nullable: true);
migrationBuilder.AddColumn<string>(name: "Kind", table: "Motions", type: "text", nullable: false, defaultValue: "Standard");
migrationBuilder.AddColumn<Guid>(name: "PriorMotionId", table: "Motions", type: "uuid", nullable: true);
migrationBuilder.AddColumn<string>(name: "ResultDigest", table: "Motions", type: "text", nullable: false, defaultValue: "");
migrationBuilder.AddColumn<int>(name: "Round", table: "Motions", type: "integer", nullable: false, defaultValue: 1);
migrationBuilder.CreateTable(
name: "SealedBallots",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
MotionId = table.Column<Guid>(type: "uuid", nullable: false),
UserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
Commitment = table.Column<string>(type: "text", nullable: false),
Revision = table.Column<int>(type: "integer", nullable: false),
CommittedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
RevealedCandidate = table.Column<string>(type: "text", nullable: true),
RevealedReason = table.Column<string>(type: "text", nullable: true),
Salt = table.Column<string>(type: "text", nullable: true),
RevealedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SealedBallots", x => x.Id);
table.ForeignKey("FK_SealedBallots_Motions_MotionId", x => x.MotionId, "Motions", "Id", onDelete: ReferentialAction.Cascade);
table.ForeignKey("FK_SealedBallots_UserAccounts_UserAccountId", x => x.UserAccountId, "UserAccounts", "Id", onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(name: "IX_SealedBallots_MotionId_UserAccountId", table: "SealedBallots", columns: new[] { "MotionId", "UserAccountId" }, unique: true);
migrationBuilder.CreateIndex(name: "IX_SealedBallots_UserAccountId", table: "SealedBallots", column: "UserAccountId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "SealedBallots");
foreach (var column in new[] { "Candidates", "CommitClosesAtUtc", "Kind", "PriorMotionId", "ResultDigest", "Round" })
{
migrationBuilder.DropColumn(name: column, table: "Motions");
}
}
}
}

View file

@ -896,15 +896,29 @@ namespace Bifrost.Web.Data.Migrations
b.Property<DateTimeOffset>("ClosesAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Candidates")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("CommitClosesAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CreatedByUserAccountId")
.HasColumnType("uuid");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("OpensAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("PriorMotionId")
.HasColumnType("uuid");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
@ -915,6 +929,13 @@ namespace Bifrost.Web.Data.Migrations
b.Property<DateTimeOffset?>("ResolvedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("ResultDigest")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Round")
.HasColumnType("integer");
b.Property<string>("Scope")
.IsRequired()
.HasColumnType("text");
@ -1414,6 +1435,50 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("VolunteerClaims");
});
modelBuilder.Entity("Bifrost.Web.Domain.SealedBallot", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Commitment")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CommittedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("MotionId")
.HasColumnType("uuid");
b.Property<string>("RevealedCandidate")
.HasColumnType("text");
b.Property<string>("RevealedReason")
.HasColumnType("text");
b.Property<DateTimeOffset?>("RevealedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<int>("Revision")
.HasColumnType("integer");
b.Property<string>("Salt")
.HasColumnType("text");
b.Property<Guid>("UserAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserAccountId");
b.HasIndex("MotionId", "UserAccountId")
.IsUnique();
b.ToTable("SealedBallots");
});
modelBuilder.Entity("Bifrost.Web.Domain.Vote", b =>
{
b.Property<Guid>("Id")
@ -2209,6 +2274,25 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("WorkItem");
});
modelBuilder.Entity("Bifrost.Web.Domain.SealedBallot", b =>
{
b.HasOne("Bifrost.Web.Domain.Motion", "Motion")
.WithMany("SealedBallots")
.HasForeignKey("MotionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
.WithMany()
.HasForeignKey("UserAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Motion");
b.Navigation("UserAccount");
});
modelBuilder.Entity("Bifrost.Web.Domain.Vote", b =>
{
b.HasOne("Bifrost.Web.Domain.Motion", "Motion")
@ -2331,6 +2415,8 @@ namespace Bifrost.Web.Data.Migrations
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
{
b.Navigation("SealedBallots");
b.Navigation("Votes");
});

View file

@ -692,11 +692,64 @@ public sealed class Motion
public string ResolutionNote { get; set; } = string.Empty;
public MotionKind Kind { get; set; } = MotionKind.Standard;
// Sealed-ballot motions only: commitments are accepted until this instant, reveals from then until ClosesAtUtc.
public DateTimeOffset? CommitClosesAtUtc { get; set; }
// Sealed-ballot motions only: candidate names, one per line.
public string Candidates { get; set; } = string.Empty;
// Sealed-ballot motions only: Delphi round number and the motion whose result this round answers.
public int Round { get; set; } = 1;
public Guid? PriorMotionId { get; set; }
// Sealed-ballot motions only: SHA-256 over the sorted commitments, written once at finalization.
public string ResultDigest { get; set; } = string.Empty;
public Project? Project { get; set; }
public UserAccount CreatedByUserAccount { get; set; } = null!;
public ICollection<Vote> Votes { get; set; } = [];
public ICollection<SealedBallot> SealedBallots { get; set; } = [];
}
public enum MotionKind
{
Standard,
SealedBallot
}
public sealed class SealedBallot
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid MotionId { get; set; }
public Guid UserAccountId { get; set; }
// Hex SHA-256 of the canonical ballot document; the only ballot-derived value stored before the reveal step.
public string Commitment { get; set; } = string.Empty;
public int Revision { get; set; } = 1;
public DateTimeOffset CommittedAtUtc { get; set; }
// Reveal step. Held unread by every code path until the motion is Closed.
public string? RevealedCandidate { get; set; }
public string? RevealedReason { get; set; }
public string? Salt { get; set; }
public DateTimeOffset? RevealedAtUtc { get; set; }
public Motion Motion { get; set; } = null!;
public UserAccount UserAccount { get; set; } = null!;
}
public sealed class Vote

View file

@ -56,7 +56,7 @@ public sealed class MotionGovernanceService(
.Include(x => x.Votes)
.SingleAsync(x => x.Id == motionId, cancellationToken);
if (motion.Status != MotionStatus.Open)
if (motion.Status != MotionStatus.Open || motion.Kind != MotionKind.Standard)
{
return;
}
@ -102,6 +102,11 @@ public sealed class MotionGovernanceService(
.Include(x => x.Votes)
.SingleAsync(x => x.Id == motionId, cancellationToken);
if (motion.Kind != MotionKind.Standard)
{
throw new InvalidOperationException("Sealed-ballot motions close only at their deadline.");
}
if (!actor.CanModerateMotions && motion.CreatedByUserAccountId != actorUser.Id)
{
throw new UnauthorizedAccessException("Only the motion creator or a moderator can close this motion.");
@ -140,6 +145,7 @@ public sealed class MotionGovernanceService(
.AsNoTracking()
.Include(x => x.Project)
.Include(x => x.Votes)
.Where(x => x.Kind == MotionKind.Standard)
.OrderBy(x => x.ClosesAtUtc)
.ToListAsync(cancellationToken);

View file

@ -0,0 +1,339 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
namespace Bifrost.Web.Features.Motions;
/// <summary>
/// Sealed-ballot motions: commit, then reveal, then one atomic publication at close.
/// This is the only code that reads <see cref="SealedBallot.RevealedCandidate"/>, <see cref="SealedBallot.RevealedReason"/>
/// or <see cref="SealedBallot.Salt"/>; a test fails if any other source file mentions them.
/// </summary>
public sealed class SealedBallotService(
BifrostDbContext dbContext,
AuditTrailService auditTrailService,
TimeProvider timeProvider)
{
public const int MaxReasonLength = 280;
private static readonly Regex HexSha256 = new("^[0-9a-f]{64}$", RegexOptions.Compiled);
private static readonly Regex HexSalt = new("^[0-9a-f]{32,128}$", RegexOptions.Compiled);
public async Task<SealedMotionState> OpenAsync(
CurrentBifrostActor actor,
OpenSealedMotionCommand command,
CancellationToken cancellationToken)
{
var user = RequireMember(actor);
if (!actor.CanModerateMotions)
{
throw new SealedBallotException(SealedBallotFailure.Forbidden, "Only a moderator opens a sealed-ballot motion.");
}
var now = timeProvider.GetUtcNow();
var candidates = command.Candidates.Select(x => x.Trim()).Where(x => x.Length > 0).ToList();
if (candidates.Count < 2 || candidates.Distinct(StringComparer.Ordinal).Count() != candidates.Count ||
candidates.Any(x => x.Contains('\n') || x.Contains('\r')))
{
throw new SealedBallotException(SealedBallotFailure.Invalid, "Two or more distinct single-line candidates are required.");
}
var commitCloses = command.CommitClosesAtUtc.ToUniversalTime();
var closes = command.ClosesAtUtc.ToUniversalTime();
if (commitCloses <= now || closes <= commitCloses)
{
throw new SealedBallotException(SealedBallotFailure.Invalid, "The commit window must end in the future and the reveal window must end after it.");
}
var motion = new Motion
{
CreatedByUserAccountId = user.Id,
Scope = MotionScope.Management,
Category = MotionCategory.Features,
Kind = MotionKind.SealedBallot,
Title = command.Title.Trim(),
Summary = command.Summary.Trim(),
Candidates = string.Join('\n', candidates),
Round = Math.Max(1, command.Round),
PriorMotionId = command.PriorMotionId,
ApprovalThreshold = 0m,
OpensAtUtc = now,
CommitClosesAtUtc = commitCloses,
ClosesAtUtc = closes,
CreatedAtUtc = now
};
dbContext.Motions.Add(motion);
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
user.Id, nameof(Motion), motion.Id, "sealed.opened",
$"Opened sealed-ballot motion {motion.Title} (round {motion.Round}, {candidates.Count} candidates).",
cancellationToken);
return BuildState(motion, now, null, user.Id);
}
public async Task<SealedBallotReceipt> CommitAsync(
CurrentBifrostActor actor,
Guid motionId,
string commitment,
CancellationToken cancellationToken)
{
var user = RequireMember(actor);
var motion = await LoadAsync(motionId, cancellationToken);
var now = timeProvider.GetUtcNow();
if (PhaseOf(motion, now) != SealedPhase.Commit)
{
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The commit window is not open.");
}
commitment = (commitment ?? string.Empty).Trim().ToLowerInvariant();
if (!HexSha256.IsMatch(commitment))
{
throw new SealedBallotException(SealedBallotFailure.Invalid, "A commitment is 64 lowercase hex characters (SHA-256).");
}
var ballot = await dbContext.SealedBallots
.SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
if (ballot is null)
{
ballot = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
dbContext.SealedBallots.Add(ballot);
}
else
{
ballot.Revision++;
}
ballot.Commitment = commitment;
ballot.CommittedAtUtc = now;
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
user.Id, nameof(Motion), motionId, "sealed.committed",
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
cancellationToken);
return new SealedBallotReceipt(motionId, user.Id, commitment, ballot.Revision, now, Revealed: false);
}
public async Task<SealedBallotReceipt> RevealAsync(
CurrentBifrostActor actor,
Guid motionId,
SealedBallotDocument document,
CancellationToken cancellationToken)
{
var user = RequireMember(actor);
var motion = await LoadAsync(motionId, cancellationToken);
var now = timeProvider.GetUtcNow();
if (PhaseOf(motion, now) != SealedPhase.Reveal)
{
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal window is not open.");
}
var ballot = await dbContext.SealedBallots
.SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken)
?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No commitment from this member on this motion.");
var reason = (document.Reason ?? string.Empty).Trim();
var candidate = (document.Candidate ?? string.Empty).Trim();
if (document.Schema != SealedBallotDocument.SchemaId || document.MotionId != motionId || document.Round != motion.Round ||
!CandidatesOf(motion).Contains(candidate, StringComparer.Ordinal) ||
reason.Length is 0 or > MaxReasonLength || reason.Contains('\n') || reason.Contains('\r') ||
!HexSalt.IsMatch(document.Salt ?? string.Empty))
{
throw new SealedBallotException(SealedBallotFailure.Invalid, "The ballot document does not fit this motion (schema, motion, round, candidate, one-line reason, 128-bit hex salt).");
}
var recomputed = SealedBallotDocument.Commit(document with { Candidate = candidate, Reason = reason }, user.Id);
if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(recomputed), Encoding.ASCII.GetBytes(ballot.Commitment)))
{
throw new SealedBallotException(SealedBallotFailure.Invalid, "The ballot does not match the stored commitment.");
}
ballot.RevealedCandidate = candidate;
ballot.RevealedReason = reason;
ballot.Salt = document.Salt;
ballot.RevealedAtUtc = now;
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
user.Id, nameof(Motion), motionId, "sealed.revealed",
$"{actor.DisplayName} submitted a reveal for commitment {ballot.Commitment}; content stays sealed until close.",
cancellationToken);
return new SealedBallotReceipt(motionId, user.Id, ballot.Commitment, ballot.Revision, ballot.CommittedAtUtc, Revealed: true);
}
/// <summary>Phase, times and the caller's own commitment status. Never another member's ballot, never revealed content.</summary>
public async Task<SealedMotionState> GetStateAsync(
CurrentBifrostActor actor,
Guid motionId,
CancellationToken cancellationToken)
{
var user = RequireMember(actor);
var motion = await LoadAsync(motionId, cancellationToken);
var now = timeProvider.GetUtcNow();
var own = await dbContext.SealedBallots
.AsNoTracking()
.Where(x => x.MotionId == motionId && x.UserAccountId == user.Id)
.Select(x => new SealedBallotReceipt(x.MotionId, x.UserAccountId, x.Commitment, x.Revision, x.CommittedAtUtc, x.RevealedAtUtc != null))
.SingleOrDefaultAsync(cancellationToken);
return BuildState(motion, now, own, user.Id);
}
/// <summary>Finalizes the motion if its deadline has passed, then publishes every ballot at once. Before close it refuses.</summary>
public async Task<SealedMotionResult> GetResultAsync(
CurrentBifrostActor actor,
Guid motionId,
CancellationToken cancellationToken)
{
RequireMember(actor);
var motion = await LoadAsync(motionId, cancellationToken);
var now = timeProvider.GetUtcNow();
if (PhaseOf(motion, now) != SealedPhase.Closed)
{
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "Ballots stay sealed until the motion closes.");
}
var ballots = await dbContext.SealedBallots
.Include(x => x.UserAccount).ThenInclude(x => x.MemberProfile)
.Where(x => x.MotionId == motionId)
.ToListAsync(cancellationToken);
if (motion.Status == MotionStatus.Open)
{
await FinalizeAsync(motion, ballots, now, cancellationToken);
}
var revealed = ballots.Where(x => x.RevealedAtUtc != null).OrderBy(x => x.Id).ToList();
var tally = CandidatesOf(motion)
.Select(c => new SealedTally(c, revealed.Count(x => x.RevealedCandidate == c)))
.ToList();
var top = tally.Max(x => x.Votes);
var leaders = top == 0 ? [] : tally.Where(x => x.Votes == top).Select(x => x.Candidate).ToList();
var voterIds = ballots.Select(x => x.UserAccountId).ToHashSet();
var nonVoters = await dbContext.Memberships
.AsNoTracking()
.Where(x => x.Status == MembershipStatus.Active && !voterIds.Contains(x.UserAccountId))
.Select(x => x.UserAccount.MemberProfile != null ? x.UserAccount.MemberProfile.Nickname : x.UserAccount.DisplayName)
.ToListAsync(cancellationToken);
return new SealedMotionResult(
motion.Id,
motion.Title,
motion.Round,
motion.PriorMotionId,
SealedBallotDocument.SchemaId,
tally,
leaders,
leaders.Count > 1 ? "tie" : leaders.Count == 1 ? "winner" : "no ballots",
revealed.Select(x => new RevealedBallot(
NameOf(x.UserAccount), x.UserAccountId, x.RevealedCandidate!, x.RevealedReason!, x.Salt!, x.Commitment)).ToList(),
ballots.Where(x => x.RevealedAtUtc == null)
.Select(x => new AbstainedMember(NameOf(x.UserAccount), "committed but did not reveal", x.Commitment)).ToList(),
nonVoters.Select(n => new AbstainedMember(n, "no commitment", null)).ToList(),
motion.ResultDigest);
}
public static SealedPhase PhaseOf(Motion motion, DateTimeOffset now) =>
motion.Status != MotionStatus.Open || now >= motion.ClosesAtUtc ? SealedPhase.Closed
: now >= motion.CommitClosesAtUtc ? SealedPhase.Reveal
: SealedPhase.Commit;
private async Task FinalizeAsync(Motion motion, List<SealedBallot> ballots, DateTimeOffset now, CancellationToken cancellationToken)
{
var lines = ballots.OrderBy(x => x.UserAccountId)
.Select(x => $"{x.UserAccountId:D}:{x.Commitment}:{(x.RevealedAtUtc != null ? "revealed" : "unrevealed")}");
motion.ResultDigest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines)))).ToLowerInvariant();
motion.Status = MotionStatus.Closed;
motion.ResolvedAtUtc = now;
motion.ResolutionNote = $"Sealed ballots published: {ballots.Count(x => x.RevealedAtUtc != null)} revealed, {ballots.Count(x => x.RevealedAtUtc == null)} committed but unrevealed.";
await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
null, nameof(Motion), motion.Id, "sealed.closed",
$"Closed sealed-ballot motion {motion.Title}; commitment digest {motion.ResultDigest}.",
cancellationToken);
}
private SealedMotionState BuildState(Motion motion, DateTimeOffset now, SealedBallotReceipt? own, Guid voterId)
{
var phase = PhaseOf(motion, now);
var announcement = phase switch
{
SealedPhase.Commit => $"Sealed ballot open: {motion.Title}. Commit by {motion.CommitClosesAtUtc:u}; reveal until {motion.ClosesAtUtc:u}.",
SealedPhase.Reveal => $"Sealed ballot in reveal: {motion.Title}. Reveal by {motion.ClosesAtUtc:u}.",
_ => $"Sealed ballot closed: {motion.Title}."
};
return new SealedMotionState(
motion.Id, motion.Title, motion.Summary, motion.Round, motion.PriorMotionId, SealedBallotDocument.SchemaId,
phase.ToString(), CandidatesOf(motion), motion.CommitClosesAtUtc!.Value, motion.ClosesAtUtc, voterId, own, announcement);
}
private async Task<Motion> LoadAsync(Guid motionId, CancellationToken cancellationToken) =>
await dbContext.Motions.SingleOrDefaultAsync(x => x.Id == motionId && x.Kind == MotionKind.SealedBallot, cancellationToken)
?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No such sealed-ballot motion.");
private static IReadOnlyList<string> CandidatesOf(Motion motion) => motion.Candidates.Split('\n');
private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName;
private static UserAccount RequireMember(CurrentBifrostActor actor) =>
actor is { IsActiveMember: true, UserAccount: { } user }
? user
: throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
}
public enum SealedPhase { Commit, Reveal, Closed }
public enum SealedBallotFailure { Forbidden, NotFound, WrongPhase, Invalid }
public sealed class SealedBallotException(SealedBallotFailure failure, string message) : Exception(message)
{
public SealedBallotFailure Failure { get; } = failure;
}
/// <summary>
/// The typed ballot document, schema <c>gamecult.sealed_ballot.v0</c>. A Delphi second round is another motion carrying this
/// same type with a higher Round. The commitment binds the voter's account id, so a commitment cannot be replayed by another member.
/// </summary>
public sealed record SealedBallotDocument(string Schema, Guid MotionId, int Round, string Candidate, string Reason, string Salt)
{
public const string SchemaId = "gamecult.sealed_ballot.v0";
public static string Commit(SealedBallotDocument d, Guid voterUserAccountId) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
$"{SchemaId}\n{d.MotionId:D}\n{voterUserAccountId:D}\n{d.Round}\n{d.Candidate}\n{d.Reason}\n{d.Salt}"))).ToLowerInvariant();
}
public sealed record OpenSealedMotionCommand(
string Title,
string Summary,
IReadOnlyList<string> Candidates,
DateTimeOffset CommitClosesAtUtc,
DateTimeOffset ClosesAtUtc,
int Round = 1,
Guid? PriorMotionId = null);
public sealed record SealedBallotReceipt(Guid MotionId, Guid VoterUserAccountId, string Commitment, int Revision, DateTimeOffset CommittedAtUtc, bool Revealed);
public sealed record SealedMotionState(
Guid Id, string Title, string Summary, int Round, Guid? PriorMotionId, string BallotSchema, string Phase,
IReadOnlyList<string> Candidates, DateTimeOffset CommitClosesAtUtc, DateTimeOffset ClosesAtUtc,
Guid YourVoterId, SealedBallotReceipt? YourCommitment, string Announcement);
public sealed record SealedTally(string Candidate, int Votes);
public sealed record RevealedBallot(string Voter, Guid VoterUserAccountId, string Candidate, string Reason, string Salt, string Commitment);
public sealed record AbstainedMember(string Member, string Why, string? Commitment);
public sealed record SealedMotionResult(
Guid Id, string Title, int Round, Guid? PriorMotionId, string BallotSchema,
IReadOnlyList<SealedTally> Tally, IReadOnlyList<string> Leaders, string Outcome,
IReadOnlyList<RevealedBallot> Ballots, IReadOnlyList<AbstainedMember> Unrevealed, IReadOnlyList<AbstainedMember> NonVoters,
string CommitmentDigest);
public sealed record SealedCommitRequest(string Commitment);

View file

@ -29,6 +29,7 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
var openMotions = await dbContext.Motions
.AsNoTracking()
.Include(x => x.Votes)
.Where(x => x.Kind == MotionKind.Standard)
.OrderBy(x => x.ClosesAtUtc)
.Take(5)
.Select(x => new DashboardMotion(

View file

@ -121,6 +121,7 @@ builder.Services.AddScoped<MembershipSynchronizationService>();
builder.Services.AddScoped<BifrostIdentityService>();
builder.Services.AddScoped<GitHubWebhookService>();
builder.Services.AddScoped<MotionGovernanceService>();
builder.Services.AddScoped<SealedBallotService>();
builder.Services.AddScoped<MotionEveSurfaceService>();
builder.Services.AddScoped<PatronageService>();
builder.Services.AddScoped<StripeWebhookService>();
@ -541,6 +542,42 @@ eveGovernance.MapGet("/surface", async (
"application/json");
});
// Sealed-ballot intake. Typed JSON documents posted directly by the voter; no ballot content ever rides in a room message,
// and no response before close carries another member's ballot.
var sealedMotions = app.MapGroup("/api/sealed-motions")
.RequireAuthorization(ActiveMemberRequirement.PolicyName);
static async Task<IResult> SealedCall(Func<Task<object>> call)
{
try
{
return Results.Ok(await call());
}
catch (SealedBallotException error)
{
return Results.Json(
new { error = error.Message },
statusCode: error.Failure switch
{
SealedBallotFailure.Forbidden => StatusCodes.Status403Forbidden,
SealedBallotFailure.NotFound => StatusCodes.Status404NotFound,
SealedBallotFailure.WrongPhase => StatusCodes.Status409Conflict,
_ => StatusCodes.Status400BadRequest
});
}
}
sealedMotions.MapPost("", (ICurrentBifrostActorAccessor actors, SealedBallotService service, OpenSealedMotionCommand command, CancellationToken ct) =>
SealedCall(async () => await service.OpenAsync(await actors.GetAsync(ct), command, ct)));
sealedMotions.MapGet("/{id:guid}", (ICurrentBifrostActorAccessor actors, SealedBallotService service, Guid id, CancellationToken ct) =>
SealedCall(async () => await service.GetStateAsync(await actors.GetAsync(ct), id, ct)));
sealedMotions.MapPost("/{id:guid}/commit", (ICurrentBifrostActorAccessor actors, SealedBallotService service, Guid id, SealedCommitRequest body, CancellationToken ct) =>
SealedCall(async () => await service.CommitAsync(await actors.GetAsync(ct), id, body.Commitment, ct)));
sealedMotions.MapPost("/{id:guid}/reveal", (ICurrentBifrostActorAccessor actors, SealedBallotService service, Guid id, SealedBallotDocument body, CancellationToken ct) =>
SealedCall(async () => await service.RevealAsync(await actors.GetAsync(ct), id, body, ct)));
sealedMotions.MapGet("/{id:guid}/result", (ICurrentBifrostActorAccessor actors, SealedBallotService service, Guid id, CancellationToken ct) =>
SealedCall(async () => await service.GetResultAsync(await actors.GetAsync(ct), id, ct)));
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
{
httpContext.Response.Headers.CacheControl = "no-store";