diff --git a/.github/workflows/publish-container.yml b/.github/workflows/publish-container.yml
deleted file mode 100644
index 56a9a18..0000000
--- a/.github/workflows/publish-container.yml
+++ /dev/null
@@ -1,55 +0,0 @@
-name: Publish Container
-
-on:
- push:
- branches:
- - main
- tags:
- - "v*"
- workflow_dispatch:
-
-env:
- REGISTRY: ghcr.io
- IMAGE_NAME: gamecult/bifrost
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
-
-jobs:
- publish:
- name: Build and publish Bifrost image
- runs-on: ubuntu-latest
- permissions:
- contents: read
- packages: write
-
- steps:
- - name: Check out repository
- uses: actions/checkout@v6
-
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v3
-
- - name: Log in to GHCR
- uses: docker/login-action@v3
- with:
- registry: ${{ env.REGISTRY }}
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
-
- - name: Extract image metadata
- id: meta
- uses: docker/metadata-action@v5
- with:
- images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- tags: |
- type=sha,prefix=sha-
- type=ref,event=branch
- type=ref,event=tag
-
- - name: Build and push image
- uses: docker/build-push-action@v6
- with:
- context: .
- file: Dockerfile
- push: true
- tags: ${{ steps.meta.outputs.tags }}
- labels: ${{ steps.meta.outputs.labels }}
diff --git a/AGENTS.md b/AGENTS.md
index c06e133..e822cf2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -30,7 +30,7 @@
## Locked Technical Defaults
- stack: ASP.NET Core 8 LTS
-- UI: Razor Pages + HTMX
+- UI: Razor Pages
- database: PostgreSQL
- hosting target: `bifrost.gamecult.org` on Yggdrasil
- deployment pattern: nginx + systemd + localhost-only Postgres, matching `E:\Projects\gamecult-ops`
@@ -80,3 +80,15 @@ Then start the first implementation milestone:
- work items
- motions
- ledgers
+
+## Live Postgres tests
+
+Most tests run on the in-memory EF provider, which enforces no unique index, transaction, concurrency token or trigger. The tests that need a real server (`tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs`: commit atomicity, the `(MergeId, Seq)` unique index, the sweeper racing the saga, overlapping merges refused by the database, the one-current-Patron-snapshot index under racing restages, the intake journal `Seq`, the write gate's shared lock racing a merge's freeze and commit, the migration's roll-forward-only guard) run only when `BIFROST_TEST_PG` holds a connection string with no `Database=`, for a role that may create databases; otherwise they are skipped with that reason. Each test creates its own database, builds it through the real migrations and the class drops it, so point the variable at a disposable server:
+
+```bash
+BIFROST_TEST_PG='Host=127.0.0.1;Port=54329;Username=postgres' dotnet test tests/Bifrost.Web.Tests --filter FullyQualifiedName~AccountMergePostgresTests
+```
+
+## Account merges are roll-forward only
+
+Once any `AccountMerges` row exists, do not deploy a build older than the `AddAccountMerges` migration, and do not revert that migration: an older build cannot read the `Merged` membership status and counts voided votes again. `Down` refuses while any merge row exists. Fix forward (`heimdall-body:ruling:merge-roll-forward-only`, `docs/account-merge.md` Rollback). Any deploy list that names a rollback must say so.
diff --git a/README.md b/README.md
index e0f9f0f..ba62504 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@ This repository now includes a viable alpha foundation slice of the ASP.NET Core
- Razor Pages app under `src/Bifrost.Web`
- PostgreSQL-backed EF Core model with an initial migration under `src/Bifrost.Web/Data/Migrations`
- Bifrost-native identity registration plus GitHub OAuth and Heimdall-linked provider identities, with invite/approval-based membership gating
+- a Linked accounts page where a member sees, links and unlinks their Heimdall provider logins, with unlink gated on a strong proof: a WebAuthn passkey (enrolled behind a fresh sign-in, 48 hour cooling-off), or a fresh Google step-up for an account with none ([docs/linked-accounts.md](docs/linked-accounts.md), [docs/passkeys.md](docs/passkeys.md))
- explicit member roles and admin-managed patron or contributor tier snapshots
- patron support event recording with derived patron point summaries and tier refresh for voting weight
- shared work board with estimates, actual time logs, review flow, and GitHub issue or PR links
@@ -36,7 +37,7 @@ It is closer to deployable now, but it is still not a finished internet-facing m
## Chosen Stack
- ASP.NET Core 8 LTS
-- Razor Pages + HTMX
+- Razor Pages
- PostgreSQL
- Bifrost-native identity registration
- GitHub OAuth for linked sign-in and repository integration
@@ -56,7 +57,7 @@ It is closer to deployable now, but it is still not a finished internet-facing m
- public app hostname: `bifrost.gamecult.org`
- infrastructure context: `Yggdrasil`
-- deployment model: GHCR image + Docker Compose behind nginx, with the older systemd path kept as rollback until the container path is boring
+- deployment model: a release directory under `/srv/bifrost/app/releases`, switched by Idunn with a rollback point; no container images are published or pulled
## Next Build Target
@@ -73,7 +74,7 @@ For the full staged roadmap, including contribution points, revenue share, patro
## Local Dev Notes
- set `GitHubOAuth:ClientId` and `GitHubOAuth:ClientSecret` before using sign-in
-- POST `/auth/bifrost/register` with `identity`, optional `displayName`, and optional `returnUrl` to create a Bifrost-native account without OAuth; this signs in as `Authenticated` but does not grant active member access
+- POST `/auth/bifrost/register` with `identity`, optional `displayName`, optional `returnUrl`, a solved proof-of-work `challenge` and `nonce` (from `GET /auth/bifrost/challenge`), and `acceptedNoticeVersion` (the `version` from `GET /auth/bifrost/notice`) to create a Bifrost-native account without OAuth; this signs in as `Authenticated` but does not grant active member access
- set `Bootstrap:AdminGitHubLogins` with at least one GitHub login for the first active admin path
- HTTP bridge ledger configuration (`BIFROST_BRIDGE_BASE_URL` / `BIFROST_BRIDGE_TOKEN`) is removed from live CLI transport. Request-lane, governance, dispatch, and bridge receipts converge on Bifrost-owned `bifrost.crossing_receipt.v1` documents in `.bifrost/bridge-receipts.cc`.
- external bridge actions must carry typed CultMesh command provenance such as `BIFROST_CULTMESH_COMMAND_ID`; unreceipted and HTTP-ledger hatches fail closed.
@@ -89,7 +90,7 @@ For the full staged roadmap, including contribution points, revenue share, patro
- set `Heimdall:PatronSupportIntakeSecret` before enabling Heimdall patron support intake in production
- default connection string points at local PostgreSQL
- build with `dotnet build Bifrost.slnx`
-- test with `DOTNET_ROLL_FORWARD=Major dotnet test Bifrost.slnx` if the machine only has the .NET 10 runtime installed
+- test with `dotnet test Bifrost.slnx`; the suite needs a real .NET 8 runtime (`DOTNET_ROOT`, with a runsettings `DotNetHostPath` if the SDK is newer; .NET 10 roll-forward makes Mvc.Testing 8.0.0 return 500 on every JSON response) and a built CultLib TypeScript runtime (`dist/` and `node_modules`) at `$VOIDBOT_CULTLIB_ROOT`
- dry-run a Reddit organizing thread with `node tools/bifrost-bridge.mjs reddit-post --title "Thread title" --persona-name Bifrost --content "Thread body" --dry-run true`
- print the Eve provider advertisement with `node tools/provider-advertisement.mjs print`
- export the Eve provider store with `node tools/provider-advertisement.mjs export --out .bifrost/provider-store.cc`
diff --git a/compose.local.yaml b/compose.local.yaml
index dbd3d85..1afb56a 100644
--- a/compose.local.yaml
+++ b/compose.local.yaml
@@ -22,7 +22,7 @@ services:
build:
context: .
dockerfile: Dockerfile
- image: ghcr.io/gamecult/bifrost:local
+ image: bifrost-web:local
container_name: bifrost-web
depends_on:
postgres:
diff --git a/docs/account-merge.md b/docs/account-merge.md
new file mode 100644
index 0000000..67e224b
--- /dev/null
+++ b/docs/account-merge.md
@@ -0,0 +1,136 @@
+# Account merge ledger
+
+What a merge of two Bifrost accounts does to Bifrost records, who owns it, and how an account stands under one. Design: `/opt/commons/handoff/heimdall-account-merge-design-20261113.md` sections 3, 5 and 7. The ledger owns what a merge does to Bifrost records; the saga (below) owns the merge's lifecycle around it and every Heimdall call. The member's pages are in Pages and flags below; with `AccountMerge:Enabled` false (the default) no page can start a merge.
+
+## Owner
+
+`Features/Membership/AccountMergeLedger.cs` is the one owner of merge effects. Outside it nothing writes `VoidedByMergeId`, `MembershipStatus.Merged`, `AccountMergeEntry`, or the states Committed, Final and Undone, and nothing but the ledger calls `IgnoreQueryFilters` on `Vote` or `ConceptAppraisal`. The ledger never reads an email, display name or login string; accounts are matched by id.
+
+## States
+
+`AccountMerge.State` (stored as a string) declares the whole lifecycle once: `Proposed`, `Confirmed`, `HeimdallMoved`, `Committed`, `Final`, `UndoRequested`, `HeimdallReversed`, `Undone`, `Failed`. Later cuts add columns, not states.
+
+An account's standing is derived from that state on every request; there is no `MergedInto` column and `Membership.Status = Merged` is never read to decide it.
+
+| State of the merge the account is folded in | `StandingAsync` |
+| --- | --- |
+| Confirmed, HeimdallMoved | `Frozen(mergeId)` |
+| Committed, Final, UndoRequested, HeimdallReversed | `Folded(mergeId, survivorId)` |
+| Proposed, Failed, Undone | none |
+
+An alias is one hop: a landed merge's survivor never folds into a third account (the `folded_is_survivor` block), so a folded account's survivor is always the account that carries the person. Every patron event is recorded through `PatronageService.RecordSupportEventAsync`, which writes through the gate below: an event for a folded account (Heimdall intake, Stripe webhook, the admin Ledger's manual record) records on the survivor and is journalled in the same save, so an undo moves it back; a provider retry returns the stored event and journals it once if it sits on the survivor.
+
+`CurrentBifrostActorAccessor` is the one gate for every cookie-authenticated route: a Frozen or Folded account resolves to an authenticated actor with no account (`CurrentBifrostActor.Merge` set), so no route can act as it. The OIDC authorize endpoint denies it with `MergedDescription`, and `ChatRefusalAsync` refuses its token and userinfo, so the logout reconciler ends its chat sessions. The accessor looks an account up by identity, then Heimdall id, then GitHub id; the first hit wins and several matching rows can no longer throw. The same standing is read at the other doors: the desk bearer door (`ActiveMemberIdAsync`) refuses a Frozen or Folded subject, the linked-accounts page and the link step of Heimdall completion refuse one (no login linked or unlinked, no passkey enrolled while the saga moves them), and every writer reads it again at the write, through the gate below, so an actor resolved before the merge froze the account writes nothing after it.
+
+## Plan, commit, undo, finalize
+
+`PlanAsync(survivorId, foldedId)` writes nothing and returns the blocks (codes only), the journal entries a commit would write, and counts of rows left untouched. Blocks: `same_account`, `account_missing`, `mind_account`, `native_account` (either side has no Heimdall id: v1 merges Heimdall-backed accounts only), `merge_in_flight`, `survivor_is_folded`, `already_folded`, `folded_is_survivor`, `sealed_ballot_pending`. The database backs the two overlap blocks the plan checks first (check-then-act): a partial unique index lets an account be folded by one live merge only (Confirmed through HeimdallReversed), and a trigger refuses a live merge whose survivor is another live merge's folded account, taking advisory locks on both accounts so racing transactions serialise.
+
+`CommitAsync(mergeId)` needs `HeimdallMoved` (Committed and Final return the receipt; any other state throws). It is total: blocks were checked before the move, so it never refuses on them. It applies everything in one `SaveChanges` together with `State = Committed` and `GraceEndsUtc = CommittedUtc + 7 days`; a failed save leaves the merge `HeimdallMoved` and applies nothing, and a retry applies once.
+
+What it reduces:
+
+- **Suspension wins.** A suspended folded account and a survivor that is not suspended: the survivor becomes Suspended with the reason `merged with a suspended account (merge )`. A survivor without a membership row (the chat tier holds none) is given a Suspended one, journalled as `Standing`/`Created`, because an absent membership chats and the next member-access claim would create an Active one; undo removes it unless an admin has taken it over since.
+- **Membership.** The folded membership becomes `Merged` (weight 0 by the not-Active rule). Roles and admin flags of the folded membership are never copied.
+- **Votes on open standard motions.** Both voted: the folded vote is voided. Only the folded account voted: the vote moves to the survivor if the survivor is Active after the suspension rule, else it is voided. A move keeps the vote's cast time and takes the survivor's weight, derived from the survivor's tiers after the patron events moved (the folded weight is journalled for undo); a later survivor cast updates the moved row (`CastVoteAsync` is per motion and account), never a second row. Closed motions are untouched.
+- **Concept appraisals.** The survivor also appraised the subject: the folded one is voided. Otherwise it moves to `account:` as a Member voter if the survivor is Active, else it is voided (the prior class and key are journalled).
+- **Patron events** of the folded account move to the survivor, and both tiers are derived again once from the events each account now holds (never tier A plus tier B). This happens only when events moved, so a tier that no event backs is not wiped by a merge with no patron history (only `PatronageService` writes Patron snapshots, so a merge with no folded events leaves both tiers as they were).
+
+Voiding stamps `VoidedByMergeId` and `VoidedUtc`; the model's query filter on `Vote` and `ConceptAppraisal` then removes the row from every tally, including future ones. Nothing is deleted.
+
+Left untouched (counted by the plan): consent receipts, passkeys, ledger entries, points, work and revenue rows.
+
+`UndoLocalAsync(mergeId)` needs `HeimdallReversed` (Undone is a no-op). In one save it replays the journal backward: it un-voids votes whose motion is still Open and appraisals, moves a moved vote or appraisal back only if the survivor did not re-cast it since, restores the folded status, restores the survivor's status only while it is still Suspended with this merge's reason, moves patron events back and derives both tiers again. What it keeps it records as `KeptAfterUndo`; nothing is updated or deleted in the journal, only appended to.
+
+`FinalizeDueAsync(now)` moves Committed merges whose grace has ended to `Final`, one save per merge; `AccountMergeSweeper` runs it every 30 seconds, after the saga's due steps (see Saga). `State` is the merge's concurrency token, so a transition computed from a stale read (the sweeper's Final over the saga's UndoRequested, or the reverse) fails its save and the other transition stands; the sweep skips a merge it lost. `UndoLocalAsync` also refuses a merge with `FinalizedUtc` set: undo is never allowed past Final.
+
+## Saga
+
+`Features/Membership/AccountMergeSaga.cs` is the one owner of the merge row's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of `HeimdallIdentityMoveClient.MoveAsync` (whose closed `Moved`/`Refused`/`Unknown` answer it consumes as is; the client retries nothing). It writes Confirmed, HeimdallMoved, Failed, UndoRequested and HeimdallReversed, the return UndoRequested to Committed, the move ids and the sealed proofs; it never writes a vote, membership or journal row (it calls `CommitAsync` and `UndoLocalAsync`), reads no standing of its own, and never judges a proof's tier or freshness (Heimdall's).
+
+| State | Written by | Key and proofs | A crash here |
+| --- | --- | --- | --- |
+| Confirmed | `ConfirmAsync`: one insert, the consent record | `HeimdallMoveId` minted (random, never derived from the merge id); both sides' Heimdall bearers sealed | Before the insert nothing exists. After it the sweep calls Heimdall with the stored id; a lost answer replays to the same receipt, because Heimdall answers a replay before it judges liveness. |
+| HeimdallMoved | `AdvanceAsync` on `Moved`, one save | proofs wiped; receipt tiers and moved login ids stored | `CommitAsync` is total and idempotent; the sweep retries it. |
+| Failed | `AdvanceAsync` on any `Refused` | proofs wiped; `FailureCode` is Heimdall's code | Terminal. Heimdall applied nothing, Bifrost changed nothing, the folded account stands as before. |
+| Committed | ledger `CommitAsync`, one save with every reduction | grace 7 days | A crash before the save leaves HeimdallMoved. |
+| UndoRequested | `RequestUndoAsync`: the survivor, fresh survivor proofs, inside the grace | `HeimdallReverseMoveId` minted; survivor bearers sealed | The sweep replays the reversal (past the grace too). A refused reversal returns the merge to Committed, proofs wiped, `LastOutcome` `undo_`. |
+| HeimdallReversed | `AdvanceAsync` on the reversal's `Moved` | proofs wiped | `UndoLocalAsync` is retried. |
+| Undone, Final | ledger | | |
+
+`AdvanceAsync(mergeId)` is the one step function: the confirm's inline advance, the sweeper's resume and an undo request all run it, forward move and reversal alike (same seal, same outcome handling, same backoff). Every transition is one save guarded by `State`, the concurrency token; the loser of a race clears its tracker, reloads and continues from the stored state, so two advances make one Heimdall move and one commit. `Proposed` is declared by the ledger and written by nobody in this cut.
+
+`ConfirmAsync` refuses (writing nothing) a third-party actor (`NotParty`), a plan with blocks (`Blocked`, codes only), a plan other than the one the member saw (`PreviewStale`: `MergePlan.Digest(survivorId, foldedId)`, a SHA-256 over a length-prefixed canonical text of the plan), and any proof of another Heimdall account (`ProofAccountMismatch`). A second live merge folding the same account, or a chain, is refused by the database (the live-merge unique index and the chain trigger) and answered `Blocked(merge_in_flight)`. Confirm and the undo request run through `AccountMergeLedger.WriteAsAsync` for the acting member, like every writer that acts for an account.
+
+**Heimdall down.** `Unknown` (a timeout, a 5xx, a 429, an unrecognised 4xx, `move_id_conflict`) never fails a merge: the saga counts `Attempts`, sets `NextAttemptUtc` (15 s, 1 min, 5 min, then 15 min) and replays the same stored id; the folded account stays Frozen until Heimdall answers. Heimdall's answer to a replay of a move it already stored does not depend on the proofs' age, but a move that never reached Heimdall does: an outage longer than the proofs' freshness (300 s for a login's weak proof, 600 s for a passkey's strong one) ends, when Heimdall is back, in `Refused proof_stale` and a Failed merge; the member confirms again with fresh sign-ins. A replay whose proofs no longer verify (Heimdall's key regenerated) answers `move_id_conflict` and stays Unknown; a receipt that names an account other than the destination is `receipt_mismatch` (proofs wiped, no retry); a sealed payload the key ring can no longer open is `proofs_unreadable` (retried in an hour, state unchanged, because Heimdall may already have moved). None of the three ends by itself: see Stuck merges.
+
+**Sealed proofs.** The saga holds the two Heimdall bearers (`ruling merge-sealed-proofs-until-move-final`) only between Confirmed (or UndoRequested) and Heimdall's final answer: protected with Data Protection (purpose `Bifrost.AccountMerge.Proofs.v1`), never logged, wiped in the save that records Moved or Refused. Logs name the merge id, state, outcome class and refusal code; never a token, account id, identity id or provider user id. Proof coverage is Heimdall's rule (`move-proof-strict-passkey`): a proof through one login moves only that login, and only an asserted passkey speaks for the whole account, so a folded account's every login must be proved (or a passkey asserted) or Heimdall answers `identity_not_proved`. A `moveId` replayed with other identities returns the first receipt (`move-replay-first-receipt`).
+
+`AccountMergeSweeper` is the one merge loop (30 s): per tick, in one scope, `MergeProofs.PruneExpired` (a proof bearer lives only in process memory and is dropped 270 s after its proof, on access and by this tick, so none outlives that plus one tick whether or not anyone opens the page; `heimdall-body:ruling:merge-proof-bearers-memory-bound`), then `AccountMergeSaga.AdvanceDueAsync` (every in-flight merge whose `NextAttemptUtc` is null or due, oldest first, a failure logged and skipped), then `FinalizeDueAsync`.
+
+## Stuck merges
+
+`/App/Merges` (platform admins only; the `/App` folder's ActiveMember policy, then `IsPlatformAdmin`) lists in-flight merges (Confirmed or UndoRequested) that stopped on `receipt_mismatch`, `proofs_unreadable` or `move_id_conflict`, or were retried eight times, with the merge id, state, last outcome, attempts and the stored move id of the leg in flight. It shows no Heimdall account id, login or account name, and calls no Heimdall. Only the first three outcomes can be ended (`AccountMergeSaga.SettleableOutcomes`); a merge listed for its attempts alone is still being retried.
+
+Two actions (`heimdall-body:ruling:merge-stuck-end-only-typed-id`), both `AccountMergeSaga.SettleStuckAsync`, both needing the leg's stored move id typed back (the forward id for a Confirmed merge, the reverse id for an UndoRequested one) and both writing one `merge.settled` audit row that names the merge and the choice only:
+
+| Action | Applies to | Result |
+| --- | --- | --- |
+| Fail the merge (`FailForward`) | Confirmed, stuck | `Failed`, `FailureCode` and `LastOutcome` `operator_failed`, proofs wiped. The folded account is free again; the pair can be confirmed anew. |
+| Give up the undo (`AbandonUndo`) | UndoRequested, stuck | back to `Committed`, `LastOutcome` `undo_operator_abandoned`, proofs wiped, the grace as it was. The merge stands; the logins stay with the survivor. |
+
+HeimdallMoved and Committed are never settleable: Heimdall answered Moved with a matching receipt there, and the saga rolls forward. A settle and the sweeper's `AdvanceAsync` meet at the `State` concurrency token; the loser changes nothing and the other transition stands (answered `lost`). A settle does not fence a replay already in flight to Heimdall, so read `identity_moves` first and read it again after.
+
+Before ending a merge, read Heimdall's `identity_moves` row by the stored move id. If Heimdall did move the logins, failing the merge leaves them moved with no Bifrost merge to match: repair or reverse at Heimdall first. For `receipt_mismatch`, repair Heimdall's or Bifrost's account link before failing. Adopting a move Heimdall made (writing HeimdallMoved from a receipt) stays manual SQL until follow-up `merge-operator-adopt-moved`; the page never does it.
+
+## Pages and flags
+
+`Pages/Membership/MergeAccounts` is the one page that creates a merge. It is `[Authorize]`, no-store, a 404 unless `AccountMergeOptions.Enabled` (section `AccountMerge`, default false; environment `AccountMerge__Enabled`) and forbidden to a frozen or folded account, as Linked accounts is. Linked accounts shows one "Merge two accounts" link, only when the flag is on and the session is Heimdall-backed.
+
+Its stage is derived on every request from `MergeProofs.Snapshot` and the `keep` query; no cookie or form field carries progress except the chosen direction and the preview digest, which the saga re-checks.
+
+1. Prove: the member names a provider for this account (`MergeProveSelf`) and for the other (`MergeProveOther`). Nothing about the other account is rendered until both proofs are held.
+2. Choose: both accounts are named by display name only, and `keep=self` or `keep=other` shows the preview. No survivor is preselected (the chat-history default needs `ChatFirstSignInUtc`, follow-up `merge-chat-default-survivor`; the chat paragraph carries the warning meanwhile).
+3. Prove the rest: one fresh sign-in for each login of the account that would be folded and is not yet proved (`ProveRemaining`). Proofs older than `MergeProofs.ProofLifetime` fall out and are asked again.
+4. Confirm: two checkboxes, one per account, the direction and the digest. `AccountMergeSaga.ConfirmAsync` inserts the Confirmed row, which is the consent record (actor, time, digest, proof providers); the page then runs `AdvanceAsync` once (a throw is logged and the sweeper resumes) and sends the member to Merge status. `MergeProofs.Clear` runs after a Confirmed outcome only: Blocked, PreviewStale, NotParty and ProofAccountMismatch come back as closed codes (`?merge=`), keep the proofs and write nothing.
+
+`MergePreview` is the one wording of the plan (counts by entry kind and action, the nine block codes, the static statements about chat, connections, StreamPixels, roles, one vote per motion, the 7-day undo and ordinary sign-ins); the digest is `MergePlan.Digest` of the plan just rendered. `MergeWording.Confirm` holds the refusal words. The page writes no merge, vote, membership or journal row.
+
+Deploy: set `AccountMerge__Enabled` only after Heimdall's identity-moves route is deployed and probed. A Confirmed merge against a Heimdall without it stays Unknown and keeps the folded account frozen.
+
+## Notices
+
+The chat host learns of merges by pulling, never by being pushed to: Bifrost has no event receiver and no outbox. `MergeNoticeFeed` derives the notices from the `AccountMerges` row on every read (merged: `CommittedUtc` set; undone: `UndoneUtc` set; final: `FinalizedUtc` set), so a notice cannot disagree with its merge, and a Failed, Frozen or Confirmed merge (no `CommittedUtc`) yields none. The only stored fact is the reader's ack, one `AccountMergeNoticeAcks` row per (merge, kind, target), written by nothing else (migration `AddAccountMergeNoticeAcks`; the table holds only acks, so its `Down` drops it). The feed never writes a merge column.
+
+```
+GET /api/merge-notices/chat?after=&limit= -> 200 JSON array, oldest first by (occurred_at, merge_id, kind)
+POST /api/merge-notices/chat/ack {"merge_id": "...", "type": "merged"} -> 204
+```
+
+Payload, exactly these keys: `type` (`merged`, `undone`, `final`), `merge_id`, `occurred_at` (the matching timestamp, ISO 8601 UTC), `grace_ends_at`, `old_subject` (the folded `UserAccount.Id`, format D, the OIDC `sub` the chat session knew), `new_subject` (the survivor's), `old_preferred_username`, `new_preferred_username` (`NormalizedBifrostIdentity`). `limit` defaults to 50 and is capped at 200. Acks are the cursor: a read returns every unacked notice; `after` only narrows the scan to notices strictly later than that time, so a reader must not skip unacked ones by it. An ack is idempotent (a repeat is 204); an ack for a (merge, kind) the feed would not emit now, such as `undone` for a merge not undone, is 404; a malformed body or unknown `type` is 400.
+
+Auth: `Authorization: Bearer `, compared in constant time after SHA-256 of both sides against `ChatNotices:Token` (environment `ChatNotices__Token`). An empty token turns both routes off (404). A missing or wrong bearer is 401 with an empty body. No cookie, no CORS, `Cache-Control: no-store`. Startup does not require the token.
+
+```
+curl -sS -H "Authorization: Bearer $TOKEN" "$BIFROST/api/merge-notices/chat?limit=50"
+curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
+ -d '{"merge_id":"","type":"merged"}' "$BIFROST/api/merge-notices/chat/ack"
+```
+
+The feed carries no email, display name, Heimdall id, Matrix id or history flag. It is information for the chat operator's side; back-channel logout (`OidcLogoutReconciler`) stays what ends chat sessions. Chat-side rules that bind Bifrost already hold: undo is refused past Final, and `preferred_username` never changes. A later reader (StreamPixels) adds a target constant and its own token over the same derivation.
+
+Deploy: set `ChatNotices__Token` on Bifrost and hand the same value to the chat host's timer script (the secret's path is the chat steward's).
+
+## Merged is terminal
+
+Only the ledger writes `Membership.Status = Merged` or leaves it. The other status writers refuse a merged row (`Membership.IsMerged`): the bootstrap-admin promotion (startup and every GitHub sign-in, which is the one status write sign-in sync makes on an existing account) skips it, the Heimdall member-access claim does not activate it, member approval refuses it and the suspension service reports `NotApplicable`. Folded standing itself is still derived from the merge state, never from this status.
+
+## Rollback
+
+Bifrost is **roll-forward only** once a merge exists (`heimdall-body:ruling:merge-roll-forward-only`). A build older than `AddAccountMerges` cannot read the `Merged` membership status (EF throws on `/App/Members` and on the folded account's sign-in) and has no query filter, so it counts voided votes and appraisals again. Deploy the merge migration knowing that a code rollback past it is not available after the first merge lands; fix forward. The migration's `Down` refuses while any `AccountMerges` row exists, whatever state, so it cannot drop the merge record and journal under a `Merged` membership. No tombstone table is built: it would fix only the recount, not the enum.
+
+## Not covered
+
+`MembershipSynchronizationService` still writes the profile of a GitHub-signed-in row that is not merged. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are. Every writer that acts for an account (votes, concept appraisals, sealed-ballot commit and reveal, patron events, the Heimdall sign-in's membership) passes through `AccountMergeLedger.WriteAsAsync`. On Postgres it opens a transaction, takes a shared advisory lock on the account (`pg_advisory_xact_lock_shared(hashtextextended(id::text, 0))`, the key the chain trigger takes exclusively when a merge row is inserted or changes state), reads standing, runs the writer's save and commits. `CommitAsync` takes the exclusive lock on the folded account before it reduces, then re-reads the merge. So: a writer whose standing read found no merge saves before a merge can freeze or fold the account, and the commit's reduction sees what it saved; a merge that is already frozen or folded when the writer reads is refused (votes, appraisals, ballots, sign-in membership) or routed (patron events). Guaranteed only for writes made through the gate, and only on Postgres: the in-memory provider has no lock or transaction (tests that rest on the lock run on live Postgres), and a writer that catches a database error inside the gate cannot continue, because the transaction is aborted. Not closed: writers outside the gate (nothing in the code base today; a new one must use it), and a writer's own stale reads taken before the gate opened (the motion a vote was loaded with), which concern the motion, not the account's standing. No operator void tool exists.
+
+`UX_TierSnapshots_MembershipId_CurrentPatron` allows one current Patron snapshot per membership, so two restages of one survivor racing cannot both leave a current snapshot: the loser's save fails on the unique index, a merge commit rolls back whole and is retried by the saga, and a patron refresh re-reads and derives again.
diff --git a/docs/bifrost-mvp-plan.md b/docs/bifrost-mvp-plan.md
index fa1bd10..29fd545 100644
--- a/docs/bifrost-mvp-plan.md
+++ b/docs/bifrost-mvp-plan.md
@@ -4,7 +4,7 @@
- Create Bifrost as a separate GameCult app repo and deploy it on Yggdrasil.
- Build a member alpha, not a public launch.
-- Use ASP.NET Core 8 with Razor Pages + HTMX and PostgreSQL.
+- Use ASP.NET Core 8 with Razor Pages and PostgreSQL.
- Support invite-only GitHub-linked members, GitHub-backed and internal work items, app-native governance, Reddit organizing threads, and internal ledgers.
- Preserve the Labor Platform loop: user/member/patron demand raises work priority and reward pressure, contributors pick up valuable work, maintainers accept completion artifacts, and Bifrost credits the contributor plus any bounty/reward allocation.
- Do not include Ethereum, wallets, DAO mechanics, or payout execution in v1.
@@ -13,7 +13,7 @@
## System Shape
- One ASP.NET web app process for v1.
-- Server-rendered UI with HTMX for progressive interactions.
+- Server-rendered UI; no client-side framework or third-party script.
- PostgreSQL as the system of record.
- Bifrost-native identity registration for login, with GitHub OAuth available as a linked external identity.
- GitHub App plus webhooks for issue and pull request lifecycle sync.
diff --git a/docs/bridge.md b/docs/bridge.md
index c2bc284..b4cf73c 100644
--- a/docs/bridge.md
+++ b/docs/bridge.md
@@ -23,7 +23,7 @@ That means Bifrost owns the operational meaning of the crossing:
It does not mean Bifrost should own OAuth sludge. Bifrost is both an identity provider and identity consumer: a GameCult actor should be able to register with Bifrost without OAuth, and that Bifrost identity should be enough to authenticate with most GameCult services. Heimdall owns outside-provider OAuth, linked-account token custody, grants, and signed account claims. Bifrost associates those Heimdall-backed accounts with the Bifrost identity, consumes the permission facts, and decides whether a bridge action is allowed in the Bifrost domain.
-The native registration surface is `POST /auth/bifrost/register`. It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody.
+The native registration surface is `POST /auth/bifrost/register`, which takes `identity`, optional `displayName` and `returnUrl`, a solved proof-of-work `challenge` and `nonce` (from `GET /auth/bifrost/challenge`), and `acceptedNoticeVersion` (from `GET /auth/bifrost/notice`). It creates a Bifrost-owned `UserAccount` with `BifrostIdentity` and `NormalizedBifrostIdentity`, signs the caller in with the Bifrost cookie, and leaves membership at `Authenticated`. It does not grant active member access, mint outside-provider tokens, or replace Heimdall's account-link and capability custody.
## Ownership
@@ -196,7 +196,90 @@ The command is a dry-run shape probe for public surfaces that are real enough to
Bifrost's native Discord gateway is the conversation observer. A direct mention of the Bifrost bot, or a reply to one of its messages, becomes an immutable typed `bifrost.discord.persona_conversation_event.v0` only when the guild and channel have one exact Persona target binding. Bot-authored, ambient, empty, over-1200-character, unbound, and ambiguously bound messages do not enter the conversation path. The 1200-character cap is the shared signed alpha boundary with Epiphany. The observation store is Bifrost-private working state, never an actuator queue, and insert collisions must contain exactly equal content. VoidBot does not observe, schedule, or answer for the target Persona.
-Persona speech goes out through Matrix, not Discord. `tools/persona-matrix-mouth.mjs` is the one process for every Persona (`PERSONAS`, a list of slugs): it holds each Persona's Matrix access token as its own systemd credential (`matrix-token-`) and nobody else holds any. Per Persona it keeps one `/sync` loop over the configured rooms and the account's direct rooms (a DM invitation from an account on `MATRIX_SERVER_NAME` is accepted while that Persona's brake is released, and one from any other server is declined), one cursor and one delivery sequence. A delivery carries the sender's Matrix id, the event's `m.mentions` user ids and whether the room is a DM. A media event (`m.image`, `m.file`, `m.audio`, `m.video`) is delivered as a typed text line, `[image filename="cat.png" mime=image/png size=2048 url=mxc://server/id]`, followed by its caption when it has one, in `text` and in context. Only `m.image` is also fetched, and only when `IMAGE_STORE_ROOT` is set (unset, the line above is all there is and nothing is downloaded). The fetch is made as the receiving Persona, with its own token, from `/_matrix/client/v1/media/download//` on its homeserver, for a message the Persona is delivered (not its own words, a room it is not joined to, or history before the ear), and only from the event's own `content.url`; a URL in the message text is never followed. An encrypted attachment (`m.room.encrypted`, or `content.file`) is never fetched. The type is decided by the magic bytes alone (png, jpeg, gif, webp; SVG and anything else is refused, the declared mime is ignored), the body is capped at 5 MiB by `Content-Length` and by the bytes actually read, and the pixel count read from the image header (never decoded) is capped at 40 MP. A refused or failed fetch leaves the typed line with a fixed-word reason (`refused=encrypted|no-url|fetch-failed|too-big|wrong-type|bad-header|too-many-pixels|store-failed`) and no image. A stored image is written to `IMAGE_STORE_ROOT///[.png|.jpg|.gif|.webp]`, the name generated by the mouth, never the sender's: files `0640`, room directories `2750` (the Persona directory is setgid to the Persona's group, so the Persona's reader opens them by group; the mouth is the only writer), each written under a temporary name and renamed. It is deleted once it is at least 24 hours old and its delivery has been acked, whichever is later; a room keeps at most 50 MiB, the oldest evicted first. The sweep runs when an image is stored and when an ack arrives. A delivery is the 12-field tuple of `gamecult.persona.chat_pending.v2`: field 11, after `is_direct`, is nil or `[path, mime, size, sha256]`, a reference and never bytes; `path` is the store-relative `/` above, `mime` the sniffed type, `size` the file length (at most 5 MiB) and `sha256` its lowercase hex digest. The reader re-checks all four against the file. A Persona turn that has no reader for it still sees the typed line. Reading wakes nothing and acks nothing: the heartbeat polls with the non-consuming `gamecult.persona.chat_pending_request.v1`, and only `chat_ack` advances a position. An ack also posts that Persona's public `m.read` receipt, per room, at the newest acked event (fire and forget: the ack never waits on it, a failure is logged once and not retried; the room's next ack covers it); the heartbeat's and a turn's pending calls post none. Her Matrix presence follows her brake: each `/sync` carries `set_presence=online` while it is released and `offline` while it is held, and a round that finds her braked makes one `PUT /presence//status` to offline first (a brake placed mid long-poll shows within `syncTimeoutMs`, 30 s, plus one PUT; a stopped mouth reads offline after Synapse's sync timeout). The mouth speaks on a `gamecult.persona.chat_send_request.v1` and joins rooms only while that Persona's brake (`/etc/gamecult/minds//control.cc`) is released. One loopback CultNet RUDP endpoint serves all of them; a request naming an unlisted Persona gets a typed `chat_refusal` (`UnknownPersona`). Document shapes: `tools/persona-chat-documents.mjs`; golden bytes: `tests/fixtures/persona-chat-v1/`, `-v2/` and `-v3/` (the pending answer; Huginn pins the same bytes). The Discord posting actuator, its permit and its RUDP listener are removed.
+Persona speech goes out through Matrix, not Discord. `tools/persona-matrix-mouth.mjs` is the one process for every Persona (`PERSONAS`, a list of slugs): it holds each Persona's Matrix access token as its own systemd credential (`matrix-token-`) and nobody else holds any. Per Persona it keeps one `/sync` loop over the configured rooms and the account's direct rooms (a DM invitation from an account on `MATRIX_SERVER_NAME` is accepted while that Persona's brake is released, and one from any other server is declined), one cursor and one delivery sequence. v1-v4 delivery ids are Matrix ids: the event id (`$`), the sender, each context line's sender and each mention (`@`) are at most 255 bytes with no whitespace, control, format or private-use characters; the mouth skips an event, drops a context or tail line, or drops a mention that fails this, and the encoder and parser refuse it. A delivery carries the sender's Matrix id, the event's `m.mentions` user ids and whether the room is a DM. A media event (`m.image`, `m.file`, `m.audio`, `m.video`) is delivered as a typed text line, `[image filename="cat.png" mime=image/png size=2048 url=mxc://server/id]`, followed by its caption when it has one, in `text` and in context. Only `m.image` is also fetched, and only when `IMAGE_STORE_ROOT` is set (unset, the line above is all there is and nothing is downloaded). The fetch is made as the receiving Persona, with its own token, from `/_matrix/client/v1/media/download//` on its homeserver, for a message the Persona is delivered (not its own words, a room it is not joined to, or history before the ear), and only from the event's own `content.url`; a URL in the message text is never followed. An encrypted attachment (`m.room.encrypted`, or `content.file`) is never fetched. The type is decided by the magic bytes alone (png, jpeg, gif, webp; SVG and anything else is refused, the declared mime is ignored), the body is capped at 5 MiB by `Content-Length` and by the bytes actually read, and the pixel count read from the image header (never decoded) is capped at 40 MP. A refused or failed fetch leaves the typed line with a fixed-word reason (`refused=encrypted|no-url|fetch-failed|too-big|wrong-type|bad-header|too-many-pixels|store-failed`) and no image. A stored image is written to `IMAGE_STORE_ROOT///[.png|.jpg|.gif|.webp]`, the name generated by the mouth, never the sender's: files `0640`, room directories `2750` (the Persona directory is setgid to the Persona's group, so the Persona's reader opens them by group; the mouth is the only writer), each written under a temporary name and renamed. It is deleted once it is at least 24 hours old and its delivery has been acked, whichever is later; a room keeps at most 50 MiB, the oldest evicted first. The sweep runs when an image is stored and when an ack arrives. A delivery is the 12-field tuple of `gamecult.persona.chat_pending.v2`: field 11, after `is_direct`, is nil or `[path, mime, size, sha256]`, a reference and never bytes; `path` is the store-relative `/` above, `mime` the sniffed type, `size` the file length (at most 5 MiB) and `sha256` its lowercase hex digest. The reader re-checks all four against the file. A Persona turn that has no reader for it still sees the typed line. Reading wakes nothing and acks nothing: the heartbeat polls with the non-consuming `gamecult.persona.chat_pending_request.v1`, and only `chat_ack` advances a position. An ack posts nothing to Matrix. That Persona's public `m.read` receipt follows `gamecult.persona.chat_read.v1` (`[persona, room_alias, event_id, at_unix_ms]`), which Huginn sends when a delivery has gone into the model's input: the mouth posts `m.read` at that event id only, for an event it delivered to that Persona in that room (to the delivered room id, whatever alias the report named), never behind the last receipt that landed there, one report per room at a time, and only while her brake is released (re-read after the presence write; fire and forget on the endpoint: a failure is logged once and not retried; pending polls and acks post none). Her Matrix presence follows a turn and her brake: `online` while a read report, a send or an ack came within `presenceGraceMs` (5 minutes), `unavailable` after that, `offline` while the brake is held. Each `/sync` carries the state as `set_presence`, and a change is also `PUT /presence//status` at once (a brake placed mid long-poll shows within `syncTimeoutMs`, 30 s, plus one PUT; a stopped mouth reads offline after Synapse's sync timeout). The mouth speaks on a `gamecult.persona.chat_send_request.v1` and joins rooms only while that Persona's brake (`/etc/gamecult/minds//control.cc`) is released. One loopback CultNet RUDP endpoint serves all of them; a request naming an unlisted Persona gets a typed `chat_refusal` (`UnknownPersona`). Document shapes: `tools/persona-chat-documents.mjs`; golden bytes: `tests/fixtures/persona-chat-v1/`, `-v2/` and `-v3/` (the pending answer; Huginn pins the same bytes). The Discord posting actuator, its permit and its RUDP listener are removed.
+
+### Addressing facts (`chat_pending.v3`)
+
+The mouth wakes no one; the heartbeat and each Persona session decide who is told a delivery (Huginn `address.rs`, ruling `eureka-body:ruling:addressed-delivery-only`). Telling every Persona every message made 71.5% of 4,351 Persona turns on 2026-11-10 do nothing. The rule stays in one place, Huginn's, because two of its inputs are not Matrix facts: the Persona's stewardship records (her projects' chat names) and the sender's role (operator or Mind). The mouth owns the other half: what Matrix itself says, per Persona, for the delivery. Matrix verifies the sender's identity and nothing else: `tag` and `room` are the sender's claim in `m.mentions` (the homeserver does not check the text against it, nor that the sender may use `@room`), and `reply` is checked against the event it targets, which the mouth reads as her account.
+
+A client asks for the facts by the kind it polls with: `gamecult.persona.chat_pending_request.v2` (the v1 tuple, `[persona, after_seq]`) is answered with `gamecult.persona.chat_pending.v3`; a v1 request still gets the 12-field `chat_pending.v2` answer unchanged. A v3 delivery is the 12 fields of the v2 delivery, then:
+
+| Field | Type | Meaning |
+|---|---|---|
+| 12 `basis` | `"direct"`, `"tag"`, `"reply"`, `"room"`, `"follow"` (only with `CHAT_FOLLOW=1`, see Follow) or nil | Why the message is for this Persona, by what Matrix says, first that holds: `direct` the room is one of her DMs; `tag` `m.mentions.user_ids` lists her id, or the client sent no `m.mentions` at all and an `` in the HTML body is exactly her `matrix.to` link; `reply` it replies to, or is in a thread under, an event her account wrote (her Self run speaks as her account, so its words count; any member's message in a thread under one of her events is a `reply` too, and the target is read once per room and event and kept for a minute, hit or failure); `room` an `@room` mention. A `notice` or an `edit` costs no reply lookup. Known limit: lookups run one at a time inside the `/sync` round (10 s each, at most two per reply), so a slow homeserver slows the round; they are not parallelised or capped per round. |
+| 13 `form` | `"message"`, `"notice"` or `"edit"` | `m.notice` is an automated line; `m.replace` is an edit of an earlier message. Only a `message` can address anyone. |
+
+What the mouth cannot know, and so what a nil `basis` means: **unproven, not "not for her"**. Her handle and public name in the text (any casing, with or without `@`, `'s`), the names her stewardships list, a project's repo name, and whether the sender is the operator or a Mind are all matched by Huginn, not here. A reply whose target the homeserver will not give is nil and logged. The mouth also cannot see whether a message was meant for her without naming her. Every delivery is still delivered, claimed tags included: nothing is dropped in the mouth, so the Huginn rule cannot lose a message the mouth had no way to judge.
+
+Proposed runtime half (follow-up `persona-wakes-on-address-only`):
+
+1. Poll with `chat_pending_request.v2` and parse `chat_pending.v3`.
+2. A delivery is *addressed* to a Persona when `form == "message"` and either `basis` is `direct`, `tag` or `reply`, or `address::addresses` matches her names or her projects' names on the text. The off-beat wake keeps the sender gate of `heartbeat.rs` `wakes` (the operator or another Mind of the roster): a stranger's tag, `@room` or DM is delivered but wakes no one off the beat. `basis == "room"` is the runtime's policy to weigh; the mouth only reports it.
+3. A real-time wake, a live session's tell and the stagger apply to addressed deliveries only. A `notice` or an `edit` never wakes, whatever its basis.
+4. A delivery that is not addressed is acked in sequence with the rest, so the position moves (the mouth stops reading at 500 unacked deliveries); it is not lost: Matrix is the record, and the next addressed delivery's `context` (up to 20 lines) and a beat's own room read show it. The room tail below gives a scheduled beat those lines without a Matrix read of its own; the mouth adds no endpoint for it.
+5. `basis` and `form` are evidence, not authority: a sender's claim is weighed by the runtime's own rule (`address.rs` for names, the sender gate for who may wake her); the mouth reports what the event says and what only Matrix could look up (the author of a reply target).
+
+### Room tail (`chat_pending.v3`, field 2)
+
+The v3 answer is `[persona, deliveries, tail, tail_gaps]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It uses the same room read as a delivery's `context` (the same function, a separate read), as her account, with no new endpoint; the cost is one `/messages` call per speakable room per poll (15 seconds cached), including every DM. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`. `chat_pending.v3` has not been deployed, but a reader that decodes it as a two-field tuple fails on the third element (rmp-serde `LengthMismatch`), so Huginn must accept `tail` and `tail_gaps` (defaulted fields) before this mouth is deployed. The array is positional: a decoder of the earlier three-field shape fails on the fourth element with the same `LengthMismatch`, so `tail_gaps` has the same deploy precondition; a decoder that reads the first three elements and ignores the rest sees `persona`, `deliveries` and `tail` unchanged.
+
+| Bound | Rule |
+|---|---|
+| Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. |
+| Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. |
+| Cursor | None. The tail is each room's newest lines whether or not they were delivered or acked: a message the wake rule left unaddressed is acked and leaves `pending`, and the tail is where a beat still finds it. A reader removes the lines a delivery already shows (by event id). Her own lines are included. |
+| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news. A room that cannot be read within 10 seconds is logged and absent; the other rooms and the deliveries are unaffected. |
+
+A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it.
+
+The tail is **data, not instruction**. A line is what a sender typed in a room, and the mouth wakes no one, acks nothing and sends nothing because of it. A reader treats the body as untrusted text and weighs `basis` as evidence, as for a delivery. The tail does not replace a delivery: a message still reaches her as a delivery, with its own `seq`, and only `chat_ack` advances a position.
+
+#### Gaps in the tail (`chat_pending.v3`, field 3, `tail_gaps`)
+
+`tail_gaps` is a list of room names (the configured alias, or the room id for a DM, as `room` in a tail line), one for each speakable room whose lines are not all in `tail`. A reader renders such a room as **unknown**, not quiet. Absent or empty means every speakable room was read fully: a room with no lines because it is quiet, and a room whose few lines all fit, are never listed. Order is the order the mouth reads rooms (configured rooms in join order, then DMs), not time; a room appears once however many causes apply. Causes, all of them:
+
+| Cause | Where |
+|---|---|
+| The room's read failed (the homeserver refused or errored) or did not answer within 10 seconds (`sendTimeoutMs`); the room is logged and contributes no lines | the mouth |
+| The room had more than 20 lines outside threads (the per-room cap; her own lines count), so older ones were left out | the mouth |
+| The read window came back full (100 raw events, before edits and thread replies are set aside), so real lines older than the window may exist and are unseen; a shorter chunk means the room's history was exhausted. A room whose history is exactly 100 events long is gapped too, since the mouth cannot tell. The rule assumes a homeserver returns the 100 events asked for whenever older history exists; a server that caps the limit lower turns a truncated read into a false "whole", and Bifrost does not detect that | the mouth |
+| One of the room's lines was cut by the 60-line total cap (only the newest 60 over all rooms are kept) | the mouth |
+| A line was dropped as malformed (no event id) | the mouth |
+| The reply byte budget (256 KiB, deliveries first) cut the room's oldest lines, or a line would not encode and was skipped | the reply |
+| The mouth has not started: every configured room is a gap (DMs are not yet known) | the mouth |
+| The whole tail read failed: every speakable room is a gap, and the deliveries are still served | the endpoint |
+
+A line a delivery already shows and a room she cannot speak in change nothing here; her own lines are lines like any other and count toward the caps. A read the mouth kept for 15 seconds counts as a read.
+
+Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines and no gap, `chat_pending.v3.tail-gaps` one line and two gap rooms; the earlier v3 samples gain an empty fourth element); Huginn pins the same bytes.
+
+### Follow (`basis` `"follow"`, `CHAT_FOLLOW=1`)
+
+A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because the basis is Huginn's `Basis::FollowUp`, wire string `follow` (`FOLLOW_UP_BASIS`, f09bc56e), and a Huginn that predates it refuses the string. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no follow state.
+
+With it on:
+
+- **Anchor.** Her own post in a public room anchors that room for W = 600 s from the post. The mouth anchors at send time (the send's own time, in `send`, in the background: the send receipt never waits on the room-state read) and also from the /sync echo of her own events, so a post from another client of her account anchors too; one event anchors once. Only her posting again re-anchors the room and re-snapshots who is counted; a follow never extends the window.
+- **Counted senders** (snapshotted at the post): those who spoke in that room in the 10 minutes before the post (a per-room ring of recent senders with event times, 200 entries), plus anyone the post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer) when the event carries it. Someone who first speaks after her post is not counted. A member who spoke in the 10 minutes before her post is counted, bounded by 3 follows per hour per (peer, room). Nothing reads message text; no ids are scraped from bodies. She herself, and bridged senders (the `platformEvent` identifier rule), never count.
+- **Follow.** A `message` (not an edit, not a notice) from a counted sender gets `follow` only when it would otherwise have no basis (a plain message); `room` (@room), `tag`, `reply` and `direct` keep their own basis, and an @room neither wakes via follow nor spends the peer's K. Its timestamp must lie inside the window (a homeserver clock up to 60 s behind still follows) and this process's clock must not be past the window's end by more than 60 s, so an old or forged `origin_server_ts` reuses nothing. At most K = 3 per (Mind, peer, room) in the hour before the message; past it the message keeps the basis it had.
+- **"Public" means non-DM, non-encrypted, non-bridged.** The room is not one of her DMs and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable or malformed state is not public). An invite-only plaintext room counts as public. Nothing is anchored in, and no follow is delivered in, any other room.
+
+State is in memory only (per-room anchor, sender ring, follow times), purged on every sync pass; nothing is stored, and a restart only shortens windows.
+
+### Reply link (`chat_pending.v4`)
+
+A reply to anyone but the Persona arrives bare in v3: `basis` is `reply` only when the quoted author is her account. v4 adds what the message quotes. **It is off unless the mouth runs with `CHAT_PENDING_V4=1`** (exactly `1`; default off), because Huginn pins the tuple bytes and must read v4 first. With the flag off, `gamecult.persona.chat_pending_request.v3` is not a served kind: it is refused as any unknown kind is (`chat_refusal` `UnknownKind`, logged), byte for byte, and v1/v2/v3 requests are answered as before. With it on, that request kind (the v1 tuple `[persona, after_seq]` again; the kind asked by names the answer) is answered with `gamecult.persona.chat_pending.v4`.
+
+The answer is `[persona, deliveries, tail, tail_gaps]` exactly as v3; each delivery is the 14 v3 fields, then field 14:
+
+| Field | Type | Meaning |
+|---|---|---|
+| 14 `reply_to` | nil or `[event_id, sender, excerpt]` | The event this message replies to (its own `m.in_reply_to`; a thread's `is_falling_back` pointer names no one and is nil). `event_id` the quoted event; `sender` its author's Matrix id, read from the homeserver as her account; `excerpt` nil, or its text. |
+
+`excerpt` is nil, with `event_id` and `sender` kept, when the quoted event is redacted (`unsigned.redacted_because` present or no content), is not a text-bearing `m.room.message`, is **edited** (it is itself an `m.replace`, or the homeserver bundles an `m.replace` in its `unsigned.m.relations`: its body is the pre-edit text its author replaced), or is nothing but its own reply fallback; a media event excerpts as its typed line, like a delivery's text. Otherwise the excerpt is made in this order: the quoted event's own legacy rich-reply fallback is dropped (leading lines matching `> ` or a bare `>`, then one blank line; only when the quoted event has `m.relates_to.m.in_reply_to`); the text is held to the 1000-byte line bound; runs of CR, LF, tab, U+2028 and U+2029 become one space; control characters (C0, DEL, C1 including NUL and ESC), format characters (Unicode Cf: bidi marks, overrides and isolates, U+061C, U+200B-200F, U+2060-2064, soft hyphen, BOM), private-use characters (Co), the tag block U+E0000-E007F, variation selectors (U+FE00-FE0F, U+E0100-E01EF, U+180B-180F), the combining grapheme joiner U+034F, the Hangul and Khmer fillers (U+115F, U+1160, U+3164, U+FFA0, U+17B4, U+17B5), the blank braille cell U+2800, the unassigned default-ignorable ranges (U+2065, U+FFF0-FFF8, U+E0080-E0FFF) and unpaired surrogates are removed (cost accepted: an emoji loses its VS16 presentation, ❤️ becomes ❤, a keycap loses its selector; Mongolian free variation selectors and ideographic variation selectors go too); the line is trimmed; then the first 240 **Unicode code points** are kept (cut on a code point so no character is split; a combining mark counts as its own code point; trailing space trimmed; no truncation marker). Cleaning comes first so hidden characters cannot spend the cap. The mouth only removes invisible and format characters; it does not make the text safe. Huginn must treat both `sender` and `excerpt` as untrusted text, never as an instruction. `event_id` must be `$` plus at least one byte and `sender` `@` plus at least one byte, each at most 255 bytes and free of Unicode whitespace, control, format, private-use and default-ignorable characters and unpaired surrogates (a localpart with a zero-width joiner or non-joiner, as in Persian or Indic names, is therefore no `reply_to`); the encoder and the parser refuse any other, and the mouth makes a quoted event whose sender is not such an id a `reply_to` nil. `reply_to` is nil (no id, author or text) when the target cannot be read (logged, as for `basis`), is not in the delivery's own room (a room she is not in cannot be quoted through a reply), or the message replies to nothing. The quoted event is read the way `basis` already reads it (`GET /rooms/{room}/event/{id}` as her account, kept per room and event; with the flag on a read, hit or failure, is kept 60 seconds, so a redaction or edit of the target shows at a re-read within a minute, and a re-read that fails transiently (network error, timeout, 5xx, 429) keeps the earlier hit's sender and renews only its age, for at most 10 minutes after the last good read (then it is the failure entry), but never its excerpt (`excerpt` is nil with the sender kept: a re-read happens only after the 60-second keep, so the text is already as old as it may be), so a redaction or edit is not outlived by an outage, while any other failure (403, 404) makes it the failure entry, so a stale excerpt never outlives her access; with the flag off a hit is kept as before v4 and nothing is re-read), so a reply costs at most one read per target, shared with the `basis` check. Per sync round the mouth makes at most 8 reply-target reads in all, `basis` reads included (it counts each uncached GET of a reply target or thread root, and an event that would take the round past 8 is not started; the context reads of a delivery, one room or thread each per round, are separate and uncounted); a target the cap check found cached is served to that event for its own reads even if its 60 s keep lapses meanwhile, which is at most one other target read (10 s timeout) late; past that the event and every later event of the round wait: the round leaves the sync position where it is (as at the pending cap), the next round resumes at that event with its read count reset, and the wait is logged. No delivery goes out without a `reply_to` it should have had, and none is lost. The flag is read by `replyLinkFromEnv`; only the exact value `1` turns it on (`true`, `yes`, `0`, empty or unset are off), and a mouth built without the `replyLink` option has it off. `basis` for v1-v3 is unchanged. `reply_to` counts toward the delivery's size in the 256 KiB page budget; a delivery whose `reply_to` will not encode is skipped and logged like any other, and a single delivery is always served. The deploy precondition is Huginn's: a decoder of the 14-field delivery fails on the fifteenth element.
+
+Golden bytes: `tests/fixtures/persona-chat-v6/` (`.msgpack` and its `.hex`: `chat_pending.v4.reply-to`, `.no-reply-to`, `.reply-to-redacted`, and the `chat_pending_request.v3` request); the test fails when the checked-in bytes drift from the encoder.
+
Bifrost admits an observation only when guild, channel, target runtime, canonical repository, Persona, producer, and producer runtime match a preconfigured `bifrost.persona_feedback.target_binding.v0` document in Bifrost's private provider store. That binding also owns source visibility, data classification, and the delivery-store target. Bifrost never infers public visibility from Discord identifiers. It classifies the author using its own `bifrost.discord.actor_link.v0` state: a match yields `linked_governance_feedback`; absence yields `unlinked_social_feedback`. Neither class grants adoption, work, release, or deployment authority.
@@ -228,6 +311,10 @@ The intended shape:
VoidBot still owns room reading, moderation judgment, archive/source retrieval, and Persona cognition. Bifrost owns Discord when Discord is being used as the Labor Platform interface or swarm transport.
+### Fetch a named file (`chat_fetch_request.v1`, `chat_fetch_receipt.v1`)
+
+A Persona's Mind shell holds no Matrix token, so the mouth keeps a file for her: `chat_fetch_request.v1` is `[request_id, persona, room, event_id]`, a room (alias or id) and an event id, nothing else. The mouth reads her live membership and the room's full state, reads the event itself and takes `content.url` from it, fetches it as her (5 MiB, magic bytes decide the type), compares the file event's `info.sha256` with the hash it computed, stores the bytes in her image store, and answers `chat_fetch_receipt.v1` `[request_id, outcome, room_id, image, receipt]` with one of 14 fixed outcome words. A file with no `info.sha256` is `StoredUnverified` and gets no receipt; a present hash that is not the computed one is `HashMismatch` and stores nothing. For a stored, hash-matching file the mouth posts the contract's `org.gamecult.file_received` event (`{event_id, sha256, size}`) as her own Matrix user, once per (file, Mind): a reply in the album thread, else a plain event with an `m.reference` to the file. The Matrix sender is the Mind; no content key names her. Idempotence is read from Matrix, not kept. Bridged and encrypted rooms and other people's rooms are refused. The kind is served only with `CHAT_FETCH=1` (exactly that value); off, it is answered as any unknown kind (`UnknownKind`). One 15 s deadline owns each fetch, and one Persona may ask 30 in an hour. Each fetch writes one log line, `fetch persona=... outcome=... receipt=...`, and a failure adds a trailing ` cause=/`, on a thrown fetch failure, a store write that throws, or a receipt not proven: `Class` is the error's class name when it matches `[A-Za-z]{1,32}`, else `Error`; `status` is the HTTP status integer of a failed Matrix call, else `-`. No error-derived text (message, code, path, URL) reaches the log; the room and event ids, already shape-checked, are the only ids on the fetch line. `isFetchId` refuses a room-version-3 event id that contains `/` (standard base64), a fail-closed side: it is answered `NoAttachment`.
+
## Heimdall Integration Target
The correct future credential path is:
diff --git a/docs/concept-mill-votes-target.md b/docs/concept-mill-votes-target.md
index 91c92e6..40935af 100644
--- a/docs/concept-mill-votes-target.md
+++ b/docs/concept-mill-votes-target.md
@@ -41,7 +41,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
### Data Protection on the live host
-18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*`, `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
+18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*` (the app secret as `Heimdall__AppSecret`; `Heimdall__AppSecretFile` is the replacement), `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
19. The service's working directory resolves to the release directory: `readlink /proc//cwd` = `/srv/bifrost/app/releases/20260723-daedcc4`. Data Protection's default application discriminator is the content-root path (prior-art note `:67`), so every deploy into a new release directory isolates payloads protected by the previous release: auth cookies, antiforgery tokens and any future device token stop decrypting after each deploy. Mechanism from source docs plus this probe; not observed as logged-out users. `SetApplicationName` is not called anywhere (`git grep SetApplicationName bf83a93` is empty).
### Proxy and client address
@@ -53,7 +53,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
21. Main lacks EF migration discovery metadata on seven migrations: `20260622142000_AddBridgeActionIdentityProvenance`, `20260622202000_AddBridgeActionTargetSurfaceName` and `20260705190000_AddPatronSupportProjectAttribution` have neither `[DbContext]` nor `[Migration]`; `20260608210000_AddHeimdallUserIdentity`, `20260609143000_AddPatronSupportDerivation`, `20260609160000_AddExternalPatronProviderIntake` and `20260622165000_AddBifrostNativeIdentity` have `[Migration]` only; none of the seven has a `.Designer.cs`. EF discovers a migration only with both attributes, so `MigrateAsync` from main would skip them on a fresh database. `daedcc4` adds exactly those attributes (17 lines). The other five migrations have Designer files and are discovered. Migrations run at startup when `Bootstrap:ApplyMigrationsOnStartup` is true (`Features/Shared/ApplicationBootstrapper.cs:17-21`); the live env sets that key.
22. Tests use EF InMemory (`tests/Bifrost.Web.Tests/Support/TestWebApplicationFactory.cs:52-58`), which enforces no unique index; a uniqueness rule must be proven in service code and in the model/migration metadata, not by an InMemory insert failing. `TestAuthHandler` offers two actors only: the bootstrap admin `test-admin`, or anonymous via header `X-Test-Anonymous` (`Support/TestAuthHandler.cs:17-37`). `CurrentBifrostActor` is a public record with a public constructor (`Features/Shared/CurrentBifrostActor.cs:5`), so service tests can build account and member actors directly. `Program` is `public partial` (`Program.cs:582`).
23. Startup configuration rules live in one owner, `Features/Shared/StartupConfigurationValidator.cs`, which skips Development and Testing and throws on a missing production key (`:15-74`).
-24. The shared layout loads HTMX from `https://unpkg.com/htmx.org@1.9.12` (`Pages/Shared/_Layout.cshtml:65`); no page posts with `hx-post` today. Admin and vote handlers use plain Razor page handlers with `RedirectToPage()` (`Pages/App/Motions/Index.cshtml.cs:56-61`).
+24. The shared layout loads no third-party script or stylesheet (HTMX was dropped; `NoThirdPartyAssetTests` fails on any cross-origin `
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
new file mode 100644
index 0000000..a92e916
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
@@ -0,0 +1,351 @@
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Configuration;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+///
+/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of
+/// (a forward move, optionally of ) and (the undo). The body
+/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant.
+///
+public sealed record HeimdallMoveRequest(
+ string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null)
+{
+ // The proofs are live bearers: the generated ToString would print them into any log or exception that holds the request.
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"MoveId = {MoveId}, FromProofs = {FromProofs?.Count}, ToProof = {(ToProof is null ? "none" : "present")}, ReversesMoveId = {ReversesMoveId}");
+ return true;
+ }
+}
+
+public enum HeimdallProofTier
+{
+ Strong,
+ Weak
+}
+
+/// The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it.
+public sealed record HeimdallMoveReceipt(
+ string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId);
+
+/// Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400.
+public enum HeimdallMoveRefusal
+{
+ AppAuthRequired,
+ NotAllowedForApp,
+ NotReversible,
+ ProofInvalid,
+ SameAccount,
+ ProofStale,
+ IdentityNotProved,
+ AlreadyMoved,
+ ProviderConflict,
+ IdentityNotFound,
+ RequestInvalid
+}
+
+public enum HeimdallProofSide
+{
+ From,
+ To
+}
+
+///
+/// The closed answer to a move. Moved: the receipt. Refused: Heimdall answered a 4xx before applying anything, so nothing changed.
+/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one, and so may a 409 move_id_conflict: Heimdall
+/// answers it to a replay of a committed move whose proofs no longer verify): the caller keeps its proofs and replays the same request.
+///
+public abstract record HeimdallMoveOutcome
+{
+ private HeimdallMoveOutcome()
+ {
+ }
+
+ public sealed record Moved(HeimdallMoveReceipt Receipt) : HeimdallMoveOutcome;
+
+ public sealed record Refused(HeimdallMoveRefusal Code, HeimdallProofSide? Side = null, string? Provider = null) : HeimdallMoveOutcome;
+
+ public sealed record Unknown(string Reason) : HeimdallMoveOutcome;
+}
+
+///
+/// Heimdall's move route under Bifrost's app secret (HeimdallAuthService.ConfigureClient adds the header). Each call sends one request and
+/// retries nothing: replay with the same is the caller's, and Heimdall answers it with the stored
+/// receipt. Logs name the outcome class and refusal code only.
+///
+public sealed partial class HeimdallIdentityMoveClient(
+ HttpClient httpClient, IOptions heimdallOptions, ILogger logger)
+{
+ /// The deadline of one call, headers and body together, set on the HttpClient by .
+ public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15);
+
+ private const int MaxMovedIdentities = 256;
+ private const int MaxIdentityIdLength = 128;
+ private const int MaxReceiptBytes = 64 * 1024;
+ public const int MaxProofLength = 8192;
+
+ // \z, not $: $ also matches before a final line feed, which Heimdall's schema pattern refuses with a 400.
+ [GeneratedRegex("^[A-Za-z0-9_-]{16,64}\\z")]
+ private static partial Regex MoveIdShape();
+
+ public async Task MoveAsync(HeimdallMoveRequest request, CancellationToken cancellationToken)
+ {
+ var body = Serialize(request);
+ var outcome = await SendAsync(request, body, cancellationToken);
+ logger.LogInformation("Heimdall identity move: {Outcome} {Code}", outcome.GetType().Name, outcome is HeimdallMoveOutcome.Refused refused ? refused.Code : null);
+ return outcome;
+ }
+
+ private async Task SendAsync(HeimdallMoveRequest request, string body, CancellationToken cancellationToken)
+ {
+ // One deadline over the whole call: HttpClient.Timeout ends at the headers, and a stalled body must not outlive it.
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(httpClient.Timeout);
+ var token = deadline.Token;
+ try
+ {
+ using var message = new HttpRequestMessage(
+ HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/identity-moves")
+ {
+ Content = new StringContent(body, Encoding.UTF8, "application/json")
+ };
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token);
+ var status = (int)response.StatusCode;
+ if (response.StatusCode == HttpStatusCode.OK)
+ {
+ return await ReadReceiptAsync(response, request, token) is { } receipt
+ ? new HeimdallMoveOutcome.Moved(receipt)
+ : new HeimdallMoveOutcome.Unknown("malformed or mismatched receipt");
+ }
+
+ if (status is < 400 or >= 500 || status == 429)
+ {
+ return new HeimdallMoveOutcome.Unknown($"HTTP {status}");
+ }
+
+ return Refused(await HeimdallRefusal.ReadAsync(response, token), status);
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ // Whatever the pipeline throws after the request may have gone out is not a refusal; only the caller's own cancellation propagates.
+ return new HeimdallMoveOutcome.Unknown("transport");
+ }
+ }
+
+ ///
+ /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute, and its error handler's invalid_request 400). A 4xx without one of those codes
+ /// (a gateway's HTML 404, a 408, a code a later Heimdall adds) proves nothing was applied, so it is Unknown. move_id_conflict is
+ /// Unknown too: a committed move answers it when its proofs no longer verify.
+ ///
+ private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal, int status)
+ {
+ if (refusal?.Code == "move_id_conflict")
+ {
+ return new HeimdallMoveOutcome.Unknown("move_id_conflict");
+ }
+
+ var code = refusal?.Code switch
+ {
+ "app_auth_required" => HeimdallMoveRefusal.AppAuthRequired,
+ "not_allowed_for_app" => HeimdallMoveRefusal.NotAllowedForApp,
+ "not_reversible" => HeimdallMoveRefusal.NotReversible,
+ "proof_invalid" => HeimdallMoveRefusal.ProofInvalid,
+ "same_account" => HeimdallMoveRefusal.SameAccount,
+ "proof_stale" => HeimdallMoveRefusal.ProofStale,
+ "identity_not_proved" => HeimdallMoveRefusal.IdentityNotProved,
+ "already_moved" => HeimdallMoveRefusal.AlreadyMoved,
+ "provider_conflict" => HeimdallMoveRefusal.ProviderConflict,
+ "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound,
+ // Heimdall's error handler gives its own 400 this code; an nginx or other edge 400 has none, so it is not Heimdall's refusal.
+ "invalid_request" when status == 400 => HeimdallMoveRefusal.RequestInvalid,
+ _ => (HeimdallMoveRefusal?)null
+ };
+ if (code is not { } known)
+ {
+ return new HeimdallMoveOutcome.Unknown($"HTTP {status} without a Heimdall refusal code");
+ }
+
+ return known switch
+ {
+ HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(known, Side: refusal?.Proof switch
+ {
+ "from" => HeimdallProofSide.From,
+ "to" => HeimdallProofSide.To,
+ _ => null
+ }),
+ HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(known, Provider: refusal?.Provider),
+ _ => new HeimdallMoveOutcome.Refused(known)
+ };
+ }
+
+ ///
+ /// A 200 body is a receipt only when it is whole and answers this request: its moveId (and reversesMoveId) equal the request's,
+ /// a forward move names a destination proof tier and a reversal does not. Anything else is not trusted as a move.
+ ///
+ private static async Task ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, CancellationToken cancellationToken)
+ {
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
+ using var buffer = new MemoryStream();
+ var chunk = new byte[4096];
+ while (await stream.ReadAsync(chunk, cancellationToken) is > 0 and var read)
+ {
+ if (buffer.Length + read > MaxReceiptBytes)
+ {
+ return null;
+ }
+
+ buffer.Write(chunk, 0, read);
+ }
+
+ using var document = JsonDocument.Parse(buffer.ToArray());
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object
+ || Text(root, "moveId") != request.MoveId
+ || Text(root, "reversesMoveId") != request.ReversesMoveId
+ || Text(root, "accountId") is not { Length: > 0 } account
+ || !root.TryGetProperty("movedIdentityIds", out var moved)
+ || moved.ValueKind != JsonValueKind.Array
+ || moved.GetArrayLength() is 0 or > MaxMovedIdentities
+ || !root.TryGetProperty("proof", out var proof)
+ || proof.ValueKind != JsonValueKind.Object
+ || Tier(proof, "from") is not { } from)
+ {
+ return null;
+ }
+
+ var ids = new List();
+ foreach (var item in moved.EnumerateArray())
+ {
+ if (item.ValueKind != JsonValueKind.String || item.GetString() is not { Length: > 0 and <= MaxIdentityIdLength })
+ {
+ return null;
+ }
+
+ ids.Add(item.GetString()!);
+ }
+
+ HeimdallProofTier? to = null;
+ if (request.ReversesMoveId is null)
+ {
+ to = Tier(proof, "to");
+ if (to is null)
+ {
+ return null;
+ }
+ }
+ else if (!proof.TryGetProperty("to", out var none) || none.ValueKind != JsonValueKind.Null)
+ {
+ return null;
+ }
+
+ return new HeimdallMoveReceipt(request.MoveId, account, ids, from, to, request.ReversesMoveId);
+ }
+
+ private static HeimdallProofTier? Tier(JsonElement proof, string name) => Text(proof, name) switch
+ {
+ "strong" => HeimdallProofTier.Strong,
+ "weak" => HeimdallProofTier.Weak,
+ _ => null
+ };
+
+ private static string? Text(JsonElement item, string name) =>
+ item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
+
+ private static bool IsBadProof(string? proof) => string.IsNullOrEmpty(proof) || proof.Length > MaxProofLength;
+
+ /// The contract's closed body, or ArgumentException before any I/O when the request breaks it.
+ private static string Serialize(HeimdallMoveRequest request)
+ {
+ if (request.MoveId is null || !MoveIdShape().IsMatch(request.MoveId))
+ {
+ throw new ArgumentException("moveId must match ^[A-Za-z0-9_-]{16,64}$", nameof(request));
+ }
+
+ if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(IsBadProof))
+ {
+ throw new ArgumentException("fromProofs must hold 1 to 8 proofs", nameof(request));
+ }
+
+ if ((request.ToProof is null) == (request.ReversesMoveId is null))
+ {
+ throw new ArgumentException("exactly one of toProof and reversesMoveId is required", nameof(request));
+ }
+
+ if (request.ToProof is not null && IsBadProof(request.ToProof))
+ {
+ throw new ArgumentException("toProof is empty", nameof(request));
+ }
+
+ if (request.ReversesMoveId is not null && !MoveIdShape().IsMatch(request.ReversesMoveId))
+ {
+ throw new ArgumentException("reversesMoveId must match the moveId shape", nameof(request));
+ }
+
+ if (request.IdentityIds is not null
+ && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrEmpty)
+ || request.IdentityIds.Distinct().Count() != request.IdentityIds.Count))
+ {
+ throw new ArgumentException("identityIds are 1 to 32 unique ids and only with toProof", nameof(request));
+ }
+
+ var body = new Dictionary { ["moveId"] = request.MoveId, ["fromProofs"] = request.FromProofs };
+ if (request.ToProof is not null)
+ {
+ body["toProof"] = request.ToProof;
+ }
+
+ if (request.IdentityIds is not null)
+ {
+ body["identityIds"] = request.IdentityIds;
+ }
+
+ if (request.ReversesMoveId is not null)
+ {
+ body["reversesMoveId"] = request.ReversesMoveId;
+ }
+
+ return JsonSerializer.Serialize(body);
+ }
+}
+
+public static class HeimdallClientServices
+{
+ ///
+ /// Every Heimdall client Bifrost owns. The auth client carries the app secret, the member client only the member's bearer and
+ /// the mover the app secret and its call deadline; all share the header redaction.
+ ///
+ public static void AddHeimdallClients(this IServiceCollection services)
+ {
+ services.AddHttpClient((serviceProvider, client) =>
+ HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+ services.AddHttpClient((serviceProvider, client) =>
+ HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+ services.AddHeimdallIdentityMoveClient();
+ }
+
+ /// A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin.
+ public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) =>
+ builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) });
+
+ ///
+ /// The mover's HttpClient: Heimdall's base address and app secret from HeimdallAuthService.ConfigureClient (the one secret path), the
+ /// call deadline, no redirects (a 3xx must never carry the secret or the proofs to another origin), and the shared header redaction.
+ ///
+ public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) =>
+ services.AddHttpClient((serviceProvider, client) =>
+ {
+ HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value);
+ client.Timeout = HeimdallIdentityMoveClient.Timeout;
+ })
+ .WithoutRedirects()
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
new file mode 100644
index 0000000..04a29d9
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
@@ -0,0 +1,112 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using Bifrost.Web.Configuration;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+/// One login a Heimdall account holds, as the Linked accounts page shows it. No provider user id, scope or email.
+public sealed record LinkedIdentitySummary(string Id, string Provider, string? DisplayName, DateTimeOffset? LinkedAt);
+
+public enum HeimdallMemberCall
+{
+ Ok,
+ SignInRequired,
+ StepUpRequired,
+ IdentityNotFound,
+ LastIdentity,
+ Error
+}
+
+public sealed record HeimdallMemberResult(HeimdallMemberCall Call, IReadOnlyList? Identities);
+
+///
+/// Heimdall's member routes (docs/service-contract.md: GET /v1/me/identities, POST /v1/me/identities/{id}/unlink). Each
+/// takes the member's bearer as an argument, uses it for that one request and keeps nothing. Its HttpClient carries no
+/// app secret: these routes act only for a member who is present, so a Bifrost fault cannot reach them without one.
+///
+public sealed class HeimdallMemberClient(HttpClient httpClient)
+{
+ private const int MaxIdentities = 32;
+ private const int MaxDisplayName = 80;
+
+ public static void ConfigureClient(HttpClient client, HeimdallOptions options) =>
+ client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
+
+ public Task ListAsync(string bearer, CancellationToken cancellationToken) =>
+ SendAsync(HttpMethod.Get, "/v1/me/identities", bearer, cancellationToken);
+
+ public Task UnlinkAsync(string bearer, string identityId, CancellationToken cancellationToken) =>
+ SendAsync(HttpMethod.Post, $"/v1/me/identities/{Uri.EscapeDataString(identityId)}/unlink", bearer, cancellationToken);
+
+ private async Task SendAsync(HttpMethod method, string path, string bearer, CancellationToken cancellationToken)
+ {
+ try
+ {
+ using var message = new HttpRequestMessage(method, path);
+ message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ if (response.StatusCode == HttpStatusCode.OK)
+ {
+ return new HeimdallMemberResult(HeimdallMemberCall.Ok, await ReadIdentitiesAsync(response, cancellationToken));
+ }
+
+ var code = await HeimdallRefusal.CodeAsync(response, cancellationToken);
+ var call = (response.StatusCode, code) switch
+ {
+ (HttpStatusCode.Unauthorized, _) => HeimdallMemberCall.SignInRequired,
+ (HttpStatusCode.Forbidden, "step_up_required") => HeimdallMemberCall.StepUpRequired,
+ (HttpStatusCode.NotFound, "identity_not_found") => HeimdallMemberCall.IdentityNotFound,
+ (HttpStatusCode.Conflict, "last_identity") => HeimdallMemberCall.LastIdentity,
+ _ => HeimdallMemberCall.Error
+ };
+ return new HeimdallMemberResult(call, null);
+ }
+ catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException
+ && !cancellationToken.IsCancellationRequested)
+ {
+ return new HeimdallMemberResult(HeimdallMemberCall.Error, null);
+ }
+ }
+
+ /// The identities array of a 200 answer, keeping only the fields the page shows; a malformed entry is dropped.
+ private static async Task> ReadIdentitiesAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ using var body = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
+ var list = new List();
+ if (body.RootElement.ValueKind != JsonValueKind.Object
+ || !body.RootElement.TryGetProperty("identities", out var identities)
+ || identities.ValueKind != JsonValueKind.Array)
+ {
+ return list;
+ }
+
+ foreach (var item in identities.EnumerateArray().Take(MaxIdentities))
+ {
+ var id = Text(item, "id");
+ var provider = Text(item, "provider");
+ if (!Guid.TryParse(id, out _)
+ || provider is not { Length: > 0 and <= 32 }
+ || !provider.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'))
+ {
+ continue;
+ }
+
+ var name = Text(item, "displayName") ?? Text(item, "username");
+ if (name is { Length: > MaxDisplayName })
+ {
+ name = name[..MaxDisplayName];
+ }
+
+ DateTimeOffset? linkedAt = DateTimeOffset.TryParse(Text(item, "linkedAt"), out var parsed) ? parsed : null;
+ list.Add(new LinkedIdentitySummary(id!, provider, name, linkedAt));
+ }
+
+ return list;
+ }
+
+ private static string? Text(JsonElement item, string name) =>
+ item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
+ ? value.GetString()
+ : null;
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
index 2e95ff3..02b41c2 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
@@ -64,23 +64,22 @@ public sealed class HeimdallPatronSupportIntakeService(
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}.");
+ return existingEvent is not null
+ ? HeimdallPatronSupportIntakeResult.Processed(
+ $"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
+ existingEvent.Id)
+ : HeimdallPatronSupportIntakeResult.BadRequest(
+ $"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
}
+ // The write gate behind RecordSupportEventAsync routes a folded account's event to its survivor and journals it, and on a
+ // provider retry returns the stored event, journalling it if it sits on the survivor and was left unjournalled.
var supportEvent = await patronageService.RecordSupportEventAsync(
actorUserAccountId: null,
userAccountId: user.Id,
@@ -98,7 +97,9 @@ public sealed class HeimdallPatronSupportIntakeService(
cancellationToken);
return HeimdallPatronSupportIntakeResult.Processed(
- $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
+ existingEvent is not null
+ ? $"Already processed {request.Provider} patron support event {request.ProviderEventId}."
+ : $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
supportEvent.Id);
}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
new file mode 100644
index 0000000..c6bd638
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
@@ -0,0 +1,58 @@
+using System.Text.Json;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+/// Reads the one thing Bifrost takes from a Heimdall refusal body: its error code, and only if it is a safe token.
+public static class HeimdallRefusal
+{
+ private const int BodyLimit = 4096;
+
+ ///
+ /// The error code in the first 4 KiB of a body when it is a short snake_case token, else null. A body that cannot be
+ /// read or parsed yields null: a refusal never becomes a 500, and free text or tokens never reach a log or a page.
+ ///
+ public static async Task CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) =>
+ (await ReadAsync(response, cancellationToken))?.Code;
+
+ ///
+ /// The error code plus the two qualifiers a move refusal carries (the contract's `proof`, only "from" or "to", and `provider`, a
+ /// short snake_case token), each kept only when it is that safe shape. Nothing else of the body is read. Null when no code reads.
+ ///
+ public static async Task ReadAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
+ var head = new byte[BodyLimit];
+ var length = 0;
+ while (length < head.Length && await stream.ReadAsync(head.AsMemory(length), cancellationToken) is > 0 and var read)
+ {
+ length += read;
+ }
+
+ using var body = JsonDocument.Parse(head.AsMemory(0, length));
+ if (body.RootElement.ValueKind == JsonValueKind.Object && Token(body.RootElement, "error", 64) is { } code)
+ {
+ var proof = body.RootElement.TryGetProperty("proof", out var side) && side.ValueKind == JsonValueKind.String ? side.GetString() : null;
+ return new HeimdallRefusalBody(code, proof is "from" or "to" ? proof : null, Token(body.RootElement, "provider", 32));
+ }
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ }
+
+ return null;
+ }
+
+ private static string? Token(JsonElement root, string name, int maxLength) =>
+ root.TryGetProperty(name, out var value)
+ && value.ValueKind == JsonValueKind.String
+ && value.GetString() is { Length: > 0 } text
+ && text.Length <= maxLength
+ && text.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_')
+ ? text
+ : null;
+}
+
+/// A Heimdall refusal's safe fields: the code, the proof side ("from"/"to") and the provider, when present and well formed.
+public sealed record HeimdallRefusalBody(string Code, string? Proof, string? Provider);
diff --git a/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs b/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
new file mode 100644
index 0000000..08a21bb
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
@@ -0,0 +1,35 @@
+using System.Collections.Concurrent;
+
+namespace Bifrost.Web.Features.Heimdall;
+
+///
+/// What the Linked accounts page last read from Heimdall for an account: id, provider, display name and link date of
+/// each login, nothing else, for . It lives in this process only, keyed by the Heimdall account id,
+/// and is never given to the browser; it holds no bearer. The page renders from it because the list is fetched inside a
+/// completion request, which redirects. After a restart it is empty and the page offers to read the list again.
+///
+public sealed class LinkedAccountsSnapshots(TimeProvider timeProvider)
+{
+ public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
+
+ private readonly ConcurrentDictionary Identities, DateTimeOffset ExpiresAt)> _held = new(StringComparer.Ordinal);
+
+ public void Put(string accountId, IReadOnlyList identities)
+ {
+ var now = timeProvider.GetUtcNow();
+ foreach (var (key, value) in _held)
+ {
+ if (value.ExpiresAt <= now)
+ {
+ _held.TryRemove(key, out _);
+ }
+ }
+
+ _held[accountId] = (identities, now + Lifetime);
+ }
+
+ public IReadOnlyList? Get(string accountId) =>
+ _held.TryGetValue(accountId, out var value) && value.ExpiresAt > timeProvider.GetUtcNow() ? value.Identities : null;
+
+ public void Remove(string accountId) => _held.TryRemove(accountId, out _);
+}
diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
new file mode 100644
index 0000000..24a61ef
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs
@@ -0,0 +1,768 @@
+using System.Globalization;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Patronage;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+/// How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.
+public abstract record MergeStanding(Guid MergeId)
+{
+ public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId);
+
+ public sealed record Folded(Guid MergeId, Guid SurvivorId) : MergeStanding(MergeId);
+}
+
+public sealed record MergePlanEntry(
+ AccountMergeEntryKind Kind,
+ AccountMergeEntryAction Action,
+ Guid RecordId,
+ Guid? PriorUserAccountId = null,
+ string? PriorText = null,
+ DateTimeOffset? PriorAtUtc = null);
+
+/// A dry run: the block codes (never account names), the journal entries a commit would write, and the record counts left untouched.
+public sealed record MergePlan(
+ IReadOnlyList Blocks,
+ IReadOnlyList Entries,
+ IReadOnlyDictionary Left)
+{
+ ///
+ /// Lowercase hex SHA-256 over a canonical text of the plan, in plan order (Left by key): what the member saw, comparable at confirm.
+ /// Every field is length-prefixed, so no value can imitate a separator. The plan holds no account ids of its own, so the caller
+ /// names the pair the plan was made for.
+ ///
+ public string Digest(Guid survivorId, Guid foldedId)
+ {
+ var text = new System.Text.StringBuilder();
+ void Field(string? value) => text.Append(value is null ? "-" : $"{value.Length}:{value}").Append('|');
+ Field(survivorId.ToString("N"));
+ Field(foldedId.ToString("N"));
+ foreach (var entry in Entries)
+ {
+ Field(entry.Kind.ToString());
+ Field(entry.Action.ToString());
+ // A Created row does not exist yet: its id is minted anew by every plan, so it cannot be part of what the member saw.
+ // Left unpinned on purpose: the mutant that keeps the id in (digest-includes-created-id in tools/merge-saga-mutants.py) is behaviourally equivalent bar one benign case.
+ Field(entry.Action == AccountMergeEntryAction.Created ? null : entry.RecordId.ToString("N"));
+ Field(entry.PriorUserAccountId?.ToString("N"));
+ Field(entry.PriorText);
+ Field(entry.PriorAtUtc?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture));
+ text.Append('\n');
+ }
+
+ text.Append("left\n");
+ foreach (var (key, count) in Left.OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ Field(key);
+ Field(count.ToString(CultureInfo.InvariantCulture));
+ }
+
+ text.Append("\nblocks\n");
+ foreach (var block in Blocks)
+ {
+ Field(block);
+ }
+
+ return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text.ToString()))).ToLowerInvariant();
+ }
+}
+
+///
+/// The one owner of what an account merge does to Bifrost records and of how an account stands under one: the plan, the Committed
+/// save, the undo save, the Final transition and StandingAsync. A merge only reduces: nothing is deleted, votes and
+/// appraisals are stamped void (the model's query filter then removes them from every tally) or re-pointed, and every change is
+/// journalled in AccountMergeEntry. Design: /opt/commons/handoff/heimdall-account-merge-design-20261113.md sections 3, 5, 7.
+///
+public sealed class AccountMergeLedger(
+ BifrostDbContext dbContext,
+ PatronageService patronageService,
+ TimeProvider timeProvider)
+{
+ public static readonly TimeSpan Grace = TimeSpan.FromDays(7);
+
+ private static readonly AccountMergeState[] FrozenStates = [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved];
+
+ private static readonly AccountMergeState[] FoldedStates =
+ [AccountMergeState.Committed, AccountMergeState.Final, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ private static readonly AccountMergeState[] InFlightStates =
+ [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ public static string SuspensionReason(Guid mergeId) => $"merged with a suspended account (merge {mergeId})";
+
+ public Task StandingAsync(Guid userAccountId, CancellationToken cancellationToken) =>
+ StandingAsync(dbContext, userAccountId, cancellationToken);
+
+ /// The single reading of standing, shared by the actor accessor and the OIDC refusal, which holds only a context. Derived from the merge state on every call.
+ public static async Task StandingAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken)
+ {
+ var merge = await db.AccountMerges.AsNoTracking()
+ .Where(x => x.FoldedUserAccountId == userAccountId &&
+ (FrozenStates.Contains(x.State) || FoldedStates.Contains(x.State)))
+ .OrderByDescending(x => x.CreatedUtc)
+ .FirstOrDefaultAsync(cancellationToken);
+
+ return merge is null
+ ? null
+ : FrozenStates.Contains(merge.State)
+ ? new MergeStanding.Frozen(merge.Id)
+ : new MergeStanding.Folded(merge.Id, merge.SurvivorUserAccountId);
+ }
+
+ ///
+ /// The one gate every writer that acts for an account passes through (votes, appraisals, sealed ballots, patron events, the Heimdall
+ /// sign-in's membership). On Postgres it holds a shared advisory lock on the account, the key the chain trigger locks exclusively
+ /// when a merge row is inserted or changes state and that takes exclusively before it reduces, across the
+ /// standing read and everything saves, then commits. So a merge cannot freeze or fold the account between a
+ /// writer's standing read and its save: it waits for the writer, and a writer that starts after it reads the new standing. The
+ /// lock covers writes made through this gate and nothing else; it is held until the transaction ends, so a writer must not
+ /// catch a database error inside and carry on (the transaction is already aborted). On the in-memory
+ /// provider there is no lock and no transaction: the standing is read, then the writer saves.
+ ///
+ public static async Task WriteAsAsync(BifrostDbContext db, Guid userAccountId, Func> write, CancellationToken cancellationToken)
+ {
+ await using var transaction = await BeginAsync(db, cancellationToken);
+ await LockAsync(db, userAccountId, exclusive: false, cancellationToken);
+ var result = await write(await StandingAsync(db, userAccountId, cancellationToken));
+ if (transaction is not null)
+ {
+ await transaction.CommitAsync(cancellationToken);
+ }
+
+ return result;
+ }
+
+ /// A transaction for the caller to commit, or null where there is none to open: not Postgres, or one already open (its owner commits).
+ private static async Task BeginAsync(BifrostDbContext db, CancellationToken cancellationToken) =>
+ db.Database.IsNpgsql() && db.Database.CurrentTransaction is null ? await db.Database.BeginTransactionAsync(cancellationToken) : null;
+
+ /// The account's lock, on the key the chain trigger uses (hashtextextended of the id's text). A no-op off Postgres.
+ private static async Task LockAsync(BifrostDbContext db, Guid userAccountId, bool exclusive, CancellationToken cancellationToken)
+ {
+ if (!db.Database.IsNpgsql())
+ {
+ return;
+ }
+
+ var key = userAccountId.ToString();
+ await (exclusive
+ ? db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))", cancellationToken)
+ : db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock_shared(hashtextextended({key}, 0))", cancellationToken));
+ }
+
+ /// Writes nothing. lets the saga re-plan a merge it already holds without it blocking itself.
+ public async Task PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
+ {
+ var blocks = await BlocksAsync(survivorId, foldedId, exceptMergeId, cancellationToken);
+ var entries = new List();
+ var left = new Dictionary();
+
+ if (!blocks.Contains("account_missing"))
+ {
+ var reduction = await ReduceAsync(survivorId, foldedId, cancellationToken);
+ entries.AddRange(reduction.Entries);
+ left["ConsentReceipts"] = await dbContext.ConsentReceipts.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ left["PasskeyCredentials"] = await dbContext.PasskeyCredentials.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ left["LedgerEntries"] = await dbContext.LedgerEntries.CountAsync(x => x.UserAccountId == foldedId, cancellationToken);
+ }
+
+ return new MergePlan(blocks, entries, left);
+ }
+
+ private async Task> BlocksAsync(Guid survivorId, Guid foldedId, Guid? exceptMergeId, CancellationToken cancellationToken)
+ {
+ var blocks = new List();
+ if (survivorId == foldedId)
+ {
+ blocks.Add("same_account");
+ }
+
+ var accounts = await dbContext.UserAccounts.AsNoTracking()
+ .Where(x => x.Id == survivorId || x.Id == foldedId)
+ .Select(x => new { x.Id, x.HeimdallAccountId })
+ .ToListAsync(cancellationToken);
+ if (accounts.Count < (survivorId == foldedId ? 1 : 2))
+ {
+ blocks.Add("account_missing");
+ return blocks;
+ }
+
+ if (await dbContext.MindPersonas.AnyAsync(x => x.UserAccountId == survivorId || x.UserAccountId == foldedId, cancellationToken))
+ {
+ blocks.Add("mind_account");
+ }
+
+ if (accounts.Any(x => string.IsNullOrWhiteSpace(x.HeimdallAccountId)))
+ {
+ blocks.Add("native_account");
+ }
+
+ if (await dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId &&
+ InFlightStates.Contains(x.State) &&
+ (x.SurvivorUserAccountId == survivorId || x.FoldedUserAccountId == survivorId ||
+ x.SurvivorUserAccountId == foldedId || x.FoldedUserAccountId == foldedId),
+ cancellationToken))
+ {
+ blocks.Add("merge_in_flight");
+ }
+
+ if (await FoldedLinkAsync(survivorId, exceptMergeId, cancellationToken))
+ {
+ blocks.Add("survivor_is_folded");
+ }
+
+ if (await FoldedLinkAsync(foldedId, exceptMergeId, cancellationToken))
+ {
+ blocks.Add("already_folded");
+ }
+
+ // One hop only: a landed merge's survivor never folds into a third account, so an alias is never a chain.
+ if (await dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId && FoldedStates.Contains(x.State) && x.SurvivorUserAccountId == foldedId,
+ cancellationToken))
+ {
+ blocks.Add("folded_is_survivor");
+ }
+
+ if (await dbContext.SealedBallots.AnyAsync(
+ x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open,
+ cancellationToken))
+ {
+ blocks.Add("sealed_ballot_pending");
+ }
+
+ return blocks;
+ }
+
+ private Task FoldedLinkAsync(Guid accountId, Guid? exceptMergeId, CancellationToken cancellationToken) =>
+ dbContext.AccountMerges.AnyAsync(
+ x => x.Id != exceptMergeId && x.FoldedUserAccountId == accountId && FoldedStates.Contains(x.State),
+ cancellationToken);
+
+ ///
+ /// Applies the merge to Bifrost records in one save, together with State=Committed. Total: blocks were checked before the move
+ /// and a refusal now would strand moved logins, so it recomputes the reductions from current rows and applies them. Committed
+ /// and Final are no-ops returning the receipt; any other state but HeimdallMoved is an error.
+ ///
+ public async Task CommitAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
+
+ // The exclusive lock first, so no writer that read the folded account's standing is still to save when the reduction reads its
+ // rows, then the state again: a commit that waited here found the merge landed and returns its receipt.
+ await using var transaction = await BeginAsync(dbContext, cancellationToken);
+ await LockAsync(dbContext, merge.FoldedUserAccountId, exclusive: true, cancellationToken);
+ await dbContext.Entry(merge).ReloadAsync(cancellationToken);
+ if (merge.State is AccountMergeState.Committed or AccountMergeState.Final)
+ {
+ return merge;
+ }
+
+ if (merge.State != AccountMergeState.HeimdallMoved)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallMoved merge can be committed.");
+ }
+
+ try
+ {
+ var reduction = await ReduceAsync(merge.SurvivorUserAccountId, merge.FoldedUserAccountId, cancellationToken, mergeId);
+ var now = timeProvider.GetUtcNow();
+ var seq = 0;
+ foreach (var entry in reduction.Entries)
+ {
+ dbContext.AccountMergeEntries.Add(Journal(merge.Id, ++seq, entry, now));
+ }
+
+ reduction.Apply(now);
+ if (reduction.MovedPatronEvents)
+ {
+ await RestageTiersAsync(reduction.Survivor, reduction.Folded, now, cancellationToken);
+ }
+
+ reduction.ReweighMovedVotes();
+ merge.State = AccountMergeState.Committed;
+ merge.CommittedUtc = now;
+ merge.GraceEndsUtc = now + Grace;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ if (transaction is not null)
+ {
+ await transaction.CommitAsync(cancellationToken);
+ }
+
+ return merge;
+ }
+ catch
+ {
+ // Nothing was saved; drop what was staged so a retry on this context starts from the stored rows.
+ dbContext.ChangeTracker.Clear();
+ throw;
+ }
+ }
+
+ /// Replays the journal backward in one save with State=Undone. Total, like commit. Undone is a no-op; any other state but HeimdallReversed is an error.
+ public async Task UndoLocalAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken);
+ if (merge.State == AccountMergeState.Undone)
+ {
+ return merge;
+ }
+
+ if (merge.State != AccountMergeState.HeimdallReversed)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is {merge.State}; only a HeimdallReversed merge can be undone locally.");
+ }
+
+ if (merge.FinalizedUtc is not null)
+ {
+ throw new InvalidOperationException($"Merge {mergeId} is Final; a merge is never undone past Final.");
+ }
+
+ try
+ {
+ var now = timeProvider.GetUtcNow();
+ var journal = await dbContext.AccountMergeEntries.Where(x => x.MergeId == mergeId).OrderByDescending(x => x.Seq).ToListAsync(cancellationToken);
+ var seq = journal.Count == 0 ? 0 : journal.Max(x => x.Seq);
+ var survivor = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == merge.SurvivorUserAccountId, cancellationToken);
+ var folded = await dbContext.UserAccounts.Include(x => x.Membership).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == merge.FoldedUserAccountId, cancellationToken);
+ var survivorKey = AppraisalKey(survivor.Id);
+ var restagePatron = false;
+
+ void Record(AccountMergeEntry original, bool restored) =>
+ dbContext.AccountMergeEntries.Add(new AccountMergeEntry
+ {
+ MergeId = mergeId,
+ Seq = ++seq,
+ Kind = original.Kind,
+ RecordId = original.RecordId,
+ Action = restored ? AccountMergeEntryAction.Restored : AccountMergeEntryAction.KeptAfterUndo,
+ PriorUserAccountId = original.PriorUserAccountId,
+ AtUtc = now
+ });
+
+ foreach (var entry in journal.Where(x => x.Action is AccountMergeEntryAction.Voided or AccountMergeEntryAction.Moved or AccountMergeEntryAction.Closed or AccountMergeEntryAction.Suspended or AccountMergeEntryAction.Created))
+ {
+ switch (entry.Kind, entry.Action)
+ {
+ case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided):
+ {
+ var vote = await dbContext.Votes.IgnoreQueryFilters().Include(x => x.Motion).SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = vote?.VoidedByMergeId == mergeId && vote.Motion.Status == MotionStatus.Open;
+ if (restore)
+ {
+ vote!.VoidedByMergeId = null;
+ vote.VoidedUtc = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved):
+ {
+ var vote = await dbContext.Votes.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = vote is not null && vote.UserAccountId == survivor.Id && vote.CastAtUtc == entry.PriorAtUtc;
+ if (restore)
+ {
+ vote!.UserAccountId = entry.PriorUserAccountId!.Value;
+ if (decimal.TryParse(entry.PriorText, NumberStyles.Number, CultureInfo.InvariantCulture, out var priorWeight))
+ {
+ vote.Weight = priorWeight;
+ }
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided):
+ {
+ var row = await dbContext.ConceptAppraisals.IgnoreQueryFilters().SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row?.VoidedByMergeId == mergeId;
+ if (restore)
+ {
+ row!.VoidedByMergeId = null;
+ row.VoidedUtc = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved):
+ {
+ var row = await dbContext.ConceptAppraisals.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row is not null && row.UserAccountId == survivor.Id && row.VoterKey == survivorKey && row.CastAtUtc == entry.PriorAtUtc;
+ if (restore)
+ {
+ row!.UserAccountId = entry.PriorUserAccountId!.Value;
+ var (priorClass, priorKey) = ParseAppraisalPrior(entry.PriorText);
+ row.VoterKey = priorKey ?? row.VoterKey;
+ row.VoterClass = priorClass ?? row.VoterClass;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed):
+ {
+ var restore = folded.Membership is { Status: MembershipStatus.Merged } && Enum.TryParse(entry.PriorText, out _);
+ if (restore)
+ {
+ folded.Membership!.Status = Enum.Parse(entry.PriorText!);
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended):
+ {
+ // Only while the survivor still carries exactly this merge's suspension; an admin who changed it since owns the standing now.
+ var restore = survivor.Membership is { Status: MembershipStatus.Suspended } member &&
+ member.SuspensionReason == SuspensionReason(mergeId) &&
+ Enum.TryParse(entry.PriorText, out _);
+ if (restore)
+ {
+ survivor.Membership!.Status = Enum.Parse(entry.PriorText!);
+ survivor.Membership.SuspensionReason = null;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created):
+ {
+ // The membership this merge made to carry a suspension goes with the merge, unless an admin has taken it over since.
+ var created = await dbContext.Memberships.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = created is { Status: MembershipStatus.Suspended } && created.SuspensionReason == SuspensionReason(mergeId);
+ if (restore)
+ {
+ dbContext.Memberships.Remove(created!);
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ case (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved):
+ {
+ var row = await dbContext.PatronSupportEvents.SingleOrDefaultAsync(x => x.Id == entry.RecordId, cancellationToken);
+ var restore = row is not null && row.UserAccountId == survivor.Id;
+ if (restore)
+ {
+ row!.UserAccountId = entry.PriorUserAccountId!.Value;
+ restagePatron = true;
+ }
+
+ Record(entry, restore);
+ break;
+ }
+ }
+ }
+
+ if (restagePatron)
+ {
+ await RestageTiersAsync(survivor, folded, now, cancellationToken);
+ }
+
+ merge.State = AccountMergeState.Undone;
+ merge.UndoneUtc = now;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return merge;
+ }
+ catch
+ {
+ dbContext.ChangeTracker.Clear();
+ throw;
+ }
+ }
+
+ ///
+ /// Committed merges whose grace has ended become Final; returns how many this call finalized. Undo is never allowed past Final.
+ /// State is the merge's concurrency token, so a merge another writer moved first (UndoRequested) fails its save and is left to that
+ /// transition: a stale Committed read can never overwrite it.
+ ///
+ public async Task FinalizeDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var dueIds = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.State == AccountMergeState.Committed && x.GraceEndsUtc <= now)
+ .Select(x => x.Id)
+ .ToListAsync(cancellationToken);
+ var finalized = 0;
+ foreach (var id in dueIds)
+ {
+ var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == id, cancellationToken);
+ if (merge.State != AccountMergeState.Committed)
+ {
+ continue;
+ }
+
+ merge.State = AccountMergeState.Final;
+ merge.FinalizedUtc = now;
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ finalized++;
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ }
+ }
+
+ return finalized;
+ }
+
+ ///
+ /// Stages the journal entry for a patron event that is on a folded account's survivor, so undo moves it back with the rest; saved
+ /// with the event by , the only caller. Idempotent: a provider retry stages nothing.
+ ///
+ public static async Task StageIntakeJournalAsync(BifrostDbContext db, Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ if (await db.AccountMergeEntries.AnyAsync(
+ x => x.MergeId == mergeId && x.Kind == AccountMergeEntryKind.PatronSupportEvent && x.RecordId == supportEventId,
+ cancellationToken))
+ {
+ return;
+ }
+
+ var seq = await db.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0;
+ db.AccountMergeEntries.Add(Journal(
+ mergeId,
+ seq + 1,
+ new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEventId, foldedUserAccountId),
+ now));
+ }
+
+ private sealed class Reduction(
+ UserAccount survivor,
+ UserAccount folded,
+ List entries,
+ List> effects,
+ List movedVotes,
+ bool movedPatronEvents)
+ {
+ public UserAccount Survivor { get; } = survivor;
+
+ public UserAccount Folded { get; } = folded;
+
+ public IReadOnlyList Entries => entries;
+
+ public bool MovedPatronEvents { get; } = movedPatronEvents;
+
+ public Guid MergeId { get; set; }
+
+ /// A moved vote carries the survivor's weight, derived once from the survivor's tiers as they stand after the restage, never the folded account's.
+ public void ReweighMovedVotes()
+ {
+ foreach (var vote in movedVotes)
+ {
+ vote.Weight = Survivor.Membership!.EffectiveVotingWeight;
+ }
+ }
+
+ public void Apply(DateTimeOffset now)
+ {
+ foreach (var effect in effects)
+ {
+ effect(MergeId, now);
+ }
+ }
+ }
+
+ ///
+ /// What a merge does to records, computed from current rows without writing: the journal entries and the effects that apply them.
+ /// Rules (design 5): suspension wins; the folded membership is closed and its roles never copied; open standard motions and
+ /// concept appraisals keep one voice per person (the survivor's), a lone folded one moving only to an Active survivor; patron
+ /// events follow the person.
+ ///
+ private async Task ReduceAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? mergeId = null)
+ {
+ var survivor = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == survivorId, cancellationToken);
+ var folded = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == foldedId, cancellationToken);
+
+ var entries = new List();
+ var effects = new List>();
+ var movedVotes = new List();
+
+ var foldedSuspended = folded.Membership?.Status == MembershipStatus.Suspended;
+ var survivorSuspendedNow = survivor.Membership?.Status == MembershipStatus.Suspended;
+ var survivorStanding = survivor.Membership?.Status;
+ if (foldedSuspended && !survivorSuspendedNow)
+ {
+ if (survivor.Membership is { } survivorMembership)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Suspended, survivorMembership.Id, null, survivorMembership.Status.ToString()));
+ effects.Add((id, _) =>
+ {
+ survivorMembership.Status = MembershipStatus.Suspended;
+ survivorMembership.SuspensionReason = SuspensionReason(id);
+ });
+ }
+ else
+ {
+ // The chat tier holds no membership, and an absent one chats: without a row the suspension would be gone. The row is journalled so undo removes it.
+ var created = new Bifrost.Web.Domain.Membership { UserAccountId = survivor.Id, Status = MembershipStatus.Suspended };
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Standing, AccountMergeEntryAction.Created, created.Id));
+ effects.Add((id, now) =>
+ {
+ created.SuspensionReason = SuspensionReason(id);
+ created.CreatedAtUtc = now;
+ created.Notes = "Created by an account merge to carry the folded account's suspension.";
+ dbContext.Memberships.Add(created);
+ });
+ }
+
+ survivorStanding = MembershipStatus.Suspended;
+ }
+
+ var survivorActive = survivorStanding == MembershipStatus.Active;
+
+ if (folded.Membership is { } foldedMembership)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed, foldedMembership.Id, null, foldedMembership.Status.ToString()));
+ effects.Add((_, _) => foldedMembership.Status = MembershipStatus.Merged);
+ }
+
+ var foldedVotes = await dbContext.Votes
+ .Where(x => x.UserAccountId == foldedId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
+ .ToListAsync(cancellationToken);
+ var survivorVotedMotions = (await dbContext.Votes
+ .Where(x => x.UserAccountId == survivorId && x.Motion.Status == MotionStatus.Open && x.Motion.Kind == MotionKind.Standard)
+ .Select(x => x.MotionId)
+ .ToListAsync(cancellationToken)).ToHashSet();
+ foreach (var vote in foldedVotes)
+ {
+ if (survivorVotedMotions.Contains(vote.MotionId) || !survivorActive)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided, vote.Id, vote.UserAccountId));
+ effects.Add((id, now) =>
+ {
+ vote.VoidedByMergeId = id;
+ vote.VoidedUtc = now;
+ });
+ }
+ else
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved, vote.Id, vote.UserAccountId, vote.Weight.ToString(CultureInfo.InvariantCulture), vote.CastAtUtc));
+ movedVotes.Add(vote);
+ effects.Add((_, _) => vote.UserAccountId = survivorId);
+ }
+ }
+
+ var survivorKey = AppraisalKey(survivorId);
+ var foldedAppraisals = await dbContext.ConceptAppraisals.Where(x => x.UserAccountId == foldedId).ToListAsync(cancellationToken);
+ var survivorSubjects = (await dbContext.ConceptAppraisals
+ .Where(x => x.UserAccountId == survivorId || x.VoterKey == survivorKey)
+ .Select(x => x.SubjectId)
+ .ToListAsync(cancellationToken)).ToHashSet();
+ foreach (var appraisal in foldedAppraisals)
+ {
+ if (survivorSubjects.Contains(appraisal.SubjectId) || !survivorActive)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided, appraisal.Id, appraisal.UserAccountId));
+ effects.Add((id, now) =>
+ {
+ appraisal.VoidedByMergeId = id;
+ appraisal.VoidedUtc = now;
+ });
+ }
+ else
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved, appraisal.Id, appraisal.UserAccountId, $"{appraisal.VoterClass}|{appraisal.VoterKey}", appraisal.CastAtUtc));
+ effects.Add((_, _) =>
+ {
+ appraisal.UserAccountId = survivorId;
+ appraisal.VoterKey = survivorKey;
+ appraisal.VoterClass = VoterClass.Member; // the survivor is Active here, which is what makes an account a Member voter
+ });
+ }
+ }
+
+ var foldedEvents = folded.PatronSupportEvents.ToList();
+ foreach (var supportEvent in foldedEvents)
+ {
+ entries.Add(new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEvent.Id, supportEvent.UserAccountId));
+ effects.Add((_, _) => supportEvent.UserAccountId = survivorId);
+ }
+
+ var reduction = new Reduction(survivor, folded, entries, effects, movedVotes, foldedEvents.Count > 0);
+ if (mergeId is { } m)
+ {
+ reduction.MergeId = m;
+ }
+
+ return reduction;
+ }
+
+ // Tiers derive once from all the events now on each account, never tier A plus tier B. Ownership is read from the
+ // tracked rows, so it holds before the save as well as after it.
+ private async Task RestageTiersAsync(UserAccount survivor, UserAccount folded, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var events = survivor.PatronSupportEvents.Concat(folded.PatronSupportEvents).DistinctBy(x => x.Id).ToList();
+ await StageIfMembershipAsync(survivor.Membership, events.Where(x => x.UserAccountId == survivor.Id).ToList(), now, cancellationToken);
+ await StageIfMembershipAsync(folded.Membership, events.Where(x => x.UserAccountId == folded.Id).ToList(), now, cancellationToken);
+ }
+
+ private async Task StageIfMembershipAsync(Bifrost.Web.Domain.Membership? membership, IEnumerable events, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ if (membership is not null && dbContext.Entry(membership).State != EntityState.Deleted)
+ {
+ await patronageService.StageTierSnapshotAsync(membership, events, now, cancellationToken);
+ }
+ }
+
+ private static AccountMergeEntry Journal(Guid mergeId, int seq, MergePlanEntry entry, DateTimeOffset now) => new()
+ {
+ MergeId = mergeId,
+ Seq = seq,
+ Kind = entry.Kind,
+ RecordId = entry.RecordId,
+ Action = entry.Action,
+ PriorUserAccountId = entry.PriorUserAccountId,
+ PriorText = entry.PriorText,
+ PriorAtUtc = entry.PriorAtUtc,
+ AtUtc = now
+ };
+
+ private static string AppraisalKey(Guid accountId) => "account:" + accountId.ToString("N");
+
+ private static (VoterClass? Class, string? Key) ParseAppraisalPrior(string? prior)
+ {
+ var split = prior?.IndexOf('|') ?? -1;
+ return split > 0 && Enum.TryParse(prior![..split], out var voterClass) ? (voterClass, prior[(split + 1)..]) : (null, null);
+ }
+}
+
+///
+/// The one merge loop, every 30 seconds: the proof holder drops expired bearers, the saga advances every due in-flight merge (confirm,
+/// replay, undo), then the ledger finalizes merges past their grace. A new scope per tick, a warning on failure, the SealedBallotCloser shape. No second merge hosted service exists.
+///
+public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger logger) : BackgroundService
+{
+ public static readonly TimeSpan Tick = TimeSpan.FromSeconds(30);
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(Tick);
+ do
+ {
+ try
+ {
+ using var scope = scopes.CreateScope();
+ var now = clock.GetUtcNow();
+ scope.ServiceProvider.GetRequiredService().PruneExpired();
+ await scope.ServiceProvider.GetRequiredService().AdvanceDueAsync(now, stoppingToken);
+ await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(now, stoppingToken);
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ logger.LogWarning(error, "Account merge sweep failed; retrying next tick.");
+ }
+ }
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
new file mode 100644
index 0000000..153ee80
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs
@@ -0,0 +1,576 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// A live Heimdall bearer a member redeemed from a fresh sign-in, with the Heimdall account and provider it came through. The token is a
+/// secret: never prints it (nor the account id), so no log or exception that holds a proof can leak it.
+///
+public sealed record MergeProof(string AccessToken, string HeimdallAccountId, string Provider)
+{
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"Provider = {Provider}");
+ return true;
+ }
+}
+
+/// What the member confirmed: the pair, the plan digest they saw, and a proof for every login of each side that must speak.
+public sealed record ConfirmMergeRequest(
+ Guid ActorUserAccountId,
+ Guid SurvivorUserAccountId,
+ Guid FoldedUserAccountId,
+ string PreviewDigest,
+ MergeProof SurvivorProof,
+ IReadOnlyList FoldedProofs);
+
+/// The closed answer to a confirm. Only Confirmed wrote a row.
+public abstract record ConfirmOutcome
+{
+ private ConfirmOutcome()
+ {
+ }
+
+ public sealed record Confirmed(Guid MergeId) : ConfirmOutcome;
+
+ /// The plan's block codes (never account names), or merge_in_flight when the database refused an overlapping merge.
+ public sealed record Blocked(IReadOnlyList Codes) : ConfirmOutcome;
+
+ public sealed record PreviewStale : ConfirmOutcome;
+
+ public sealed record NotParty : ConfirmOutcome;
+
+ public sealed record ProofAccountMismatch : ConfirmOutcome;
+}
+
+/// The closed answer to an undo request. Only Requested wrote.
+public abstract record UndoOutcome
+{
+ private UndoOutcome()
+ {
+ }
+
+ public sealed record Requested : UndoOutcome;
+
+ public sealed record NotCommitted : UndoOutcome;
+
+ public sealed record GraceOver : UndoOutcome;
+
+ public sealed record NotSurvivor : UndoOutcome;
+
+ public sealed record ProofAccountMismatch : UndoOutcome;
+}
+
+/// The two ways an operator may end a stuck leg: the forward move is failed, or the undo is given up and the merge stands.
+public enum SettleChoice
+{
+ FailForward,
+ AbandonUndo
+}
+
+/// The closed answer to an operator's settle. Only Settled wrote.
+public abstract record SettleOutcome
+{
+ private SettleOutcome()
+ {
+ }
+
+ public sealed record Settled : SettleOutcome;
+
+ /// The merge is missing, in another state than the choice ends, or not stuck on one of the settleable outcomes.
+ public sealed record NotStuck : SettleOutcome;
+
+ public sealed record WrongMoveId : SettleOutcome;
+
+ /// The State token went to another writer first; the other transition stands and nothing was changed.
+ public sealed record Lost : SettleOutcome;
+}
+
+///
+/// The one owner of an account merge's lifecycle outside the ledger's Committed, Final and Undone, and the only caller of
+/// . It inserts Confirmed (the consent record, with the Heimdall bearers sealed and the move
+/// id minted), runs the one idempotent step function (move, commit, reverse, undo), and writes
+/// HeimdallMoved, Failed, UndoRequested and HeimdallReversed. It never writes votes, memberships or journal rows (the ledger's), never
+/// judges a proof's tier or freshness (Heimdall's), and reads no standing of its own: the plan's blocks and the database's live-merge
+/// index answer overlap, and the writers that act for an account go through .
+/// Every transition is one save guarded by State, the merge's concurrency token; the loser of a race reloads and continues from the
+/// stored state. Heimdall's closed outcome is consumed as is: Unknown (a lost answer, an outage) is replayed with the same stored
+/// move id and never fails a merge. Logs name the merge id, state, outcome class and refusal code only.
+///
+public sealed partial class AccountMergeSaga(
+ BifrostDbContext dbContext,
+ AccountMergeLedger ledger,
+ HeimdallIdentityMoveClient mover,
+ IDataProtectionProvider dataProtection,
+ AuditTrailService audit,
+ TimeProvider timeProvider,
+ ILogger logger)
+{
+ public const string MergeInFlight = "merge_in_flight";
+ public const string ReceiptMismatch = "receipt_mismatch";
+ public const string ProofsUnreadable = "proofs_unreadable";
+ public const string MoveIdConflict = "move_id_conflict";
+ public const string OperatorFailed = "operator_failed";
+ public const string UndoOperatorAbandoned = "undo_operator_abandoned";
+
+ private const string LiveMergeIndex = "UX_AccountMerges_FoldedUserAccountId_Live";
+ private const int MaxProofs = 8;
+
+ private static readonly TimeSpan[] Backoff = [TimeSpan.FromSeconds(15), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15)];
+ private static readonly TimeSpan UnreadableRetry = TimeSpan.FromHours(1);
+
+ private static readonly AccountMergeState[] DueStates =
+ [AccountMergeState.Confirmed, AccountMergeState.HeimdallMoved, AccountMergeState.UndoRequested, AccountMergeState.HeimdallReversed];
+
+ private readonly IDataProtector _seal = dataProtection.CreateProtector("Bifrost.AccountMerge.Proofs.v1");
+
+ private sealed record ProofSeal(List From, string? To)
+ {
+ // The seal holds live bearers: the generated ToString would print them into any log or exception that holds it.
+ private bool PrintMembers(StringBuilder builder)
+ {
+ builder.Append($"From = {From?.Count}, To = {(To is null ? "none" : "present")}");
+ return true;
+ }
+ }
+
+ // ---- confirm ----
+
+ ///
+ /// The member's consent, as one insert. The actor must be one of the pair; the plan must have no blocks and be the one the member
+ /// saw (digest); every proof must be of its side's Heimdall account. Calls no Heimdall: the caller runs .
+ ///
+ public async Task ConfirmAsync(ConfirmMergeRequest request, CancellationToken cancellationToken)
+ {
+ RequireProofs(request.SurvivorProof, request.FoldedProofs);
+ if (request.ActorUserAccountId != request.SurvivorUserAccountId && request.ActorUserAccountId != request.FoldedUserAccountId)
+ {
+ return new ConfirmOutcome.NotParty();
+ }
+
+ try
+ {
+ return await AccountMergeLedger.WriteAsAsync(dbContext, request.ActorUserAccountId, _ => InsertConfirmedAsync(request, cancellationToken), cancellationToken);
+ }
+ catch (DbUpdateException error) when (IsLiveMergeViolation(error))
+ {
+ dbContext.ChangeTracker.Clear();
+ return new ConfirmOutcome.Blocked([MergeInFlight]);
+ }
+ }
+
+ private async Task InsertConfirmedAsync(ConfirmMergeRequest request, CancellationToken cancellationToken)
+ {
+ var plan = await ledger.PlanAsync(request.SurvivorUserAccountId, request.FoldedUserAccountId, cancellationToken);
+ if (plan.Blocks.Count > 0)
+ {
+ return new ConfirmOutcome.Blocked(plan.Blocks);
+ }
+
+ if (!string.Equals(plan.Digest(request.SurvivorUserAccountId, request.FoldedUserAccountId), request.PreviewDigest, StringComparison.Ordinal))
+ {
+ return new ConfirmOutcome.PreviewStale();
+ }
+
+ var survivorHeimdall = await HeimdallAccountAsync(request.SurvivorUserAccountId, cancellationToken);
+ var foldedHeimdall = await HeimdallAccountAsync(request.FoldedUserAccountId, cancellationToken);
+ if (request.SurvivorProof.HeimdallAccountId != survivorHeimdall || request.FoldedProofs.Any(x => x.HeimdallAccountId != foldedHeimdall))
+ {
+ return new ConfirmOutcome.ProofAccountMismatch();
+ }
+
+ var now = timeProvider.GetUtcNow();
+ var merge = new AccountMerge
+ {
+ State = AccountMergeState.Confirmed,
+ SurvivorUserAccountId = request.SurvivorUserAccountId,
+ FoldedUserAccountId = request.FoldedUserAccountId,
+ CreatedUtc = now,
+ ConfirmedByUserAccountId = request.ActorUserAccountId,
+ ConfirmedUtc = now,
+ PreviewDigest = request.PreviewDigest,
+ SurvivorProofProvider = request.SurvivorProof.Provider,
+ FoldedProofProviders = string.Join(',', request.FoldedProofs.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)),
+ // Heimdall's idempotency key: random, minted once here, read back from the row on every call, never derived from the merge id.
+ HeimdallMoveId = Guid.NewGuid().ToString("N"),
+ SealedProofs = Seal(request.FoldedProofs.Select(x => x.AccessToken), request.SurvivorProof.AccessToken),
+ LastOutcome = "confirmed"
+ };
+ dbContext.AccountMerges.Add(merge);
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State);
+ return new ConfirmOutcome.Confirmed(merge.Id);
+ }
+
+ // ---- undo request ----
+
+ ///
+ /// The survivor's request to give the moved logins back, inside the grace and with fresh survivor proofs. One save: UndoRequested, a
+ /// freshly minted reverse move id, the sealed proofs. Losing the race to the Final sweep is the State token's, answered GraceOver.
+ ///
+ public async Task RequestUndoAsync(
+ Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken)
+ {
+ RequireProofs(null, survivorProofs);
+ try
+ {
+ return await AccountMergeLedger.WriteAsAsync(dbContext, actorUserAccountId, _ => WriteUndoRequestedAsync(mergeId, actorUserAccountId, survivorProofs, cancellationToken), cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ return new UndoOutcome.GraceOver();
+ }
+ }
+
+ private async Task WriteUndoRequestedAsync(
+ Guid mergeId, Guid actorUserAccountId, IReadOnlyList survivorProofs, CancellationToken cancellationToken)
+ {
+ var merge = await LoadAsync(mergeId, cancellationToken);
+ if (merge is null)
+ {
+ return new UndoOutcome.NotCommitted();
+ }
+
+ var now = timeProvider.GetUtcNow();
+ if (actorUserAccountId != merge.SurvivorUserAccountId)
+ {
+ return new UndoOutcome.NotSurvivor();
+ }
+
+ if (merge.State == AccountMergeState.Final || merge.FinalizedUtc is not null)
+ {
+ return new UndoOutcome.GraceOver();
+ }
+
+ if (merge.State != AccountMergeState.Committed)
+ {
+ return new UndoOutcome.NotCommitted();
+ }
+
+ if (merge.GraceEndsUtc is not { } graceEnds || now >= graceEnds)
+ {
+ return new UndoOutcome.GraceOver();
+ }
+
+ var survivorHeimdall = await HeimdallAccountAsync(merge.SurvivorUserAccountId, cancellationToken);
+ if (survivorProofs.Any(x => x.HeimdallAccountId != survivorHeimdall))
+ {
+ return new UndoOutcome.ProofAccountMismatch();
+ }
+
+ merge.State = AccountMergeState.UndoRequested;
+ merge.UndoRequestedUtc = now;
+ merge.HeimdallReverseMoveId = Guid.NewGuid().ToString("N");
+ merge.SealedProofs = Seal(survivorProofs.Select(x => x.AccessToken), null);
+ merge.Attempts = 0;
+ merge.NextAttemptUtc = null;
+ merge.LastOutcome = "undo_requested";
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}", merge.Id, merge.State);
+ return new UndoOutcome.Requested();
+ }
+
+ // ---- the step function ----
+
+ ///
+ /// The one step function: confirm's inline advance, the sweeper's resume after a crash and an undo request all run it. From the
+ /// stored state it makes the Heimdall move (or reversal) under the stored id, records the answer, and calls the ledger's commit (or
+ /// local undo). Idempotent: every state has one next step and every step is safe to repeat. Other states are a no-op.
+ ///
+ public async Task AdvanceAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ for (var lost = 0; ; lost++)
+ {
+ try
+ {
+ return await AdvanceOnceAsync(mergeId, cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException) when (lost < 2)
+ {
+ // Another advancer saved first: forget what this context staged and continue from the stored state.
+ dbContext.ChangeTracker.Clear();
+ }
+ }
+ }
+
+ private async Task AdvanceOnceAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var merge = await LoadAsync(mergeId, cancellationToken) ?? throw new InvalidOperationException($"Merge {mergeId} does not exist.");
+ if (merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested)
+ {
+ merge = await MoveAsync(merge, cancellationToken);
+ }
+
+ return merge.State switch
+ {
+ AccountMergeState.HeimdallMoved => await ledger.CommitAsync(merge.Id, cancellationToken),
+ AccountMergeState.HeimdallReversed => await ledger.UndoLocalAsync(merge.Id, cancellationToken),
+ _ => merge
+ };
+ }
+
+ private async Task MoveAsync(AccountMerge merge, CancellationToken cancellationToken)
+ {
+ if (merge.LastOutcome == ReceiptMismatch)
+ {
+ return merge; // Heimdall answered, wrongly, and its proofs are wiped: replay can only repeat the same answer.
+ }
+
+ var forward = merge.State == AccountMergeState.Confirmed;
+ var now = timeProvider.GetUtcNow();
+ if (Open(merge.SealedProofs) is not { } proofs)
+ {
+ // The key ring is lost or rotated out. Heimdall may already have moved, so nothing changes but the retry time.
+ merge.LastOutcome = ProofsUnreadable;
+ merge.NextAttemptUtc = now + UnreadableRetry;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogError("Account merge {MergeId} {State}: sealed proofs unreadable", merge.Id, merge.State);
+ return merge;
+ }
+
+ var request = forward
+ ? new HeimdallMoveRequest(merge.HeimdallMoveId!, proofs.From, proofs.To)
+ : new HeimdallMoveRequest(merge.HeimdallReverseMoveId!, proofs.From, ReversesMoveId: merge.HeimdallMoveId);
+ var outcome = await mover.MoveAsync(request, cancellationToken);
+ var code = outcome is HeimdallMoveOutcome.Refused refused ? RefusalCode(refused.Code) : null;
+ switch (outcome)
+ {
+ case HeimdallMoveOutcome.Moved moved:
+ // The leg's destination is the survivor going forward and the folded account coming back.
+ var destination = await HeimdallAccountAsync(forward ? merge.SurvivorUserAccountId : merge.FoldedUserAccountId, cancellationToken);
+ merge.SealedProofs = null;
+ if (moved.Receipt.AccountId != destination)
+ {
+ merge.LastOutcome = ReceiptMismatch;
+ break;
+ }
+
+ merge.Attempts = 0;
+ merge.NextAttemptUtc = null;
+ merge.LastOutcome = "moved";
+ if (forward)
+ {
+ merge.State = AccountMergeState.HeimdallMoved;
+ merge.ProofFromTier = Tier(moved.Receipt.ProofFrom);
+ merge.ProofToTier = moved.Receipt.ProofTo is { } to ? Tier(to) : null;
+ merge.MovedIdentityIds = JsonSerializer.Serialize(moved.Receipt.MovedIdentityIds);
+ }
+ else
+ {
+ merge.State = AccountMergeState.HeimdallReversed;
+ merge.ReversedUtc = now;
+ }
+
+ break;
+ case HeimdallMoveOutcome.Refused:
+ // Heimdall applied nothing before a 4xx. A forward refusal ends the merge; a refused undo leaves it as it was.
+ merge.SealedProofs = null;
+ merge.NextAttemptUtc = null;
+ if (forward)
+ {
+ merge.State = AccountMergeState.Failed;
+ merge.FailedUtc = now;
+ merge.FailureCode = code!;
+ merge.LastOutcome = "refused";
+ }
+ else
+ {
+ merge.State = AccountMergeState.Committed;
+ merge.LastOutcome = "undo_" + code;
+ }
+
+ break;
+ case HeimdallMoveOutcome.Unknown unknown:
+ merge.Attempts++;
+ merge.NextAttemptUtc = now + Backoff[Math.Min(merge.Attempts, Backoff.Length) - 1];
+ merge.LastOutcome = unknown.Reason.Length > 64 ? unknown.Reason[..64] : unknown.Reason;
+ break;
+ }
+
+ await dbContext.SaveChangesAsync(cancellationToken);
+ logger.LogInformation("Account merge {MergeId} {State}: {Outcome} {Code}", merge.Id, merge.State, outcome.GetType().Name, code);
+ return merge;
+ }
+
+ /// Advances every in-flight merge that is due, oldest first. One that throws is logged and skipped; returns how many were advanced.
+ public async Task AdvanceDueAsync(DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var due = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => DueStates.Contains(x.State) && (x.NextAttemptUtc == null || x.NextAttemptUtc <= now))
+ .OrderBy(x => x.CreatedUtc)
+ .Select(x => x.Id)
+ .ToListAsync(cancellationToken);
+ var advanced = 0;
+ foreach (var id in due)
+ {
+ try
+ {
+ await AdvanceAsync(id, cancellationToken);
+ advanced++;
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ dbContext.ChangeTracker.Clear();
+ logger.LogWarning("Account merge {MergeId} advance failed: {Error}", id, error.GetType().Name);
+ }
+ }
+
+ return advanced;
+ }
+
+ // ---- operator settle ----
+
+ /// The Heimdall answers no replay can change: the one the saga recorded and stopped on, the key ring's loss, and a move Heimdall holds but will not confirm.
+ public static readonly IReadOnlyList SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict];
+
+ ///
+ /// Whether an operator may end this merge's leg: in flight (Confirmed or UndoRequested) and stopped on one of the closed
+ /// outcomes. Derived from the row on every read; there is no stuck flag.
+ ///
+ public static bool IsSettleable(AccountMerge merge) =>
+ merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome);
+
+ ///
+ /// A platform admin's end of a stuck leg (ruling merge-stuck-end-only-typed-id): FailForward turns a stuck Confirmed merge into
+ /// Failed, AbandonUndo returns a stuck UndoRequested merge to Committed with its grace. Only with the leg's stored move id typed back.
+ /// Never adopts or invents a Heimdall receipt; a merge Heimdall moved (HeimdallMoved, Committed) is never settleable. One save
+ /// guarded by State carries the transition and its audit row (choice only): the loser of a race with
+ /// answers Lost and changes nothing. The caller has checked the operator's authority.
+ ///
+ public async Task SettleStuckAsync(
+ Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken)
+ {
+ var forward = choice == SettleChoice.FailForward;
+ var merge = await LoadAsync(mergeId, cancellationToken);
+ if (merge is null || merge.State != (forward ? AccountMergeState.Confirmed : AccountMergeState.UndoRequested) || !IsSettleable(merge))
+ {
+ return new SettleOutcome.NotStuck();
+ }
+
+ if (!string.Equals(typedMoveId, forward ? merge.HeimdallMoveId : merge.HeimdallReverseMoveId, StringComparison.Ordinal))
+ {
+ return new SettleOutcome.WrongMoveId();
+ }
+
+ merge.SealedProofs = null;
+ merge.NextAttemptUtc = null;
+ if (forward)
+ {
+ merge.State = AccountMergeState.Failed;
+ merge.FailedUtc = timeProvider.GetUtcNow();
+ merge.FailureCode = OperatorFailed;
+ merge.LastOutcome = OperatorFailed;
+ }
+ else
+ {
+ merge.State = AccountMergeState.Committed;
+ merge.LastOutcome = UndoOperatorAbandoned;
+ }
+
+ try
+ {
+ await audit.RecordAsync(operatorUserAccountId, nameof(AccountMerge), merge.Id, "merge.settled", choice.ToString(), cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ dbContext.ChangeTracker.Clear();
+ return new SettleOutcome.Lost();
+ }
+
+ logger.LogInformation("Account merge {MergeId} {State}: settled by an operator ({Choice})", merge.Id, merge.State, choice);
+ return new SettleOutcome.Settled();
+ }
+
+ // ---- helpers ----
+
+ /// The merge as stored now: a row this context already tracks is reloaded, never trusted.
+ private async Task LoadAsync(Guid mergeId, CancellationToken cancellationToken)
+ {
+ var tracked = dbContext.AccountMerges.Local.FirstOrDefault(x => x.Id == mergeId);
+ if (tracked is not null)
+ {
+ await dbContext.Entry(tracked).ReloadAsync(cancellationToken);
+ return dbContext.Entry(tracked).State == EntityState.Detached ? null : tracked;
+ }
+
+ return await dbContext.AccountMerges.SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
+ }
+
+ private Task HeimdallAccountAsync(Guid userAccountId, CancellationToken cancellationToken) =>
+ dbContext.UserAccounts.AsNoTracking().Where(x => x.Id == userAccountId).Select(x => x.HeimdallAccountId).SingleAsync(cancellationToken);
+
+ /// Shapes Heimdall would 400 are refused before a row exists, so a confirm can never store a merge that cannot call. Messages name no value.
+ private static void RequireProofs(MergeProof? one, IReadOnlyList many)
+ {
+ if (many is not { Count: >= 1 and <= MaxProofs })
+ {
+ throw new ArgumentException("1 to 8 proofs are required", nameof(many));
+ }
+
+ foreach (var proof in one is null ? many : [one, .. many])
+ {
+ if (string.IsNullOrEmpty(proof.AccessToken) || proof.AccessToken.Length > HeimdallIdentityMoveClient.MaxProofLength
+ || string.IsNullOrEmpty(proof.HeimdallAccountId) || string.IsNullOrEmpty(proof.Provider) || proof.Provider.Length > 32)
+ {
+ throw new ArgumentException("a proof is malformed", nameof(many));
+ }
+ }
+
+ if (many.Select(x => x.Provider).Distinct(StringComparer.Ordinal).Sum(x => x.Length + 1) > 121)
+ {
+ throw new ArgumentException("the proofs' providers do not fit the record", nameof(many));
+ }
+ }
+
+ private string Seal(IEnumerable from, string? to) => _seal.Protect(JsonSerializer.Serialize(new ProofSeal([.. from], to)));
+
+ private ProofSeal? Open(string? sealedProofs)
+ {
+ if (sealedProofs is null)
+ {
+ return null;
+ }
+
+ try
+ {
+ return JsonSerializer.Deserialize(_seal.Unprotect(sealedProofs)) is { From.Count: > 0 } proofs ? proofs : null;
+ }
+ catch (Exception error) when (error is CryptographicException or JsonException)
+ {
+ return null;
+ }
+ }
+
+ private static string Tier(HeimdallProofTier tier) => tier == HeimdallProofTier.Strong ? "strong" : "weak";
+
+ private static string RefusalCode(HeimdallMoveRefusal code) =>
+ code == HeimdallMoveRefusal.RequestInvalid ? "invalid_request" : WordBoundary().Replace(code.ToString(), "_$1").ToLowerInvariant();
+
+ [GeneratedRegex("(?The database's refusal of an overlapping merge: the live-merge unique index or the chain trigger's exclusion violation.
+ private static bool IsLiveMergeViolation(DbUpdateException error)
+ {
+ for (var current = (Exception?)error; current is not null; current = current.InnerException)
+ {
+ if (current is PostgresException { SqlState: "23P01" } or PostgresException { SqlState: "23505", ConstraintName: LiveMergeIndex })
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
index d485b91..aa1bf8a 100644
--- a/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
+++ b/src/Bifrost.Web/Features/Membership/BifrostIdentityService.cs
@@ -12,20 +12,34 @@ public sealed partial class BifrostIdentityService(
BifrostDbContext dbContext,
TimeProvider timeProvider)
{
- public async Task RegisterNativeAsync(
- string identity,
- string? displayName,
- CancellationToken cancellationToken)
+ ///
+ /// The one rule set for a new native identity: well formed, not reserved, not taken. Returns the normalized identity or
+ /// throws . Spends nothing; the unique index at insert stays the race backstop.
+ ///
+ public async Task CheckAvailableAsync(string identity, CancellationToken cancellationToken)
{
var normalizedIdentity = NormalizeIdentity(identity);
- var exists = await dbContext.UserAccounts.AnyAsync(
- x => x.NormalizedBifrostIdentity == normalizedIdentity,
- cancellationToken);
- if (exists)
+ if (IsReserved(normalizedIdentity))
+ {
+ throw new BifrostIdentityException("That Bifrost identity is reserved.");
+ }
+
+ if (await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity, cancellationToken))
{
throw new BifrostIdentityException("That Bifrost identity is already registered.");
}
+ return normalizedIdentity;
+ }
+
+ public async Task RegisterNativeAsync(
+ string identity,
+ string? displayName,
+ int? noticeVersion,
+ CancellationToken cancellationToken)
+ {
+ var normalizedIdentity = await CheckAvailableAsync(identity, cancellationToken);
+
var now = timeProvider.GetUtcNow();
var publicIdentity = ToPublicIdentity(normalizedIdentity);
var resolvedDisplayName = string.IsNullOrWhiteSpace(displayName)
@@ -52,11 +66,42 @@ public sealed partial class BifrostIdentityService(
}
};
+ // One SaveChanges: an account that agreed never exists without its receipt. No version, no receipt.
dbContext.UserAccounts.Add(userAccount);
- await dbContext.SaveChangesAsync(cancellationToken);
+ if (noticeVersion is { } agreed)
+ {
+ dbContext.ConsentReceipts.Add(new ConsentReceipt
+ {
+ UserAccount = userAccount,
+ NoticeVersion = agreed,
+ AcceptedAtUtc = now
+ });
+ }
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // Only a lost race on the unique index is the caller's mistake; anything else is a fault and propagates.
+ if (!await IdentityTakenAsync(normalizedIdentity))
+ {
+ throw;
+ }
+
+ throw new BifrostIdentityException("That Bifrost identity is already registered.");
+ }
+
return userAccount;
}
+ // A lost race on the unique index: the tracked insert is dropped and the identity is read fresh.
+ private async Task IdentityTakenAsync(string normalizedIdentity)
+ {
+ dbContext.ChangeTracker.Clear();
+ return await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity);
+ }
+
public async Task EnsureIdentityAsync(
UserAccount userAccount,
string preferredIdentity,
@@ -69,7 +114,9 @@ public sealed partial class BifrostIdentityService(
var normalizedBase = NormalizeCandidate(preferredIdentity);
var normalizedIdentity = normalizedBase;
- for (var suffix = 2; await IdentityExistsAsync(userAccount.Id, normalizedIdentity, cancellationToken); suffix++)
+ for (var suffix = 2;
+ IsReserved(normalizedIdentity) || await IdentityExistsAsync(userAccount.Id, normalizedIdentity, cancellationToken);
+ suffix++)
{
normalizedIdentity = $"{normalizedBase}-{suffix}";
}
@@ -104,6 +151,20 @@ public sealed partial class BifrostIdentityService(
return new ClaimsPrincipal(identity);
}
+ // Matrix localparts that already belong to someone else, and system names. The identity becomes the Matrix
+ // localpart at SSO, so a new account must never mint one of these. Applied to the normalized identity when an
+ // account is created (native register refuses, a derived identity takes the next free suffix); lookups of
+ // existing accounts go through NormalizeIdentity and are untouched. There is no exemption path: Minds and
+ // other known holders do not sign in through Bifrost identities.
+ private static readonly HashSet ReservedIdentities = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "admin", "aqua", "deru", "eureka", "heimdall", "ivixey", "kiko", "libby", "meta", "nibu", "unnie", "void", "weksa",
+ "root", "system", "matrix", "synapse", "support", "bot", "mod", "moderator", "postmaster", "gamecult",
+ "bifrost", "idunn", "odin", "huginn", "ratatoskr"
+ };
+
+ public static bool IsReserved(string normalizedIdentity) => ReservedIdentities.Contains(normalizedIdentity);
+
public static string NormalizeIdentity(string identity)
{
var normalized = identity.Trim().ToLowerInvariant();
diff --git a/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs
new file mode 100644
index 0000000..06e5622
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MembershipSuspensionService.cs
@@ -0,0 +1,87 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+public enum SuspensionOutcome
+{
+ Done,
+ NotAdmin,
+ NoReason,
+ NoSuchAccount,
+ NotApplicable,
+ ProtectedAccount
+}
+
+///
+/// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit
+/// receipt naming the admin and the account (the reason is kept on the membership row, readable by admins only), and no sign-in path writes or lifts a suspension (Heimdall and GitHub
+/// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved,
+/// Authenticated for one that never was; a pending request is not remembered.
+///
+public sealed class MembershipSuspensionService(BifrostDbContext dbContext, AuditTrailService auditTrailService)
+{
+ public const int MaxReasonLength = 500;
+
+ public Task SuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ ChangeAsync(actor, userAccountId, reason, suspend: true, cancellationToken);
+
+ public Task UnsuspendAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, CancellationToken cancellationToken) =>
+ ChangeAsync(actor, userAccountId, reason, suspend: false, cancellationToken);
+
+ private async Task ChangeAsync(CurrentBifrostActor actor, Guid userAccountId, string? reason, bool suspend, CancellationToken cancellationToken)
+ {
+ if (!actor.CanManageMembership || actor.UserAccount is null)
+ {
+ return SuspensionOutcome.NotAdmin;
+ }
+
+ if (string.IsNullOrWhiteSpace(reason))
+ {
+ return SuspensionOutcome.NoReason;
+ }
+
+ var user = await dbContext.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+ if (user?.Membership is not { } membership)
+ {
+ return SuspensionOutcome.NoSuchAccount;
+ }
+
+ // A merged account is terminal: only the merge ledger leaves that status, so neither suspending nor lifting applies.
+ if (membership.IsMerged)
+ {
+ return SuspensionOutcome.NotApplicable;
+ }
+
+ // An admin cannot suspend themselves or another platform admin here (the same derivation that makes an actor an admin):
+ // bootstrap admins are re-promoted to Active at sign-in by configuration, so the suspension would be undone without a receipt.
+ if (suspend && (user.Id == actor.UserAccount.Id || new CurrentBifrostActor(true, user).IsPlatformAdmin))
+ {
+ return SuspensionOutcome.ProtectedAccount;
+ }
+
+ if (suspend == (membership.Status == MembershipStatus.Suspended))
+ {
+ return SuspensionOutcome.NotApplicable;
+ }
+
+ var before = membership.Status;
+ membership.Status = suspend
+ ? MembershipStatus.Suspended
+ : membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active;
+ // The reason is a column on the membership, for admins; the receipt names who and what changed, never why.
+ var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim();
+ membership.SuspensionReason = suspend ? clipped : null;
+ // One save: the status change, the reason and the receipt stand or fall together (RecordAsync saves the shared context).
+ await auditTrailService.RecordAsync(
+ actor.UserAccount.Id,
+ nameof(Membership),
+ membership.Id,
+ suspend ? "membership.suspended" : "membership.unsuspended",
+ $"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}).",
+ cancellationToken);
+ return SuspensionOutcome.Done;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
index 8ee13a0..6d41d73 100644
--- a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
+++ b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
@@ -12,7 +12,9 @@ public sealed class MembershipSynchronizationService(
BifrostDbContext dbContext,
BifrostIdentityService bifrostIdentityService,
IOptions bootstrapOptions,
- TimeProvider timeProvider)
+ TimeProvider timeProvider,
+ AuditTrailService auditTrailService,
+ ILogger logger)
{
public async Task SynchronizeAsync(ClaimsPrincipal principal, CancellationToken cancellationToken)
{
@@ -109,9 +111,14 @@ public sealed class MembershipSynchronizationService(
invitation.AcceptedAtUtc = now;
}
+ MembershipStatus? promotedFrom = null;
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
{
- PromoteToBootstrapAdmin(userAccount.Membership!, now);
+ promotedFrom = userAccount.Membership!.Status;
+ if (!ApplicationBootstrapper.TryPromoteBootstrapAdmin(userAccount, now, logger))
+ {
+ promotedFrom = null;
+ }
}
else if (userAccount.Membership!.Status == MembershipStatus.Active)
{
@@ -125,22 +132,16 @@ public sealed class MembershipSynchronizationService(
userAccount.MemberProfile!.UpdatedAtUtc = now;
+ if (promotedFrom is { } before && before != userAccount.Membership!.Status)
+ {
+ // One save: the promotion and its receipt stand or fall together.
+ await ApplicationBootstrapper.RecordPromotionAsync(auditTrailService, userAccount, before, cancellationToken);
+ return;
+ }
+
await dbContext.SaveChangesAsync(cancellationToken);
}
- private static void PromoteToBootstrapAdmin(Bifrost.Web.Domain.Membership membership, DateTimeOffset now)
- {
- membership.Status = MembershipStatus.Active;
- membership.IsPlatformAdmin = true;
- membership.CanManageProjects = true;
- membership.CanManageLedger = true;
- membership.CanModerateMotions = true;
- membership.ApprovedAtUtc ??= now;
-
- ApplicationBootstrapper.EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
- ApplicationBootstrapper.EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
- }
-
private static bool TryReadGitHubIdentity(
ClaimsPrincipal principal,
out long gitHubUserId,
diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
new file mode 100644
index 0000000..909d8b9
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeNoticeEndpoints.cs
@@ -0,0 +1,131 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Domain;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The chat host's pull of merge notices: GET the unacked feed, POST an ack. JSON only because the reader is the chat host's script (a xenos
+/// boundary). The bearer is the chat host's own secret (ChatNotices:Token); an empty token turns both routes off. No cookie, no CORS, never stored.
+///
+public static class MergeNoticeEndpoints
+{
+ private const int MaxAckBodyBytes = 1024;
+
+ public static void Map(WebApplication app)
+ {
+ app.MapGet("/api/merge-notices/chat", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) =>
+ {
+ if (Gate(http, options.Value) is { } refused)
+ {
+ return refused;
+ }
+
+ DateTimeOffset? after = null;
+ if (http.Request.Query.TryGetValue("after", out var raw) && raw.Count > 0)
+ {
+ if (!DateTimeOffset.TryParse(raw[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
+ {
+ return Results.StatusCode(StatusCodes.Status400BadRequest);
+ }
+
+ after = parsed;
+ }
+
+ int? limit = http.Request.Query.TryGetValue("limit", out var rawLimit) && int.TryParse(rawLimit[0], CultureInfo.InvariantCulture, out var n) ? n : null;
+ var notices = await feed.ReadAsync(AccountMergeNoticeTarget.Chat, after, limit, ct);
+ return Results.Text(JsonSerializer.Serialize(notices.Select(Wire)), "application/json");
+ }).AllowAnonymous();
+
+ app.MapPost("/api/merge-notices/chat/ack", async (HttpContext http, IOptions options, MergeNoticeFeed feed, CancellationToken ct) =>
+ {
+ if (Gate(http, options.Value) is { } refused)
+ {
+ return refused;
+ }
+
+ if (await ReadAckAsync(http.Request, ct) is not var (mergeId, kind))
+ {
+ return Results.StatusCode(StatusCodes.Status400BadRequest);
+ }
+
+ return await feed.AckAsync(AccountMergeNoticeTarget.Chat, mergeId, kind, ct)
+ ? Results.StatusCode(StatusCodes.Status204NoContent)
+ : Results.StatusCode(StatusCodes.Status404NotFound);
+ }).AllowAnonymous();
+ }
+
+ private static IResult? Gate(HttpContext http, ChatNoticesOptions options)
+ {
+ http.Response.Headers.CacheControl = "no-store";
+ if (string.IsNullOrEmpty(options.Token))
+ {
+ return Results.StatusCode(StatusCodes.Status404NotFound);
+ }
+
+ var header = http.Request.Headers.Authorization.ToString();
+ const string scheme = "Bearer ";
+ var presented = header.StartsWith(scheme, StringComparison.Ordinal) ? header[scheme.Length..] : string.Empty;
+ // Both sides are hashed first, so the comparison is over equal-length digests and says nothing about the token's length.
+ var matches = CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(presented)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Token)));
+ return matches && presented.Length > 0 ? null : Results.StatusCode(StatusCodes.Status401Unauthorized);
+ }
+
+ private static async Task<(Guid MergeId, AccountMergeNoticeKind Kind)?> ReadAckAsync(HttpRequest request, CancellationToken ct)
+ {
+ var buffer = new byte[MaxAckBodyBytes + 1];
+ var read = 0;
+ int n;
+ while (read < buffer.Length && (n = await request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0)
+ {
+ read += n;
+ }
+
+ if (read == 0 || read > MaxAckBodyBytes)
+ {
+ return null;
+ }
+
+ try
+ {
+ using var document = JsonDocument.Parse(buffer.AsMemory(0, read));
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object ||
+ !root.TryGetProperty("merge_id", out var id) || id.ValueKind != JsonValueKind.String || !Guid.TryParse(id.GetString(), out var mergeId) ||
+ !root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String)
+ {
+ return null;
+ }
+
+ AccountMergeNoticeKind? kind = type.GetString() switch
+ {
+ "merged" => AccountMergeNoticeKind.Merged,
+ "undone" => AccountMergeNoticeKind.Undone,
+ "final" => AccountMergeNoticeKind.Final,
+ _ => null
+ };
+ return kind is { } k ? (mergeId, k) : null;
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ /// The wire shape, exactly these keys: ids in format D, times ISO 8601 UTC, no email, display name, Heimdall id or Matrix id.
+ private static Dictionary Wire(MergeNotice notice) => new()
+ {
+ ["type"] = notice.Kind.ToString().ToLowerInvariant(),
+ ["merge_id"] = notice.MergeId.ToString("D"),
+ ["occurred_at"] = notice.OccurredAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
+ ["grace_ends_at"] = notice.GraceEndsAt?.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
+ ["old_subject"] = notice.OldSubject.ToString("D"),
+ ["new_subject"] = notice.NewSubject.ToString("D"),
+ ["old_preferred_username"] = notice.OldPreferredUsername,
+ ["new_preferred_username"] = notice.NewPreferredUsername
+ };
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs b/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
new file mode 100644
index 0000000..bc0fe05
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeNoticeFeed.cs
@@ -0,0 +1,96 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Membership;
+
+/// What the chat host is told about one merge. Derived from the merge row on every read; never stored.
+public sealed record MergeNotice(
+ AccountMergeNoticeKind Kind,
+ Guid MergeId,
+ DateTimeOffset OccurredAt,
+ DateTimeOffset? GraceEndsAt,
+ Guid OldSubject,
+ Guid NewSubject,
+ string OldPreferredUsername,
+ string NewPreferredUsername);
+
+///
+/// The one owner of what a notice reader is told about merges: merged (CommittedUtc), undone (UndoneUtc) and final (FinalizedUtc) are read off
+/// the AccountMerges row on every call, so a notice cannot disagree with the merge, and the reader's ack row is the only thing stored.
+/// Reads only AccountMerges and UserAccounts; writes only AccountMergeNoticeAck.
+///
+public sealed class MergeNoticeFeed(BifrostDbContext dbContext, TimeProvider timeProvider)
+{
+ public const int DefaultLimit = 50;
+ public const int MaxLimit = 200;
+
+ private static readonly AccountMergeNoticeKind[] Kinds = [AccountMergeNoticeKind.Merged, AccountMergeNoticeKind.Undone, AccountMergeNoticeKind.Final];
+
+ private static DateTimeOffset? OccurredAt(AccountMerge merge, AccountMergeNoticeKind kind) => kind switch
+ {
+ AccountMergeNoticeKind.Merged => merge.CommittedUtc,
+ AccountMergeNoticeKind.Undone => merge.UndoneUtc,
+ _ => merge.FinalizedUtc
+ };
+
+ /// Unacked notices for , oldest first by (occurred_at, merge_id, kind), strictly later than when given. Acks are the cursor; after only narrows the scan.
+ public async Task> ReadAsync(AccountMergeNoticeTarget target, DateTimeOffset? after, int? limit, CancellationToken cancellationToken)
+ {
+ var take = limit is > 0 ? Math.Min(limit.Value, MaxLimit) : DefaultLimit;
+ var picked = new List<(AccountMerge Merge, AccountMergeNoticeKind Kind, DateTimeOffset At)>();
+ // Each kind's own oldest `take` rows contain every row of the overall oldest `take`, so merging three bounded lists is exact.
+ foreach (var kind in Kinds)
+ {
+ var rows = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) != null)
+ .Where(x => after == null || (kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc) > after)
+ .Where(x => !dbContext.AccountMergeNoticeAcks.Any(a => a.MergeId == x.Id && a.Kind == kind && a.Target == target))
+ .OrderBy(x => kind == AccountMergeNoticeKind.Merged ? x.CommittedUtc : kind == AccountMergeNoticeKind.Undone ? x.UndoneUtc : x.FinalizedUtc)
+ .ThenBy(x => x.Id)
+ .Take(take)
+ .ToListAsync(cancellationToken);
+ picked.AddRange(rows.Select(x => (x, kind, OccurredAt(x, kind)!.Value)));
+ }
+
+ var page = picked.OrderBy(x => x.At).ThenBy(x => x.Merge.Id).ThenBy(x => x.Kind).Take(take).ToList();
+ var ids = page.SelectMany(x => new[] { x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId }).Distinct().ToList();
+ var names = await dbContext.UserAccounts.AsNoTracking().Where(x => ids.Contains(x.Id))
+ .Select(x => new { x.Id, x.NormalizedBifrostIdentity }).ToDictionaryAsync(x => x.Id, x => x.NormalizedBifrostIdentity, cancellationToken);
+ return [.. page.Select(x => new MergeNotice(
+ x.Kind, x.Merge.Id, x.At, x.Merge.GraceEndsUtc, x.Merge.FoldedUserAccountId, x.Merge.SurvivorUserAccountId,
+ names.GetValueOrDefault(x.Merge.FoldedUserAccountId, string.Empty), names.GetValueOrDefault(x.Merge.SurvivorUserAccountId, string.Empty)))];
+ }
+
+ /// Records that the reader has seen (merge, kind). False when the feed would not emit that notice now (no such merge, or its timestamp unset); true otherwise, a repeat included.
+ public async Task AckAsync(AccountMergeNoticeTarget target, Guid mergeId, AccountMergeNoticeKind kind, CancellationToken cancellationToken)
+ {
+ var merge = await dbContext.AccountMerges.AsNoTracking().SingleOrDefaultAsync(x => x.Id == mergeId, cancellationToken);
+ if (merge is null || OccurredAt(merge, kind) is null)
+ {
+ return false;
+ }
+
+ if (await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
+ {
+ return true;
+ }
+
+ dbContext.AccountMergeNoticeAcks.Add(new AccountMergeNoticeAck { MergeId = mergeId, Kind = kind, Target = target, AckedUtc = timeProvider.GetUtcNow() });
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // A concurrent ack of the same key won the unique index; the notice is acked, which is what the caller asked for.
+ dbContext.ChangeTracker.Clear();
+ if (!await dbContext.AccountMergeNoticeAcks.AnyAsync(x => x.MergeId == mergeId && x.Kind == kind && x.Target == target, cancellationToken))
+ {
+ throw;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergePreview.cs b/src/Bifrost.Web/Features/Membership/MergePreview.cs
new file mode 100644
index 0000000..d241a68
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergePreview.cs
@@ -0,0 +1,93 @@
+using Bifrost.Web.Domain;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The only wording of what a merge would do, in closed vocabulary: counts by entry kind and action from , the
+/// sentence for each block code, and the statements every merge carries. It decides nothing, and names no account: the plan holds none.
+///
+public static class MergePreview
+{
+ public static IReadOnlyList Lines(MergePlan plan)
+ {
+ var lines = new List();
+ foreach (var group in plan.Entries.GroupBy(x => (x.Kind, x.Action)))
+ {
+ var n = group.Count();
+ lines.Add(group.Key switch
+ {
+ (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "open vote")} of the other account on motions you did not vote on move to the kept account.",
+ (AccountMergeEntryKind.Vote, AccountMergeEntryAction.Voided) =>
+ $"{Count(n, "open vote")} of the other account are set aside: the kept account already voted on that motion or cannot vote.",
+ (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "appraisal")} of the other account move to the kept account.",
+ (AccountMergeEntryKind.ConceptAppraisal, AccountMergeEntryAction.Voided) =>
+ $"{Count(n, "appraisal")} of the other account are set aside: the kept account already appraised the same thing or cannot.",
+ (AccountMergeEntryKind.Membership, AccountMergeEntryAction.Closed) =>
+ "The other account's membership closes; the kept account's membership stays.",
+ (AccountMergeEntryKind.Standing, _) =>
+ "The kept account is suspended too, because the other account is.",
+ (AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved) =>
+ $"{Count(n, "patron event")} of the other account count for the kept account.",
+ _ => $"{Count(n, "other record")} change."
+ });
+ }
+
+ foreach (var (key, n) in plan.Left.OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ if (n > 0 && Remains(key) is { } noun)
+ {
+ lines.Add($"{Count(n, noun)} stay{(n == 1 ? "s" : string.Empty)} where {(n == 1 ? "it is" : "they are")}.");
+ }
+ }
+
+ if (lines.Count == 0)
+ {
+ lines.Add("No votes, appraisals or patron events change.");
+ }
+
+ return lines;
+ }
+
+ /// Why a pair cannot be merged, by the plan's block code. No account is named; a code this class does not know gets a generic line, never an echo.
+ public static string Block(string code) => code switch
+ {
+ "same_account" => "These are the same account.",
+ "account_missing" => "One of the accounts no longer exists.",
+ "mind_account" => "An account that belongs to a Mind cannot be merged.",
+ "native_account" => "An account without a Heimdall sign-in cannot be merged.",
+ "merge_in_flight" => "One of the accounts is already part of a merge that has not finished.",
+ "survivor_is_folded" => "The account you would keep was already merged into another account.",
+ "already_folded" => "The other account was already merged into another account.",
+ "folded_is_survivor" => "Another account was merged into the other account, so it cannot be folded in turn.",
+ "sealed_ballot_pending" => "The other account has a sealed ballot on an open motion; wait until it is revealed.",
+ _ => "These accounts cannot be merged now."
+ };
+
+ /// The block for two accounts that both hold a login of one provider, which Heimdall will not combine. Providers only: no account is named.
+ public static string ProviderConflict(IEnumerable providerNames) =>
+ $"Both accounts hold a {string.Join(" and ", providerNames)} login, and Heimdall will not combine two logins of one provider. Unlink one of them first, then prove that account again: the sign-in you gave still carries the old list of its logins.";
+
+ /// What every merge says, whatever the plan: what it cannot carry over, what it asks again, and how long it can be undone.
+ public static IReadOnlyList Statements { get; } =
+ [
+ "Chat: your chat history, rooms and keys belong to one chat id and cannot be moved. Keep the account you use in chat. Whichever you keep, the other chat id stays behind: rooms you were in on it must be joined again with the kept one, and messages encrypted for it cannot be read on the kept one.",
+ "Your connections (Twitch, Discord and others) will ask for consent again.",
+ "If you stream or moderate with StreamPixels and one of these connections is the one it uses for your channel, that connection stops until you reconnect it.",
+ "Roles and admin rights of the other account end; a steward must grant them again.",
+ "You will have one membership and one vote per motion: where both accounts voted on an open motion, the kept account's vote counts and the other is set aside. Nothing is added together.",
+ "You can undo this for 7 days, from Merge status. After that it is final.",
+ "The merge is approved with ordinary sign-ins, which is the weaker proof, and a notice stays on your account until the 7 days end."
+ ];
+
+ private static string Count(int n, string noun) => n == 1 ? $"1 {noun}" : $"{n} {noun}s";
+
+ private static string? Remains(string key) => key switch
+ {
+ "ConsentReceipts" => "consent record",
+ "PasskeyCredentials" => "passkey",
+ "LedgerEntries" => "ledger entry",
+ _ => null
+ };
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeProofs.cs b/src/Bifrost.Web/Features/Membership/MergeProofs.cs
new file mode 100644
index 0000000..86b45f4
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeProofs.cs
@@ -0,0 +1,238 @@
+using Bifrost.Web.Features.Heimdall;
+
+namespace Bifrost.Web.Features.Membership;
+
+public enum MergeSide
+{
+ /// The account signed in here.
+ Self,
+
+ /// The second account, proved by its own fresh sign-in.
+ Other
+}
+
+public enum PutOutcome
+{
+ Stored,
+ AmbiguousLogins,
+ TooManyProofs
+}
+
+/// What a page may know of one side: no bearer, no Heimdall account id, no login names.
+public sealed record MergeSideView(
+ Guid UserAccountId, IReadOnlyList ProvedProviders, IReadOnlyList LoginProviders, TimeSpan OldestProofAge, DateTimeOffset ExpiresAt);
+
+public sealed record MergeProofsView(MergeSideView? Self, MergeSideView? Other);
+
+public abstract record PeekResult
+{
+ private PeekResult()
+ {
+ }
+
+ public sealed record Ready(MergeProof Survivor, IReadOnlyList Folded) : PeekResult;
+
+ /// A side holds no live proof.
+ public sealed record Expired : PeekResult;
+
+ /// Logins whose provider has no live proof, by provider name only.
+ public sealed record LoginsUnproved(IReadOnlyList Providers) : PeekResult;
+
+ /// Both accounts hold a login of these providers, a pair Heimdall always refuses; by provider name only.
+ public sealed record ProviderConflict(IReadOnlyList Providers) : PeekResult;
+}
+
+public abstract record UndoPeekResult
+{
+ private UndoPeekResult()
+ {
+ }
+
+ public sealed record Ready(IReadOnlyList Proofs) : UndoPeekResult;
+
+ public sealed record Expired : UndoPeekResult;
+
+ public sealed record LoginsUnproved(IReadOnlyList Providers) : UndoPeekResult;
+}
+
+///
+/// The one holder of live Heimdall bearers between a merge-proof sign-in's completion and the page's call into the saga, keyed by the
+/// acting Bifrost account. It lives in this process's memory only and is never persisted, logged or sent to a browser; after a restart
+/// the member proves again. It decides nothing about the merge: the saga owns consent, the move and the lifecycle, and Heimdall judges
+/// each proof's tier and freshness. is only a margin under Heimdall's 300 s weak window, so a stale proof
+/// is not sent to fail a merge. Provider is the only proof bookkeeping Bifrost has (the redeem names the provider, not the identity),
+/// so a login list holding two logins of one provider is refused, and two sides holding a login of one provider are a conflict Peek names before consent. Every access, and the merge sweeper's tick, drops expired bearers. Peek never consumes: the caller s once the saga
+/// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof.
+///
+public sealed class MergeProofs(TimeProvider timeProvider)
+{
+ public static readonly TimeSpan ProofLifetime = TimeSpan.FromSeconds(270);
+
+ /// The saga's own bound on the proofs of one move.
+ public const int MaxProofsPerSide = 8;
+
+ private sealed record Held(MergeProof Proof, DateTimeOffset RedeemedAt);
+
+ private sealed class Side(Guid userAccountId, string heimdallAccountId)
+ {
+ public Guid UserAccountId { get; } = userAccountId;
+
+ public string HeimdallAccountId { get; } = heimdallAccountId;
+
+ public IReadOnlyList Logins { get; set; } = [];
+
+ public Dictionary Proofs { get; } = new(StringComparer.Ordinal);
+ }
+
+ private readonly Dictionary> _held = [];
+ private readonly object _gate = new();
+
+ public PutOutcome Put(Guid actorId, MergeSide side, MergeProof proof, Guid userAccountId, IReadOnlyList logins)
+ {
+ if (logins.GroupBy(x => x.Provider, StringComparer.Ordinal).Any(x => x.Count() > 1))
+ {
+ return PutOutcome.AmbiguousLogins;
+ }
+
+ lock (_gate)
+ {
+ var now = timeProvider.GetUtcNow();
+ Prune(now);
+ var sides = _held.TryGetValue(actorId, out var existing) ? existing : _held[actorId] = [];
+ if (!sides.TryGetValue(side, out var held) || held.UserAccountId != userAccountId || held.HeimdallAccountId != proof.HeimdallAccountId)
+ {
+ held = new Side(userAccountId, proof.HeimdallAccountId);
+ }
+
+ if (!held.Proofs.ContainsKey(proof.Provider) && held.Proofs.Count >= MaxProofsPerSide)
+ {
+ return PutOutcome.TooManyProofs;
+ }
+
+ held.Logins = logins;
+ held.Proofs[proof.Provider] = new Held(proof, now);
+ sides[side] = held;
+ return PutOutcome.Stored;
+ }
+ }
+
+ public MergeProofsView Snapshot(Guid actorId)
+ {
+ lock (_gate)
+ {
+ var now = timeProvider.GetUtcNow();
+ Prune(now);
+ var sides = _held.GetValueOrDefault(actorId);
+ return new MergeProofsView(View(sides, MergeSide.Self, now), View(sides, MergeSide.Other, now));
+ }
+ }
+
+ public PeekResult Peek(Guid actorId, MergeSide survivorSide)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ var sides = _held.GetValueOrDefault(actorId);
+ if (sides is null || !sides.TryGetValue(survivorSide, out var survivor)
+ || !sides.TryGetValue(survivorSide == MergeSide.Self ? MergeSide.Other : MergeSide.Self, out var folded))
+ {
+ return new PeekResult.Expired();
+ }
+
+ var shared = survivor.Logins.Select(x => x.Provider).Intersect(folded.Logins.Select(x => x.Provider), StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
+ if (shared.Length > 0)
+ {
+ return new PeekResult.ProviderConflict(shared);
+ }
+
+ var unproved = UnprovedProviders(folded, folded.Logins.Select(x => x.Provider));
+ return unproved.Count > 0
+ ? new PeekResult.LoginsUnproved(unproved)
+ : new PeekResult.Ready(survivor.Proofs.Values.MaxBy(x => x.RedeemedAt)!.Proof, [.. folded.Proofs.Values.Select(x => x.Proof)]);
+ }
+ }
+
+ /// The Self side's proofs for an undo, once every login whose id is in is proved.
+ public UndoPeekResult PeekUndo(Guid actorId, IReadOnlyCollection movedIdentityIds)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ if (!_held.TryGetValue(actorId, out var sides) || !sides.TryGetValue(MergeSide.Self, out var self))
+ {
+ return new UndoPeekResult.Expired();
+ }
+
+ var needed = self.Logins.Where(x => movedIdentityIds.Contains(x.Id)).Select(x => x.Provider).ToArray();
+ var unproved = UnprovedProviders(self, needed);
+ if (needed.Length < movedIdentityIds.Count)
+ {
+ // A moved login the list does not hold cannot be proved by it.
+ return new UndoPeekResult.LoginsUnproved(unproved);
+ }
+
+ return unproved.Count > 0
+ ? new UndoPeekResult.LoginsUnproved(unproved)
+ : new UndoPeekResult.Ready([.. needed.Distinct(StringComparer.Ordinal).Select(x => self.Proofs[x].Proof)]);
+ }
+ }
+
+ public void Clear(Guid actorId)
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ _held.Remove(actorId);
+ }
+ }
+
+ /// Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives plus one tick.
+ public void PruneExpired()
+ {
+ lock (_gate)
+ {
+ Prune(timeProvider.GetUtcNow());
+ }
+ }
+
+ private static List UnprovedProviders(Side side, IEnumerable providers) =>
+ [.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))];
+
+ private MergeSideView? View(Dictionary? sides, MergeSide which, DateTimeOffset now) =>
+ sides is not null && sides.TryGetValue(which, out var side)
+ ? new MergeSideView(
+ side.UserAccountId,
+ [.. side.Proofs.Keys],
+ [.. side.Logins.Select(x => x.Provider)],
+ now - side.Proofs.Values.Min(x => x.RedeemedAt),
+ side.Proofs.Values.Min(x => x.RedeemedAt) + ProofLifetime)
+ : null;
+
+ /// Drops every proof at or past its lifetime, then every side without one, then every actor without a side.
+ private void Prune(DateTimeOffset now)
+ {
+ foreach (var (actor, sides) in _held.ToArray())
+ {
+ foreach (var (which, side) in sides.ToArray())
+ {
+ foreach (var (provider, held) in side.Proofs.ToArray())
+ {
+ if (now - held.RedeemedAt >= ProofLifetime)
+ {
+ side.Proofs.Remove(provider);
+ }
+ }
+
+ if (side.Proofs.Count == 0)
+ {
+ sides.Remove(which);
+ }
+ }
+
+ if (sides.Count == 0)
+ {
+ _held.Remove(actor);
+ }
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Features/Membership/MergeWording.cs b/src/Bifrost.Web/Features/Membership/MergeWording.cs
new file mode 100644
index 0000000..9d6984d
--- /dev/null
+++ b/src/Bifrost.Web/Features/Membership/MergeWording.cs
@@ -0,0 +1,114 @@
+using System.Globalization;
+using Bifrost.Web.Domain;
+
+namespace Bifrost.Web.Features.Membership;
+
+///
+/// The one closed set of words the merge pages say, so no page ever prints what the store holds: a state, a Heimdall refusal code, a
+/// saga outcome and an undo answer each map to a sentence here, and anything this class does not know gets a generic line, never an
+/// echo. Dates are UTC.
+///
+public static class MergeWording
+{
+ public static string State(AccountMergeState state) => state switch
+ {
+ AccountMergeState.Proposed => "Proposed, not yet confirmed.",
+ AccountMergeState.Confirmed => "Confirmed; Heimdall has not yet moved the logins.",
+ AccountMergeState.HeimdallMoved => "The logins have moved; Bifrost is finishing the merge.",
+ AccountMergeState.Committed => "Merged. You can still undo it.",
+ AccountMergeState.Final => "Merged for good; the undo window has ended.",
+ AccountMergeState.UndoRequested => "Undo requested; the logins are being given back.",
+ AccountMergeState.HeimdallReversed => "The logins are back; Bifrost is restoring the accounts.",
+ AccountMergeState.Undone => "Undone; the accounts are separate again.",
+ AccountMergeState.Failed => "The merge did not happen and nothing was merged.",
+ _ => "In an unknown state."
+ };
+
+ /// Why Heimdall refused a merge, by its refusal code; null for a code this class does not know.
+ public static string? Failure(string code) => code switch
+ {
+ "app_auth_required" or "not_allowed_for_app" => "Heimdall would not take Bifrost's request.",
+ "not_reversible" => "Heimdall says those logins cannot be moved back.",
+ "proof_invalid" => "Heimdall did not accept a sign-in as proof.",
+ "same_account" => "Both sides were the same Heimdall account.",
+ "proof_stale" => "A sign-in was too old by the time Heimdall saw it.",
+ "identity_not_proved" => "A login was not proved by a fresh sign-in.",
+ "already_moved" => "Heimdall had already moved one of those logins.",
+ "provider_conflict" => "Both accounts hold a login of the same provider, which Heimdall will not combine.",
+ "identity_not_found" => "A login was no longer on its account.",
+ "invalid_request" => "Heimdall could not read the request.",
+ _ => null
+ };
+
+ /// The saga's last note on a merge, in words. Always a sentence: an outcome this class does not know is a retry line, never its own text.
+ public static string Outcome(string lastOutcome) => lastOutcome switch
+ {
+ "confirmed" => "Waiting for Heimdall to move the logins.",
+ "moved" => "Heimdall moved the logins.",
+ "refused" => "Heimdall refused the merge.",
+ "undo_requested" => "Waiting for Heimdall to give the logins back.",
+ "operator_failed" => "A steward ended this merge. Nothing was merged.",
+ "undo_operator_abandoned" => "A steward ended the undo, so the merge stands.",
+ "receipt_mismatch" => "Heimdall's answer did not match the merge. An operator must look at it.",
+ "proofs_unreadable" => "The stored proofs cannot be read. An operator must look at it.",
+ "transport" or "move_id_conflict" or "malformed or mismatched receipt" => "Heimdall could not be reached or gave an answer Bifrost could not use. It will try again.",
+ _ when lastOutcome.StartsWith("undo_", StringComparison.Ordinal) && Failure(lastOutcome["undo_".Length..]) is { } reason =>
+ "Heimdall refused the undo, so the merge stands. " + reason,
+ _ => "Waiting to try again."
+ };
+
+ /// The words for a closed undo code ( or logins_unproved ); empty for anything else.
+ public static string Undo(string code) => code switch
+ {
+ "requested" => "Undo requested. The logins are being given back.",
+ "not_committed" => "This merge is not in a state that can be undone.",
+ "grace_over" => "The undo window has ended.",
+ "not_survivor" => "Only the account the merge kept can undo it.",
+ "proof_account_mismatch" => "That sign-in was not for this account. Nothing was changed.",
+ "logins_unproved" => "Every login that moved needs a fresh sign-in first. Nothing was changed.",
+ _ => string.Empty
+ };
+
+ /// The words for a closed code the merge page answers a confirm or a start with; empty for anything else.
+ public static string Confirm(string code) => code switch
+ {
+ "blocked" => "These accounts cannot be merged now. Nothing was changed.",
+ "preview_stale" => "Something changed since you looked; review the merge again. Nothing was changed and your sign-ins are kept.",
+ "not_party" => "Only one of the two accounts can confirm this merge. Nothing was changed.",
+ "proof_account_mismatch" => "A sign-in was not for the account it was meant for. Nothing was changed.",
+ "proofs_needed" => "Both accounts need a fresh sign-in, one for every login of the account that would be folded. Nothing was changed.",
+ "consent_needed" => "Tick both boxes to confirm. Nothing was changed.",
+ "bad_choice" => "Choose which account to keep. Nothing was changed.",
+ _ => string.Empty
+ };
+
+ public static string UndoCode(UndoOutcome outcome) => outcome switch
+ {
+ UndoOutcome.Requested => "requested",
+ UndoOutcome.NotCommitted => "not_committed",
+ UndoOutcome.GraceOver => "grace_over",
+ UndoOutcome.NotSurvivor => "not_survivor",
+ UndoOutcome.ProofAccountMismatch => "proof_account_mismatch",
+ _ => "not_committed"
+ };
+
+ public static string TierNote(string? fromTier, DateTimeOffset graceEnds) => fromTier == "strong"
+ ? $"Approved with a passkey; you have until {Date(graceEnds)} to undo."
+ : $"Approved with ordinary sign-ins; you have until {Date(graceEnds)} to undo.";
+
+ /// Whole days from to , rounded up, at least one while the window is open.
+ public static int DaysUntil(DateTimeOffset end, DateTimeOffset now) => Math.Max(1, (int)Math.Ceiling((end - now).TotalDays));
+
+ public static string DaysLeft(int days) => days == 1 ? "1 day left" : $"{days} days left";
+
+ public static string SurvivorNotice(int days) => $"A merge into your account can still be undone: {DaysLeft(days)}. Review it on Merge status.";
+
+ public static string UndoRequestedNotice() => "A merge into your account is being undone: Heimdall is giving the logins back. Review it on Merge status.";
+
+ public static string FrozenNotice() => "A merge is in progress; you cannot act until it settles.";
+
+ public static string FoldedNotice(DateTimeOffset mergedOn) =>
+ $"This account was merged on {Date(mergedOn)}; sign in with a login you had on it to reach the account that holds them.";
+
+ public static string Date(DateTimeOffset when) => when.UtcDateTime.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + " UTC";
+}
diff --git a/src/Bifrost.Web/Features/Motions/MindIntakeService.cs b/src/Bifrost.Web/Features/Motions/MindIntakeService.cs
new file mode 100644
index 0000000..0b111fb
--- /dev/null
+++ b/src/Bifrost.Web/Features/Motions/MindIntakeService.cs
@@ -0,0 +1,277 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Org.BouncyCastle.Math.EC.Rfc8032;
+
+namespace Bifrost.Web.Features.Motions;
+
+///
+/// Signed intake for Minds. A Mind holds an Ed25519 private key; Bifrost holds only registered public keys. The signature,
+/// not a session, is the credential: a verified envelope is handed to as the Mind's member
+/// account, so Minds and members share one set of rules. Registration and revocation are moderator acts and are audited.
+///
+public sealed class MindIntakeService(
+ BifrostDbContext dbContext,
+ SealedBallotService sealedBallots,
+ AuditTrailService auditTrailService,
+ TimeProvider timeProvider)
+{
+ public const string Domain = "gamecult.sealed_intake.v0";
+ public static readonly TimeSpan Skew = TimeSpan.FromMinutes(10);
+
+ // Diagnostics: every Ed25519 verification the intake performs, real or dummy. A refusal that skips the verify is a timing tell.
+ public static long SignatureChecks;
+
+ // A valid signature by a throwaway key over a different message: verifying it does the full work and fails at the end.
+ private static readonly (byte[] Public, byte[] Signature, byte[] Message) Dummy = MakeDummy();
+
+ private static (byte[], byte[], byte[]) MakeDummy()
+ {
+ var secret = new byte[32];
+ System.Security.Cryptography.RandomNumberGenerator.Fill(secret);
+ var pub = new byte[32];
+ Ed25519.GeneratePublicKey(secret, 0, pub, 0);
+ var message = Encoding.UTF8.GetBytes("dummy");
+ var sig = new byte[64];
+ Ed25519.Sign(secret, 0, pub, 0, null, message, 0, message.Length, sig, 0);
+ return (pub, sig, Encoding.UTF8.GetBytes("not the dummy message"));
+ }
+
+ private static bool Verify(byte[] signature, byte[] publicKey, byte[] message)
+ {
+ Interlocked.Increment(ref SignatureChecks);
+ return Ed25519.Verify(signature, 0, publicKey, 0, message, 0, message.Length);
+ }
+ private static readonly Regex PersonaPattern = new(@"^[a-z0-9][a-z0-9-]{0,31}\z", RegexOptions.Compiled);
+ private static readonly Regex NoncePattern = new(@"^[A-Za-z0-9_-]{16,64}\z", RegexOptions.Compiled);
+
+ public async Task RegisterKeyAsync(
+ CurrentBifrostActor actor, string persona, Guid userAccountId, string publicKey, CancellationToken cancellationToken)
+ {
+ var moderator = RequireModerator(actor);
+ persona = (persona ?? string.Empty).Trim();
+ if (!PersonaPattern.IsMatch(persona))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "A persona id is 1-32 lowercase letters, digits or hyphens.");
+ }
+
+ if (!TryKey(publicKey, out _))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "A public key is the base64 of 32 bytes (Ed25519).");
+ }
+
+ var account = await dbContext.UserAccounts.Include(x => x.Membership).SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
+ if (account?.Membership?.Status != MembershipStatus.Active)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The persona's member account must exist and be Active.");
+ }
+
+ // One persona <-> one account, both ways (a shared account would let one persona overwrite the other's commit).
+ // The unique indexes on MindPersonas are the arbiter; these reads only give a plain error before them.
+ var binding = await dbContext.MindPersonas.SingleOrDefaultAsync(x => x.PersonaId == persona || x.UserAccountId == userAccountId, cancellationToken);
+ if (binding is not null && (binding.PersonaId != persona || binding.UserAccountId != userAccountId))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "That persona or member account is already bound to a different account or persona.");
+ }
+
+ if (await dbContext.MindKeys.AnyAsync(x => x.PersonaId == persona && x.PublicKey == publicKey, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That key is already registered for the persona.");
+ }
+
+ var key = new MindKey
+ {
+ PersonaId = persona, UserAccountId = userAccountId, PublicKey = publicKey,
+ RegisteredByUserAccountId = moderator.Id, RegisteredAtUtc = timeProvider.GetUtcNow()
+ };
+ dbContext.MindKeys.Add(key);
+ if (binding is null)
+ {
+ dbContext.MindPersonas.Add(new MindPersona { PersonaId = persona, UserAccountId = userAccountId });
+ }
+
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException) when (binding is null)
+ {
+ // Lost a registration race on the unique persona/account indexes.
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "That persona or member account is already bound to a different account or persona.");
+ }
+
+ await auditTrailService.RecordAsync(moderator.Id, nameof(MindKey), key.Id, "mindkey.registered",
+ $"Registered a key for persona {persona} (member account {userAccountId}).", cancellationToken);
+ return View(key);
+ }
+
+ public async Task RevokeKeyAsync(CurrentBifrostActor actor, Guid keyId, CancellationToken cancellationToken)
+ {
+ var moderator = RequireModerator(actor);
+ var key = await dbContext.MindKeys.SingleOrDefaultAsync(x => x.Id == keyId, cancellationToken)
+ ?? throw new SealedBallotException(SealedBallotFailure.NotFound, "No such key.");
+ if (key.RevokedAtUtc is not null)
+ {
+ return;
+ }
+
+ key.RevokedAtUtc = timeProvider.GetUtcNow();
+ key.RevokedByUserAccountId = moderator.Id;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ await auditTrailService.RecordAsync(moderator.Id, nameof(MindKey), key.Id, "mindkey.revoked",
+ $"Revoked a key for persona {key.PersonaId}.", cancellationToken);
+ }
+
+ public async Task> ListKeysAsync(CurrentBifrostActor actor, CancellationToken cancellationToken)
+ {
+ RequireModerator(actor);
+ return (await dbContext.MindKeys.AsNoTracking().OrderBy(x => x.PersonaId).ThenBy(x => x.RegisteredAtUtc).ToListAsync(cancellationToken))
+ .Select(View).ToList();
+ }
+
+ /// Verifies the envelope, spends its nonce, then runs the verb as the persona's member account.
+ public async Task HandleAsync(Guid routeMotionId, MindEnvelope envelope, CancellationToken cancellationToken)
+ {
+ var persona = envelope.Persona ?? string.Empty;
+ if (!PersonaPattern.IsMatch(persona) || envelope.Verb is not ("commit" or "reveal") || !NoncePattern.IsMatch(envelope.Nonce ?? string.Empty) ||
+ new[] { envelope.Commitment, envelope.Candidate, envelope.Reason, envelope.Salt }.Any(f => (f ?? string.Empty).AsSpan().IndexOfAny('\n', '\r') >= 0))
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope is malformed.");
+ }
+
+ // Signature first. Every path below that can tell a caller anything about state comes after a verified signature, and
+ // every refusal before it costs one Ed25519 verification (a dummy one when there is no key or no usable signature).
+ var keys = await dbContext.MindKeys.AsNoTracking().Where(x => x.PersonaId == persona && x.RevokedAtUtc == null).ToListAsync(cancellationToken);
+ var message = Encoding.UTF8.GetBytes(SigningText(envelope));
+ var raw = new byte[64];
+ var wellFormed = Convert.TryFromBase64String(envelope.Signature ?? string.Empty, raw, out var written) && written == 64;
+ MindKey? signer = null;
+ if (!wellFormed || keys.Count == 0)
+ {
+ _ = Verify(Dummy.Signature, Dummy.Public, Dummy.Message);
+ }
+ else
+ {
+ signer = keys.FirstOrDefault(k => TryKey(k.PublicKey, out var pub) && Verify(raw, pub, message));
+ }
+
+ if (signer is null)
+ {
+ // One answer for unknown persona, revoked key, wrong key and bad signature: nothing to probe.
+ throw new SealedBallotException(SealedBallotFailure.Unauthorized, "The envelope is not signed by a registered key for that persona.");
+ }
+
+ if (envelope.MotionId != routeMotionId)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope was signed for a different motion.");
+ }
+
+ var now = timeProvider.GetUtcNow();
+ if (Math.Abs((now - DateTimeOffset.FromUnixTimeSeconds(Math.Clamp(envelope.IssuedAt, 0, 253402300799))).TotalSeconds) > Skew.TotalSeconds)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Invalid, "The envelope is outside the accepted clock window.");
+ }
+
+ // Spend the nonce only after the signature verifies, so an unsigned caller cannot burn a persona's nonces. Nonces older
+ // than twice the skew can no longer pass the window above, so they are pruned here.
+ if (await dbContext.MindNonces.AnyAsync(x => x.PersonaId == persona && x.Nonce == envelope.Nonce, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That nonce was already used.");
+ }
+
+ // Pruning is housekeeping and runs apart from the write that spends the nonce: two requests can load and delete the same
+ // expired rows, and the loser's concurrency exception must never fail a valid request.
+ try
+ {
+ var cutoff = now - 2 * Skew;
+ dbContext.MindNonces.RemoveRange(await dbContext.MindNonces.Where(x => x.SeenAtUtc < cutoff).ToListAsync(cancellationToken));
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ dbContext.ChangeTracker.Clear();
+ }
+
+ dbContext.MindNonces.Add(new MindNonce { PersonaId = persona, Nonce = envelope.Nonce!, SeenAtUtc = now });
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateException)
+ {
+ // A replay only if the nonce is now there (the unique index lost a race); any other write failure is a fault, not a replay.
+ dbContext.ChangeTracker.Clear();
+ if (await dbContext.MindNonces.AnyAsync(x => x.PersonaId == persona && x.Nonce == envelope.Nonce, cancellationToken))
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "That nonce was already used.");
+ }
+
+ throw;
+ }
+
+ var account = await dbContext.UserAccounts.AsNoTracking()
+ .Include(x => x.MemberProfile)
+ .Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots)
+ .SingleAsync(x => x.Id == signer.UserAccountId, cancellationToken);
+ var actor = new CurrentBifrostActor(true, account);
+
+ return envelope.Verb == "commit"
+ ? await sealedBallots.CommitAsync(actor, routeMotionId, envelope.Commitment ?? string.Empty, cancellationToken)
+ : await sealedBallots.RevealAsync(actor, routeMotionId,
+ new SealedBallotDocument(SealedBallotDocument.SchemaId, routeMotionId, envelope.Round, envelope.Candidate ?? string.Empty,
+ envelope.Reason ?? string.Empty, envelope.Salt ?? string.Empty, persona),
+ cancellationToken, persona);
+ }
+
+ /// The exact text a Mind signs: every field, fixed order, newline separated, unused fields empty.
+ public static string SigningText(MindEnvelope e) =>
+ string.Join('\n', Domain, e.Persona, e.Verb, e.MotionId.ToString("D"), e.Nonce, e.IssuedAt, e.Commitment ?? "", e.Round, e.Candidate ?? "", e.Reason ?? "", e.Salt ?? "");
+
+ private static bool TryKey(string base64, out byte[] key)
+ {
+ key = new byte[32];
+ return Convert.TryFromBase64String(base64 ?? string.Empty, key, out var n) && n == 32;
+ }
+
+ private static UserAccount RequireModerator(CurrentBifrostActor actor) =>
+ actor is { IsActiveMember: true, CanModerateMotions: true, UserAccount: { } user }
+ ? user
+ : throw new SealedBallotException(SealedBallotFailure.Forbidden, "Only a moderator manages Mind keys.");
+
+ private static MindKeyView View(MindKey k) => new(k.Id, k.PersonaId, k.UserAccountId, k.PublicKey, k.RegisteredAtUtc, k.RevokedAtUtc);
+}
+
+/// A signed Mind verb. Signature is base64 Ed25519 over .
+public sealed record MindEnvelope(
+ string Persona, string Verb, Guid MotionId, string Nonce, long IssuedAt,
+ string? Commitment, int Round, string? Candidate, string? Reason, string? Salt, string Signature);
+
+public sealed record MindKeyView(Guid Id, string Persona, Guid UserAccountId, string PublicKey, DateTimeOffset RegisteredAtUtc, DateTimeOffset? RevokedAtUtc);
+
+public sealed record RegisterMindKeyRequest(string Persona, Guid UserAccountId, string PublicKey);
+
+/// Limits on the anonymous signed-intake endpoint (section "MindIntake").
+public sealed class MindIntakeOptions
+{
+ public const string SectionName = "MindIntake";
+
+ public int Permits { get; init; } = 30;
+
+ public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1);
+
+ public int MaxTrackedKeys { get; init; } = 10_000;
+
+ public int MaxBodyBytes { get; init; } = 4096;
+}
+
+/// Per-source permit budget for the intake, on the shared . Spent before the body is read.
+public sealed class MindIntakeRateLimit(Microsoft.Extensions.Options.IOptions options, TimeProvider clock)
+{
+ private readonly FixedWindowBudget budget = new(options.Value.Permits, options.Value.Window, options.Value.MaxTrackedKeys, clock);
+
+ public BudgetDenial? Spend(string source) => budget.Spend(source);
+}
diff --git a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
index 8c10dcf..ba60a2f 100644
--- a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
+++ b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs
@@ -1,5 +1,6 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
@@ -52,37 +53,54 @@ public sealed class MotionGovernanceService(
CancellationToken cancellationToken)
{
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
+
var motion = await dbContext.Motions
.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;
}
- var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
- if (vote is null)
+ // An actor resolved before a merge froze this account must not write a vote after it: the write gate reads standing at the write.
+ var wrote = await AccountMergeLedger.WriteAsAsync(dbContext, actorUser.Id, async standing =>
{
- dbContext.Votes.Add(new Vote
+ if (standing is not null)
{
- MotionId = motionId,
- UserAccountId = actorUser.Id,
- Choice = choice,
- Weight = actor.EffectiveVotingWeight,
- Comment = comment?.Trim() ?? string.Empty,
- CastAtUtc = timeProvider.GetUtcNow()
- });
- }
- else
+ return false;
+ }
+
+ var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
+ if (vote is null)
+ {
+ dbContext.Votes.Add(new Vote
+ {
+ MotionId = motionId,
+ UserAccountId = actorUser.Id,
+ Choice = choice,
+ Weight = actor.EffectiveVotingWeight,
+ Comment = comment?.Trim() ?? string.Empty,
+ CastAtUtc = timeProvider.GetUtcNow()
+ });
+ }
+ else
+ {
+ vote.Choice = choice;
+ vote.Weight = actor.EffectiveVotingWeight;
+ vote.Comment = comment?.Trim() ?? string.Empty;
+ vote.CastAtUtc = timeProvider.GetUtcNow();
+ }
+
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return true;
+ }, cancellationToken);
+
+ if (!wrote)
{
- vote.Choice = choice;
- vote.Weight = actor.EffectiveVotingWeight;
- vote.Comment = comment?.Trim() ?? string.Empty;
- vote.CastAtUtc = timeProvider.GetUtcNow();
+ return;
}
- await dbContext.SaveChangesAsync(cancellationToken);
await auditTrailService.RecordAsync(
actorUser.Id,
nameof(Motion),
@@ -102,6 +120,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.");
@@ -121,7 +144,21 @@ public sealed class MotionGovernanceService(
? $"Closed with {votesFor:0.##} for and {votesAgainst:0.##} against at a {motion.ApprovalThreshold:P0} threshold."
: "Closed without decisive votes.";
- await dbContext.SaveChangesAsync(cancellationToken);
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ // Status is a concurrency token: another closer won. Adopt its result and record nothing a second time.
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ return;
+ }
+
await auditTrailService.RecordAsync(
actorUser.Id,
nameof(Motion),
@@ -140,6 +177,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);
diff --git a/src/Bifrost.Web/Features/Motions/SealedBallotService.cs b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs
new file mode 100644
index 0000000..7fc3af0
--- /dev/null
+++ b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs
@@ -0,0 +1,462 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace Bifrost.Web.Features.Motions;
+
+///
+/// Sealed-ballot motions: commit, then reveal, then one atomic publication at close.
+/// This is the only code that reads ,
+/// or ; a test fails if any other source file mentions them.
+///
+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}\z", RegexOptions.Compiled);
+ private static readonly Regex HexSalt = new(@"^[0-9a-f]{32,128}\z", RegexOptions.Compiled);
+
+ public async Task 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 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 AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
+ {
+ RequireStanding(standing);
+ var written = await dbContext.SealedBallots
+ .SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
+ if (written is null)
+ {
+ written = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
+ dbContext.SealedBallots.Add(written);
+ }
+ else
+ {
+ written.Revision++;
+ }
+
+ written.Commitment = commitment;
+ written.CommittedAtUtc = now;
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return written;
+ }, 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 RevealAsync(
+ CurrentBifrostActor actor,
+ Guid motionId,
+ SealedBallotDocument document,
+ CancellationToken cancellationToken,
+ string persona = "")
+ {
+ 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.Persona ?? string.Empty) != persona || 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.");
+ }
+
+ // RevealSeq and Status are concurrency tokens. A conflict means either the close froze the set (refuse, truthfully) or
+ // another voter's reveal landed first while the window is still open (re-read the row and write again).
+ // Standing is read once, under the gate's lock, which holds across every attempt: a merge cannot freeze the account between them.
+ await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing =>
+ {
+ RequireStanding(standing);
+ for (var attempt = 0; ; attempt++)
+ {
+ ballot.RevealedCandidate = candidate;
+ ballot.RevealedReason = reason;
+ ballot.Salt = document.Salt;
+ ballot.RevealedAtUtc = now;
+ motion.RevealSeq++;
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ break;
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ if (PhaseOf(motion, now) != SealedPhase.Reveal)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over.");
+ }
+
+ if (attempt >= 4)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again.");
+ }
+ }
+ }
+
+ return true;
+ }, 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);
+ }
+
+ /// Phase, times and the caller's own commitment status. Never another member's ballot, never revealed content.
+ public async Task 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);
+ }
+
+ /// Finalizes the motion if its deadline has passed, then publishes every ballot at once. Before close it refuses.
+ public async Task 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.");
+ }
+
+ // Freeze: the close counts the reveals it read and succeeds only if no reveal landed since (RevealSeq is a concurrency
+ // token); a conflict re-reads and retries, so the digest always covers exactly the set that is published.
+ for (var attempt = 0; motion.Status == MotionStatus.Open && attempt < 5; attempt++)
+ {
+ var frozen = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motionId).ToListAsync(cancellationToken);
+ if (await FinalizeAsync(motion, frozen, now, cancellationToken))
+ {
+ break;
+ }
+ }
+
+ if (motion.Status == MotionStatus.Open)
+ {
+ throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The close is contended; read again.");
+ }
+
+ var ballots = await dbContext.SealedBallots.AsNoTracking()
+ .Include(x => x.UserAccount).ThenInclude(x => x.MemberProfile)
+ .Where(x => x.MotionId == motionId)
+ .ToListAsync(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;
+
+ ///
+ /// Closes the motion once. Motion.Status is a concurrency token, so of two racing closers exactly one SaveChanges wins;
+ /// the loser reloads the winner's result and writes nothing (no second audit event).
+ ///
+ private async Task FinalizeAsync(Motion motion, List ballots, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ var lines = ballots.OrderBy(x => x.UserAccountId)
+ .Select(x => $"{x.UserAccountId:D}:{x.Commitment}:{(x.RevealedAtUtc != null ? "revealed" : "unrevealed")}")
+ .Prepend($"reveals:{motion.RevealSeq}");
+ 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.";
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException error)
+ {
+ foreach (var entry in error.Entries)
+ {
+ await entry.ReloadAsync(cancellationToken);
+ }
+
+ return motion.Status != MotionStatus.Open;
+ }
+
+ await auditTrailService.RecordAsync(
+ null, nameof(Motion), motion.Id, "sealed.closed",
+ $"Closed sealed-ballot motion {motion.Title}; commitment digest {motion.ResultDigest}.",
+ cancellationToken);
+ return true;
+ }
+
+ /// Closes every sealed-ballot motion whose deadline has passed, so a motion nobody reads still closes.
+ public async Task FinalizeDueAsync(CancellationToken cancellationToken)
+ {
+ var now = timeProvider.GetUtcNow();
+ var due = await dbContext.Motions
+ .Where(x => x.Kind == MotionKind.SealedBallot && x.Status == MotionStatus.Open && x.ClosesAtUtc <= now)
+ .ToListAsync(cancellationToken);
+ foreach (var motion in due)
+ {
+ var ballots = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync(cancellationToken);
+ await FinalizeAsync(motion, ballots, now, cancellationToken);
+ }
+
+ return due.Count;
+ }
+
+ 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 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 CandidatesOf(Motion motion) => motion.Candidates.Split('\n');
+
+ private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName;
+
+ // A member resolved before a merge froze the account must not write a ballot after it: the write gate reads standing at the write.
+ private static void RequireStanding(MergeStanding? standing)
+ {
+ if (standing is not null)
+ {
+ throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
+ }
+ }
+
+ 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, Unauthorized }
+
+public sealed class SealedBallotException(SealedBallotFailure failure, string message) : Exception(message)
+{
+ public SealedBallotFailure Failure { get; } = failure;
+}
+
+///
+/// The typed ballot document, schema gamecult.sealed_ballot.v0 . A Delphi second round is another motion carrying this
+/// same type with a higher Round. The commitment binds the voter's account id and, for a Mind casting through the signed intake, its persona id (empty for member casts), so a commitment cannot be replayed by another member or persona.
+///
+public sealed record SealedBallotDocument(string Schema, Guid MotionId, int Round, string Candidate, string Reason, string Salt, string Persona = "")
+{
+ 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.Persona}\n{d.Round}\n{d.Candidate}\n{d.Reason}\n{d.Salt}"))).ToLowerInvariant();
+}
+
+public sealed record OpenSealedMotionCommand(
+ string Title,
+ string Summary,
+ IReadOnlyList 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 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 Tally, IReadOnlyList Leaders, string Outcome,
+ IReadOnlyList Ballots, IReadOnlyList Unrevealed, IReadOnlyList NonVoters,
+ string CommitmentDigest);
+public sealed record SealedCommitRequest(string Commitment);
+
+/// Sweeps due sealed-ballot motions once a minute. Reads also close on demand; this covers a motion nobody reads.
+public sealed class SealedBallotCloser(IServiceScopeFactory scopes, ILogger logger) : BackgroundService
+{
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
+ do
+ {
+ try
+ {
+ using var scope = scopes.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(stoppingToken);
+ }
+ catch (Exception error) when (error is not OperationCanceledException)
+ {
+ logger.LogWarning(error, "Sealed-ballot close sweep failed; retrying next tick.");
+ }
+ }
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs
index edf1dd3..c393afd 100644
--- a/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs
+++ b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs
@@ -14,10 +14,17 @@ public sealed class OidcClientSeeder(
IServiceScopeFactory scopeFactory,
OidcIssuerOptions options,
OidcKeyMaterial material,
- IOptions serverOptions) : IHostedService
+ IOptions serverOptions,
+ ILogger logger) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
+ if (string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri))
+ {
+ logger.LogWarning(
+ "Bifrost:Oidc:Clients:Mas:BackchannelLogoutUri is not set: suspending an account stops new sign-ins and token refresh but does not end its existing chat sessions.");
+ }
+
// Reading the server options now runs their configuration, so a bad issuer stops startup rather than the first request.
_ = serverOptions.Value;
diff --git a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs
index b435347..1fc0628 100644
--- a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs
+++ b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs
@@ -2,6 +2,9 @@ using System.Security.Claims;
using Microsoft.AspNetCore;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Desk;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Registration;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication;
@@ -19,8 +22,11 @@ namespace Bifrost.Web.Features.Oidc;
///
public static class OidcEndpoints
{
- public const string NotActiveDescription = "The account is not an active GameCult member.";
+ public const string SuspendedDescription = "The account is suspended.";
+ public const string MergedDescription = "The account is part of an account merge and can no longer sign in.";
public const string NoIdentityDescription = "The account has no Bifrost identity.";
+ public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
+ public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
private const string OpenIddictScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
private const string IdentityAuthenticationType = "Bifrost.Oidc";
@@ -32,7 +38,7 @@ public static class OidcEndpoints
app.MapMethods(OidcServiceCollectionExtensions.UserInfoPath, ["GET", "POST"], (Delegate)UserInfoAsync).AllowAnonymous();
}
- private static async Task AuthorizeAsync(HttpContext http, ICurrentBifrostActorAccessor actors)
+ private static async Task AuthorizeAsync(HttpContext http, ICurrentBifrostActorAccessor actors, BifrostDbContext db)
{
var request = http.GetOpenIddictServerRequest()
?? throw new InvalidOperationException("The OpenIddict request could not be retrieved.");
@@ -47,9 +53,16 @@ public static class OidcEndpoints
}
var actor = await actors.GetAsync(http.RequestAborted);
- if (actor.UserAccount is null || !actor.IsActiveMember)
+ // Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written;
+ // every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
+ if (actor.UserAccount is null)
{
- return Deny(Errors.AccessDenied, NotActiveDescription);
+ return Deny(Errors.AccessDenied, actor.Merge is not null ? MergedDescription : NoIdentityDescription);
+ }
+
+ if (actor.Membership?.Status == MembershipStatus.Suspended)
+ {
+ return Deny(Errors.AccessDenied, SuspendedDescription);
}
var account = actor.UserAccount;
@@ -58,6 +71,13 @@ public static class OidcEndpoints
return Deny(Errors.AccessDenied, NoIdentityDescription);
}
+ // The identity becomes the Matrix localpart. Creation refuses reserved names (BifrostIdentityService), but a row minted
+ // before that refusal may hold one, and there is no rename path: the issuer never vouches for a Mind's or a system's localpart.
+ if (BifrostIdentityService.IsReserved(account.NormalizedBifrostIdentity))
+ {
+ return Deny(Errors.AccessDenied, ReservedIdentityDescription);
+ }
+
var identity = new ClaimsIdentity(IdentityAuthenticationType, Claims.Name, Claims.Role);
identity.SetClaim(Claims.Subject, account.Id.ToString("D"));
identity.SetClaim(Claims.PreferredUsername, account.NormalizedBifrostIdentity);
@@ -67,6 +87,13 @@ public static class OidcEndpoints
var principal = new ClaimsPrincipal(identity);
principal.SetScopes(request.GetScopes());
+ // A desk scope is what makes a token a desk token: its audience is the desk's. The client's permissions already
+ // decided whether it may ask for the scope (the MAS client may not), so this branch is reached only by one that may.
+ if (request.GetScopes().Any(DeskEndpoints.IsDeskScope))
+ {
+ principal.SetResources(DeskEndpoints.Audience);
+ }
+
principal.SetDestinations(claim => claim.Type switch
{
Claims.Subject => [Destinations.AccessToken, Destinations.IdentityToken],
@@ -75,19 +102,32 @@ public static class OidcEndpoints
_ => [Destinations.AccessToken]
});
+ // The training notice is the chat's: a desk token is not a chat token and needs no receipt (Meta's ruling, 2026-11-11).
+ // Last, so a refusal that no agreement can cure (suspended, no identity, reserved) is never answered with an invitation to agree.
+ // Not an OIDC error: the member is sent to the consent page with this request's resume path, and the parked request
+ // (single use, ten minutes) is still there when they come back, because only an OpenIddict response spends it.
+ if (!IsDeskToken(principal) && !await ConsentEndpoints.HasLiveReceiptAsync(db, account.Id, http.RequestAborted))
+ {
+ return Results.Redirect(ConsentEndpoints.PathFor(http.Request.PathBase + http.Request.Path + http.Request.QueryString));
+ }
+
return Results.SignIn(principal, properties: null, OpenIddictScheme);
}
+ /// A token whose scopes include a desk scope is a desk token. Only the chat token requires the training-notice receipt.
+ // Only a token whose every scope is a desk scope skips the consent gate: a client that may hold chat scopes too cannot ride a desk scope past the receipt.
+ private static bool IsDeskToken(ClaimsPrincipal? principal) => principal is not null && principal.GetScopes() is { Length: > 0 } scopes && scopes.All(DeskEndpoints.IsDeskScope);
+
private static async Task ExchangeAsync(HttpContext http, BifrostDbContext db)
{
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
- // The code's own principal carries the claims chosen at authorize time; membership is read again here,
- // because the code outlives the authorize decision (a member suspended since gets no tokens).
+ // The code's own principal carries the claims chosen at authorize time; suspension and agreement are read again here,
+ // because the code outlives the authorize decision (an account suspended or withdrawn since gets no tokens).
var result = await http.AuthenticateAsync(OpenIddictScheme);
var subject = result.Principal?.GetClaim(Claims.Subject);
- if (!await IsStillActiveMemberAsync(db, subject, http.RequestAborted))
+ if (await ChatRefusalAsync(db, subject, http.RequestAborted, IsDeskToken(result.Principal)) is { } refusal)
{
- return Deny(Errors.InvalidGrant, NotActiveDescription);
+ return Deny(Errors.InvalidGrant, refusal);
}
return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme);
@@ -101,10 +141,10 @@ public static class OidcEndpoints
return Results.Challenge(authenticationSchemes: [OpenIddictScheme]);
}
- // An access token outlives the authorize decision too: a member suspended since is no longer answered.
- if (!await IsStillActiveMemberAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted))
+ // An access token outlives the authorize decision too: an account suspended since, or one whose agreement has gone, is no longer answered.
+ if (await ChatRefusalAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted, IsDeskToken(result.Principal)) is { } refusal)
{
- return Deny(Errors.InsufficientAccess, NotActiveDescription);
+ return Deny(Errors.InsufficientAccess, refusal);
}
var claims = new Dictionary { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) };
@@ -117,18 +157,53 @@ public static class OidcEndpoints
return Results.Json(claims);
}
- /// The one reading of "this subject is still an Active member", shared by the token and userinfo endpoints and the logout reconciler.
- internal static async Task IsStillActiveMemberAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken)
+ ///
+ /// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
+ /// null when they may, else the description of why not. The account exists, its membership is not Suspended (absent, pending
+ /// or Active all chat), and, for a chat token (not a desk token), it holds a live receipt for the notice version in force. Re-read on every call.
+ ///
+ internal static async Task ChatRefusalAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken, bool deskToken = false)
{
if (!Guid.TryParse(subject, out var accountId))
{
- return false;
+ return SuspendedDescription;
}
var account = await db.UserAccounts.AsNoTracking()
.Include(x => x.Membership)
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
- return new CurrentBifrostActor(true, account).IsActiveMember;
+ if (account is null || account.Membership?.Status == MembershipStatus.Suspended)
+ {
+ return SuspendedDescription;
+ }
+
+ // A folded or frozen subject's chat sessions end: token, userinfo and the logout reconciler all read this one refusal.
+ if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
+ {
+ return MergedDescription;
+ }
+
+ return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
+ }
+
+ /// The account id of the subject when it is an Active member now, else null. The door to the fork desk (cookie surfaces check IsActiveMember); a chat-tier token does not pass it. Re-read on every call.
+ internal static async Task ActiveMemberIdAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken)
+ {
+ if (!Guid.TryParse(subject, out var accountId))
+ {
+ return null;
+ }
+
+ // A folded or frozen subject's live token acts as nobody on the desk too: the same standing the cookie gate and ChatRefusalAsync read.
+ if (await AccountMergeLedger.StandingAsync(db, accountId, cancellationToken) is not null)
+ {
+ return null;
+ }
+
+ var account = await db.UserAccounts.AsNoTracking()
+ .Include(x => x.Membership)
+ .SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
+ return new CurrentBifrostActor(true, account).IsActiveMember ? accountId : null;
}
private static IResult Deny(string error, string description) =>
diff --git a/src/Bifrost.Web/Features/Oidc/OidcGuard.cs b/src/Bifrost.Web/Features/Oidc/OidcGuard.cs
new file mode 100644
index 0000000..d4d09d5
--- /dev/null
+++ b/src/Bifrost.Web/Features/Oidc/OidcGuard.cs
@@ -0,0 +1,172 @@
+using System.Net;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Microsoft.EntityFrameworkCore;
+using OpenIddict.EntityFrameworkCore.Models;
+using Bifrost.Web.Features.Shared;
+using Microsoft.Extensions.Options;
+using OpenIddict.Abstractions;
+using static OpenIddict.Abstractions.OpenIddictConstants;
+using OpenIddict.Server.AspNetCore;
+
+namespace Bifrost.Web.Features.Oidc;
+
+///
+/// The issuer's front door, ahead of OpenIddict: the marker brake, the per-address budget, and the bound
+/// on token rows. The address is the connection's, already corrected by the forwarded-headers handling that trusts only
+/// the local proxy, so a caller cannot pick its own. It fails closed: anything this middleware cannot decide is a 503, never a pass.
+///
+public sealed class OidcGuardMiddleware(RequestDelegate next, OidcIssuerOptions options, OidcRateLimit limit, ILogger logger)
+{
+ public async Task InvokeAsync(HttpContext http, IOpenIddictTokenManager tokens)
+ {
+ var endpoint = EndpointOf(http.Request.Path);
+ if (endpoint is null)
+ {
+ await next(http);
+ return;
+ }
+
+ try
+ {
+ if (BrakeEngaged(options.BrakePath))
+ {
+ await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1));
+ return;
+ }
+
+ if (limit.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is { } byAddress)
+ {
+ await RefuseAsync(http, StatusCodes.Status429TooManyRequests, "too_many_requests", byAddress.RetryAfter);
+ return;
+ }
+
+ // A new authorize request parks a row for anyone who can name the (public) client; a resumed one carries request_uri and parks none.
+ if (endpoint == Authorize && !http.Request.Query.ContainsKey("request_uri") && await tokens.CountAsync(http.RequestAborted) >= options.Limits.MaxTokenRows)
+ {
+ await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", options.Limits.PruneInterval);
+ return;
+ }
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ logger.LogError("OIDC guard could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name);
+ await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1));
+ return;
+ }
+
+ await next(http);
+ }
+
+ private const string Authorize = "authorize";
+
+ // OpenIddict answers these paths with or without a trailing slash, so the match is by segments, never exact equality.
+ private static string? EndpointOf(PathString path) =>
+ path.StartsWithSegments(OidcServiceCollectionExtensions.AuthorizationPath, StringComparison.OrdinalIgnoreCase) ? Authorize
+ : path.StartsWithSegments(OidcServiceCollectionExtensions.TokenPath, StringComparison.OrdinalIgnoreCase) ? "token"
+ : path.StartsWithSegments(OidcServiceCollectionExtensions.UserInfoPath, StringComparison.OrdinalIgnoreCase) ? "userinfo"
+ : null;
+
+ // A marker that cannot be told apart from an absent one (a permission or I/O error) throws, and the guard answers 503: the brake never releases by accident.
+ private static bool BrakeEngaged(string path)
+ {
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ return false;
+ }
+
+ try
+ {
+ File.GetAttributes(path);
+ return true;
+ }
+ catch (Exception exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
+ {
+ return false;
+ }
+ }
+
+ private static Task RefuseAsync(HttpContext http, int status, string error, TimeSpan retryAfter)
+ {
+ http.Response.StatusCode = status;
+ http.Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ http.Response.ContentType = "application/json";
+ return http.Response.WriteAsync($"{{\"error\":\"{error}\"}}", http.RequestAborted);
+ }
+}
+
+///
+/// The issuer's per-address permits on the shared fixed-window budget. There is no per-client budget: the one client's id is
+/// public and what a caller names unverified, so a budget on it would let anyone spend the real client's permits.
+///
+public sealed class OidcRateLimit(OidcIssuerOptions options, TimeProvider clock)
+{
+ private readonly FixedWindowBudget addresses = new(options.Limits.PerAddressPermits, options.Limits.Window, options.Limits.MaxTrackedKeys, clock);
+
+ public BudgetDenial? Spend(string address) => addresses.Spend(address);
+}
+
+///
+/// Deletes expired and orphaned authorizations and tokens on a schedule: tokens past their expiry (parked authorize
+/// requests, codes, access tokens) or no longer valid, then authorizations that are no longer valid or are ad hoc with no
+/// token left. Live rows are never touched. Plain queries, not OpenIddict's ExecuteDelete prune, which the in-memory test provider
+/// cannot run; an authorization takes its remaining tokens with it, because the foreign key has no cascade on Postgres.
+///
+public sealed class OidcPruner(IServiceScopeFactory scopes, OidcIssuerOptions options, TimeProvider clock, ILogger logger) : BackgroundService
+{
+ private const int Batch = 500;
+
+ // A fresh authorization briefly has no token yet; leave anything younger than this alone.
+ private static readonly TimeSpan AuthorizationGrace = TimeSpan.FromMinutes(5);
+
+ public async Task PruneAsync(CancellationToken cancellationToken)
+ {
+ await using var scope = scopes.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var now = clock.GetUtcNow();
+ var young = now - AuthorizationGrace;
+
+ int removed;
+ do
+ {
+ var tokens = await db.Set()
+ .Where(token => token.ExpirationDate < now || (token.Status != Statuses.Valid && token.CreationDate < young))
+ .Take(Batch).ToListAsync(cancellationToken);
+ db.RemoveRange(tokens);
+ await db.SaveChangesAsync(cancellationToken);
+ removed = tokens.Count;
+ }
+ while (removed == Batch);
+
+ do
+ {
+ // A token row references its authorization (no cascade in the database), so the tokens go with it.
+ var authorizations = await db.Set()
+ .Include(authorization => authorization.Tokens)
+ .Where(authorization => authorization.CreationDate < young
+ && (authorization.Status != Statuses.Valid || (authorization.Type == AuthorizationTypes.AdHoc && !authorization.Tokens.Any())))
+ .Take(Batch).ToListAsync(cancellationToken);
+ db.RemoveRange(authorizations.SelectMany(authorization => authorization.Tokens));
+ db.RemoveRange(authorizations);
+ await db.SaveChangesAsync(cancellationToken);
+ removed = authorizations.Count;
+ }
+ while (removed == Batch);
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ using var timer = new PeriodicTimer(options.Limits.PruneInterval, clock);
+ while (await timer.WaitForNextTickAsync(stoppingToken))
+ {
+ try
+ {
+ await PruneAsync(stoppingToken);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ logger.LogError("OIDC prune failed ({ExceptionType}); the next tick tries again.", exception.GetType().Name);
+ }
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs b/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs
index ac6fa72..273acd9 100644
--- a/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs
+++ b/src/Bifrost.Web/Features/Oidc/OidcLogoutReconciler.cs
@@ -11,8 +11,8 @@ using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Bifrost.Web.Features.Oidc;
///
-/// Ends the chat sessions of a subject who is no longer an Active member. Each tick it lists the subjects holding valid
-/// authorizations of the configured client; for each one the shared active-member reading refuses, it POSTs one signed
+/// Ends the chat sessions of a subject who is no longer allowed to chat (suspended, the account gone, or no live receipt for the training notice in force). Each tick it lists the subjects holding valid
+/// authorizations of the configured client; for each one the shared chat-eligibility reading refuses, it POSTs one signed
/// OIDC back-channel logout token to MAS and, only after a 2xx, revokes that subject's authorizations. The
/// authorizations table is the queue: nothing is stored, so a restart, a MAS outage or a later-set URI resumes from it.
/// Per-subject backoff lives in memory only. One subject's unexpected exception is logged and skipped, never aborting the
@@ -127,7 +127,7 @@ public sealed class OidcLogoutReconciler(
{
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
- if (await OidcEndpoints.IsStillActiveMemberAsync(db, subject, cancellationToken))
+ if (await OidcEndpoints.ChatRefusalAsync(db, subject, cancellationToken) is null)
{
_backoff.Remove(subject);
return;
diff --git a/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs
index 5ad30b8..78526af 100644
--- a/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs
+++ b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs
@@ -67,6 +67,9 @@ public static class OidcServiceCollectionExtensions
server.Issuer = issuer;
});
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddHostedService(provider => provider.GetRequiredService());
services.AddHostedService();
if (!string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri))
{
diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
new file mode 100644
index 0000000..ddbb36f
--- /dev/null
+++ b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
@@ -0,0 +1,139 @@
+using Bifrost.Web.Features.Shared;
+
+namespace Bifrost.Web.Features.Passkeys;
+
+public enum CeremonyKind
+{
+ /// Permission to enrol one passkey, earned by a fresh Heimdall sign-in. Held by id in a cookie of the browser that signed in.
+ EnrolTicket,
+ /// The WebAuthn creation options in flight for an account.
+ EnrolChallenge,
+ /// The WebAuthn request options in flight for an account's unlink of one identity.
+ UnlinkChallenge,
+ /// The fact "this account's passkey assertion was verified for unlinking this identity". Carries no bearer and no credential.
+ UnlinkProof
+}
+
+///
+/// The short-lived single-use server-side state of the passkey flows, in this process only (like the Linked accounts list):
+/// a restart empties it and every flow is simply begun again. Every entry is bound to an account and a kind, and the unlink
+/// kinds to the identity they are for; Take removes the entry whether or not the caller then succeeds, so a
+/// challenge, a ticket or an assertion fact can be spent once. A challenge kind has one live entry per account: a newer one
+/// replaces the older. A full table refuses new entries rather than grow.
+///
+public sealed class PasskeyCeremonies(TimeProvider clock)
+{
+ public static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(5);
+ public static readonly TimeSpan ChallengeLifetime = TimeSpan.FromMinutes(2);
+ public static readonly TimeSpan ProofLifetime = TimeSpan.FromMinutes(5);
+ public const int MaxLive = 2048;
+
+ public sealed record Entry(string Id, CeremonyKind Kind, string Account, string? Subject, string? Data, DateTimeOffset ExpiresAt);
+
+ private readonly Dictionary _held = new(StringComparer.Ordinal);
+ private readonly object _gate = new();
+
+ /// Adds an entry and returns its id, or null when the table is full.
+ public string? Issue(CeremonyKind kind, string account, string? subject, string? data, TimeSpan lifetime)
+ {
+ lock (_gate)
+ {
+ Purge();
+ if (kind != CeremonyKind.UnlinkProof)
+ {
+ foreach (var old in _held.Values.Where(x => x.Kind == kind && x.Account == account).ToList())
+ {
+ _held.Remove(old.Id);
+ }
+ }
+
+ if (_held.Count >= MaxLive)
+ {
+ return null;
+ }
+
+ var id = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))
+ .Replace('+', '-').Replace('/', '_').TrimEnd('=');
+ _held[id] = new Entry(id, kind, account, subject, data, clock.GetUtcNow() + lifetime);
+ return id;
+ }
+ }
+
+ /// The live entry, without spending it. null finds the account's one current entry of that kind.
+ public Entry? Peek(CeremonyKind kind, string account, string? subject, string? id)
+ {
+ lock (_gate)
+ {
+ Purge();
+ return Find(kind, account, subject, id);
+ }
+ }
+
+ /// The live entry, removed: it can be taken once.
+ public Entry? Take(CeremonyKind kind, string account, string? subject, string? id)
+ {
+ lock (_gate)
+ {
+ Purge();
+ var entry = Find(kind, account, subject, id);
+ if (entry is not null)
+ {
+ _held.Remove(entry.Id);
+ }
+
+ return entry;
+ }
+ }
+
+ public void Discard(string? id)
+ {
+ if (id is not null)
+ {
+ lock (_gate)
+ {
+ _held.Remove(id);
+ }
+ }
+ }
+
+ private Entry? Find(CeremonyKind kind, string account, string? subject, string? id)
+ {
+ var entry = id is null
+ ? _held.Values.FirstOrDefault(x => x.Kind == kind && x.Account == account)
+ : _held.GetValueOrDefault(id);
+ return entry is not null && entry.Kind == kind
+ && string.Equals(entry.Account, account, StringComparison.Ordinal)
+ && string.Equals(entry.Subject, subject, StringComparison.Ordinal)
+ ? entry
+ : null;
+ }
+
+ private void Purge()
+ {
+ var now = clock.GetUtcNow();
+ foreach (var dead in _held.Values.Where(x => x.ExpiresAt <= now).ToList())
+ {
+ _held.Remove(dead.Id);
+ }
+ }
+}
+
+///
+/// The budgets on the passkey ceremonies, per Heimdall account, on the shared . Two separate
+/// ones: asking for options or starting an enrolment sign-in (anyone holding the session can do that), and verifying a
+/// registration or an assertion, which is spent only after the caller holds what the verification needs (a live ticket, or one of
+/// the account's own strong credentials and a live challenge). Junk from a session thief that names no credential of the account, or
+/// arrives with no live challenge, spends nothing; junk naming one of the account's credentials spends one permit per challenge that
+/// was asked for, because the first such post takes the challenge. A session holder can still exhaust both budgets by asking for
+/// challenges over and over: a lockout the same session already has through revoking passkeys, not a bypass. Budgets are per process.
+///
+public sealed class PasskeyRateLimit(TimeProvider clock)
+{
+ public const int Permits = 20;
+ public static readonly TimeSpan Window = TimeSpan.FromMinutes(10);
+
+ private readonly FixedWindowBudget _options = new(Permits, Window, 10_000, clock);
+ private readonly FixedWindowBudget _verifications = new(Permits, Window, 10_000, clock);
+
+ public bool TryAcquire(string account, bool verification = false) => (verification ? _verifications : _options).Spend(account) is null;
+}
diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
new file mode 100644
index 0000000..38aae13
--- /dev/null
+++ b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
@@ -0,0 +1,54 @@
+using Bifrost.Web.Configuration;
+using Fido2NetLib;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Passkeys;
+
+///
+/// The relying party every passkey ceremony runs as. RP ID and origin come from and from
+/// nothing the browser sends: the public base URL must be https and its host must be the expected host, otherwise passkeys
+/// are unavailable (the page offers none and every ceremony endpoint refuses). A passkey is bound to the RP ID by the
+/// authenticator, so a wrong or http origin would enrol keys that cannot be used or can be phished.
+///
+public sealed class PasskeyRelyingParty
+{
+ public const string Name = "Bifrost";
+
+ public PasskeyRelyingParty(IOptions hostOptions, ILogger logger)
+ {
+ var host = hostOptions.Value;
+ if (host.ExpectedHost.Contains(':') || System.Net.IPAddress.TryParse(host.ExpectedHost.Trim('[', ']'), out _))
+ {
+ logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare DNS host name, with no port and not an IP address (an IP address is not a valid RP ID).");
+ return;
+ }
+
+ if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var url)
+ || url.Scheme != Uri.UriSchemeHttps
+ || string.IsNullOrWhiteSpace(host.ExpectedHost)
+ || !string.Equals(url.Host, host.ExpectedHost, StringComparison.OrdinalIgnoreCase))
+ {
+ logger.LogWarning("Passkeys are unavailable: Host:PublicBaseUrl must be https and its host must equal Host:ExpectedHost.");
+ return;
+ }
+
+ Origin = url.GetLeftPart(UriPartial.Authority);
+ RpId = url.Host.ToLowerInvariant();
+ Fido2 = new Fido2(new Fido2Configuration
+ {
+ RPID = RpId,
+ RPName = Name,
+ Origins = new HashSet([Origin], StringComparer.Ordinal),
+ ChallengeSize = 32,
+ Timeout = 120_000
+ });
+ }
+
+ public bool IsAvailable => Fido2 is not null;
+
+ public string? Origin { get; }
+
+ public string? RpId { get; }
+
+ public IFido2? Fido2 { get; }
+}
diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
new file mode 100644
index 0000000..367d13c
--- /dev/null
+++ b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
@@ -0,0 +1,470 @@
+using System.Globalization;
+using System.Text;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Fido2NetLib;
+using Fido2NetLib.Objects;
+using Microsoft.AspNetCore.WebUtilities;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.Features.Passkeys;
+
+/// One passkey as the Linked accounts page shows it: a label, its cooling-off state, never a key.
+public sealed record PasskeyView(Guid Id, string Label, DateTimeOffset CreatedUtc, DateTimeOffset StrongFromUtc, DateTimeOffset? LastUsedUtc, bool IsStrong);
+
+/// The base64url fields a browser posts after navigator.credentials.get (an assertion) or .create (an enrolment).
+public sealed record PasskeyFields(
+ string? Id, string? RawId, string? AuthenticatorData, string? ClientDataJson, string? Signature, string? UserHandle,
+ string? AttestationObject, string? Transports);
+
+///
+/// Passkeys for accounts that have a Heimdall account id (docs/passkeys.md). Enrolment needs a ticket earned by a fresh
+/// Heimdall sign-in and starts a credential in a 48 hour cooling-off; an assertion for an unlink needs a credential that is
+/// the session's own, not revoked and past its cooling-off, and records a single-use fact for that account and identity.
+/// The WebAuthn parsing and verification (CBOR, COSE, signatures, origin, RP ID, challenge, user verification, sign count)
+/// is Fido2NetLib's; this class decides who may begin, what is bound to what, and what is kept. Outcomes are the closed set
+/// of the page words itself.
+///
+public sealed class PasskeyService(
+ BifrostDbContext db,
+ PasskeyRelyingParty relyingParty,
+ PasskeyCeremonies ceremonies,
+ PasskeyRateLimit rateLimit,
+ TimeProvider clock,
+ ILogger logger)
+{
+ public const int MaxActive = 5;
+ public const int MaxLabel = 40;
+ public static readonly TimeSpan CoolingOff = TimeSpan.FromHours(48);
+
+ private static readonly HashSet TransportNames = new(StringComparer.Ordinal)
+ {
+ "usb", "nfc", "ble", "internal", "hybrid", "smart-card"
+ };
+
+ public bool IsAvailable => relyingParty.IsAvailable;
+
+ private Task AccountAsync(string heimdallAccountId, CancellationToken ct) =>
+ string.IsNullOrEmpty(heimdallAccountId)
+ ? Task.FromResult(null)
+ : db.UserAccounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, ct);
+
+ private IQueryable Active(Guid userId) =>
+ db.PasskeyCredentials.Where(x => x.UserAccountId == userId && x.RevokedUtc == null);
+
+ public async Task> ListAsync(string heimdallAccountId, CancellationToken ct)
+ {
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return [];
+ }
+
+ var now = clock.GetUtcNow();
+ var rows = await Active(user.Id).ToListAsync(ct);
+ return rows.OrderBy(x => x.CreatedUtc)
+ .Select(x => new PasskeyView(x.Id, x.Label, x.CreatedUtc, x.StrongFromUtc, x.LastUsedUtc, x.StrongFromUtc <= now))
+ .ToList();
+ }
+
+ /// Whether a fresh enrolment ticket is held by this browser for this account.
+ public bool HasTicket(string heimdallAccountId, string? ticketId) =>
+ ticketId is not null && ceremonies.Peek(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId) is not null;
+
+ /// Why a fresh sign-in for enrolment may not even start, or null when it may. Spends a ceremony permit.
+ public async Task PreflightEnrolStartAsync(string heimdallAccountId, CancellationToken ct)
+ {
+ if (!relyingParty.IsAvailable)
+ {
+ return HeimdallLinkOutcome.PasskeysUnavailable;
+ }
+
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return HeimdallLinkOutcome.Error;
+ }
+
+ if (await Active(user.Id).CountAsync(ct) >= MaxActive)
+ {
+ return HeimdallLinkOutcome.PasskeyLimit;
+ }
+
+ return rateLimit.TryAcquire(heimdallAccountId) ? null : HeimdallLinkOutcome.RateLimited;
+ }
+
+ /// The creation options for one enrolment, bound to the account; needs the ticket the fresh sign-in earned.
+ public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginEnrolAsync(string heimdallAccountId, string? ticketId, CancellationToken ct)
+ {
+ if (!relyingParty.IsAvailable)
+ {
+ return (HeimdallLinkOutcome.PasskeysUnavailable, null);
+ }
+
+ if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return (HeimdallLinkOutcome.EnrolNeedsSignIn, null);
+ }
+
+ if (!rateLimit.TryAcquire(heimdallAccountId))
+ {
+ return (HeimdallLinkOutcome.RateLimited, null);
+ }
+
+ var existing = await Active(user.Id).Select(x => x.CredentialId).ToListAsync(ct);
+ if (existing.Count >= MaxActive)
+ {
+ return (HeimdallLinkOutcome.PasskeyLimit, null);
+ }
+
+ var options = relyingParty.Fido2!.RequestNewCredential(new RequestNewCredentialParams
+ {
+ User = new Fido2User { Id = user.Id.ToByteArray(), Name = Label(user.DisplayName, "Bifrost member"), DisplayName = Label(user.DisplayName, "Bifrost member") },
+ ExcludeCredentials = existing.Select(x => new PublicKeyCredentialDescriptor(x)).ToList(),
+ AuthenticatorSelection = new AuthenticatorSelection
+ {
+ ResidentKey = ResidentKeyRequirement.Preferred,
+ UserVerification = UserVerificationRequirement.Required
+ },
+ AttestationPreference = AttestationConveyancePreference.None
+ });
+ var json = options.ToJson();
+ return ceremonies.Issue(CeremonyKind.EnrolChallenge, heimdallAccountId, null, json, PasskeyCeremonies.ChallengeLifetime) is null
+ ? (HeimdallLinkOutcome.Error, null)
+ : (null, json);
+ }
+
+ ///
+ /// Verifies a registration and stores the credential, cooling off for . The ticket and the
+ /// challenge are both spent here, whatever the outcome: a failed attempt needs a fresh sign-in and a new challenge.
+ ///
+ public async Task EnrolAsync(
+ string heimdallAccountId, string? ticketId, PasskeyFields fields, string? label, CancellationToken ct)
+ {
+ if (!relyingParty.IsAvailable)
+ {
+ return HeimdallLinkOutcome.PasskeysUnavailable;
+ }
+
+ // The caller's own preconditions first, spending nothing: someone with only the session has no ticket, so junk from them
+ // can neither burn the member's ticket and challenge nor spend the verification permits.
+ if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return HeimdallLinkOutcome.EnrolNeedsSignIn;
+ }
+
+ if (await Active(user.Id).CountAsync(ct) >= MaxActive)
+ {
+ return HeimdallLinkOutcome.PasskeyLimit;
+ }
+
+ if (!TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AttestationObject, out var attestation)
+ || !TryDecode(fields.ClientDataJson, out var clientData) || fields.Id is null)
+ {
+ return HeimdallLinkOutcome.PasskeyFailed;
+ }
+
+ if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
+ {
+ return HeimdallLinkOutcome.RateLimited;
+ }
+
+ // Now both are spent, whatever the outcome.
+ var ticket = ceremonies.Take(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId);
+ var challenge = ceremonies.Take(CeremonyKind.EnrolChallenge, heimdallAccountId, null, null);
+ if (ticket is null)
+ {
+ return HeimdallLinkOutcome.EnrolNeedsSignIn;
+ }
+
+ if (challenge?.Data is null)
+ {
+ return HeimdallLinkOutcome.PasskeyExpired;
+ }
+
+ try
+ {
+ var registered = await relyingParty.Fido2!.MakeNewCredentialAsync(new MakeNewCredentialParams
+ {
+ AttestationResponse = new AuthenticatorAttestationRawResponse
+ {
+ Id = fields.Id,
+ RawId = rawId,
+ Type = PublicKeyCredentialType.PublicKey,
+ ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
+ Response = new AuthenticatorAttestationRawResponse.AttestationResponse
+ {
+ AttestationObject = attestation,
+ ClientDataJson = clientData,
+ Transports = Transports(fields.Transports)
+ }
+ },
+ OriginalOptions = CredentialCreateOptions.FromJson(challenge.Data),
+ IsCredentialIdUniqueToUserCallback = async (parameters, token) =>
+ !await db.PasskeyCredentials.AnyAsync(x => x.CredentialId == parameters.CredentialId, token)
+ }, ct);
+
+ var now = clock.GetUtcNow();
+ db.PasskeyCredentials.Add(new PasskeyCredential
+ {
+ UserAccountId = user.Id,
+ CredentialId = registered.Id,
+ PublicKey = registered.PublicKey,
+ SignCount = registered.SignCount,
+ Transports = string.Join(',', Transports(fields.Transports).Select(x => TransportName(x))),
+ AaGuid = registered.AaGuid == Guid.Empty ? null : registered.AaGuid,
+ Label = Label(label, "Passkey"),
+ CreatedUtc = now,
+ StrongFromUtc = now + CoolingOff
+ });
+ await db.SaveChangesAsync(ct);
+ return HeimdallLinkOutcome.PasskeyAdded;
+ }
+ catch (Exception error) when (error is Fido2VerificationException or DbUpdateException or FormatException or System.Text.Json.JsonException)
+ {
+ logger.LogWarning("Passkey enrolment refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
+ return HeimdallLinkOutcome.PasskeyFailed;
+ }
+ }
+
+ /// Revokes one of the session's own passkeys. Needs no strong proof; the page shows the revocation.
+ public async Task RevokeAsync(string heimdallAccountId, Guid credentialId, CancellationToken ct)
+ {
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return HeimdallLinkOutcome.Error;
+ }
+
+ var credential = await Active(user.Id).SingleOrDefaultAsync(x => x.Id == credentialId, ct);
+ if (credential is null)
+ {
+ return HeimdallLinkOutcome.PasskeyFailed;
+ }
+
+ credential.RevokedUtc = clock.GetUtcNow();
+ await db.SaveChangesAsync(ct);
+ return HeimdallLinkOutcome.PasskeyRevoked;
+ }
+
+ private IQueryable Strong(Guid userId)
+ {
+ var now = clock.GetUtcNow();
+ return Active(userId).Where(x => x.StrongFromUtc <= now);
+ }
+
+ public async Task HasStrongAsync(string heimdallAccountId, CancellationToken ct) =>
+ await AccountAsync(heimdallAccountId, ct) is { } user && await Strong(user.Id).AnyAsync(ct);
+
+ /// When the first cooling-off credential becomes strong, or null when none is cooling.
+ public async Task NextStrongAtAsync(string heimdallAccountId, CancellationToken ct)
+ {
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return null;
+ }
+
+ var now = clock.GetUtcNow();
+ var cooling = await Active(user.Id).Where(x => x.StrongFromUtc > now).Select(x => x.StrongFromUtc).ToListAsync(ct);
+ return cooling.Count == 0 ? null : cooling.Min();
+ }
+
+ /// The request options for unlinking one identity: only the account's strong passkeys may answer, with user verification.
+ public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginAssertionAsync(string heimdallAccountId, string identityId, CancellationToken ct)
+ {
+ if (!relyingParty.IsAvailable)
+ {
+ return (HeimdallLinkOutcome.PasskeysUnavailable, null);
+ }
+
+ if (!rateLimit.TryAcquire(heimdallAccountId))
+ {
+ return (HeimdallLinkOutcome.RateLimited, null);
+ }
+
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user)
+ {
+ return (HeimdallLinkOutcome.Error, null);
+ }
+
+ var strong = await Strong(user.Id).ToListAsync(ct);
+ if (strong.Count == 0)
+ {
+ return (HeimdallLinkOutcome.PasskeyRequired, null);
+ }
+
+ var options = relyingParty.Fido2!.GetAssertionOptions(new GetAssertionOptionsParams
+ {
+ AllowedCredentials = strong.Select(x => new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PublicKey, x.CredentialId, Transports(x.Transports))).ToList(),
+ UserVerification = UserVerificationRequirement.Required
+ });
+ var json = options.ToJson();
+ return ceremonies.Issue(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, json, PasskeyCeremonies.ChallengeLifetime) is null
+ ? (HeimdallLinkOutcome.Error, null)
+ : (null, json);
+ }
+
+ ///
+ /// Verifies an assertion made for unlinking . The challenge is spent first. On success the
+ /// credential's sign count and last use are recorded and a single-use fact for this account and identity is issued; its id
+ /// (not a credential, not a bearer) is what the fresh Heimdall sign-in's attempt carries.
+ ///
+ public async Task<(HeimdallLinkOutcome? Refusal, string? FactId)> VerifyAssertionAsync(
+ string heimdallAccountId, string identityId, PasskeyFields fields, CancellationToken ct)
+ {
+ if (!relyingParty.IsAvailable)
+ {
+ return (HeimdallLinkOutcome.PasskeysUnavailable, null);
+ }
+
+ // The caller's own preconditions first, spending nothing: a decodable assertion naming one of this account's strong,
+ // un-revoked credentials. Junk from someone holding only the session fails here and burns neither the member's challenge
+ // nor the verification permits.
+ if (await AccountAsync(heimdallAccountId, ct) is not { } user
+ || !TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AuthenticatorData, out var authenticatorData)
+ || !TryDecode(fields.ClientDataJson, out var clientData) || !TryDecode(fields.Signature, out var signature)
+ || fields.Id is null)
+ {
+ return (HeimdallLinkOutcome.PasskeyFailed, null);
+ }
+
+ byte[]? userHandle = null;
+ if (!string.IsNullOrEmpty(fields.UserHandle) && !TryDecode(fields.UserHandle, out userHandle))
+ {
+ return (HeimdallLinkOutcome.PasskeyFailed, null);
+ }
+
+ // The credential must be this session's own, not revoked and past its cooling-off. Anything else is not a strong proof.
+ var credential = await Strong(user.Id).SingleOrDefaultAsync(x => x.CredentialId == rawId, ct);
+ if (credential is null)
+ {
+ return (HeimdallLinkOutcome.PasskeyFailed, null);
+ }
+
+ // Without a live challenge for this account and identity nothing can verify, so no permit is spent either: junk naming the
+ // account's own credential spends at most one permit per challenge that was asked for (the first junk then takes it).
+ if (ceremonies.Peek(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null) is null)
+ {
+ return (HeimdallLinkOutcome.PasskeyExpired, null);
+ }
+
+ if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
+ {
+ return (HeimdallLinkOutcome.RateLimited, null);
+ }
+
+ // Spent from here on, whatever the outcome.
+ var challenge = ceremonies.Take(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null);
+ if (challenge?.Data is null)
+ {
+ return (HeimdallLinkOutcome.PasskeyExpired, null);
+ }
+
+ try
+ {
+ var result = await relyingParty.Fido2!.MakeAssertionAsync(new MakeAssertionParams
+ {
+ AssertionResponse = new AuthenticatorAssertionRawResponse
+ {
+ Id = fields.Id,
+ RawId = rawId,
+ Type = PublicKeyCredentialType.PublicKey,
+ ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
+ Response = new AuthenticatorAssertionRawResponse.AssertionResponse
+ {
+ AuthenticatorData = authenticatorData,
+ ClientDataJson = clientData,
+ Signature = signature,
+ UserHandle = userHandle
+ }
+ },
+ OriginalOptions = AssertionOptions.FromJson(challenge.Data),
+ StoredPublicKey = credential.PublicKey,
+ StoredSignatureCounter = (uint)credential.SignCount,
+ IsUserHandleOwnerOfCredentialIdCallback = (parameters, _) =>
+ Task.FromResult(parameters.UserHandle.AsSpan().SequenceEqual(user.Id.ToByteArray()) && parameters.CredentialId.AsSpan().SequenceEqual(credential.CredentialId))
+ }, ct);
+
+ credential.SignCount = result.SignCount;
+ credential.LastUsedUtc = clock.GetUtcNow();
+ await db.SaveChangesAsync(ct);
+ }
+ catch (Exception error) when (error is Fido2VerificationException or FormatException or System.Text.Json.JsonException)
+ {
+ logger.LogWarning("Passkey assertion refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
+ return (HeimdallLinkOutcome.PasskeyFailed, null);
+ }
+
+ var fact = ceremonies.Issue(CeremonyKind.UnlinkProof, heimdallAccountId, identityId, credential.Id.ToString(), PasskeyCeremonies.ProofLifetime);
+ return fact is null ? (HeimdallLinkOutcome.Error, null) : (null, fact);
+ }
+
+ public void DiscardFact(string? factId) => ceremonies.Discard(factId);
+
+ ///
+ /// Whether the credential an assertion fact was made with is still this account's own, un-revoked and strong. Asked in the
+ /// completion, before Heimdall is: a passkey revoked between the assertion and the completion no longer proves anything.
+ ///
+ public async Task StillStrongAsync(string heimdallAccountId, string? credentialId, CancellationToken ct) =>
+ Guid.TryParse(credentialId, out var id) && await AccountAsync(heimdallAccountId, ct) is { } user
+ && await Strong(user.Id).AnyAsync(x => x.Id == id, ct);
+
+ /// A label from a form field: trimmed, control characters dropped, bounded; the fallback when nothing is left.
+ private static string Label(string? value, string fallback)
+ {
+ // By rune and by text element, never by UTF-16 unit: a cut inside a surrogate pair is not valid text and Postgres refuses it.
+ // Control and format characters (bidi overrides, joiners, zero-width marks) are dropped; a lone surrogate becomes U+FFFD.
+ var runes = (value ?? string.Empty).EnumerateRunes()
+ .Where(r => Rune.GetUnicodeCategory(r) is not (UnicodeCategory.Control or UnicodeCategory.Format))
+ .Take(MaxLabel * 4);
+ var cleaned = string.Concat(runes.Select(r => r.ToString())).Trim();
+ var elements = new StringInfo(cleaned);
+ if (elements.LengthInTextElements > MaxLabel)
+ {
+ cleaned = elements.SubstringByTextElements(0, MaxLabel);
+ }
+
+ return cleaned.Length == 0 ? fallback : cleaned;
+ }
+
+ private static bool TryDecode(string? value, out byte[] bytes)
+ {
+ bytes = [];
+ if (string.IsNullOrEmpty(value) || value.Length > 16_384)
+ {
+ return false;
+ }
+
+ try
+ {
+ bytes = WebEncoders.Base64UrlDecode(value);
+ return bytes.Length > 0;
+ }
+ catch (FormatException)
+ {
+ return false;
+ }
+ }
+
+ private static AuthenticatorTransport[] Transports(string? csv)
+ {
+ var parsed = new List();
+ foreach (var name in (csv ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct())
+ {
+ try
+ {
+ // Only names of the closed set reach the converter; one it does not know is dropped.
+ if (TransportNames.Contains(name))
+ {
+ parsed.Add(System.Text.Json.JsonSerializer.Deserialize($"\"{name}\""));
+ }
+ }
+ catch (System.Text.Json.JsonException)
+ {
+ }
+ }
+
+ return parsed.ToArray();
+ }
+
+ private static string TransportName(AuthenticatorTransport transport) =>
+ System.Text.Json.JsonSerializer.Serialize(transport).Trim('"');
+}
diff --git a/src/Bifrost.Web/Features/Patronage/PatronageService.cs b/src/Bifrost.Web/Features/Patronage/PatronageService.cs
index 8301356..e8cfbfe 100644
--- a/src/Bifrost.Web/Features/Patronage/PatronageService.cs
+++ b/src/Bifrost.Web/Features/Patronage/PatronageService.cs
@@ -1,5 +1,6 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
@@ -10,6 +11,13 @@ public sealed class PatronageService(
AuditTrailService auditTrailService,
TimeProvider timeProvider)
{
+ private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron";
+
+ ///
+ /// Records a patron event for an account, through the merge ledger's write gate: an event for a folded account lands on its survivor
+ /// and is journalled in the same save (an undo moves it back); an event for a frozen account lands on it, where the commit's
+ /// reduction finds it. A provider retry returns the stored event and, if it sits on a folded account's survivor, journals it once.
+ ///
public async Task RecordSupportEventAsync(
Guid? actorUserAccountId,
Guid userAccountId,
@@ -27,105 +35,128 @@ public sealed class PatronageService(
CancellationToken cancellationToken,
Guid? projectId = null)
{
- var user = await dbContext.UserAccounts
- .Include(x => x.Membership)
- .SingleAsync(x => x.Id == userAccountId, cancellationToken);
-
- if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended)
- {
- throw new InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account.");
- }
-
- 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))
+ var (supportEvent, recordedOn, isNew, recordedFor) = await AccountMergeLedger.WriteAsAsync(dbContext, userAccountId, async standing =>
{
- throw new InvalidOperationException("External patron provider events require a provider event id.");
- }
+ var folded = standing as MergeStanding.Folded;
+ var recordOnId = folded?.SurvivorId ?? userAccountId;
+ var now = timeProvider.GetUtcNow();
- var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
- ? null
- : await dbContext.PatronSupportEvents
- .SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
+ 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"
- : currencyCode.Trim().ToUpperInvariant();
-
- if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport)
- {
- var existingCurrentEvents = await dbContext.PatronSupportEvents
- .Where(x => x.UserAccountId == userAccountId &&
- x.Kind == PatronSupportEventKind.RecurringSupportSnapshot &&
- x.IsCurrentRecurringSupport)
- .ToListAsync(cancellationToken);
-
- foreach (var existing in existingCurrentEvents)
+ if (existingProviderEvent is not null)
{
- existing.IsCurrentRecurringSupport = false;
+ if (folded is not null && existingProviderEvent.UserAccountId == folded.SurvivorId)
+ {
+ await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, existingProviderEvent.Id, now, cancellationToken);
+ await dbContext.SaveChangesAsync(cancellationToken);
+ }
+
+ return (existingProviderEvent, recordOnId, false, string.Empty);
}
+
+ var user = await dbContext.UserAccounts
+ .Include(x => x.Membership)
+ .SingleAsync(x => x.Id == recordOnId, cancellationToken);
+
+ if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended)
+ {
+ throw new PatronSupportRefusedException();
+ }
+
+ 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.");
+ }
+
+ if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
+ {
+ throw new InvalidOperationException("External patron provider events require a provider event id.");
+ }
+
+ var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
+ ? "USD"
+ : currencyCode.Trim().ToUpperInvariant();
+
+ if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport)
+ {
+ var existingCurrentEvents = await dbContext.PatronSupportEvents
+ .Where(x => x.UserAccountId == recordOnId &&
+ x.Kind == PatronSupportEventKind.RecurringSupportSnapshot &&
+ x.IsCurrentRecurringSupport)
+ .ToListAsync(cancellationToken);
+
+ foreach (var existing in existingCurrentEvents)
+ {
+ existing.IsCurrentRecurringSupport = false;
+ }
+ }
+
+ var created = new PatronSupportEvent
+ {
+ UserAccountId = recordOnId,
+ ProjectId = projectId,
+ Kind = kind,
+ ExternalSupportId = externalSupportId.Trim(),
+ Provider = provider,
+ ProviderEventId = normalizedProviderEventId,
+ ProviderPayerId = providerPayerId.Trim(),
+ ProviderSubscriptionId = providerSubscriptionId.Trim(),
+ Amount = amount,
+ CurrencyCode = normalizedCurrency,
+ IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport,
+ SupportedAtUtc = supportedAtUtc.ToUniversalTime(),
+ RecordedAtUtc = now,
+ Notes = notes.Trim()
+ };
+
+ dbContext.PatronSupportEvents.Add(created);
+ dbContext.PointTransactions.Add(new PointTransaction
+ {
+ UserAccountId = recordOnId,
+ ProjectId = projectId,
+ Type = PointTransactionType.PatronSupport,
+ Amount = amount,
+ IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
+ CreatedAtUtc = now,
+ Note = $"Recorded {provider} {kind} patron support event {created.ExternalSupportId}."
+ });
+
+ if (folded is not null)
+ {
+ await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, created.Id, now, cancellationToken);
+ }
+
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return (created, recordOnId, true, user.DisplayName);
+ }, cancellationToken);
+
+ if (isNew)
+ {
+ await auditTrailService.RecordAsync(
+ actorUserAccountId,
+ nameof(PatronSupportEvent),
+ supportEvent.Id,
+ "patron-support.recorded",
+ $"Recorded {amount:0.##} {supportEvent.CurrencyCode} {provider} {kind} patron support for {recordedFor}.",
+ cancellationToken);
+
+ await RefreshPatronTierSnapshotAsync(actorUserAccountId, recordedOn, cancellationToken);
}
- var supportEvent = new PatronSupportEvent
- {
- UserAccountId = userAccountId,
- ProjectId = projectId,
- Kind = kind,
- ExternalSupportId = externalSupportId.Trim(),
- Provider = provider,
- ProviderEventId = normalizedProviderEventId,
- ProviderPayerId = providerPayerId.Trim(),
- ProviderSubscriptionId = providerSubscriptionId.Trim(),
- Amount = amount,
- CurrencyCode = normalizedCurrency,
- IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport,
- SupportedAtUtc = supportedAtUtc.ToUniversalTime(),
- RecordedAtUtc = now,
- Notes = notes.Trim()
- };
-
- dbContext.PatronSupportEvents.Add(supportEvent);
- dbContext.PointTransactions.Add(new PointTransaction
- {
- UserAccountId = userAccountId,
- ProjectId = projectId,
- Type = PointTransactionType.PatronSupport,
- Amount = amount,
- IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
- CreatedAtUtc = now,
- Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}."
- });
-
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- actorUserAccountId,
- nameof(PatronSupportEvent),
- supportEvent.Id,
- "patron-support.recorded",
- $"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.",
- cancellationToken);
-
- await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
return supportEvent;
}
@@ -134,24 +165,67 @@ public sealed class PatronageService(
Guid userAccountId,
CancellationToken cancellationToken)
{
- dbContext.ChangeTracker.Clear();
-
- var user = await dbContext.UserAccounts
- .Include(x => x.Membership)
- .Include(x => x.PatronSupportEvents)
- .SingleAsync(x => x.Id == userAccountId, cancellationToken);
-
- if (user.Membership is null)
+ // One current Patron snapshot per membership is a database invariant (UX_TierSnapshots_MembershipId_CurrentPatron). A restage that
+ // lost a race to another restage of the same membership reads the winner's snapshot and derives again from the events it now sees.
+ UserAccount user;
+ PatronPointSummary summary;
+ PatronTierDefinition? tier;
+ for (var attempt = 0; ; attempt++)
{
- throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
+ dbContext.ChangeTracker.Clear();
+
+ user = await dbContext.UserAccounts
+ .Include(x => x.Membership)
+ .Include(x => x.PatronSupportEvents)
+ .SingleAsync(x => x.Id == userAccountId, cancellationToken);
+
+ if (user.Membership is null)
+ {
+ throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
+ }
+
+ (summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
+
+ try
+ {
+ await dbContext.SaveChangesAsync(cancellationToken);
+ break;
+ }
+ catch (DbUpdateException error) when (attempt < 3 &&
+ error.InnerException is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation, ConstraintName: CurrentPatronIndex })
+ {
+ }
}
- var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
+ await auditTrailService.RecordAsync(
+ actorUserAccountId,
+ nameof(TierSnapshot),
+ user.Membership.Id,
+ "patron-tier.derived",
+ tier is null
+ ? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
+ : $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
+ cancellationToken);
+
+ return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
+ }
+
+ ///
+ /// Derives the membership's patron tier from the events once and stages it on the tracker: demotes the current Patron snapshots
+ /// and adds the new one. It never saves and never clears the tracker, so a caller can stage it inside a larger single save
+ /// (the account merge ledger does).
+ ///
+ public async Task<(PatronPointSummary Summary, PatronTierDefinition? Tier)> StageTierSnapshotAsync(
+ Bifrost.Web.Domain.Membership membership,
+ IEnumerable events,
+ DateTimeOffset now,
+ CancellationToken cancellationToken)
+ {
+ var summary = CalculatePatronPoints(events, now);
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
- var now = timeProvider.GetUtcNow();
var currentPatronSnapshots = await dbContext.TierSnapshots
- .Where(x => x.MembershipId == user.Membership.Id &&
+ .Where(x => x.MembershipId == membership.Id &&
x.Kind == TierSnapshotKind.Patron &&
x.IsCurrent)
.ToListAsync(cancellationToken);
@@ -165,7 +239,7 @@ public sealed class PatronageService(
{
dbContext.TierSnapshots.Add(new TierSnapshot
{
- MembershipId = user.Membership.Id,
+ MembershipId = membership.Id,
Kind = TierSnapshotKind.Patron,
Label = PatronTierPolicy.SnapshotLabel(tier),
Weight = tier.VotingWeight,
@@ -176,18 +250,7 @@ public sealed class PatronageService(
});
}
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- actorUserAccountId,
- nameof(TierSnapshot),
- user.Membership.Id,
- "patron-tier.derived",
- tier is null
- ? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
- : $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
- cancellationToken);
-
- return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
+ return (summary, tier);
}
public static PatronPointSummary CalculatePatronPoints(
@@ -215,6 +278,9 @@ public sealed class PatronageService(
}
}
+/// The account patron support would record on has no membership or is suspended.
+public sealed class PatronSupportRefusedException() : InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account.");
+
public sealed record PatronPointSummary(
decimal RecurringPoints,
decimal HistoricalPoints,
diff --git a/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs b/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs
index 4293ffe..4dbcda7 100644
--- a/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs
+++ b/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs
@@ -66,7 +66,7 @@ public sealed class StripeWebhookService(
var patronageAccount = await ResolvePatronageAccountAsync(session, stripeOptions, cancellationToken);
- if (patronageAccount?.Membership is null || patronageAccount.Membership.Status == MembershipStatus.Suspended)
+ if (patronageAccount is null)
{
return StripeWebhookResult.NotConfigured(
"Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
@@ -83,22 +83,32 @@ public sealed class StripeWebhookService(
? "USD"
: session.Currency.ToUpperInvariant();
- await patronageService.RecordSupportEventAsync(
- actorUserAccountId: null,
- patronageAccount.Id,
- PatronSupportEventKind.OneTimeDonation,
- amount,
- currencyCode,
- session.Id,
- ExternalPatronProvider.Stripe,
- stripeEvent.Id,
- session.Customer,
- string.Empty,
- DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created),
- isCurrentRecurringSupport: false,
- BuildNotes(session),
- cancellationToken,
- projectId.ProjectId);
+ // A checkout opened by an account that has since folded pays the survivor: the write gate behind RecordSupportEventAsync routes it.
+ PatronSupportEvent supportEvent;
+ try
+ {
+ supportEvent = await patronageService.RecordSupportEventAsync(
+ actorUserAccountId: null,
+ patronageAccount.Id,
+ PatronSupportEventKind.OneTimeDonation,
+ amount,
+ currencyCode,
+ session.Id,
+ ExternalPatronProvider.Stripe,
+ stripeEvent.Id,
+ session.Customer,
+ string.Empty,
+ DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created),
+ isCurrentRecurringSupport: false,
+ BuildNotes(session),
+ cancellationToken,
+ projectId.ProjectId);
+ }
+ catch (PatronSupportRefusedException)
+ {
+ return StripeWebhookResult.NotConfigured(
+ "Stripe checkout session is not linked to an unsuspended Bifrost patron account.");
+ }
return StripeWebhookResult.Processed("Stripe patronage support event recorded.");
}
diff --git a/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs b/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs
new file mode 100644
index 0000000..6682d14
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/ConsentEndpoints.cs
@@ -0,0 +1,199 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Registration;
+
+///
+/// The consent page and its two form posts, for any signed-in account. The receipt rows are the only state: a receipt is
+/// live while is null, and an account's messages count only while a live
+/// receipt for the version in force exists. Both posts are refused by before
+/// anything is read or written, since a signed-in session is a cookie and these carry no antiforgery token.
+///
+public static class ConsentEndpoints
+{
+ public const string Path = "/auth/bifrost/consent";
+
+ public static void MapConsent(this IEndpointRouteBuilder app)
+ {
+ app.MapGet(Path, async (HttpContext http, ICurrentBifrostActorAccessor actors, BifrostDbContext db, CancellationToken ct) =>
+ {
+ var actor = await actors.GetAsync(ct);
+ if (!actor.IsAuthenticated || actor.UserAccount is null)
+ {
+ return Results.Redirect($"/auth/sign-in?returnUrl={Uri.EscapeDataString(LocalReturnPath.Parse(Path).Value)}");
+ }
+
+ return await PageAsync(db, actor.UserAccount.Id, null, StatusCodes.Status200OK, ct, ReturnPathOf(http.Request.Query["returnUrl"]));
+ }).AllowAnonymous();
+
+ app.MapPost(Path + "/accept", async (
+ HttpContext http,
+ ICurrentBifrostActorAccessor actors,
+ BifrostDbContext db,
+ TimeProvider clock,
+ IOptions host,
+ CancellationToken ct) =>
+ {
+ if (!RequestOriginGuard.Allows(http.Request, host.Value))
+ {
+ return Refused();
+ }
+
+ var actor = await actors.GetAsync(ct);
+ if (!actor.IsAuthenticated || actor.UserAccount is null)
+ {
+ return Results.Unauthorized();
+ }
+
+ var form = await ReadFormAsync(http.Request, ct);
+ if (form is null || form["version"].ToString() != TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture))
+ {
+ return await PageAsync(db, actor.UserAccount.Id, $"Send the version in force, {TrainingNotice.Version}, to agree.", StatusCodes.Status400BadRequest, ct, ReturnPathOf(form?["returnUrl"] ?? default));
+ }
+
+ var accountId = actor.UserAccount.Id;
+ if (!await HasLiveReceiptAsync(db, accountId, ct))
+ {
+ db.ConsentReceipts.Add(new ConsentReceipt
+ {
+ UserAccountId = accountId,
+ NoticeVersion = TrainingNotice.Version,
+ AcceptedAtUtc = clock.GetUtcNow()
+ });
+ try
+ {
+ await db.SaveChangesAsync(ct);
+ }
+ catch (DbUpdateException error) when (IsUniqueViolation(error))
+ {
+ // The filtered unique index refused a second live receipt: another request holds it, so this accept has nothing to add.
+ // Only that violation is swallowed; any other store fault propagates. Not re-checked: a withdraw may already have stamped the winner, and the outcome for this request is the same.
+ db.ChangeTracker.Clear();
+ }
+ }
+
+ return new SeeOther(ReturnPathOf(form["returnUrl"]) ?? Path);
+ }).AllowAnonymous();
+
+ app.MapPost(Path + "/withdraw", async (
+ HttpContext http,
+ ICurrentBifrostActorAccessor actors,
+ BifrostDbContext db,
+ TimeProvider clock,
+ IOptions host,
+ CancellationToken ct) =>
+ {
+ if (!RequestOriginGuard.Allows(http.Request, host.Value))
+ {
+ return Refused();
+ }
+
+ var actor = await actors.GetAsync(ct);
+ if (!actor.IsAuthenticated || actor.UserAccount is null)
+ {
+ return Results.Unauthorized();
+ }
+
+ var live = await db.ConsentReceipts
+ .Where(x => x.UserAccountId == actor.UserAccount.Id && x.WithdrawnAtUtc == null)
+ .ToListAsync(ct);
+ if (live.Count > 0)
+ {
+ var now = clock.GetUtcNow();
+ foreach (var receipt in live)
+ {
+ receipt.WithdrawnAtUtc = now;
+ }
+
+ await db.SaveChangesAsync(ct);
+ }
+
+ return Back();
+ }).AllowAnonymous();
+ }
+
+ // Postgres SqlState 23505, on the exception or anywhere down its inner chain.
+ private static bool IsUniqueViolation(Exception error)
+ {
+ for (var e = (Exception?)error; e is not null; e = e.InnerException)
+ {
+ if (e is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation })
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static IResult Refused() => Results.Text("Cross-site consent changes are refused.", statusCode: StatusCodes.Status403Forbidden);
+
+ /// Where the consent page sends the member after agreeing: a local path ( ) the refused chat authorize names, else the page itself.
+ internal static string? ReturnPathOf(Microsoft.Extensions.Primitives.StringValues requested) =>
+ requested.ToString() is { Length: > 0 } text ? LocalReturnPath.Parse(text).Value : null;
+
+ /// The consent page that a refused chat sign-in lands on, carrying the request to resume once the member agrees.
+ public static string PathFor(string returnPath) => $"{Path}?returnUrl={Uri.EscapeDataString(returnPath)}";
+
+ private static IResult Back() => new SeeOther(Path);
+
+ /// The one reading of "may speak": a live receipt for the version in force. A receipt for any other version, or a withdrawn one, does not count.
+ internal static Task HasLiveReceiptAsync(BifrostDbContext db, Guid accountId, CancellationToken ct) =>
+ db.ConsentReceipts.AnyAsync(x => x.UserAccountId == accountId && x.NoticeVersion == TrainingNotice.Version && x.WithdrawnAtUtc == null, ct);
+
+ private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct)
+ {
+ const int MaxFormBytes = 1024;
+ if (!request.HasFormContentType || request.ContentLength > MaxFormBytes)
+ {
+ return null;
+ }
+
+ if (request.HttpContext.Features.Get() is { IsReadOnly: false } limit)
+ {
+ limit.MaxRequestBodySize = MaxFormBytes;
+ }
+
+ try
+ {
+ return await request.ReadFormAsync(ct);
+ }
+ catch (Exception error) when (error is InvalidDataException or BadHttpRequestException)
+ {
+ return null;
+ }
+ }
+
+ private sealed class SeeOther(string location) : IResult
+ {
+ public Task ExecuteAsync(HttpContext httpContext)
+ {
+ httpContext.Response.StatusCode = StatusCodes.Status303SeeOther;
+ httpContext.Response.Headers.Location = location;
+ httpContext.Response.Headers.CacheControl = "no-store";
+ return Task.CompletedTask;
+ }
+ }
+
+ private static async Task PageAsync(BifrostDbContext db, Guid accountId, string? error, int status, CancellationToken ct, string? returnPath = null)
+ {
+ var receipts = await db.ConsentReceipts.AsNoTracking().Where(x => x.UserAccountId == accountId).ToListAsync(ct);
+ return new HtmlPage(ConsentPage.Render(ConsentPage.StateOf(receipts), error, returnPath), status);
+ }
+
+ private sealed class HtmlPage(string html, int status) : IResult
+ {
+ public async Task ExecuteAsync(HttpContext httpContext)
+ {
+ httpContext.Response.StatusCode = status;
+ httpContext.Response.ContentType = "text/html; charset=utf-8";
+ httpContext.Response.Headers.CacheControl = "no-store";
+ await httpContext.Response.WriteAsync(html);
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/ConsentPage.cs b/src/Bifrost.Web/Features/Registration/ConsentPage.cs
new file mode 100644
index 0000000..f34719f
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/ConsentPage.cs
@@ -0,0 +1,105 @@
+using System.Net;
+using Bifrost.Web.Domain;
+
+namespace Bifrost.Web.Features.Registration;
+
+/// Where an account stands against the notice in force. Exactly one holds.
+public abstract record ConsentState
+{
+ public sealed record None : ConsentState;
+
+ public sealed record Current(DateTimeOffset AgreedAtUtc) : ConsentState;
+
+ public sealed record Older(int Version, DateTimeOffset AgreedAtUtc) : ConsentState;
+
+ public sealed record Withdrawn(DateTimeOffset WithdrawnAtUtc) : ConsentState;
+}
+
+///
+/// The server-rendered consent page: the notice in force, the account's state and the buttons that apply. No script,
+/// no external asset, no cookie of its own.
+///
+public static class ConsentPage
+{
+ /// A live receipt for the version in force wins, then a live older one, then the latest withdrawal, else none.
+ public static ConsentState StateOf(IReadOnlyCollection receipts)
+ {
+ var live = receipts.Where(x => x.WithdrawnAtUtc is null).ToList();
+ if (live.FirstOrDefault(x => x.NoticeVersion == TrainingNotice.Version) is { } current)
+ {
+ return new ConsentState.Current(current.AcceptedAtUtc);
+ }
+
+ if (live.OrderByDescending(x => x.NoticeVersion).FirstOrDefault() is { } older)
+ {
+ return new ConsentState.Older(older.NoticeVersion, older.AcceptedAtUtc);
+ }
+
+ return receipts.Count > 0
+ ? new ConsentState.Withdrawn(receipts.Max(x => x.WithdrawnAtUtc!.Value))
+ : new ConsentState.None();
+ }
+
+ private static string Iso(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture);
+
+ public static string Render(ConsentState state, string? error, string? returnPath = null)
+ {
+ static string E(string? text) => WebUtility.HtmlEncode(text ?? "");
+ var version = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ var (message, anyLive) = state switch
+ {
+ ConsentState.Current current => ($"You agreed to version {version} on {Iso(current.AgreedAtUtc)}. You may speak in a recorded room, and your messages may be used as the notice says.", true),
+ ConsentState.Older older => ($"You agreed to version {older.Version} on {Iso(older.AgreedAtUtc)}; version {version} is in force; you cannot speak in a recorded room and your messages are not used until you agree to it.", true),
+ ConsentState.Withdrawn withdrawn => ($"You withdrew on {Iso(withdrawn.WithdrawnAtUtc)}. You cannot speak in a recorded room, and your messages are not used. Lines you already spoke stay.", false),
+ _ => ("You have not agreed. You cannot speak in a recorded room, and your messages are not used.", false)
+ };
+ var summary = error is null ? "" : $"""That did not go through. {E(error)}
""";
+ // Withdraw whenever any live receipt exists (an older one included); Agree whenever none is live for the version in force.
+ var back = returnPath is null ? "" : $""" """;
+ var withdrawButton = anyLive
+ ? """"""
+ : "";
+ var agreeButton = state is ConsentState.Current
+ ? ""
+ : $"""""";
+ var button = agreeButton + withdrawButton;
+
+ return $$"""
+
+
+
+
+
+ Training consent - Bifrost
+
+
+
+
+ Your account
+ Training consent
+ {{summary}}
+ {{E(message)}}
+
+ Training notice, version {{version}}
+ {{TrainingNotice.Html("notice")}}
+
+ {{button}}
+
+
+
+ """;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/NativeRegistration.cs b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs
new file mode 100644
index 0000000..042b615
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/NativeRegistration.cs
@@ -0,0 +1,123 @@
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+
+namespace Bifrost.Web.Features.Registration;
+
+/// What a client sent to register. claims the time-lock path instead of a proof of work.
+public sealed record RegistrationAttempt(
+ string? Identity,
+ string? DisplayName,
+ string? Challenge,
+ string? Nonce,
+ bool Waited,
+ int? AcceptedNoticeVersion);
+
+/// Which input a refusal is about, so the form can mark it invalid.
+public enum RegistrationField { None, Identity, Consent }
+
+///
+/// Either a signed-in , or a to return as is (the rate limits), or a rejection
+/// with a status and message. is set when the challenge was not spent and a retry needs only a correction, so the form should carry it on (the time-lock clock must not restart).
+///
+public sealed record RegistrationOutcome(
+ UserAccount? Account,
+ IResult? Refusal,
+ int Status,
+ string? Message,
+ RegistrationField Field,
+ bool KeepChallenge)
+{
+ public static RegistrationOutcome Reject(int status, string message, RegistrationField field = RegistrationField.None, bool keepChallenge = false) =>
+ new(null, null, status, message, field, keepChallenge);
+}
+
+///
+/// The one registration gate, run by the JSON endpoint and the form alike after each has spent the general address budget.
+/// Order: consent version (when sent), one proof only, the identity rules (which spend nothing), the challenge (proof of work, or the
+/// time-lock plus its tighter budget), then the account (and its receipt when consent was sent) in one save, then the cookie. A refusal at any step
+/// creates nothing, and a refusal before the challenge step spends neither the challenge nor a fallback permit.
+///
+public sealed class NativeRegistration(
+ BifrostIdentityService identities,
+ RegistrationChallengeService challenges,
+ RegistrationRateLimit rateLimit)
+{
+ public async Task RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
+ {
+ // Consent is optional: none sends no receipt. A version that is sent must be the one in force; a refusal here creates nothing.
+ if (attempt.AcceptedNoticeVersion is { } sent && sent != TrainingNotice.Version)
+ {
+ return RegistrationOutcome.Reject(
+ StatusCodes.Status400BadRequest,
+ $"The training notice in force is version {TrainingNotice.Version}; send that version to agree, or send none to register without agreeing.",
+ RegistrationField.Consent);
+ }
+
+ var hasNonce = !string.IsNullOrEmpty(attempt.Nonce);
+ if (hasNonce && attempt.Waited)
+ {
+ return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Send a nonce or waited, not both.");
+ }
+
+ try
+ {
+ await identities.CheckAvailableAsync(attempt.Identity ?? "", cancellationToken);
+ }
+ catch (BifrostIdentityException error)
+ {
+ return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity, keepChallenge: true);
+ }
+
+ var failed = RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Registration challenge failed.");
+ if (hasNonce)
+ {
+ if (!challenges.TryConsume(attempt.Challenge, attempt.Nonce))
+ {
+ return failed;
+ }
+ }
+ else if (attempt.Waited)
+ {
+ if (challenges.WaitRemaining(attempt.Challenge) is not { } remaining)
+ {
+ return failed;
+ }
+
+ if (remaining > TimeSpan.Zero)
+ {
+ var seconds = (int)Math.Ceiling(remaining.TotalSeconds);
+ return RegistrationOutcome.Reject(
+ StatusCodes.Status400BadRequest,
+ $"Too early: {seconds} more second{(seconds == 1 ? "" : "s")} to wait after the page opened. Your challenge is still good; submit again then.",
+ keepChallenge: true);
+ }
+
+ if (rateLimit.RefuseFallback(http) is { } fallbackRefused)
+ {
+ return new(null, fallbackRefused, 0, null, RegistrationField.None, false);
+ }
+
+ if (!challenges.TryConsumeWaited(attempt.Challenge))
+ {
+ return failed;
+ }
+ }
+ else
+ {
+ return failed;
+ }
+
+ try
+ {
+ var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken);
+ await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account));
+ return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false);
+ }
+ catch (BifrostIdentityException error)
+ {
+ return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity);
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs b/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs
new file mode 100644
index 0000000..764810d
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/RegistrationChallengeService.cs
@@ -0,0 +1,180 @@
+using System.Security.Cryptography;
+using System.Text;
+using Bifrost.Web.Configuration;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Registration;
+
+public sealed record RegistrationChallenge(string Challenge, int Difficulty, DateTimeOffset ExpiresAt);
+
+///
+/// Self-hosted proof-of-work challenge for the anonymous registration. A challenge is a data-protected
+/// (random id, expiry) payload, so the server keeps nothing per issue; only consumed ids are remembered, in a bounded
+/// set whose entries are dropped at expiry. A full set refuses both issuing and consuming rather than grow.
+///
+public sealed class RegistrationChallengeService(
+ IDataProtectionProvider dataProtection,
+ IOptions options,
+ TimeProvider clock)
+{
+ public const string Purpose = "Bifrost.Registration.Challenge.v1";
+
+ public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
+
+ public const int MaxConsumed = 10_000;
+
+ private const int MaxNonceLength = 20;
+
+ private readonly IDataProtector protector = dataProtection.CreateProtector(Purpose);
+ private readonly HashSet consumed = new(StringComparer.Ordinal);
+ // Ordered by expiry: a challenge consumed late has an earlier expiry than one consumed before it, so a plain FIFO would strand it.
+ private readonly PriorityQueue expiries = new();
+ private readonly object gate = new();
+
+ private int Difficulty => options.Value.Captcha.Difficulty;
+
+ /// Null when the consumed set is full: refuse rather than grow.
+ public RegistrationChallenge? Issue()
+ {
+ var now = clock.GetUtcNow();
+ lock (gate)
+ {
+ Purge(now);
+ if (consumed.Count >= MaxConsumed)
+ {
+ return null;
+ }
+ }
+
+ var expiresAt = now + Lifetime;
+ var difficulty = Difficulty;
+ var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
+ var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}.{now.ToUnixTimeMilliseconds()}");
+ return new RegistrationChallenge(challenge, difficulty, expiresAt);
+ }
+
+ /// Proof-of-work path: the nonce must meet the difficulty the challenge was issued with. Spends the challenge.
+ public bool TryConsume(string? challenge, string? nonce)
+ {
+ if (!IsNonce(nonce) || Open(challenge) is not { } open)
+ {
+ return false;
+ }
+
+ var hash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + nonce));
+ return LeadingZeroBits(hash) >= open.Difficulty && Spend(open);
+ }
+
+ ///
+ /// Time-lock path, step one: how long until a waited submission of this challenge is accepted. Null when the
+ /// token is not a live challenge of ours; zero when the wait is over. Spends nothing.
+ ///
+ public TimeSpan? WaitRemaining(string? challenge)
+ {
+ if (Open(challenge) is not { } open)
+ {
+ return null;
+ }
+
+ var remaining = open.IssuedAt + TimeSpan.FromSeconds(options.Value.Captcha.FallbackWaitSeconds) - clock.GetUtcNow();
+ return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
+ }
+
+ /// Time-lock path, step two: spends the challenge if its wait is over. No proof of work is checked.
+ public bool TryConsumeWaited(string? challenge) =>
+ WaitRemaining(challenge) == TimeSpan.Zero && Open(challenge) is { } open && Spend(open);
+
+ /// True when the token is ours, unexpired and not yet spent, so a form may carry it into its next attempt.
+ public bool IsLive(string? challenge)
+ {
+ if (Open(challenge) is not { } open)
+ {
+ return false;
+ }
+
+ lock (gate)
+ {
+ return !consumed.Contains(open.Id);
+ }
+ }
+
+ private sealed record OpenChallenge(string Id, int Difficulty, DateTimeOffset ExpiresAt, DateTimeOffset IssuedAt);
+
+ /// The payload of a challenge that we protected and that has not expired; null otherwise.
+ private OpenChallenge? Open(string? challenge)
+ {
+ if (string.IsNullOrEmpty(challenge))
+ {
+ return null;
+ }
+
+ OpenChallenge open;
+ try
+ {
+ var payload = protector.Unprotect(challenge).Split('.');
+ if (payload.Length != 4)
+ {
+ return null;
+ }
+
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
+ open = new OpenChallenge(
+ payload[0],
+ int.Parse(payload[2], culture),
+ DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[1], culture)),
+ DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[3], culture)));
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+
+ return clock.GetUtcNow() >= open.ExpiresAt ? null : open;
+ }
+
+ private bool Spend(OpenChallenge open)
+ {
+ var now = clock.GetUtcNow();
+ lock (gate)
+ {
+ Purge(now);
+ if (consumed.Count >= MaxConsumed || !consumed.Add(open.Id))
+ {
+ return false;
+ }
+
+ expiries.Enqueue(open.Id, open.ExpiresAt);
+ return true;
+ }
+ }
+
+ private void Purge(DateTimeOffset now)
+ {
+ while (expiries.TryPeek(out var id, out var expiresAt) && expiresAt <= now)
+ {
+ expiries.Dequeue();
+ consumed.Remove(id);
+ }
+ }
+
+ private static bool IsNonce(string? nonce) =>
+ nonce is { Length: >= 1 and <= MaxNonceLength } && nonce.All(c => c is >= '0' and <= '9');
+
+ public static int LeadingZeroBits(ReadOnlySpan hash)
+ {
+ var bits = 0;
+ foreach (var b in hash)
+ {
+ if (b == 0)
+ {
+ bits += 8;
+ continue;
+ }
+
+ return bits + System.Numerics.BitOperations.LeadingZeroCount((uint)b) - 24;
+ }
+
+ return bits;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/RegistrationPage.cs b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs
new file mode 100644
index 0000000..ef0e232
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/RegistrationPage.cs
@@ -0,0 +1,177 @@
+using System.Net;
+using System.Text;
+
+namespace Bifrost.Web.Features.Registration;
+
+/// What the sign-up page shows. Everything user-supplied is HTML-encoded on the way out.
+public sealed record RegistrationPageModel(
+ string ReturnPath,
+ string Challenge,
+ int Difficulty,
+ int WaitSeconds,
+ string Identity = "",
+ string DisplayName = "",
+ string? Error = null,
+ RegistrationField ErrorField = RegistrationField.None);
+
+///
+/// The server-rendered sign-up form. It works with no script (time-lock path); the inline script, when it can, replaces the
+/// wait by solving the proof of work. No external asset, no cookie, no third party.
+///
+public static class RegistrationPage
+{
+ // Hash rule is RegistrationChallengeService's: SHA-256 of challenge + ":" + nonce, leading zero bits >= difficulty.
+ // Hashes run in batches that yield to the UI between them. If the browser has no crypto.subtle, nothing here runs
+ // and the form submits on the time-lock path.
+ public const string Script = """
+ (function () {
+ var form = document.getElementById("register");
+ var status = document.getElementById("status");
+ if (!form || !status || !window.crypto || !window.crypto.subtle || !window.TextEncoder) { return; }
+ var BATCH = 256;
+ var busy = false;
+ var solved = false;
+ var skipped = false;
+
+ function zeroBits(bytes) {
+ var bits = 0;
+ for (var i = 0; i < bytes.length; i++) {
+ if (bytes[i] === 0) { bits += 8; continue; }
+ return bits + Math.clz32(bytes[i]) - 24;
+ }
+ return bits;
+ }
+
+ async function solve(challenge, difficulty) {
+ var encoder = new TextEncoder();
+ for (var start = 0; !skipped; start += BATCH) {
+ var tries = [];
+ for (var n = start; n < start + BATCH; n++) {
+ tries.push(crypto.subtle.digest("SHA-256", encoder.encode(challenge + ":" + n)));
+ }
+ var hashes = await Promise.all(tries);
+ for (var i = 0; i < hashes.length; i++) {
+ if (zeroBits(new Uint8Array(hashes[i])) >= difficulty) { return String(start + i); }
+ }
+ await new Promise(function (resolve) { setTimeout(resolve, 0); });
+ }
+ return null;
+ }
+
+ form.addEventListener("submit", function (event) {
+ if (event.submitter && event.submitter.id === "skip") {
+ // The way out of a slow solve: stop it and let this submit go on the time-lock path.
+ skipped = true;
+ solved = true;
+ form.elements.nonce.value = "";
+ form.elements.waited.disabled = false;
+ status.textContent = "Skipping the automatic check.";
+ return;
+ }
+ if (solved) { return; }
+ event.preventDefault();
+ if (busy) { return; }
+ busy = true;
+ status.textContent = "Checking. This can take longer on a slow device; press Skip the automatic check to wait " + form.getAttribute("data-wait") + " seconds instead.";
+ solve(form.elements.challenge.value, parseInt(form.getAttribute("data-difficulty"), 10)).then(function (nonce) {
+ if (skipped || nonce === null) { return; }
+ form.elements.nonce.value = nonce;
+ form.elements.waited.disabled = true;
+ solved = true;
+ status.textContent = "Creating your account";
+ form.submit();
+ }, function () {
+ solved = true;
+ busy = false;
+ status.textContent = "The automatic check did not run in this browser. Press Skip the automatic check and wait as described below.";
+ });
+ });
+ })();
+ """;
+
+ public static string Render(RegistrationPageModel model)
+ {
+ static string E(string? text) => WebUtility.HtmlEncode(text ?? "");
+ var notice = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ var summary = new StringBuilder();
+ if (model.Error is not null)
+ {
+ var link = model.ErrorField switch
+ {
+ RegistrationField.Identity => """""",
+ RegistrationField.Consent => """""",
+ _ => ""
+ };
+ summary.Append($"""Registration did not go through. {E(model.Error)}
{link}
""");
+ }
+
+ string Invalid(RegistrationField field) => model.Error is not null && model.ErrorField == field ? " aria-invalid=\"true\" aria-describedby=\"errors\"" : "";
+ var wait = model.WaitSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
+
+ return $$"""
+
+
+
+
+
+ Create an account - Bifrost
+
+
+
+
+ Public registration
+ Create a Bifrost account
+ A new account can chat. It has no vote and opens no member or governance surface.
+ {{summary}}
+
+ Without a script, or if the automatic check is slow, wait {{wait}} seconds after the page opened and press the button to skip it (or Create account when there is no script). Pressed sooner, the page comes back saying how many seconds remain and keeps your names; the consent box comes back unchecked, so tick it again if you want to agree. Without the automatic check only a few registrations per hour are accepted from one address.
+ After registering, Bifrost returns you to {{E(model.ReturnPath)}}.
+
+
+
+
+ """;
+ }
+}
diff --git a/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs b/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs
new file mode 100644
index 0000000..d95e7f3
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/RegistrationRateLimit.cs
@@ -0,0 +1,56 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Features.Shared;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Registration;
+
+///
+/// The per-address permits on the registration endpoints (challenge and register share one budget), on the shared
+/// fixed-window budget. It exists so one address cannot fill the consumed-challenge set alone. It fails closed:
+/// anything it cannot decide is a 503, never a pass.
+///
+public sealed class RegistrationRateLimit(IOptions options, TimeProvider clock, ILogger logger)
+{
+ private readonly FixedWindowBudget addresses = new(
+ options.Value.Limits.PerAddressPermits,
+ options.Value.Limits.Window,
+ options.Value.Limits.MaxTrackedKeys,
+ clock);
+
+ // Time-lock submissions cost the client no work, so they get their own, much tighter budget per address.
+ private readonly FixedWindowBudget fallbacks = new(
+ options.Value.Limits.FallbackPermits,
+ options.Value.Limits.FallbackWindow,
+ options.Value.Limits.MaxTrackedKeys,
+ clock);
+
+ /// Null when the request may proceed; otherwise the refusal to return.
+ public IResult? Refuse(HttpContext http) => Refuse(http, addresses, "Too many registration requests from this address.");
+
+ /// The stricter budget for a submission that passed the time-lock instead of the proof of work.
+ public IResult? RefuseFallback(HttpContext http) =>
+ Refuse(http, fallbacks, "Too many registrations without the quick check from this address; try again later or let the page run its script.");
+
+ private IResult? Refuse(HttpContext http, FixedWindowBudget budget, string message)
+ {
+ try
+ {
+ if (budget.Spend(ClientAddress.BudgetKey(http.Connection.RemoteIpAddress)) is not { } denial)
+ {
+ return null;
+ }
+
+ http.Response.Headers.RetryAfter = RetryAfter(denial.RetryAfter);
+ return Results.Text(message, statusCode: StatusCodes.Status429TooManyRequests);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ logger.LogError("Registration rate limit could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name);
+ http.Response.Headers.RetryAfter = "60";
+ return Results.Text("Registration is unavailable; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable);
+ }
+ }
+
+ private static string RetryAfter(TimeSpan wait) =>
+ Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
+}
diff --git a/src/Bifrost.Web/Features/Registration/TrainingNotice.cs b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs
new file mode 100644
index 0000000..a823426
--- /dev/null
+++ b/src/Bifrost.Web/Features/Registration/TrainingNotice.cs
@@ -0,0 +1,36 @@
+using System.Net;
+using System.Text;
+
+namespace Bifrost.Web.Features.Registration;
+
+///
+/// The training notice a person may agree to. Changing the wording in substance means a new (a
+/// positive integer, no leading zeros), because a receipt records the version the person agreed to; a receipt for any
+/// other version no longer counts, the chat sign-in is refused, and the person is asked again on the consent page.
+/// The text is frozen once served: a test pins its hash per version, so an edit without a version bump fails.
+///
+public static class TrainingNotice
+{
+ public const int Version = 1;
+
+ public const string Text =
+ "GameCult chat training notice, version 1\n\n" +
+ "GameCult may use messages you post in GameCult chat to train and evaluate AI models that GameCult builds and runs.\n\n" +
+ "What counts. The text of your messages, with their time and room, tied to your account name. Not your email address, your sign-in details or anything you did not post. Nothing that came from Discord is used, in any form.\n\n" +
+ "It is your choice. Agreement is needed to speak in a recorded room. You can have a GameCult account, see the members page and vote without agreeing. If you do not agree, you cannot speak in a recorded room and none of your messages are used.\n\n" +
+ "If you agree, we record your account, this notice's version number and the time. Nothing else is stored with it.\n\n" +
+ "If you withdraw, you can no longer speak in a recorded room, and we leave all your messages out of every training set made after that moment. Lines you have already spoken stay: withdrawing deletes nothing. Your messages stay in chat and on our servers, anything already used to train a model stays used, and a dataset already built is not recalled. We keep the record that you agreed and when you withdrew.\n\n" +
+ "You can agree or withdraw at any time on your consent page while signed in. If the notice changes, its version changes and we ask again; until you agree to the new version, you cannot speak in a recorded room and your messages are not used.";
+
+ /// The text as HTML-encoded paragraphs inside a div with the given id.
+ public static string Html(string id)
+ {
+ var html = new StringBuilder($"");
+ foreach (var paragraph in Text.Split("\n\n"))
+ {
+ html.Append("
").Append(WebUtility.HtmlEncode(paragraph)).Append("
");
+ }
+
+ return html.Append("
").ToString();
+ }
+}
diff --git a/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs b/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
index 1a3cd0f..f7cf59b 100644
--- a/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
+++ b/src/Bifrost.Web/Features/Shared/ApplicationBootstrapper.cs
@@ -10,6 +10,7 @@ public sealed class ApplicationBootstrapper(
BifrostDbContext dbContext,
IOptions bootstrapOptions,
TimeProvider timeProvider,
+ AuditTrailService auditTrailService,
ILogger logger)
{
public async Task RunAsync(CancellationToken cancellationToken)
@@ -40,16 +41,11 @@ public sealed class ApplicationBootstrapper(
foreach (var adminUser in adminUsers.Where(x => x.Membership is not null))
{
- var membership = adminUser.Membership!;
- membership.Status = MembershipStatus.Active;
- membership.IsPlatformAdmin = true;
- membership.CanManageProjects = true;
- membership.CanManageLedger = true;
- membership.CanModerateMotions = true;
- membership.ApprovedAtUtc ??= now;
-
- EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
- EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
+ var before = adminUser.Membership!.Status;
+ if (TryPromoteBootstrapAdmin(adminUser, now, logger) && before != adminUser.Membership.Status)
+ {
+ await RecordPromotionAsync(auditTrailService, adminUser, before, cancellationToken);
+ }
}
if (dbContext.ChangeTracker.HasChanges())
@@ -58,6 +54,47 @@ public sealed class ApplicationBootstrapper(
}
}
+ ///
+ /// The one bootstrap-admin promotion, used at startup and at sign-in. A Merged or Suspended account is left exactly as it is (an admin's
+ /// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
+ ///
+ public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
+ {
+ var membership = account.Membership!;
+ if (membership.IsMerged)
+ {
+ logger.LogWarning("Bootstrap admin promotion skipped for merged account {UserAccountId}.", account.Id);
+ return false;
+ }
+
+ if (membership.Status == MembershipStatus.Suspended)
+ {
+ logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
+ return false;
+ }
+
+ membership.Status = MembershipStatus.Active;
+ membership.IsPlatformAdmin = true;
+ membership.CanManageProjects = true;
+ membership.CanManageLedger = true;
+ membership.CanModerateMotions = true;
+ membership.ApprovedAtUtc ??= now;
+
+ EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
+ EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
+ return true;
+ }
+
+ /// The receipt for a bootstrap promotion that changed membership status; saves together with the promotion.
+ public static Task RecordPromotionAsync(AuditTrailService auditTrailService, UserAccount account, MembershipStatus before, CancellationToken cancellationToken) =>
+ auditTrailService.RecordAsync(
+ null,
+ nameof(Bifrost.Web.Domain.Membership),
+ account.Membership!.Id,
+ "membership.bootstrap-promoted",
+ $"Bootstrap admin promotion of {account.DisplayName} ({before} -> {account.Membership.Status}).",
+ cancellationToken);
+
public static void EnsureRole(
Bifrost.Web.Domain.Membership membership,
MemberRole role,
diff --git a/src/Bifrost.Web/Features/Shared/BifrostCookies.cs b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs
new file mode 100644
index 0000000..0a99cf0
--- /dev/null
+++ b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs
@@ -0,0 +1,18 @@
+namespace Bifrost.Web.Features.Shared;
+
+// Every cookie Bifrost sets carries the __Host- prefix: the browser then accepts it only with Secure, Path=/ and no
+// Domain, so no sibling subdomain of gamecult.org (the preview host is same-site) can plant or shadow one by setting
+// a Domain=gamecult.org cookie of the same name. The prefix forbids a narrower Path, so these all live at Path=/.
+public static class BifrostCookies
+{
+ public const string HostPrefix = "__Host-";
+
+ public const string Session = HostPrefix + "bifrost_session";
+ public const string OAuthCorrelation = HostPrefix + "bifrost_oauth_correlation";
+ public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
+ public const string Voter = HostPrefix + "bifrost_voter";
+ public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
+ public const string PasskeyTicket = HostPrefix + "bifrost_passkey_ticket";
+
+ public const string Path = "/";
+}
diff --git a/src/Bifrost.Web/Features/Shared/ClientAddress.cs b/src/Bifrost.Web/Features/Shared/ClientAddress.cs
new file mode 100644
index 0000000..f959e24
--- /dev/null
+++ b/src/Bifrost.Web/Features/Shared/ClientAddress.cs
@@ -0,0 +1,32 @@
+using System.Net;
+
+namespace Bifrost.Web.Features.Shared;
+
+public static class ClientAddress
+{
+ ///
+ /// The partition key for a per-address budget: the connection's address, already corrected by the forwarded-headers
+ /// handling that trusts only the local proxy. An IPv6 caller owns its /64, so rotating the low bits buys nothing.
+ ///
+ public static string BudgetKey(IPAddress? address)
+ {
+ if (address is null)
+ {
+ return "unknown";
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
+ {
+ return address.ToString();
+ }
+
+ var bytes = address.GetAddressBytes();
+ Array.Clear(bytes, 8, 8);
+ return new IPAddress(bytes).ToString() + "/64";
+ }
+}
diff --git a/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs b/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
index 648c662..412dada 100644
--- a/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
+++ b/src/Bifrost.Web/Features/Shared/CurrentBifrostActor.cs
@@ -1,9 +1,13 @@
using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
namespace Bifrost.Web.Features.Shared;
public sealed record CurrentBifrostActor(bool IsAuthenticated, UserAccount? UserAccount)
{
+ /// Set when the account behind this sign-in is frozen or folded by an account merge; the actor then has no account.
+ public MergeStanding? Merge { get; init; }
+
public static readonly CurrentBifrostActor Anonymous = new(false, null);
public Bifrost.Web.Domain.Membership? Membership => UserAccount?.Membership;
diff --git a/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs b/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
index 5d34fad..ae9839b 100644
--- a/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
+++ b/src/Bifrost.Web/Features/Shared/CurrentBifrostActorAccessor.cs
@@ -12,7 +12,8 @@ public interface ICurrentBifrostActorAccessor
public sealed class CurrentBifrostActorAccessor(
IHttpContextAccessor httpContextAccessor,
- BifrostDbContext dbContext) : ICurrentBifrostActorAccessor
+ BifrostDbContext dbContext,
+ AccountMergeLedger ledger) : ICurrentBifrostActorAccessor
{
private const string CacheKey = "Bifrost.CurrentActor";
@@ -45,18 +46,41 @@ public sealed class CurrentBifrostActorAccessor(
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
- var userAccount = await dbContext.UserAccounts
+ // One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
+ // one principal (a merge can leave a login on either side) must never throw or pick by luck.
+ var accounts = dbContext.UserAccounts
.AsNoTracking()
.Include(x => x.MemberProfile)
.Include(x => x.Membership!)
.ThenInclude(x => x.RoleAssignments)
.Include(x => x.Membership!)
- .ThenInclude(x => x.TierSnapshots)
- .SingleOrDefaultAsync(
- x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
- (!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
- (hasGitHubUserId && x.GitHubUserId == gitHubUserId),
- cancellationToken);
+ .ThenInclude(x => x.TierSnapshots);
+
+ Bifrost.Web.Domain.UserAccount? userAccount = null;
+ if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
+ }
+
+ if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
+ }
+
+ if (userAccount is null && hasGitHubUserId)
+ {
+ userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
+ }
+
+ // A folded or frozen account acts as nobody on every route: this is the one gate (merge ledger standing, derived per request).
+ if (userAccount is not null)
+ {
+ var standing = await ledger.StandingAsync(userAccount.Id, cancellationToken);
+ if (standing is not null)
+ {
+ return Cache(httpContext, new CurrentBifrostActor(true, null) { Merge = standing });
+ }
+ }
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
}
diff --git a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
index 9f07cf9..0837f7e 100644
--- a/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
+++ b/src/Bifrost.Web/Features/Shared/DashboardSnapshotService.cs
@@ -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(
@@ -91,6 +92,7 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
var recentActivity = await dbContext.AuditEvents
.AsNoTracking()
.Include(x => x.ActorUserAccount)
+ .Where(x => !x.Action.StartsWith("membership.suspended") && !x.Action.StartsWith("membership.unsuspended") && x.Action != "membership.bootstrap-promoted") // suspension reasons and the bootstrap-admin promotion are for admins, not the member dashboard
.OrderByDescending(x => x.OccurredAtUtc)
.Take(8)
.Select(x => new DashboardActivity(
diff --git a/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs b/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
new file mode 100644
index 0000000..be1f701
--- /dev/null
+++ b/src/Bifrost.Web/Features/Shared/RequestOriginGuard.cs
@@ -0,0 +1,41 @@
+using Bifrost.Web.Configuration;
+using Microsoft.AspNetCore.Http;
+
+namespace Bifrost.Web.Features.Shared;
+
+// The one place that decides whether a state-changing request to an anonymous form (the vote page, the sign-up form) came from
+// the site itself. These flows carry no antiforgery token and no antiforgery cookie, so a cross-site form post is refused here instead
+// (OWASP Fetch Metadata): the Origin header must equal the configured site origin byte for byte, or, when the browser
+// sent no Origin, Sec-Fetch-Site must be exactly same-origin. Same-site, cross-site, none, absent and a repeated header
+// are all refused. Header values are compared, never echoed.
+public static class RequestOriginGuard
+{
+ public static bool Allows(HttpRequest request, BifrostHostOptions host)
+ {
+ if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var site))
+ {
+ return false;
+ }
+
+ var origin = request.Headers.Origin;
+ if (request.Headers.ContainsKey("Origin"))
+ {
+ return origin.Count == 1 && string.Equals(origin[0], site.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal);
+ }
+
+ var fetchSite = request.Headers["Sec-Fetch-Site"];
+ return fetchSite.Count == 1 && string.Equals(fetchSite[0], "same-origin", StringComparison.Ordinal);
+ }
+
+ ///
+ /// For the no-script sign-up form only. Text browsers (Lynx, w3m, Links) send neither Origin nor Sec-Fetch-Site, so a
+ /// request with neither is let through when it carries no Bifrost session cookie: there is no session to replace.
+ /// Any Origin or Sec-Fetch-Site present is judged exactly as judges it, and a headerless request
+ /// that does carry a session cookie is refused.
+ ///
+ public static bool AllowsFormWithoutFetchMetadata(HttpRequest request, BifrostHostOptions host) =>
+ Allows(request, host) ||
+ (!request.Headers.ContainsKey("Origin") &&
+ !request.Headers.ContainsKey("Sec-Fetch-Site") &&
+ !request.Cookies.Keys.Any(name => name.StartsWith(BifrostCookies.Session, StringComparison.Ordinal)));
+}
diff --git a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
index 98b8dc7..58fe2fb 100644
--- a/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
+++ b/src/Bifrost.Web/Features/Shared/StartupConfigurationValidator.cs
@@ -1,5 +1,6 @@
using Bifrost.Web.Configuration;
using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Registration;
using Microsoft.Extensions.Options;
namespace Bifrost.Web.Features.Shared;
@@ -12,12 +13,18 @@ public sealed class StartupConfigurationValidator(
IOptions heimdallOptions,
IOptions stripeOptions,
IOptions hostOptions,
- IOptions conceptVoteOptions)
+ IOptions conceptVoteOptions,
+ IOptions deskOptions,
+ IOptions registrationOptions,
+ OidcIssuerOptions? oidcOptions = null)
{
public void Validate()
{
var failures = new List();
+ // Building the options resolves Heimdall:AppSecretFile, and a bad file stops startup in every environment.
+ _ = heimdallOptions.Value;
+
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
var conceptVotes = conceptVoteOptions.Value;
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
@@ -45,6 +52,32 @@ public sealed class StartupConfigurationValidator(
failures.Add("ConceptVotes:MaxTrackedKeys must be at least 1.");
}
+ ValidateDesk(deskOptions.Value, failures);
+
+ var difficulty = registrationOptions.Value.Captcha.Difficulty;
+ if (difficulty < RegistrationOptions.MinDifficulty || difficulty > RegistrationOptions.MaxDifficulty)
+ {
+ failures.Add($"Bifrost:Registration:Captcha:Difficulty must be between {RegistrationOptions.MinDifficulty} and {RegistrationOptions.MaxDifficulty}.");
+ }
+
+ var wait = registrationOptions.Value.Captcha.FallbackWaitSeconds;
+ if (wait < RegistrationOptions.MinFallbackWaitSeconds || wait > RegistrationOptions.MaxFallbackWaitSeconds ||
+ wait >= RegistrationChallengeService.Lifetime.TotalSeconds)
+ {
+ failures.Add($"Bifrost:Registration:Captcha:FallbackWaitSeconds must be between {RegistrationOptions.MinFallbackWaitSeconds} and {RegistrationOptions.MaxFallbackWaitSeconds} and shorter than the challenge lifetime ({RegistrationChallengeService.Lifetime.TotalSeconds:0} seconds).");
+ }
+
+ var limits = registrationOptions.Value.Limits;
+ if (limits.PerAddressPermits < 1 || limits.Window <= TimeSpan.Zero || limits.MaxTrackedKeys < 1)
+ {
+ failures.Add("Bifrost:Registration:Limits:PerAddressPermits and MaxTrackedKeys must be at least 1 and Window must be positive.");
+ }
+
+ if (limits.FallbackPermits < 1 || limits.FallbackWindow <= TimeSpan.Zero)
+ {
+ failures.Add("Bifrost:Registration:Limits:FallbackPermits must be at least 1 and FallbackWindow must be positive.");
+ }
+
if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing"))
{
Refuse(failures);
@@ -72,6 +105,13 @@ public sealed class StartupConfigurationValidator(
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
}
+ // The options are already resolved, so a secret from Heimdall:AppSecretFile or Heimdall:AppSecret lands in AppSecret.
+ // Blank would silently switch Discord and Patreon member sign-in off.
+ if (string.IsNullOrWhiteSpace(heimdallOptions.Value.AppSecret))
+ {
+ failures.Add("Heimdall:AppSecretFile (or Heimdall:AppSecret) must supply the Heimdall app secret outside development.");
+ }
+
if (stripeOptions.Value.EnableCheckout)
{
if (!stripeOptions.Value.IsCheckoutConfigured)
@@ -116,6 +156,112 @@ public sealed class StartupConfigurationValidator(
Refuse(failures);
}
+ // Checked in every environment: a bad Mind list or decider id would otherwise pass startup and misroute or
+ // mis-attribute answers. Account existence is a request-time question, not a startup one.
+ private void ValidateDesk(DeskOptions desk, List failures)
+ {
+ // The desk's bearer is validated against Bifrost's own issuer: without Bifrost:Oidc there is no credential to serve with.
+ if (oidcOptions is null && configuration.GetSection(DeskOptions.SectionName).Exists())
+ {
+ failures.Add("Bifrost:Oidc must be configured when the Desk section exists: the desk validates its bearer tokens against Bifrost's own issuer.");
+ }
+
+ if (!desk.IsConfigured)
+ {
+ if (configuration.GetSection(DeskOptions.SectionName).Exists())
+ {
+ failures.Add("Desk:Minds must list at least one Mind when the Desk section exists.");
+ }
+
+ return;
+ }
+
+ if (!Uri.TryCreate(desk.AllowedOrigin, UriKind.Absolute, out var origin) ||
+ origin.Scheme is not ("http" or "https") ||
+ !string.Equals(desk.AllowedOrigin, origin.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal))
+ {
+ failures.Add("Desk:AllowedOrigin must be one http(s) origin: scheme, host and optional port, no path.");
+ }
+
+ if (desk.MaxBodyBytes < 1)
+ {
+ failures.Add("Desk:MaxBodyBytes must be at least 1.");
+ }
+
+ if (desk.RetryAfterSeconds < 1)
+ {
+ failures.Add("Desk:RetryAfterSeconds must be at least 1.");
+ }
+
+ var ids = new HashSet(StringComparer.Ordinal);
+ var sockets = new HashSet(StringComparer.Ordinal);
+ for (var i = 0; i < desk.Minds.Count; i++)
+ {
+ var mind = desk.Minds[i];
+ if (string.IsNullOrWhiteSpace(mind.Id))
+ {
+ failures.Add($"Desk:Minds:{i}:Id must not be blank.");
+ }
+ else if (!ids.Add(mind.Id))
+ {
+ failures.Add($"Desk:Minds:{i}:Id repeats an earlier Mind id.");
+ }
+
+ if (!Path.IsPathFullyQualified(mind.Socket))
+ {
+ failures.Add($"Desk:Minds:{i}:Socket must be an absolute path.");
+ }
+ else if (!sockets.Add(mind.Socket))
+ {
+ failures.Add($"Desk:Minds:{i}:Socket repeats an earlier Mind's socket.");
+ }
+
+ if (mind.Deciders.Count is < 1 or > DeskMindOptions.MaxDeciders)
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders must hold 1 to {DeskMindOptions.MaxDeciders} account ids.");
+ }
+
+ var deciders = new HashSet(StringComparer.Ordinal);
+ foreach (var decider in mind.Deciders)
+ {
+ if (!IsLowercaseGuid(decider))
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders entries must be lowercase D-format account ids.");
+ }
+ else if (!deciders.Add(decider))
+ {
+ failures.Add($"Desk:Minds:{i}:Deciders repeats an account id.");
+ }
+ }
+ }
+
+ var attribution = desk.Attribution;
+ if (!string.IsNullOrEmpty(attribution.Operator) && !IsLowercaseGuid(attribution.Operator))
+ {
+ failures.Add("Desk:Attribution:Operator must be a lowercase D-format account id.");
+ }
+
+ var stewards = new HashSet(StringComparer.Ordinal);
+ foreach (var steward in attribution.Stewards)
+ {
+ if (!IsLowercaseGuid(steward))
+ {
+ failures.Add("Desk:Attribution:Stewards entries must be lowercase D-format account ids.");
+ }
+ else if (!stewards.Add(steward))
+ {
+ failures.Add("Desk:Attribution:Stewards repeats an account id.");
+ }
+ else if (string.Equals(steward, attribution.Operator, StringComparison.Ordinal))
+ {
+ failures.Add("Desk:Attribution:Operator must not also be a steward.");
+ }
+ }
+ }
+
+ private static bool IsLowercaseGuid(string? value) =>
+ Guid.TryParseExact(value, "D", out var guid) && string.Equals(value, guid.ToString("D"), StringComparison.Ordinal);
+
private static void Refuse(List failures)
{
if (failures.Count > 0)
diff --git a/src/Bifrost.Web/Pages/App/Index.cshtml b/src/Bifrost.Web/Pages/App/Index.cshtml
index 889675a..c3406be 100644
--- a/src/Bifrost.Web/Pages/App/Index.cshtml
+++ b/src/Bifrost.Web/Pages/App/Index.cshtml
@@ -14,12 +14,7 @@
governance pressure, and recent team activity in one place.
-
- Refresh snapshot
-
+ Refresh snapshot
diff --git a/src/Bifrost.Web/Pages/App/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Index.cshtml.cs
index ed0db5c..9d8a800 100644
--- a/src/Bifrost.Web/Pages/App/Index.cshtml.cs
+++ b/src/Bifrost.Web/Pages/App/Index.cshtml.cs
@@ -18,11 +18,4 @@ public sealed class IndexModel(
Actor = await actorAccessor.GetAsync(cancellationToken);
Snapshot = await snapshotService.GetAsync(Actor.UserAccount?.Id, cancellationToken);
}
-
- public async Task
OnGetSummaryAsync(CancellationToken cancellationToken)
- {
- Actor = await actorAccessor.GetAsync(cancellationToken);
- Snapshot = await snapshotService.GetAsync(Actor.UserAccount?.Id, cancellationToken);
- return Partial("_SummaryCards", Snapshot);
- }
}
diff --git a/src/Bifrost.Web/Pages/App/Members/Index.cshtml b/src/Bifrost.Web/Pages/App/Members/Index.cshtml
index 0d9d546..6521c2b 100644
--- a/src/Bifrost.Web/Pages/App/Members/Index.cshtml
+++ b/src/Bifrost.Web/Pages/App/Members/Index.cshtml
@@ -14,6 +14,11 @@
because trust and contributor accountability are product concerns, not just auth concerns.
+ @if (!string.IsNullOrEmpty(Model.Notice))
+ {
+ @Model.Notice
+ }
+
@if (Model.Actor.CanManageMembership)
{
- @if (Model.Actor.CanManageMembership && user.Status != MembershipStatus.Active)
+ @if (Model.Actor.CanManageMembership && user.Status != MembershipStatus.Active && user.Status != MembershipStatus.Suspended)
{
}
+ @if (Model.Actor.CanManageMembership)
+ {
+ @if (user.Status == MembershipStatus.Suspended)
+ {
+ @(string.IsNullOrWhiteSpace(user.SuspensionReason) ? Bifrost.Web.Pages.App.Members.IndexModel.LegacySuspensionText : "Suspended: " + user.SuspensionReason)
+ }
+
+ }
+
@if (Model.Actor.CanManageMembership)
{
+ @if (Model.CanManageLogins)
+ {
+
+
Linked accounts
+
See, add and remove the provider logins that sign in to this account.
+
+ }
+
+ @if (Model.HasMerges)
+ {
+
+
Merge status
+
See an account merge and, for seven days, undo it.
+
+ }
+
@if (Model.Invitation is not null)
{
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
index d579dd3..1c78e11 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
@@ -1,5 +1,7 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using System.Security.Claims;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
@@ -12,6 +14,12 @@ public sealed class StatusModel(
ICurrentBifrostActorAccessor actorAccessor,
BifrostDbContext dbContext) : PageModel
{
+ ///
Whether this session belongs to a Heimdall account whose logins the Linked accounts page can manage.
+ public bool CanManageLogins => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 };
+
+ ///
Whether this account is in, or was in, a merge: the link to Merge status is shown only then.
+ public bool HasMerges { get; private set; }
+
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public MembershipInvitation? Invitation { get; private set; }
@@ -45,6 +53,9 @@ public sealed class StatusModel(
public async Task OnGetAsync(CancellationToken cancellationToken)
{
Actor = await actorAccessor.GetAsync(cancellationToken);
+ HasMerges = Actor.Merge is not null
+ || (Actor.UserAccount is { } account
+ && await dbContext.AccountMerges.AnyAsync(x => x.SurvivorUserAccountId == account.Id || x.FoldedUserAccountId == account.Id, cancellationToken));
if (Actor.UserAccount is null)
{
diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml b/src/Bifrost.Web/Pages/Mill/Vote.cshtml
index fe75338..d9e67f2 100644
--- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml
+++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml
@@ -28,15 +28,15 @@
-
-
@if (stance is not null)
{
-
}
diff --git a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
index dd87f6d..41ed934 100644
--- a/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Mill/Vote.cshtml.cs
@@ -29,7 +29,7 @@ public sealed class VoteModel(
// The single gate before any handler runs. A request that selects no handler (a POST with no or an unknown handler,
// any other method) is a client error, never a view over a null subject. A cast is accepted only from the site's own
- // origin (CastRequestGuard); no antiforgery cookie or token exists on this flow.
+ // origin (RequestOriginGuard); no antiforgery cookie or token exists on this flow.
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var method = context.HttpContext.Request.Method;
@@ -50,7 +50,7 @@ public sealed class VoteModel(
return;
}
- if (HttpMethods.IsPost(method) && !CastRequestGuard.Allows(context.HttpContext.Request, host.Value))
+ if (HttpMethods.IsPost(method) && !RequestOriginGuard.Allows(context.HttpContext.Request, host.Value))
{
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
return;
diff --git a/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml b/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml
new file mode 100644
index 0000000..c9ea380
--- /dev/null
+++ b/src/Bifrost.Web/Pages/Shared/Components/MergeNotice/Default.cshtml
@@ -0,0 +1,5 @@
+@model string
+
diff --git a/src/Bifrost.Web/Pages/Shared/_Layout.cshtml b/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
index 34c68cb..232bc65 100644
--- a/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
+++ b/src/Bifrost.Web/Pages/Shared/_Layout.cshtml
@@ -17,7 +17,7 @@
-
+
+ @if (User.Identity?.IsAuthenticated == true)
+ {
+ @await Component.InvokeAsync("MergeNotice")
+ }
+
@RenderBody()
-
@await RenderSectionAsync("Scripts", required: false)
diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs
index d0656d3..800db8c 100644
--- a/src/Bifrost.Web/Program.cs
+++ b/src/Bifrost.Web/Program.cs
@@ -7,12 +7,14 @@ using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Bridge;
using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Desk;
using Bifrost.Web.Features.GitHub;
using Bifrost.Web.Features.Heimdall;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Motions;
using Bifrost.Web.Features.Oidc;
using Bifrost.Web.Features.Patronage;
+using Bifrost.Web.Features.Registration;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -62,7 +64,8 @@ builder.Services
builder.Services
.AddOptions
()
- .BindConfiguration(HeimdallOptions.SectionName);
+ .BindConfiguration(HeimdallOptions.SectionName)
+ .PostConfigure>(HeimdallOptions.ResolveAppSecret);
builder.Services
.AddOptions()
@@ -76,9 +79,21 @@ builder.Services
.AddOptions()
.BindConfiguration(ConceptVoteOptions.SectionName);
+builder.Services
+ .AddOptions()
+ .BindConfiguration(DeskOptions.SectionName);
+
+builder.Services.AddAntiforgery(options =>
+{
+ options.Cookie.Name = BifrostCookies.Antiforgery;
+ options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
+ options.Cookie.Path = BifrostCookies.Path;
+});
+
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/Membership/Status");
+ options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
options.Conventions.AllowAnonymousToFolder("/Mill");
});
@@ -105,6 +120,7 @@ builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -114,6 +130,22 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddOptions().BindConfiguration(MindIntakeOptions.SectionName);
+builder.Services.AddSingleton(); // TimeProvider and options resolve from the container
+builder.Services.AddOptions().BindConfiguration(RegistrationOptions.SectionName);
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddScoped();
+builder.Services.AddHostedService();
+builder.Services.AddOptions().BindConfiguration(AccountMergeOptions.SectionName);
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddOptions().BindConfiguration(ChatNoticesOptions.SectionName);
+builder.Services.AddSingleton();
+builder.Services.AddHostedService();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
@@ -126,9 +158,13 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddScoped();
-builder.Services.AddHttpClient((serviceProvider, client) =>
- HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
- .RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
+// The app-secret and member-bearer clients and the mover: no redirects (see HeimdallClientServices).
+builder.Services.AddHeimdallClients();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddScoped();
builder.Services.AddSingleton();
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService>().Value));
@@ -167,6 +203,10 @@ var authenticationBuilder = builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
+ options.Cookie.Name = BifrostCookies.Session;
+ options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
+ options.Cookie.Path = BifrostCookies.Path;
+ options.Cookie.Domain = null;
options.LoginPath = "/auth/sign-in";
options.AccessDeniedPath = "/Membership/Status";
options.SlidingExpiration = true;
@@ -183,6 +223,9 @@ if (configuredGitHubOAuthOptions.IsConfigured)
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint = "https://api.github.com/user";
options.SaveTokens = true;
+ options.CorrelationCookie.Name = BifrostCookies.OAuthCorrelation;
+ options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
+ options.CorrelationCookie.Path = BifrostCookies.Path;
options.Scope.Add("read:user");
options.Scope.Add("user:email");
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
@@ -233,10 +276,19 @@ if (oidcOptions is not null)
builder.Services.AddBifrostOidc(oidcOptions);
}
+// The desk is mapped only when the Desk section exists, and a configured desk needs its credential and door ports.
+var deskConfigured = builder.Configuration.GetSection(DeskOptions.SectionName).Exists();
+if (deskConfigured)
+{
+ builder.Services.AddBifrostDesk(oidcConfigured: oidcOptions is not null);
+}
+
var app = builder.Build();
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
app.Services.GetRequiredService().Validate();
+// Resolved now so a misconfigured RP (not https, host differs, a port in ExpectedHost) is logged once at boot, not on the first ceremony.
+_ = app.Services.GetRequiredService();
await using (var scope = app.Services.CreateAsyncScope())
{
await scope.ServiceProvider
@@ -254,6 +306,11 @@ if (!app.Environment.IsDevelopment())
app.UseHttpLogging();
app.UseHttpsRedirection();
+if (oidcOptions is not null)
+{
+ app.UseMiddleware(); // before authentication: OpenIddict answers /connect/* inside it
+}
+
app.UseStaticFiles();
app.UseRouting();
app.UseConceptTallyCors();
@@ -274,12 +331,18 @@ app.MapGet("/readyz", async (ReadinessService readinessService, CancellationToke
}).AllowAnonymous();
app.MapConceptTallyExport();
+app.MapConceptRankedExport();
if (oidcOptions is not null)
{
app.MapBifrostOidc();
}
+if (deskConfigured)
+{
+ app.MapDesk();
+}
+
app.MapPost("/github/webhooks", async (
HttpRequest request,
GitHubWebhookService gitHubWebhookService,
@@ -342,35 +405,173 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions
{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ var outcome = await registration.RunAsync(
+ httpContext,
+ new RegistrationAttempt(request.Identity, request.DisplayName, request.Challenge, request.Nonce, request.Waited == true, request.AcceptedNoticeVersion),
+ cancellationToken);
+ if (outcome.Refusal is not null)
+ {
+ return outcome.Refusal;
+ }
+
+ if (outcome.Account is not { } userAccount)
+ {
+ return Results.Text(outcome.Message!, statusCode: outcome.Status);
+ }
+
+ var returnUrl = string.IsNullOrWhiteSpace(request.ReturnUrl) ? "/App" : request.ReturnUrl;
+ return JsonResult(
+ new NativeBifrostRegistrationResponse(
+ userAccount.Id,
+ userAccount.BifrostIdentity,
+ userAccount.DisplayName,
+ userAccount.Membership?.Status.ToString() ?? MembershipStatus.Authenticated.ToString(),
+ returnUrl),
+ appJsonSerializerOptions);
+}).AllowAnonymous();
+
+// GET issues a challenge, so it spends the same per-address budget as /auth/bifrost/challenge.
+app.MapGet("/auth/bifrost/register", (
+ HttpContext httpContext,
+ RegistrationChallengeService challenges,
+ RegistrationRateLimit rateLimit,
+ IOptions registrationOptions) =>
+{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
+ return RegistrationFormResult(httpContext, challenges, registrationOptions.Value, new RegistrationPageModel(returnPath.Value, "", 0, registrationOptions.Value.Captcha.FallbackWaitSeconds), null, StatusCodes.Status200OK);
+}).AllowAnonymous();
+
+// No antiforgery token or cookie exists for an anonymous visitor, so a cross-site post is refused by origin instead
+// (RequestOriginGuard, the same Fetch Metadata check as the vote page, except that a request with no Origin and no
+// Sec-Fetch-Site and no session cookie passes: text browsers send neither, and there is no session to replace). Without it a foreign page could post here with
+// a challenge of its own and replace the visitor's session cookie with an empty account holding a forged consent.
+// Order: origin, then the general address budget, then the body cap, then the form; a refusal sets no cookie.
+app.MapPost("/auth/bifrost/register/form", async (
+ HttpContext httpContext,
+ NativeRegistration registration,
+ RegistrationChallengeService challenges,
+ RegistrationRateLimit rateLimit,
+ IOptions hostOptions,
+ IOptions registrationOptions,
+ CancellationToken cancellationToken) =>
+{
+ if (!RequestOriginGuard.AllowsFormWithoutFetchMetadata(httpContext.Request, hostOptions.Value))
+ {
+ return Results.Text("Cross-site registration is refused.", statusCode: StatusCodes.Status403Forbidden);
+ }
+
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ if (!(httpContext.Request.ContentType ?? "").StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
+ {
+ return Results.Text("Send the form as application/x-www-form-urlencoded.", statusCode: StatusCodes.Status415UnsupportedMediaType);
+ }
+
+ // The form is a handful of short fields: refuse a big body before reading any of it.
+ const int MaxFormBytes = 16 * 1024;
+ if (httpContext.Request.ContentLength > MaxFormBytes)
+ {
+ return Results.Text("The form is too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
+ }
+
+ if (httpContext.Features.Get() is { IsReadOnly: false } limit)
+ {
+ limit.MaxRequestBodySize = MaxFormBytes;
+ }
+
+ IFormCollection form;
try
{
- var userAccount = await bifrostIdentityService.RegisterNativeAsync(
- request.Identity,
- request.DisplayName,
- cancellationToken);
- await httpContext.SignInAsync(
- CookieAuthenticationDefaults.AuthenticationScheme,
- bifrostIdentityService.BuildPrincipal(userAccount));
-
- var returnUrl = string.IsNullOrWhiteSpace(request.ReturnUrl) ? "/App" : request.ReturnUrl;
- return JsonResult(
- new NativeBifrostRegistrationResponse(
- userAccount.Id,
- userAccount.BifrostIdentity,
- userAccount.DisplayName,
- userAccount.Membership?.Status.ToString() ?? MembershipStatus.Authenticated.ToString(),
- returnUrl),
- appJsonSerializerOptions);
+ form = await httpContext.Request.ReadFormAsync(cancellationToken);
}
- catch (BifrostIdentityException error)
+ catch (BadHttpRequestException error) when (error.StatusCode == StatusCodes.Status413PayloadTooLarge)
{
- return Results.Text(error.Message, statusCode: StatusCodes.Status400BadRequest);
+ return Results.Text("The form is too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
}
+ catch (Exception error) when (error is InvalidDataException or BadHttpRequestException)
+ {
+ return Results.Text("The form could not be read.", statusCode: StatusCodes.Status400BadRequest);
+ }
+
+ string Field(string name) => form[name].FirstOrDefault() ?? "";
+ var returnPath = LocalReturnPath.Parse(Field("returnUrl"));
+ // The checkbox is the consent act and is optional: unticked, the posted notice version is ignored and no receipt is made.
+ // Anything but the canonical decimal of the version in force ("02" included) with the box ticked is sent as -1 and refused, never read as "did not agree".
+ int? accepted = Field("consent") != "yes"
+ ? null
+ : Field("acceptedNoticeVersion") == TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture) ? TrainingNotice.Version : -1;
+ var identity = Field("identity");
+ var displayName = Field("displayName");
+ var challenge = Field("challenge");
+
+ var outcome = await registration.RunAsync(
+ httpContext,
+ new RegistrationAttempt(identity, displayName, challenge, Field("nonce"), Field("waited") == "true", accepted),
+ cancellationToken);
+ if (outcome.Refusal is not null)
+ {
+ return outcome.Refusal;
+ }
+
+ if (outcome.Account is not null)
+ {
+ // A Location header takes ASCII only; anything else is not a path worth keeping.
+ var target = returnPath.Value.All(c => c > ' ' && c < '\u007f') ? returnPath.Value : LocalReturnPath.Default.Value;
+ httpContext.Response.Headers.CacheControl = "no-store";
+ httpContext.Response.Headers.Location = target;
+ return Results.StatusCode(StatusCodes.Status303SeeOther);
+ }
+
+ // A refusal that spent nothing and needs only a correction (a taken identity, a too-early time-lock) keeps its
+ // challenge, whose clock must not restart. Any other failure gets a fresh challenge. The consent box always comes back unchecked.
+ var options = registrationOptions.Value;
+ return RegistrationFormResult(
+ httpContext,
+ challenges,
+ options,
+ new RegistrationPageModel(returnPath.Value, "", 0, options.Captcha.FallbackWaitSeconds, Truncate(identity), Truncate(displayName), outcome.Message, outcome.Field),
+ outcome.KeepChallenge && challenges.IsLive(challenge) ? challenge : null,
+ outcome.Status);
+
+ static string Truncate(string text) => text.Length <= 256 ? text : text[..256];
}).AllowAnonymous();
+app.MapGet("/auth/bifrost/challenge", (HttpContext httpContext, RegistrationChallengeService challenges, RegistrationRateLimit rateLimit) =>
+{
+ if (rateLimit.Refuse(httpContext) is { } refused)
+ {
+ return refused;
+ }
+
+ httpContext.Response.Headers.CacheControl = "no-store";
+ var challenge = challenges.Issue();
+ return challenge is null
+ ? Results.Text("Registration is busy; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable)
+ : JsonResult(challenge, appJsonSerializerOptions);
+}).AllowAnonymous();
+
+app.MapGet("/auth/bifrost/notice", () =>
+ JsonResult(new { version = TrainingNotice.Version, text = TrainingNotice.Text }, appJsonSerializerOptions)).AllowAnonymous();
+
+app.MapConsent();
+
app.MapGet("/auth/heimdall/{provider}", async (
string provider,
HttpContext httpContext,
@@ -527,6 +728,103 @@ 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);
+
+async Task SealedCall(Func> call)
+{
+ try
+ {
+ return Results.Text(JsonSerializer.Serialize(await call(), appJsonSerializerOptions), "application/json");
+ }
+ catch (SealedBallotException error)
+ {
+ return Results.Text(
+ JsonSerializer.Serialize(new { error = error.Message }, appJsonSerializerOptions),
+ "application/json",
+ statusCode: error.Failure switch
+ {
+ SealedBallotFailure.Forbidden => StatusCodes.Status403Forbidden,
+ SealedBallotFailure.Unauthorized => StatusCodes.Status401Unauthorized,
+ 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)));
+
+sealedMotions.MapPost("/mind-keys", (ICurrentBifrostActorAccessor actors, MindIntakeService service, RegisterMindKeyRequest body, CancellationToken ct) =>
+ SealedCall(async () => await service.RegisterKeyAsync(await actors.GetAsync(ct), body.Persona, body.UserAccountId, body.PublicKey, ct)));
+sealedMotions.MapGet("/mind-keys", (ICurrentBifrostActorAccessor actors, MindIntakeService service, CancellationToken ct) =>
+ SealedCall(async () => await service.ListKeysAsync(await actors.GetAsync(ct), ct)));
+sealedMotions.MapDelete("/mind-keys/{keyId:guid}", (ICurrentBifrostActorAccessor actors, MindIntakeService service, Guid keyId, CancellationToken ct) =>
+ SealedCall(async () =>
+ {
+ await service.RevokeKeyAsync(await actors.GetAsync(ct), keyId, ct);
+ return new { revoked = keyId };
+ }));
+
+// Signed Mind intake: the Ed25519 signature is the credential. No session, no cookie; the verified envelope runs the same
+// SealedBallotService verbs as a member cast.
+app.MapPost("/api/sealed-motions/{id:guid}/mind", async (
+ HttpContext http, MindIntakeService service, MindIntakeRateLimit limiter, IOptions limits, Guid id, CancellationToken ct) =>
+{
+ // Per-source permit and a hard body cap, both before any parsing or database work.
+ if (limiter.Spend(http.Connection.RemoteIpAddress?.ToString() ?? "unknown") is { } denied)
+ {
+ http.Response.Headers.RetryAfter = Math.Ceiling(denied.RetryAfter.TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ return Results.Text("{\"error\":\"Too many requests.\"}", "application/json", statusCode: StatusCodes.Status429TooManyRequests);
+ }
+
+ var max = limits.Value.MaxBodyBytes;
+ if (http.Request.ContentLength > max)
+ {
+ return Results.Text("{\"error\":\"Envelope too large.\"}", "application/json", statusCode: StatusCodes.Status413PayloadTooLarge);
+ }
+
+ var buffer = new byte[max + 1];
+ var read = 0;
+ int n;
+ while (read < buffer.Length && (n = await http.Request.Body.ReadAsync(buffer.AsMemory(read), ct)) > 0)
+ {
+ read += n;
+ }
+
+ if (read > max)
+ {
+ return Results.Text("{\"error\":\"Envelope too large.\"}", "application/json", statusCode: StatusCodes.Status413PayloadTooLarge);
+ }
+
+ MindEnvelope? envelope;
+ try
+ {
+ envelope = JsonSerializer.Deserialize(buffer.AsSpan(0, read), new JsonSerializerOptions(JsonSerializerDefaults.Web));
+ }
+ catch (JsonException)
+ {
+ envelope = null;
+ }
+
+ return envelope is null
+ ? Results.Text("{\"error\":\"The envelope is malformed.\"}", "application/json", statusCode: StatusCodes.Status400BadRequest)
+ : await SealedCall(async () => await service.HandleAsync(id, envelope, ct));
+}).AllowAnonymous();
+
+MergeNoticeEndpoints.Map(app);
+
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
{
httpContext.Response.Headers.CacheControl = "no-store";
@@ -541,11 +839,53 @@ app.MapPost("/auth/heimdall/complete", async (
ILogger logger,
CancellationToken cancellationToken) =>
{
+ // Every answer here sets or clears an attempt cookie or signs someone in: none may be stored.
+ httpContext.Response.Headers.CacheControl = "no-store";
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
var attempt = form?["attempt"].ToString();
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
+ var linking = held is not null
+ && heimdallAuthService.PurposeOf(held.Value.Value, attempt) is not (null or HeimdallAttemptPurpose.SignIn);
try
{
+ if (linking)
+ {
+ // A link step never signs anyone in: the session in this browser is the one being linked.
+ var step = await heimdallAuthService.ContinueLinkAsync(
+ hostOptions.Value.PublicBaseUrl,
+ attempt,
+ held!.Value.Name,
+ held.Value.Value,
+ form?["code"].ToString(),
+ form?["pendingLinkId"].ToString(),
+ // A folded or frozen account links nothing: the actor accessor's standing decides, not the raw claim.
+ (await httpContext.RequestServices.GetRequiredService().GetAsync(cancellationToken)).Merge is null
+ ? httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId)
+ : null,
+ cancellationToken);
+ if (step.Next is not null)
+ {
+ httpContext.Response.Cookies.Append(step.CookieName, step.CookieValue!, HeimdallAttemptCookie.Options());
+ return Results.Redirect(step.Next.ToString());
+ }
+
+ if (step.EnrolTicket is not null)
+ {
+ // The ticket id goes only to the browser that completed the fresh sign-in; the server holds what it is bound to.
+ httpContext.Response.Cookies.Append(BifrostCookies.PasskeyTicket, step.EnrolTicket, new CookieOptions
+ {
+ HttpOnly = true,
+ Secure = true,
+ SameSite = SameSiteMode.Lax,
+ Path = BifrostCookies.Path,
+ MaxAge = Bifrost.Web.Features.Passkeys.PasskeyCeremonies.TicketLifetime
+ });
+ }
+
+ httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
+ return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value, step.ReturnPath));
+ }
+
var signIn = await heimdallAuthService.CompleteAsync(
hostOptions.Value.PublicBaseUrl,
attempt,
@@ -564,7 +904,9 @@ app.MapPost("/auth/heimdall/complete", async (
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
}
- return Results.Redirect(HeimdallAuthService.ErrorRedirect);
+ return linking
+ ? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error, heimdallAuthService.MergeReturnPathOf(held?.Value, attempt)))
+ : Results.Redirect(HeimdallAuthService.ErrorRedirect);
}
}).AllowAnonymous();
@@ -601,6 +943,36 @@ static async Task ReadFormOrNullAsync(HttpRequest request, Can
}
}
+// Renders the sign-up page with a challenge: the kept one when given, else a fresh one (null when the issuing set is full).
+static IResult RegistrationFormResult(
+ HttpContext httpContext,
+ RegistrationChallengeService challenges,
+ RegistrationOptions options,
+ RegistrationPageModel model,
+ string? keepChallenge,
+ int statusCode)
+{
+ var token = keepChallenge;
+ var difficulty = options.Captcha.Difficulty;
+ if (token is null)
+ {
+ var issued = challenges.Issue();
+ if (issued is null)
+ {
+ return Results.Text("Registration is busy; try again shortly.", statusCode: StatusCodes.Status503ServiceUnavailable);
+ }
+
+ token = issued.Challenge;
+ difficulty = issued.Difficulty;
+ }
+
+ httpContext.Response.Headers.CacheControl = "no-store";
+ return Results.Content(
+ RegistrationPage.Render(model with { Challenge = token, Difficulty = difficulty }),
+ "text/html; charset=utf-8",
+ statusCode: statusCode);
+}
+
static async Task WriteSignInChooserAsync(HttpContext httpContext, string returnUrl)
{
httpContext.Response.ContentType = "text/html; charset=utf-8";
@@ -654,7 +1026,11 @@ public partial class Program;
public sealed record NativeBifrostRegistrationRequest(
string Identity,
string? DisplayName,
- string? ReturnUrl);
+ string? ReturnUrl,
+ string? Challenge,
+ string? Nonce,
+ int? AcceptedNoticeVersion,
+ bool? Waited = null);
public sealed record NativeBifrostRegistrationResponse(
Guid UserAccountId,
diff --git a/src/Bifrost.Web/ViewComponents/MergeNotice.cs b/src/Bifrost.Web/ViewComponents/MergeNotice.cs
new file mode 100644
index 0000000..5a3c779
--- /dev/null
+++ b/src/Bifrost.Web/ViewComponents/MergeNotice.cs
@@ -0,0 +1,57 @@
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+namespace Bifrost.Web.ViewComponents;
+
+///
+/// The layout's merge notice for a signed-in actor: the survivor of a Committed or UndoRequested merge inside its grace (days left), a
+/// frozen account (a merge is in progress) or a folded one (where to sign in). It reads the merge row once per page view and keeps no
+/// state of its own; the words are 's, and no account name or id is ever in them.
+///
+public sealed class MergeNotice(ICurrentBifrostActorAccessor actors, BifrostDbContext dbContext, TimeProvider timeProvider) : ViewComponent
+{
+ public async Task InvokeAsync()
+ {
+ var actor = await actors.GetAsync(HttpContext.RequestAborted);
+ var text = await TextAsync(actor, HttpContext.RequestAborted);
+ return text is null ? Content(string.Empty) : View("Default", text);
+ }
+
+ private async Task TextAsync(CurrentBifrostActor actor, CancellationToken cancellationToken)
+ {
+ var now = timeProvider.GetUtcNow();
+ if (actor.Merge is { } standing)
+ {
+ if (standing is MergeStanding.Frozen)
+ {
+ return MergeWording.FrozenNotice();
+ }
+
+ var mergedOn = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.Id == standing.MergeId)
+ .Select(x => x.CommittedUtc ?? x.CreatedUtc)
+ .FirstOrDefaultAsync(cancellationToken);
+ return MergeWording.FoldedNotice(mergedOn);
+ }
+
+ if (actor.UserAccount is not { } account)
+ {
+ return null;
+ }
+
+ var open = await dbContext.AccountMerges.AsNoTracking()
+ .Where(x => x.SurvivorUserAccountId == account.Id
+ && (x.State == AccountMergeState.Committed || x.State == AccountMergeState.UndoRequested)
+ && x.GraceEndsUtc > now)
+ .OrderBy(x => x.GraceEndsUtc)
+ .Select(x => new { x.State, x.GraceEndsUtc })
+ .FirstOrDefaultAsync(cancellationToken);
+ return open is null ? null
+ : open.State == AccountMergeState.UndoRequested ? MergeWording.UndoRequestedNotice()
+ : MergeWording.SurvivorNotice(MergeWording.DaysUntil(open.GraceEndsUtc!.Value, now));
+ }
+}
diff --git a/src/Bifrost.Web/appsettings.json b/src/Bifrost.Web/appsettings.json
index 47bbb7b..09b3310 100644
--- a/src/Bifrost.Web/appsettings.json
+++ b/src/Bifrost.Web/appsettings.json
@@ -28,6 +28,7 @@
"BaseUrl": "https://heimdall.gamecult.org",
"AppSlug": "bifrost",
"AppSecret": "",
+ "AppSecretFile": "",
"DiscordGuildId": "",
"DiscordAllowedRoleIds": [],
"PatreonTierTitle": "Inner Sanctum",
diff --git a/src/Bifrost.Web/packages.lock.json b/src/Bifrost.Web/packages.lock.json
index bd15130..796baa1 100644
--- a/src/Bifrost.Web/packages.lock.json
+++ b/src/Bifrost.Web/packages.lock.json
@@ -8,6 +8,30 @@
"resolved": "2.4.0",
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
},
+ "Fido2": {
+ "type": "Direct",
+ "requested": "[4.3.3, )",
+ "resolved": "4.3.3",
+ "contentHash": "++G8ohXlhp9AH49FXIvYqziXUAEpuCtT+z5HBevX6+Pl6sYz9zfDHGTgvne6t3UEhM0hudesgMudyNG7RlpaEA==",
+ "dependencies": {
+ "Fido2.Models": "4.3.3",
+ "Microsoft.Extensions.Http": "9.0.0",
+ "Microsoft.IdentityModel.JsonWebTokens": "8.2.0",
+ "NSec.Cryptography": "25.4.0",
+ "System.Formats.Cbor": "9.0.24"
+ }
+ },
+ "MessagePack": {
+ "type": "Direct",
+ "requested": "[3.1.12, )",
+ "resolved": "3.1.12",
+ "contentHash": "m1QEsd59gUj82ji5tEQbZiyjV6y0F7cYfGVhil6pAlNZpyzR7ze9TucMu4lPpi8cZAV8aNl3D9/T9J1HbFz15Q==",
+ "dependencies": {
+ "MessagePack.Annotations": "3.1.12",
+ "MessagePackAnalyzer": "3.1.12",
+ "Microsoft.NET.StringTools": "17.11.4"
+ }
+ },
"Microsoft.EntityFrameworkCore.Design": {
"type": "Direct",
"requested": "[8.0.0, )",
@@ -75,17 +99,59 @@
"OpenIddict.Server": "7.7.1"
}
},
+ "OpenIddict.Validation.AspNetCore": {
+ "type": "Direct",
+ "requested": "[7.7.1, )",
+ "resolved": "7.7.1",
+ "contentHash": "9Gpw13k6KRif6LCeIfzS5cfDPxzEvg5I4l8JKwMxNL4mqal8eT00T069RnuXuDY8CwOO43FLD55JY7Wh3an5cg==",
+ "dependencies": {
+ "OpenIddict.Validation": "7.7.1"
+ }
+ },
+ "OpenIddict.Validation.ServerIntegration": {
+ "type": "Direct",
+ "requested": "[7.7.1, )",
+ "resolved": "7.7.1",
+ "contentHash": "tZd5oqlVHftWjo3gthwXRvDE09NGmOjo5yjyRH8W2q4Yw9Hntkfi70+T2ESFKJ++oqueQT4YG5ilyot/o0OBMA==",
+ "dependencies": {
+ "OpenIddict.Server": "7.7.1",
+ "OpenIddict.Validation": "7.7.1"
+ }
+ },
"System.Text.Json": {
"type": "Direct",
"requested": "[8.0.5, )",
"resolved": "8.0.5",
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
},
+ "Fido2.Models": {
+ "type": "Transitive",
+ "resolved": "4.3.3",
+ "contentHash": "G/Q8MYgptOwMrbWgDoGsy90u3J5GTdNAHub8aZRg/mQrUETzB5CqFzstGdTXE9UhL0qD6sRynOoPUnqCwKRnMw==",
+ "dependencies": {
+ "Microsoft.Bcl.Memory": "9.0.14"
+ }
+ },
"Humanizer.Core": {
"type": "Transitive",
"resolved": "2.14.1",
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
},
+ "libsodium": {
+ "type": "Transitive",
+ "resolved": "1.0.20.1",
+ "contentHash": "pkiceEqJDQFHjbga3k/oPfTVX9g+GKJZ1VrkuiLhaymt9YNw1Dr7cX9hNuZuNaWcr9WD0moW55k4pMwzQ7JaZQ=="
+ },
+ "MessagePack.Annotations": {
+ "type": "Transitive",
+ "resolved": "3.1.12",
+ "contentHash": "LdI67sY7F3KK+JsrG02+DP1XFkowaZSoyfL2M88hjm1MOOsjf8amBLAJolV+zxoPUZf3uGbKzq1cMQD8PlpSpA=="
+ },
+ "MessagePackAnalyzer": {
+ "type": "Transitive",
+ "resolved": "3.1.12",
+ "contentHash": "iNSNatPh6bafRUbkQKlClExjpPpd8hiZgfZsodGf7bheIlkizGbMzsJ2mPui8jOHRe4Ky9eg5ou/fFzI7CT3fg=="
+ },
"Microsoft.Bcl.AsyncInterfaces": {
"type": "Transitive",
"resolved": "6.0.0",
@@ -99,6 +165,11 @@
"System.Formats.Asn1": "10.0.2"
}
},
+ "Microsoft.Bcl.Memory": {
+ "type": "Transitive",
+ "resolved": "9.0.14",
+ "contentHash": "laQCcjTM2FnbyznkAu9hwBuQh3z2/OtJKwjGkJOUevylFpFXZIUVq/+MU2jM0HQm1n5wsjjwtLIDOiWJ6Nai3A=="
+ },
"Microsoft.CodeAnalysis.Analyzers": {
"type": "Transitive",
"resolved": "3.3.3",
@@ -186,26 +257,43 @@
"Microsoft.Extensions.Primitives": "8.0.0"
}
},
+ "Microsoft.Extensions.Configuration": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "YIMO9T3JL8MeEXgVozKt2v79hquo/EFtnY0vgxmLnUvk1Rei/halI7kOWZL2RBeV9FMGzgM9LZA8CVaNwFMaNA==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.0",
- "contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==",
+ "resolved": "9.0.0",
+ "contentHash": "lqvd7W3FGKUO1+ZoUEMaZ5XDJeWvjpy2/M/ptCGz3tXLD4HWVaSzjufsAsjemasBEg+2SxXVtYVvGt5r2nKDlg==",
"dependencies": {
- "Microsoft.Extensions.Primitives": "8.0.0"
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Configuration.Binder": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "RiScL99DcyngY9zJA2ROrri7Br8tn5N4hP4YNvGdTN/bvg1A3dwvDOxHnNZ3Im7x2SJ5i4LkX1uPiR/MfSFBLQ==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
- "resolved": "8.0.1",
- "contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==",
+ "resolved": "9.0.0",
+ "contentHash": "MCPrg7v3QgNMr0vX4vzRXvkNGgLg8vKWX0nKCWUxu2uPyMsaRgiRc1tHBnbTcfJMhMKj2slE/j2M9oGkd25DNw==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
+ "resolved": "9.0.0",
+ "contentHash": "+6f2qv2a3dLwd5w6JanPIPs47CxRbnk+ZocMJUhv9NxP88VlOcJYZs9jY+MYSjxvady08bUZn6qgiNh7DadGgg=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
@@ -216,37 +304,83 @@
"System.Text.Json": "8.0.0"
}
},
+ "Microsoft.Extensions.Diagnostics": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "0CF9ZrNw5RAlRfbZuVIvzzhP8QeWqHiUmMBU/2H7Nmit8/vwP3/SbHeEctth7D4Gz2fBnEbokPc1NU8/j/1ZLw==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration": "9.0.0",
+ "Microsoft.Extensions.Diagnostics.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options.ConfigurationExtensions": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Diagnostics.Abstractions": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "1K8P7XzuzX8W8pmXcZjcrqS6x5eSSdvhQohmcpgiQNY/HlDAlnrhR9dvlURfFz428A+RTCJpUyB+aKTA6AgVcQ==",
+ "dependencies": {
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0",
+ "System.Diagnostics.DiagnosticSource": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Http": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "DqI4q54U4hH7bIAq9M5a/hl5Odr/KBAoaZ0dcT4OgutD8dook34CbkvAfAIzkMVjYXiL+E5ul9etwwqiX4PHGw==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Diagnostics": "9.0.0",
+ "Microsoft.Extensions.Logging": "9.0.0",
+ "Microsoft.Extensions.Logging.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0"
+ }
+ },
"Microsoft.Extensions.Logging": {
"type": "Transitive",
- "resolved": "8.0.1",
- "contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==",
+ "resolved": "9.0.0",
+ "contentHash": "crjWyORoug0kK7RSNJBTeSE6VX8IQgLf3nUpTB9m62bPXp/tzbnOsnbe8TXEG0AASNaKZddnpHKw7fET8E++Pg==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection": "8.0.1",
- "Microsoft.Extensions.Logging.Abstractions": "8.0.2",
- "Microsoft.Extensions.Options": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection": "9.0.0",
+ "Microsoft.Extensions.Logging.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==",
+ "resolved": "9.0.0",
+ "contentHash": "g0UfujELzlLbHoVG8kPKVBaW470Ewi+jnptGS9KUi6jcb+k2StujtK3m26DFSGGwQ/+bVgZfsWqNzlP6YOejvw==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "System.Diagnostics.DiagnosticSource": "9.0.0"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
- "resolved": "8.0.2",
- "contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==",
+ "resolved": "9.0.0",
+ "contentHash": "y2146b3jrPI3Q0lokKXdKLpmXqakYbDIPDV6r3M8SqvSf45WwOTzkyfDpxnZXJsJQEpAsAqjUq5Pu8RCJMjubg==",
"dependencies": {
- "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
- "Microsoft.Extensions.Primitives": "8.0.0"
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
+ }
+ },
+ "Microsoft.Extensions.Options.ConfigurationExtensions": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "Ob3FXsXkcSMQmGZi7qP07EQ39kZpSBlTcAZLbJLdI4FIf0Jug8biv2HTavWmnTirchctPlq9bl/26CXtQRguzA==",
+ "dependencies": {
+ "Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Configuration.Binder": "9.0.0",
+ "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
+ "Microsoft.Extensions.Options": "9.0.0",
+ "Microsoft.Extensions.Primitives": "9.0.0"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
- "resolved": "8.0.0",
- "contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g=="
+ "resolved": "9.0.0",
+ "contentHash": "N3qEBzmLMYiASUlKxxFIISP4AiwuPTHF5uCh+2CWSwwzAJiIYx0kBJsS30cp1nvhSySFAVi30jecD307jV+8Kg=="
},
"Microsoft.IdentityModel.Abstractions": {
"type": "Transitive",
@@ -269,6 +403,14 @@
"Microsoft.IdentityModel.Abstractions": "8.19.2"
}
},
+ "Microsoft.IdentityModel.Protocols": {
+ "type": "Transitive",
+ "resolved": "8.19.2",
+ "contentHash": "sGxSsSrZXNmca6D+jHH2rVRyo2nNRd/g4H9CFbPmLLq0xgoH1U0orLWE5minfijw7+zq49tBs7txenbfAErRoQ==",
+ "dependencies": {
+ "Microsoft.IdentityModel.Tokens": "8.19.2"
+ }
+ },
"Microsoft.IdentityModel.Tokens": {
"type": "Transitive",
"resolved": "8.19.2",
@@ -279,6 +421,11 @@
"Microsoft.IdentityModel.Logging": "8.19.2"
}
},
+ "Microsoft.NET.StringTools": {
+ "type": "Transitive",
+ "resolved": "17.11.4",
+ "contentHash": "mudqUHhNpeqIdJoUx2YDWZO/I9uEDYVowan89R6wsomfnUJQk6HteoQTlNjZDixhT2B4IXMkMtgZtoceIjLRmA=="
+ },
"Mono.TextTemplating": {
"type": "Transitive",
"resolved": "2.2.1",
@@ -287,6 +434,14 @@
"System.CodeDom": "4.4.0"
}
},
+ "NSec.Cryptography": {
+ "type": "Transitive",
+ "resolved": "25.4.0",
+ "contentHash": "Z3wPpG0xefMLmhn9T+Ka/EzAmMQPT0THL/5E4lf9cXI/N9rbGH0G23ZFpRcPnD0ast2k7ieG6QSVNIjmfPCXBQ==",
+ "dependencies": {
+ "libsodium": "[1.0.20.1, 1.0.21)"
+ }
+ },
"OpenIddict.Abstractions": {
"type": "Transitive",
"resolved": "7.7.1",
@@ -323,6 +478,17 @@
"OpenIddict.Abstractions": "7.7.1"
}
},
+ "OpenIddict.Validation": {
+ "type": "Transitive",
+ "resolved": "7.7.1",
+ "contentHash": "09FOsvek+iSKrNbEehH2c1uBWSFurZk1U8vyTKk5aiaCV2bbj+j/68KRA/iHOgSe8qV3+0ZrquhmjFMpcojVSw==",
+ "dependencies": {
+ "Microsoft.Extensions.Logging": "8.0.1",
+ "Microsoft.IdentityModel.JsonWebTokens": "8.19.2",
+ "Microsoft.IdentityModel.Protocols": "8.19.2",
+ "OpenIddict.Abstractions": "7.7.1"
+ }
+ },
"System.CodeDom": {
"type": "Transitive",
"resolved": "4.4.0",
@@ -384,11 +550,21 @@
"System.Composition.Runtime": "6.0.0"
}
},
+ "System.Diagnostics.DiagnosticSource": {
+ "type": "Transitive",
+ "resolved": "9.0.0",
+ "contentHash": "ddppcFpnbohLWdYKr/ZeLZHmmI+DXFgZ3Snq+/E7SwcdW4UnvxmaugkwGywvGVWkHPGCSZjCP+MLzu23AL5SDw=="
+ },
"System.Formats.Asn1": {
"type": "Transitive",
"resolved": "10.0.2",
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
},
+ "System.Formats.Cbor": {
+ "type": "Transitive",
+ "resolved": "9.0.24",
+ "contentHash": "SEfEvHu6qXcXoDsDKagddLDf8A9iHIhHUD0hGemdmwlP206KLLCI5ksskOpeXMgNpQCs2diB0fOBKcnjySHFUQ=="
+ },
"System.IO.Pipelines": {
"type": "Transitive",
"resolved": "6.0.3",
diff --git a/src/Bifrost.Web/wwwroot/js/passkeys.js b/src/Bifrost.Web/wwwroot/js/passkeys.js
new file mode 100644
index 0000000..3d898f0
--- /dev/null
+++ b/src/Bifrost.Web/wwwroot/js/passkeys.js
@@ -0,0 +1,125 @@
+// The Linked accounts page's passkey ceremonies (docs/passkeys.md). First-party, no dependency. It asks the server for
+// WebAuthn options, calls navigator.credentials, and posts back only base64url strings in a same-origin form. Nothing it
+// reads from the options is shown or evaluated; the server checks the origin, the challenge and the signature.
+(function () {
+ "use strict";
+
+ var status = document.getElementById("passkey-status");
+
+ function say(text) {
+ if (status) {
+ status.textContent = text;
+ }
+ }
+
+ function toBytes(value) {
+ var padded = value.replace(/-/g, "+").replace(/_/g, "/");
+ while (padded.length % 4) {
+ padded += "=";
+ }
+ var raw = atob(padded);
+ var bytes = new Uint8Array(raw.length);
+ for (var i = 0; i < raw.length; i++) {
+ bytes[i] = raw.charCodeAt(i);
+ }
+ return bytes.buffer;
+ }
+
+ function toText(buffer) {
+ var bytes = new Uint8Array(buffer);
+ var raw = "";
+ for (var i = 0; i < bytes.length; i++) {
+ raw += String.fromCharCode(bytes[i]);
+ }
+ return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ }
+
+ function token(form) {
+ var field = form.querySelector("input[name=__RequestVerificationToken]");
+ return field ? field.value : "";
+ }
+
+ // Posts to a handler of this page with the form's antiforgery token and returns the parsed JSON, or throws.
+ function options(handler, form, fields) {
+ return fetch(location.pathname + "?handler=" + handler, {
+ method: "POST",
+ credentials: "same-origin",
+ headers: { "RequestVerificationToken": token(form), "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams(fields)
+ }).then(function (response) {
+ return response.json().then(function (body) {
+ if (!response.ok) {
+ throw new Error(body && body.error ? body.error : "error");
+ }
+ return body;
+ });
+ });
+ }
+
+ function descriptors(list) {
+ return (list || []).map(function (item) {
+ var copy = { type: item.type, id: toBytes(item.id) };
+ if (item.transports) {
+ copy.transports = item.transports;
+ }
+ return copy;
+ });
+ }
+
+ function set(form, name, value) {
+ form.elements[name].value = value;
+ }
+
+ function failed(error) {
+ var code = error && error.message ? error.message : "error";
+ location.assign(location.pathname + "?result=" + (/^[a-z_]+$/.test(code) && code !== "error" ? encodeURIComponent(code) : "passkey_failed"));
+ }
+
+ document.querySelectorAll("form[data-passkey-enrol]").forEach(function (form) {
+ form.addEventListener("submit", function (event) {
+ if (form.dataset.ready === "1") {
+ return;
+ }
+ event.preventDefault();
+ say("Waiting for your device...");
+ options("PasskeyEnrolOptions", form, {}).then(function (created) {
+ created.challenge = toBytes(created.challenge);
+ created.user.id = toBytes(created.user.id);
+ created.excludeCredentials = descriptors(created.excludeCredentials);
+ return navigator.credentials.create({ publicKey: created });
+ }).then(function (credential) {
+ set(form, "id", credential.id);
+ set(form, "rawId", toText(credential.rawId));
+ set(form, "attestationObject", toText(credential.response.attestationObject));
+ set(form, "clientDataJson", toText(credential.response.clientDataJSON));
+ set(form, "transports", credential.response.getTransports ? credential.response.getTransports().join(",") : "");
+ form.dataset.ready = "1";
+ form.submit();
+ }).catch(failed);
+ });
+ });
+
+ document.querySelectorAll("form[data-passkey-unlink]").forEach(function (form) {
+ form.addEventListener("submit", function (event) {
+ if (form.dataset.ready === "1") {
+ return;
+ }
+ event.preventDefault();
+ say("Waiting for your device...");
+ options("PasskeyChallenge", form, { identityId: form.elements.identityId.value }).then(function (requested) {
+ requested.challenge = toBytes(requested.challenge);
+ requested.allowCredentials = descriptors(requested.allowCredentials);
+ return navigator.credentials.get({ publicKey: requested });
+ }).then(function (credential) {
+ set(form, "id", credential.id);
+ set(form, "rawId", toText(credential.rawId));
+ set(form, "authenticatorData", toText(credential.response.authenticatorData));
+ set(form, "clientDataJson", toText(credential.response.clientDataJSON));
+ set(form, "signature", toText(credential.response.signature));
+ set(form, "userHandle", credential.response.userHandle ? toText(credential.response.userHandle) : "");
+ form.dataset.ready = "1";
+ form.submit();
+ }).catch(failed);
+ });
+ });
+})();
diff --git a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
new file mode 100644
index 0000000..e148132
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs
@@ -0,0 +1,439 @@
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Tests.Support;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Bifrost.Web.Tests;
+
+/// A folded member's browser and Heimdall's patron intake, over HTTP: the merge ledger is the single gate behind both.
+public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : IClassFixture
+{
+ private sealed record Seeded(Guid Survivor, Guid Folded, Guid Motion, string FoldedHeimdallId, long SurvivorGitHubId, long FoldedGitHubId);
+
+ private async Task SeedAsync()
+ {
+ using var scope = factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var seed = Random.Shared.NextInt64(1_000_000, 900_000_000);
+ UserAccount Make(string name, long gitHubId) => new()
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, GitHubUserId = gitHubId, GitHubLogin = name, NormalizedGitHubLogin = name,
+ HeimdallAccountId = "hd-" + name,
+ MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = DateTimeOffset.UtcNow },
+ Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
+ };
+ var survivor = Make($"surv-{seed}", seed);
+ var folded = Make($"fold-{seed}", seed + 1);
+ db.UserAccounts.AddRange(survivor, folded);
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = survivor.Id, Title = "Open motion", Status = MotionStatus.Open, OpensAtUtc = DateTimeOffset.UtcNow.AddHours(-1),
+ ClosesAtUtc = DateTimeOffset.UtcNow.AddDays(2), CreatedAtUtc = DateTimeOffset.UtcNow
+ };
+ db.Motions.Add(motion);
+ await db.SaveChangesAsync();
+ return new Seeded(survivor.Id, folded.Id, motion.Id, folded.HeimdallAccountId, seed, seed + 1);
+ }
+
+ private HttpClient ClientFor(long gitHubId, string login)
+ {
+ var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = true });
+ client.DefaultRequestHeaders.Add("X-Test-GitHub-Id", gitHubId.ToString());
+ client.DefaultRequestHeaders.Add("X-Test-GitHub-Login", login);
+ return client;
+ }
+
+ private static async Task TokenAsync(HttpClient client)
+ {
+ using var page = await client.GetAsync("/App/Motions");
+ var html = await page.Content.ReadAsStringAsync();
+ var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
+ Assert.NotEmpty(token);
+ return token;
+ }
+
+ private static Task VoteAsync(HttpClient client, Guid motion, string token) =>
+ client.PostAsync("/App/Motions?handler=Vote", new FormUrlEncodedContent(new Dictionary
+ {
+ ["motionId"] = motion.ToString(), ["choice"] = "For", ["comment"] = "yes", ["__RequestVerificationToken"] = token
+ }));
+
+ private async Task WithDb(Func> read)
+ {
+ using var scope = factory.Services.CreateScope();
+ return await read(scope.ServiceProvider.GetRequiredService());
+ }
+
+ private Task VoteRowsAsync(Guid motion) => WithDb(db => db.Votes.IgnoreQueryFilters().CountAsync(x => x.MotionId == motion));
+
+ private async Task MergeAsync(Seeded s, AccountMergeState state)
+ {
+ using var scope = factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var merge = new AccountMerge { SurvivorUserAccountId = s.Survivor, FoldedUserAccountId = s.Folded, State = state, CreatedUtc = DateTimeOffset.UtcNow };
+ db.AccountMerges.Add(merge);
+ await db.SaveChangesAsync();
+ return merge.Id;
+ }
+
+ private async Task SetStateAsync(Guid mergeId, AccountMergeState state) =>
+ await WithDb(async db =>
+ {
+ (await db.AccountMerges.SingleAsync(x => x.Id == mergeId)).State = state;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ [Fact]
+ public async Task A_folded_session_cookie_acts_as_nobody_while_Frozen_and_after_Committed_and_the_survivor_still_votes()
+ {
+ var s = await SeedAsync();
+ using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
+ var token = await TokenAsync(folded); // a live, valid form from before the merge: the cookie outlives the merge
+ var merge = await MergeAsync(s, AccountMergeState.Confirmed);
+
+ using (var whileFrozen = await VoteAsync(folded, s.Motion, token))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, whileFrozen.StatusCode);
+ }
+
+ Assert.Equal(0, await VoteRowsAsync(s.Motion));
+ using (var page = await folded.GetAsync("/App/Motions"))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, page.StatusCode);
+ }
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallMoved);
+ await SetStateAsync(merge, AccountMergeState.Committed);
+ using (var afterCommit = await VoteAsync(folded, s.Motion, token))
+ {
+ Assert.NotEqual(HttpStatusCode.OK, afterCommit.StatusCode);
+ }
+
+ Assert.Equal(0, await VoteRowsAsync(s.Motion));
+
+ using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
+ using var control = await VoteAsync(survivor, s.Motion, await TokenAsync(survivor));
+ Assert.Equal(HttpStatusCode.Redirect, control.StatusCode);
+ Assert.Equal(1, await VoteRowsAsync(s.Motion));
+ }
+
+ private async Task IntakeAsync(Seeded s, string eventId)
+ {
+ var payload = JsonSerializer.Serialize(new
+ {
+ heimdallAccountId = s.FoldedHeimdallId, provider = "PayPal", providerEventId = eventId, kind = "OneTimeDonation",
+ amount = 25m, currencyCode = "USD", externalSupportId = "CAPTURE-1", supportedAtUtc = DateTimeOffset.UtcNow, isCurrentRecurringSupport = false
+ });
+ using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("test-heimdall-intake-secret"));
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/heimdall/patron-support/events");
+ request.Headers.Add("X-Heimdall-Signature-256", "sha256=" + Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant());
+ request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
+ using var client = factory.CreateClient();
+ using var response = await client.SendAsync(request);
+ return response.StatusCode;
+ }
+
+ private Task> EventOwnersAsync(Seeded s) =>
+ WithDb(db => db.PatronSupportEvents.Where(x => x.UserAccountId == s.Survivor || x.UserAccountId == s.Folded).Select(x => x.UserAccountId).ToListAsync());
+
+ /// Lands the merge through the ledger's own commit, as the saga will: the move done, then the Bifrost records reduced.
+ private async Task CommitMergeAsync(Seeded s)
+ {
+ var merge = await MergeAsync(s, AccountMergeState.HeimdallMoved);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().CommitAsync(merge, default);
+ return 0;
+ });
+ return merge;
+ }
+
+ [Fact]
+ public async Task Patron_intake_for_a_folded_heimdall_id_records_on_the_survivor()
+ {
+ var s = await SeedAsync();
+ await MergeAsync(s, AccountMergeState.Final);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}"));
+
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_patron_event_that_lands_during_grace_is_journalled_once_and_undo_moves_it_back_to_the_folded_account()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); // the provider retries: nothing doubles
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ Assert.Equal(1, await WithDb(db => db.AccountMergeEntries.CountAsync(x => x.MergeId == merge && x.Kind == AccountMergeEntryKind.PatronSupportEvent)));
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ private Task> PatronJournalAsync(Guid merge) =>
+ WithDb(db => db.AccountMergeEntries.Where(x => x.MergeId == merge).OrderBy(x => x.Seq).ToListAsync());
+
+ [Fact]
+ public async Task A_single_patron_event_during_grace_is_journalled_by_its_own_delivery_and_undo_moves_it_back()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}")); // no retry follows
+
+ var journal = await PatronJournalAsync(merge);
+ Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); // the new entry takes its own Seq
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_provider_retry_journals_an_event_the_first_delivery_left_unjournalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+ await WithDb(async db => // the first delivery recorded on the survivor, then died before journalling
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = s.Survivor, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1",
+ Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ return 0;
+ });
+ Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+
+ Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_stripe_checkout_opened_by_an_account_that_folded_pays_the_survivor_and_is_journalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ using var response = await StripeCheckoutAsync(s);
+
+ Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(s.Folded, entry.PriorUserAccountId); // the journal names the folded account as the previous owner
+
+ await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await UndoAsync(merge);
+ Assert.Equal([s.Folded], await EventOwnersAsync(s)); // so an undo sends the donation back where it was opened
+ }
+
+ private async Task StripeCheckoutAsync(Seeded s)
+ {
+ var payload = JsonSerializer.Serialize(new
+ {
+ id = $"evt_{Guid.NewGuid():N}", type = "checkout.session.completed", created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
+ data = new { @object = new { id = $"cs_{Guid.NewGuid():N}", customer = "cus_1", currency = "usd", amount_total = 1900, payment_status = "paid",
+ metadata = new Dictionary { ["bifrost_user_account_id"] = s.Folded.ToString("N") } } }
+ });
+ var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
+ using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("whsec_test_webhook_secret"));
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/patronage/stripe/webhook");
+ request.Headers.Add("Stripe-Signature", $"t={timestamp},v1={Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}.{payload}"))).ToLowerInvariant()}");
+ request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
+ using var client = factory.CreateClient();
+
+ return await client.SendAsync(request);
+ }
+
+ private Task UndoAsync(Guid merge) =>
+ WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default);
+ return 0;
+ });
+
+ [Fact]
+ public async Task A_stripe_checkout_opened_by_an_account_that_folded_into_a_suspended_survivor_is_refused_as_not_configured_and_records_nothing()
+ {
+ var s = await SeedAsync();
+ await CommitMergeAsync(s);
+ await WithDb(async db =>
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Survivor)).Status = MembershipStatus.Suspended;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ using var response = await StripeCheckoutAsync(s);
+
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ Assert.Empty(await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task The_admin_ledgers_manual_patron_record_for_a_folded_account_lands_on_the_survivor_and_is_journalled()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+
+ await WithDb(async db =>
+ {
+ using var scope = factory.Services.CreateScope();
+ await scope.ServiceProvider.GetRequiredService().RecordSupportEventAsync(
+ s.Survivor, s.Folded, PatronSupportEventKind.OneTimeDonation, 10m, "USD", "manual-1", ExternalPatronProvider.Manual,
+ string.Empty, string.Empty, string.Empty, DateTimeOffset.UtcNow, false, string.Empty, default); // as Pages/App/Ledger records it
+ return 0;
+ });
+
+ Assert.Equal([s.Survivor], await EventOwnersAsync(s));
+ var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal(s.Folded, entry.PriorUserAccountId);
+ }
+
+ [Fact]
+ public async Task A_provider_retry_of_an_event_stranded_on_the_folded_account_journals_nothing_because_nothing_moved()
+ {
+ var s = await SeedAsync();
+ var merge = await CommitMergeAsync(s);
+ var eventId = $"WH-{Guid.NewGuid():N}";
+ await WithDb(async db => // recorded on the folded account by a delivery that straddled the commit
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = s.Folded, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1",
+ Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
+
+ Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ Assert.Equal([s.Folded], await EventOwnersAsync(s));
+ }
+
+ [Fact]
+ public async Task A_folded_bootstrap_admins_sign_in_does_not_reactivate_the_merged_membership_and_an_approval_is_refused()
+ {
+ var s = await SeedAsync();
+ await CommitMergeAsync(s);
+ using var folded = ClientFor(s.FoldedGitHubId, "test-admin"); // the bootstrap login: every request would re-promote it
+
+ using (await folded.GetAsync("/"))
+ {
+ }
+
+ Assert.Equal((MembershipStatus.Merged, false), await WithDb(async db =>
+ {
+ var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded);
+ return (membership.Status, membership.IsPlatformAdmin);
+ }));
+
+ using var admin = ClientFor(Random.Shared.NextInt64(1_000_000_000, 2_000_000_000), "test-admin");
+ var token = await TokenAsync(admin);
+ using var approve = await admin.PostAsync("/App/Members?handler=Approve", new FormUrlEncodedContent(new Dictionary
+ {
+ ["userAccountId"] = s.Folded.ToString(), ["__RequestVerificationToken"] = token
+ }));
+ Assert.Equal(HttpStatusCode.Redirect, approve.StatusCode);
+ Assert.Equal(MembershipStatus.Merged, await WithDb(async db => (await db.Memberships.SingleAsync(x => x.UserAccountId == s.Folded)).Status));
+ }
+
+ /// Forbid answers 403 or sends the browser to the access-denied page; either way the page and its Heimdall flows are not served.
+ private static void AssertRefused(HttpResponseMessage response)
+ {
+ Assert.True(response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.Found, response.StatusCode.ToString());
+ Assert.DoesNotContain("heimdall", response.Headers.Location?.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Committed)]
+ public async Task A_frozen_or_folded_cookie_cannot_reach_the_linked_accounts_page_or_start_one_of_its_flows(AccountMergeState state)
+ {
+ var s = await SeedAsync();
+ using var folded = ClientFor(s.FoldedGitHubId, $"fold-{s.SurvivorGitHubId}");
+ var token = await TokenAsync(folded);
+ using (var control = await folded.GetAsync("/Membership/LinkedAccounts"))
+ {
+ Assert.Equal(HttpStatusCode.OK, control.StatusCode); // before the merge the page is theirs
+ }
+
+ await MergeAsync(s, state);
+
+ using var page = await folded.GetAsync("/Membership/LinkedAccounts");
+ AssertRefused(page);
+ using var refresh = await folded.PostAsync("/Membership/LinkedAccounts?handler=Refresh", new FormUrlEncodedContent(new Dictionary
+ {
+ ["via"] = "google", ["__RequestVerificationToken"] = token
+ }));
+ AssertRefused(refresh);
+
+ using var survivor = ClientFor(s.SurvivorGitHubId, $"surv-{s.SurvivorGitHubId}");
+ using var other = await survivor.GetAsync("/Membership/LinkedAccounts");
+ Assert.Equal(HttpStatusCode.OK, other.StatusCode);
+ }
+}
+
+/// The desk's bearer door judges standing the way the cookie gate and the chat refusal do.
+public sealed class AccountMergeDeskTests
+{
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Committed)]
+ public async Task A_frozen_or_folded_subjects_live_desk_token_is_forbidden(AccountMergeState state)
+ {
+ using var factory = new DeskWebApplicationFactory();
+ DeskReplay.HoldVectorForks(factory.Door);
+ await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true);
+ var token = factory.Token(DeskWebApplicationFactory.Alice, "bifrost-desk", "desk.read");
+ Task ListAsync() => factory.SendAsync("GET", DeskReplay.Target("list", "gamecult-chat", null), null, token);
+
+ Assert.Equal(200, (await ListAsync()).Status); // the live member, before the merge
+
+ using (var scope = factory.Services.CreateScope())
+ {
+ var db = scope.ServiceProvider.GetRequiredService();
+ var survivor = new UserAccount { BifrostIdentity = "desk-survivor", NormalizedBifrostIdentity = "desk-survivor", GitHubLogin = "desk-survivor", NormalizedGitHubLogin = "desk-survivor" };
+ db.UserAccounts.Add(survivor);
+ db.AccountMerges.Add(new AccountMerge
+ {
+ SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = Guid.Parse(DeskWebApplicationFactory.Alice), State = state, CreatedUtc = DateTimeOffset.UtcNow
+ });
+ await db.SaveChangesAsync();
+ }
+
+ Assert.Equal(403, (await ListAsync()).Status);
+ }
+}
diff --git a/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs b/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
new file mode 100644
index 0000000..3185be5
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeLedgerTests.cs
@@ -0,0 +1,1121 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.ConceptVotes;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Motions;
+using Bifrost.Web.Features.Patronage;
+using Bifrost.Web.Features.Shared;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Tests;
+
+///
+/// The merge ledger from its consumers' side: the motion state and close a member sees, the concept tallies a visitor sees, the actor
+/// a sign-in resolves to, the patron weight, and the undo. Each operation opens its own context, as a request scope would.
+///
+public sealed class AccountMergeLedgerTests
+{
+ public static readonly DateTimeOffset T0 = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
+
+ public sealed class Clock(DateTimeOffset start) : TimeProvider
+ {
+ public DateTimeOffset Now { get; set; } = start;
+
+ public override DateTimeOffset GetUtcNow() => Now;
+ }
+
+ /// The merge fixtures. In memory by default; points the same fixtures at a real database, where unique indexes, transactions, tokens and triggers exist.
+ public sealed class World
+ {
+ private readonly string _name = $"merge-{Guid.NewGuid():N}";
+ private readonly SaveChangesInterceptor[] _interceptors;
+ private readonly string? _postgres;
+
+ public World(params SaveChangesInterceptor[] interceptors) => _interceptors = interceptors;
+
+ private World(string postgres, SaveChangesInterceptor[] interceptors) : this(interceptors) => _postgres = postgres;
+
+ public static World OnPostgres(string connectionString, params SaveChangesInterceptor[] interceptors) => new(connectionString, interceptors);
+
+ public Clock Clock { get; } = new(T0);
+
+ public BifrostDbContext Db()
+ {
+ var options = new DbContextOptionsBuilder().AddInterceptors(_interceptors);
+ if (_postgres is null)
+ {
+ options.UseInMemoryDatabase(_name).ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
+ }
+ else
+ {
+ options.UseNpgsql(_postgres);
+ }
+
+ return new BifrostDbContext(options.Options);
+ }
+
+ public AccountMergeLedger Ledger(BifrostDbContext db) => new(db, new PatronageService(db, new AuditTrailService(db, Clock), Clock), Clock);
+
+ public MotionGovernanceService Motions(BifrostDbContext db) => new(db, new AuditTrailService(db, Clock), Clock);
+
+ public ConceptAppraisalService Concepts(BifrostDbContext db) =>
+ new(db, new AuditTrailService(db, Clock), Clock, Options.Create(new ConceptVoteOptions()));
+
+ public async Task AccountAsync(string name, MembershipStatus status = MembershipStatus.Active, bool heimdall = true, bool moderator = false, params MemberRole[] roles)
+ {
+ await using var db = Db();
+ var account = new UserAccount
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = BifrostIdentityService.NormalizeIdentity(name),
+ HeimdallAccountId = heimdall ? $"hd-{name}-{Guid.NewGuid():N}" : string.Empty,
+ CreatedAtUtc = T0, LastSeenAtUtc = T0
+ };
+ account.Membership = new Membership { UserAccountId = account.Id, Status = status, CanModerateMotions = moderator };
+ foreach (var role in roles)
+ {
+ account.Membership.RoleAssignments.Add(new RoleAssignment { Role = role });
+ }
+
+ db.UserAccounts.Add(account);
+ await db.SaveChangesAsync();
+ return account;
+ }
+
+ public async Task MotionAsync(string title = "m", MotionStatus status = MotionStatus.Open, MotionKind kind = MotionKind.Standard)
+ {
+ await using var db = Db();
+ var author = await AccountAsync("author-" + Guid.NewGuid().ToString("N")[..6]);
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = author.Id, Title = title, Status = status, Kind = kind, OpensAtUtc = T0,
+ ClosesAtUtc = T0.AddDays(3), CreatedAtUtc = T0, ApprovalThreshold = 0.5m
+ };
+ db.Motions.Add(motion);
+ await db.SaveChangesAsync();
+ return motion;
+ }
+
+ public async Task VoteAsync(Motion motion, UserAccount who, VoteChoice choice, decimal weight = 1m, DateTimeOffset? at = null)
+ {
+ await using var db = Db();
+ db.Votes.Add(new Vote { MotionId = motion.Id, UserAccountId = who.Id, Choice = choice, Weight = weight, CastAtUtc = at ?? T0.AddHours(1) });
+ await db.SaveChangesAsync();
+ }
+
+ public async Task MergeAsync(UserAccount survivor, UserAccount folded, AccountMergeState state = AccountMergeState.HeimdallMoved)
+ {
+ await using var db = Db();
+ var merge = new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = T0 };
+ db.AccountMerges.Add(merge);
+ await db.SaveChangesAsync();
+ return merge;
+ }
+
+ public async Task CommitAsync(AccountMerge merge)
+ {
+ await using var db = Db();
+ return await Ledger(db).CommitAsync(merge.Id, default);
+ }
+
+ public async Task SetStateAsync(AccountMerge merge, AccountMergeState state)
+ {
+ await using var db = Db();
+ (await db.AccountMerges.SingleAsync(x => x.Id == merge.Id)).State = state;
+ await db.SaveChangesAsync();
+ }
+
+ public async Task StateOfAsync(Motion motion, UserAccount viewer)
+ {
+ await using var db = Db();
+ var actorAccount = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .SingleAsync(x => x.Id == viewer.Id);
+ var state = await Motions(db).GetStateAsync(new CurrentBifrostActor(true, actorAccount), default);
+ return state.Motions.Single(x => x.Id == motion.Id);
+ }
+
+ public async Task ActorAsync(Guid accountId)
+ {
+ await using var db = Db();
+ var account = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.TierSnapshots).Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments)
+ .SingleAsync(x => x.Id == accountId);
+ return new CurrentBifrostActor(true, account);
+ }
+
+ public async Task CloseAsync(Motion motion, UserAccount moderator)
+ {
+ await using var db = Db();
+ await Motions(db).CloseMotionAsync(await ActorAsync(moderator.Id), motion.Id, default);
+ await using var check = Db();
+ return (await check.Motions.SingleAsync(x => x.Id == motion.Id)).Status;
+ }
+
+ public async Task> AllVotesAsync(Motion motion)
+ {
+ await using var db = Db();
+ return await db.Votes.IgnoreQueryFilters().AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync();
+ }
+
+ public async Task> JournalAsync(AccountMerge merge)
+ {
+ await using var db = Db();
+ return await db.AccountMergeEntries.AsNoTracking().Where(x => x.MergeId == merge.Id).OrderBy(x => x.Seq).ToListAsync();
+ }
+
+ public async Task MembershipOfAsync(UserAccount account)
+ {
+ await using var db = Db();
+ return await db.Memberships.AsNoTracking().Include(x => x.TierSnapshots).Include(x => x.RoleAssignments).SingleAsync(x => x.UserAccountId == account.Id);
+ }
+ }
+
+ // ---- votes ----
+
+ [Fact]
+ public async Task Both_voted_on_an_open_motion_only_the_survivors_weight_counts_in_state_and_close()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, survivor, VoteChoice.Against, 1m);
+ await world.VoteAsync(motion, folded, VoteChoice.For, 3m);
+ var before = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((3m, 1m), (before.VotesFor, before.VotesAgainst));
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var after = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((0m, 1m), (after.VotesFor, after.VotesAgainst));
+ Assert.Equal(MotionStatus.Failed, await world.CloseAsync(motion, moderator));
+ Assert.Equal(2, (await world.AllVotesAsync(motion)).Count); // nothing is deleted
+ }
+
+ [Fact]
+ public async Task A_vote_only_the_folded_account_cast_moves_and_a_later_survivor_cast_replaces_it_never_doubling()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(1m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ await using (var db = world.Db())
+ {
+ await world.Motions(db).CastVoteAsync(await world.ActorAsync(survivor.Id), motion.Id, VoteChoice.Against, "changed my mind", default);
+ }
+
+ var item = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((0m, 1m), (item.VotesFor, item.VotesAgainst));
+ var row = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal(survivor.Id, row.UserAccountId);
+ Assert.Null(row.VoidedByMergeId);
+ }
+
+ [Fact]
+ public async Task A_vote_only_the_folded_account_cast_is_voided_when_the_survivor_is_not_active()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor", MembershipStatus.PendingApproval);
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(0m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ var row = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal(merge.Id, row.VoidedByMergeId);
+ Assert.Equal(folded.Id, row.UserAccountId);
+ }
+
+ [Fact]
+ public async Task Closed_motions_keep_every_vote_and_tally()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync(status: MotionStatus.Passed);
+ await world.VoteAsync(motion, survivor, VoteChoice.For, 1m);
+ await world.VoteAsync(motion, folded, VoteChoice.For, 2m);
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(3m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+ Assert.All(await world.AllVotesAsync(motion), v => Assert.Null(v.VoidedByMergeId));
+ }
+
+ // ---- concept appraisals ----
+
+ [Fact]
+ public async Task Appraisals_reduce_to_one_voice_per_person_and_the_tallies_count_the_person_once()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ Guid both, onlyFolded;
+ await using (var db = world.Db())
+ {
+ var s1 = new ConceptSubject { Collection = "c", Key = "both", Title = "Both", RegisteredAtUtc = T0 };
+ var s2 = new ConceptSubject { Collection = "c", Key = "only-folded", Title = "Only folded", RegisteredAtUtc = T0 };
+ db.ConceptSubjects.AddRange(s1, s2);
+ ConceptAppraisal Row(ConceptSubject s, UserAccount who, ConceptStance stance) => new()
+ {
+ SubjectId = s.Id, UserAccountId = who.Id, VoterKey = "account:" + who.Id.ToString("N"), Stance = stance,
+ VoterClass = VoterClass.Member, CastAtUtc = T0
+ };
+ db.ConceptAppraisals.AddRange(Row(s1, survivor, ConceptStance.Up), Row(s1, folded, ConceptStance.Down), Row(s2, folded, ConceptStance.Down));
+ await db.SaveChangesAsync();
+ (both, onlyFolded) = (s1.Id, s2.Id);
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ await using var read = world.Db();
+ var tallies = await world.Concepts(read).GetTalliesAsync("c", default);
+ Assert.Equal((1, 0), (tallies["both"].Up, tallies["both"].Down));
+ Assert.Equal((0, 1), (tallies["only-folded"].Up, tallies["only-folded"].Down));
+ var moved = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded);
+ Assert.Equal(survivor.Id, moved.UserAccountId);
+ Assert.Equal("account:" + survivor.Id.ToString("N"), moved.VoterKey);
+ Assert.Equal(1, await read.ConceptAppraisals.IgnoreQueryFilters().CountAsync(x => x.SubjectId == both && x.VoidedByMergeId != null));
+ }
+
+ // ---- membership, standing, patronage ----
+
+ [Fact]
+ public async Task The_folded_membership_becomes_Merged_with_weight_zero_and_no_role_or_admin_flag_is_carried()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor", roles: MemberRole.StandardMember);
+ var folded = await world.AccountAsync("folded", roles: [MemberRole.PlatformAdmin, MemberRole.Producer]);
+ await using (var db = world.Db())
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).IsPlatformAdmin = true;
+ await db.SaveChangesAsync();
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var foldedMembership = await world.MembershipOfAsync(folded);
+ Assert.Equal(MembershipStatus.Merged, foldedMembership.Status);
+ Assert.Equal(0m, foldedMembership.EffectiveVotingWeight);
+ var survivorMembership = await world.MembershipOfAsync(survivor);
+ Assert.Equal([MemberRole.StandardMember], survivorMembership.RoleAssignments.Select(x => x.Role));
+ Assert.False(survivorMembership.IsPlatformAdmin);
+ Assert.Equal(MembershipStatus.Active, survivorMembership.Status);
+ }
+
+ [Fact]
+ public async Task A_suspended_folded_account_suspends_the_survivor_and_undo_restores_it_only_if_unchanged()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded", MembershipStatus.Suspended);
+ var untouched = await world.MergeAsync(survivor, folded);
+ await world.CommitAsync(untouched);
+
+ var suspended = await world.MembershipOfAsync(survivor);
+ Assert.Equal(MembershipStatus.Suspended, suspended.Status);
+ Assert.Equal(AccountMergeLedger.SuspensionReason(untouched.Id), suspended.SuspensionReason);
+
+ await world.SetStateAsync(untouched, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(untouched.Id, default);
+ }
+
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(survivor)).Status);
+ Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(folded)).Status);
+
+ // The same again, but a steward re-suspends the survivor for their own reason before the undo: that standing is theirs now.
+ var folded2 = await world.AccountAsync("folded2", MembershipStatus.Suspended);
+ var second = await world.MergeAsync(survivor, folded2);
+ await world.CommitAsync(second);
+ await using (var db = world.Db())
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)).SuspensionReason = "steward decision";
+ await db.SaveChangesAsync();
+ }
+
+ await world.SetStateAsync(second, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(second.Id, default);
+ }
+
+ Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(survivor)).Status);
+ Assert.Contains(await world.JournalAsync(second), e => e.Kind == AccountMergeEntryKind.Standing && e.Action == AccountMergeEntryAction.KeptAfterUndo);
+ }
+
+ [Fact]
+ public async Task Patron_events_follow_the_person_and_the_survivors_tier_derives_once_from_all_events_not_tier_plus_tier()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ await using (var db = world.Db())
+ {
+ PatronSupportEvent Event(UserAccount who, decimal amount) => new()
+ {
+ UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = amount,
+ ProviderEventId = Guid.NewGuid().ToString("N"), SupportedAtUtc = T0, RecordedAtUtc = T0
+ };
+ db.PatronSupportEvents.AddRange(Event(survivor, 90m), Event(folded, 1000m));
+ var memberships = await db.Memberships.ToListAsync();
+ foreach (var (who, weight) in new[] { (survivor, 1m), (folded, 3m) })
+ {
+ db.TierSnapshots.Add(new TierSnapshot { MembershipId = memberships.Single(m => m.UserAccountId == who.Id).Id, Kind = TierSnapshotKind.Patron, Label = "t", Weight = weight, IsCurrent = true, EffectiveFromUtc = T0, CapturedAtUtc = T0 });
+ }
+
+ await db.SaveChangesAsync();
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var survivorMembership = await world.MembershipOfAsync(survivor);
+ Assert.Equal(3m, survivorMembership.EffectiveVotingWeight); // 1090 points: Gold, not Bronze 1 + Gold 3
+ Assert.Single(survivorMembership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent);
+ Assert.DoesNotContain(( await world.MembershipOfAsync(folded)).TierSnapshots, x => x.IsCurrent);
+ await using var db2 = world.Db();
+ Assert.All(await db2.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId));
+ }
+
+ // ---- who the actor is ----
+
+ [Fact]
+ public async Task A_principal_whose_identity_names_one_row_and_whose_heimdall_id_names_another_resolves_the_first_and_does_not_throw()
+ {
+ var world = new World();
+ var byIdentity = await world.AccountAsync("by-identity");
+ var byHeimdall = await world.AccountAsync("by-heimdall");
+ var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
+ http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
+ [
+ new System.Security.Claims.Claim(BifrostClaimTypes.BifrostIdentity, byIdentity.BifrostIdentity),
+ new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, byHeimdall.HeimdallAccountId)
+ ], "test"));
+ await using var db = world.Db();
+ var accessor = new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db));
+
+ var actor = await accessor.GetAsync(default);
+
+ Assert.Equal(byIdentity.Id, actor.UserAccount!.Id);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed, true)]
+ [InlineData(AccountMergeState.HeimdallMoved, true)]
+ [InlineData(AccountMergeState.Committed, false)]
+ [InlineData(AccountMergeState.Final, false)]
+ [InlineData(AccountMergeState.UndoRequested, false)]
+ [InlineData(AccountMergeState.HeimdallReversed, false)]
+ public async Task A_folded_account_is_frozen_then_folded_and_acts_as_nobody_while_the_survivor_acts_normally(AccountMergeState state, bool frozen)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded", roles: MemberRole.PlatformAdmin);
+ var merge = await world.MergeAsync(survivor, folded, state);
+
+ foreach (var (account, isFolded) in new[] { (folded, true), (survivor, false) })
+ {
+ var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
+ http.User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(
+ [new System.Security.Claims.Claim(BifrostClaimTypes.HeimdallAccountId, account.HeimdallAccountId)], "test"));
+ await using var db = world.Db();
+ var actor = await new CurrentBifrostActorAccessor(new Microsoft.AspNetCore.Http.HttpContextAccessor { HttpContext = http }, db, world.Ledger(db)).GetAsync(default);
+
+ if (!isFolded)
+ {
+ Assert.Equal(survivor.Id, actor.UserAccount!.Id);
+ Assert.Null(actor.Merge);
+ continue;
+ }
+
+ Assert.True(actor.IsAuthenticated);
+ Assert.Null(actor.UserAccount);
+ Assert.False(actor.IsPlatformAdmin);
+ Assert.False(actor.IsActiveMember);
+ Assert.Equal(merge.Id, actor.Merge!.MergeId);
+ Assert.Equal(frozen, actor.Merge is MergeStanding.Frozen);
+ Assert.Equal(!frozen, actor.Merge is MergeStanding.Folded f && f.SurvivorId == survivor.Id);
+ }
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Proposed)]
+ [InlineData(AccountMergeState.Failed)]
+ [InlineData(AccountMergeState.Undone)]
+ public async Task A_merge_that_never_reached_or_has_left_the_move_leaves_the_folded_account_standing_alone(AccountMergeState state)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ await world.MergeAsync(survivor, folded, state);
+
+ await using var db = world.Db();
+ Assert.Null(await world.Ledger(db).StandingAsync(folded.Id, default));
+ }
+
+ // ---- plan ----
+
+ [Fact]
+ public async Task Plan_writes_nothing_and_says_what_a_commit_would_do()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+
+ await using (var db = world.Db())
+ {
+ var plan = await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default);
+ Assert.Empty(plan.Blocks);
+ Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Vote && e.Action == AccountMergeEntryAction.Moved);
+ Assert.Contains(plan.Entries, e => e.Kind == AccountMergeEntryKind.Membership && e.Action == AccountMergeEntryAction.Closed);
+ }
+
+ await using var check = world.Db();
+ Assert.Empty(check.AccountMerges);
+ Assert.Empty(check.AccountMergeEntries);
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
+ Assert.Equal(folded.Id, Assert.Single(await world.AllVotesAsync(motion)).UserAccountId);
+ }
+
+ public static IEnumerable BlockCases() =>
+ new[] { "same_account", "mind_account", "native_account", "merge_in_flight", "survivor_is_folded", "already_folded", "folded_is_survivor", "sealed_ballot_pending" }
+ .Select(x => new object[] { x });
+
+ [Theory]
+ [MemberData(nameof(BlockCases))]
+ public async Task Plan_reports_each_block_by_code(string code)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded", heimdall: code != "native_account");
+ var other = await world.AccountAsync("other");
+ var (planSurvivor, planFolded) = (survivor.Id, folded.Id);
+ switch (code)
+ {
+ case "same_account":
+ planFolded = survivor.Id;
+ break;
+ case "mind_account":
+ await using (var db = world.Db())
+ {
+ db.MindPersonas.Add(new MindPersona { PersonaId = "p", UserAccountId = folded.Id });
+ await db.SaveChangesAsync();
+ }
+
+ break;
+ case "merge_in_flight":
+ await world.MergeAsync(other, folded, AccountMergeState.Confirmed);
+ break;
+ case "survivor_is_folded":
+ await world.MergeAsync(other, survivor, AccountMergeState.Final);
+ break;
+ case "already_folded":
+ await world.MergeAsync(other, folded, AccountMergeState.Committed);
+ break;
+ case "folded_is_survivor":
+ await world.MergeAsync(folded, other, AccountMergeState.Final);
+ break;
+ case "sealed_ballot_pending":
+ var motion = await world.MotionAsync(kind: MotionKind.SealedBallot);
+ await using (var db = world.Db())
+ {
+ db.SealedBallots.Add(new SealedBallot { MotionId = motion.Id, UserAccountId = folded.Id, Commitment = "c", CommittedAtUtc = T0 });
+ await db.SaveChangesAsync();
+ }
+
+ break;
+ }
+
+ await using var read = world.Db();
+ var plan = await world.Ledger(read).PlanAsync(planSurvivor, planFolded, default);
+
+ Assert.Contains(code, plan.Blocks);
+ }
+
+ // ---- commit, undo, finalize ----
+
+ [Fact]
+ public async Task Commit_twice_is_a_no_op_the_second_time_and_the_journal_is_unchanged()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+ var merge = await world.MergeAsync(survivor, folded);
+
+ var first = await world.CommitAsync(merge);
+ var journal = await world.JournalAsync(merge);
+ world.Clock.Now = T0.AddDays(1);
+ var second = await world.CommitAsync(merge);
+
+ Assert.Equal(AccountMergeState.Committed, second.State);
+ Assert.Equal(first.CommittedUtc, second.CommittedUtc);
+ Assert.Equal(first.GraceEndsUtc, T0 + TimeSpan.FromDays(7));
+ Assert.Equal(journal.Count, (await world.JournalAsync(merge)).Count);
+ Assert.NotEmpty(journal);
+ }
+
+ private sealed class FailOnce : SaveChangesInterceptor
+ {
+ public bool Armed { get; set; }
+
+ public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ if (Armed)
+ {
+ Armed = false;
+ throw new DbUpdateException("simulated store failure");
+ }
+
+ return base.SavingChangesAsync(eventData, result, cancellationToken);
+ }
+ }
+
+ [Fact]
+ public async Task A_commit_whose_save_fails_applies_nothing_and_a_retry_applies_exactly_once()
+ {
+ var failure = new FailOnce();
+ var world = new World(failure);
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+ var merge = await world.MergeAsync(survivor, folded);
+
+ failure.Armed = true;
+ await using (var db = world.Db())
+ {
+ var ledger = world.Ledger(db);
+ await Assert.ThrowsAsync(() => ledger.CommitAsync(merge.Id, default));
+ await using var check = world.Db();
+ Assert.Equal(AccountMergeState.HeimdallMoved, (await check.AccountMerges.SingleAsync()).State);
+ Assert.Empty(check.AccountMergeEntries);
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
+
+ await ledger.CommitAsync(merge.Id, default); // the same context, retried
+ }
+
+ var journal = await world.JournalAsync(merge);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote));
+ Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Proposed)]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Failed)]
+ public async Task Commit_from_any_state_but_HeimdallMoved_throws_and_undo_from_Committed_throws(AccountMergeState state)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var merge = await world.MergeAsync(survivor, folded, state);
+
+ await using var db = world.Db();
+ await Assert.ThrowsAsync(() => world.Ledger(db).CommitAsync(merge.Id, default));
+ await world.SetStateAsync(merge, AccountMergeState.Committed);
+ await using var db2 = world.Db();
+ await Assert.ThrowsAsync(() => world.Ledger(db2).UndoLocalAsync(merge.Id, default));
+ }
+
+ [Fact]
+ public async Task Undo_restores_open_motion_votes_keeps_voided_ones_on_since_closed_motions_and_a_survivor_recast_and_restores_membership_and_patron_events()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var bothOpen = await world.MotionAsync("both-open");
+ var bothClosing = await world.MotionAsync("both-closing");
+ var movedKept = await world.MotionAsync("moved-recast");
+ var movedBack = await world.MotionAsync("moved-back");
+ foreach (var motion in new[] { bothOpen, bothClosing })
+ {
+ await world.VoteAsync(motion, survivor, VoteChoice.For);
+ await world.VoteAsync(motion, folded, VoteChoice.Against);
+ }
+
+ await world.VoteAsync(movedKept, folded, VoteChoice.For, at: T0.AddHours(2));
+ await world.VoteAsync(movedBack, folded, VoteChoice.For, at: T0.AddHours(3));
+ await using (var db = world.Db())
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = folded.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 100m,
+ ProviderEventId = "e1", SupportedAtUtc = T0, RecordedAtUtc = T0
+ });
+ await db.SaveChangesAsync();
+ }
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+ Assert.Equal(2m, (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight);
+
+ // After the merge: one motion closes, and the survivor re-casts on a moved vote.
+ await world.CloseAsync(bothClosing, moderator);
+ world.Clock.Now = T0.AddDays(1);
+ await using (var db = world.Db())
+ {
+ await world.Motions(db).CastVoteAsync(await world.ActorAsync(survivor.Id), movedKept.Id, VoteChoice.Against, null, default);
+ }
+
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ Assert.Equal(AccountMergeState.Undone, (await world.Ledger(db).UndoLocalAsync(merge.Id, default)).State);
+ }
+
+ var open = (await world.AllVotesAsync(bothOpen)).Single(v => v.UserAccountId == folded.Id);
+ Assert.Null(open.VoidedByMergeId);
+ var closed = (await world.AllVotesAsync(bothClosing)).Single(v => v.UserAccountId == folded.Id);
+ Assert.Equal(merge.Id, closed.VoidedByMergeId);
+ var recast = Assert.Single(await world.AllVotesAsync(movedKept));
+ Assert.Equal((survivor.Id, VoteChoice.Against), (recast.UserAccountId, recast.Choice));
+ Assert.Equal(folded.Id, Assert.Single(await world.AllVotesAsync(movedBack)).UserAccountId);
+
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
+ Assert.Equal(2m, (await world.MembershipOfAsync(folded)).EffectiveVotingWeight);
+ Assert.Equal(1m, (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight);
+ await using var read = world.Db();
+ Assert.Equal(folded.Id, (await read.PatronSupportEvents.SingleAsync()).UserAccountId);
+ var journal = await world.JournalAsync(merge);
+ Assert.Contains(journal, e => e.Action == AccountMergeEntryAction.KeptAfterUndo && e.Kind == AccountMergeEntryKind.Vote);
+ Assert.Contains(journal, e => e.Action == AccountMergeEntryAction.Restored && e.Kind == AccountMergeEntryKind.Membership);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ Assert.Equal(AccountMergeState.Undone, (await world.Ledger(read).UndoLocalAsync(merge.Id, default)).State); // a second undo is a no-op
+ }
+
+ [Fact]
+ public async Task Finalize_moves_Committed_merges_past_their_grace_to_Final_and_leaves_the_rest()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var due = await world.AccountAsync("due");
+ var young = await world.AccountAsync("young");
+ var dueMerge = await world.CommitAsync(await world.MergeAsync(survivor, due));
+ world.Clock.Now = T0.AddDays(5);
+ var youngMerge = await world.CommitAsync(await world.MergeAsync(survivor, young));
+
+ world.Clock.Now = T0.AddDays(7);
+ await using var db = world.Db();
+ Assert.Equal(1, await world.Ledger(db).FinalizeDueAsync(world.Clock.Now, default));
+
+ await using var read = world.Db();
+ var final = await read.AccountMerges.SingleAsync(x => x.Id == dueMerge.Id);
+ Assert.Equal((AccountMergeState.Final, T0.AddDays(7)), (final.State, final.FinalizedUtc));
+ Assert.Equal(AccountMergeState.Committed, (await read.AccountMerges.SingleAsync(x => x.Id == youngMerge.Id)).State);
+ }
+
+ // ---- verdict cut-merge-ledger.s1: the rules each fix decides ----
+
+ [Theory]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.HeimdallMoved)]
+ [InlineData(AccountMergeState.UndoRequested)]
+ [InlineData(AccountMergeState.HeimdallReversed)]
+ public async Task Plan_blocks_while_either_account_is_in_a_merge_in_flight(AccountMergeState state)
+ {
+ foreach (var survivorSide in new[] { true, false })
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var other = await world.AccountAsync("other");
+ await (survivorSide ? world.MergeAsync(survivor, other, state) : world.MergeAsync(other, folded, state));
+
+ await using var read = world.Db();
+ Assert.Contains("merge_in_flight", (await world.Ledger(read).PlanAsync(survivor.Id, folded.Id, default)).Blocks);
+ }
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Committed)]
+ [InlineData(AccountMergeState.Final)]
+ public async Task A_landed_merges_survivor_cannot_itself_fold_so_an_alias_is_never_a_chain(AccountMergeState state)
+ {
+ var world = new World();
+ var a = await world.AccountAsync("acct-a");
+ var b = await world.AccountAsync("acct-b");
+ var c = await world.AccountAsync("acct-c");
+ await world.MergeAsync(b, a, state);
+
+ await using var read = world.Db();
+ Assert.Contains("folded_is_survivor", (await world.Ledger(read).PlanAsync(c.Id, b.Id, default)).Blocks);
+ Assert.Empty((await world.Ledger(read).PlanAsync(b.Id, c.Id, default)).Blocks); // the other direction is an ordinary merge
+ Assert.Equal(b.Id, ((MergeStanding.Folded)(await world.Ledger(read).StandingAsync(a.Id, default))!).SurvivorId);
+ }
+
+ private static async Task DropMembershipAsync(World world, UserAccount account)
+ {
+ await using var db = world.Db();
+ db.Memberships.Remove(await db.Memberships.SingleAsync(x => x.UserAccountId == account.Id));
+ await db.SaveChangesAsync();
+ }
+
+ [Fact]
+ public async Task A_suspension_is_not_laundered_into_a_survivor_without_a_membership_and_undo_removes_the_row_it_made()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ await DropMembershipAsync(world, survivor);
+ var folded = await world.AccountAsync("folded", MembershipStatus.Suspended);
+ var merge = await world.MergeAsync(survivor, folded);
+
+ await using (var db = world.Db())
+ {
+ var plan = await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default);
+ Assert.Contains(plan.Entries, e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.Created });
+ Assert.Empty(db.Memberships.Where(x => x.UserAccountId == survivor.Id)); // a plan writes nothing
+ }
+
+ await world.CommitAsync(merge);
+
+ var carried = await world.MembershipOfAsync(survivor);
+ Assert.Equal(MembershipStatus.Suspended, carried.Status);
+ Assert.Equal(AccountMergeLedger.SuspensionReason(merge.Id), carried.SuspensionReason);
+ Assert.False((await world.ActorAsync(survivor.Id)).IsActiveMember);
+
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(merge.Id, default);
+ }
+
+ await using var read = world.Db();
+ Assert.Empty(read.Memberships.Where(x => x.UserAccountId == survivor.Id));
+ Assert.Contains(await world.JournalAsync(merge), e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.Restored });
+ }
+
+ [Fact]
+ public async Task Undo_keeps_the_membership_a_merge_made_for_a_suspension_once_an_admin_has_taken_it_over()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ await DropMembershipAsync(world, survivor);
+ var folded = await world.AccountAsync("folded", MembershipStatus.Suspended);
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+ await using (var db = world.Db())
+ {
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)).SuspensionReason = "steward decision";
+ await db.SaveChangesAsync();
+ }
+
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(merge.Id, default);
+ }
+
+ Assert.Equal(MembershipStatus.Suspended, (await world.MembershipOfAsync(survivor)).Status);
+ Assert.Contains(await world.JournalAsync(merge), e => e is { Kind: AccountMergeEntryKind.Standing, Action: AccountMergeEntryAction.KeptAfterUndo });
+ }
+
+ [Fact]
+ public async Task A_moved_vote_carries_the_survivors_weight_not_the_folded_accounts_and_undo_restores_it()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 5m);
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var moved = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal((survivor.Id, 1m), (moved.UserAccountId, moved.Weight));
+ Assert.Equal(1m, (await world.StateOfAsync(motion, moderator)).VotesFor);
+
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(merge.Id, default);
+ }
+
+ var back = Assert.Single(await world.AllVotesAsync(motion));
+ Assert.Equal((folded.Id, 5m), (back.UserAccountId, back.Weight));
+ }
+
+ [Fact]
+ public async Task A_moved_vote_takes_the_survivors_weight_after_the_patron_tiers_were_derived_again()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For, 1m);
+ await using (var db = world.Db())
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = folded.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 100m,
+ ProviderEventId = "e1", SupportedAtUtc = T0, RecordedAtUtc = T0
+ });
+ await db.SaveChangesAsync();
+ }
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var weight = (await world.MembershipOfAsync(survivor)).EffectiveVotingWeight;
+ Assert.Equal(2m, weight);
+ Assert.Equal(weight, Assert.Single(await world.AllVotesAsync(motion)).Weight);
+ }
+
+ private static async Task<(Guid Both, Guid OnlyFolded)> SeedAppraisalsAsync(World world, UserAccount survivor, UserAccount folded, VoterClass foldedClass)
+ {
+ await using var db = world.Db();
+ var both = new ConceptSubject { Collection = "c", Key = "both", Title = "Both", RegisteredAtUtc = T0 };
+ var only = new ConceptSubject { Collection = "c", Key = "only-folded", Title = "Only folded", RegisteredAtUtc = T0 };
+ db.ConceptSubjects.AddRange(both, only);
+ ConceptAppraisal Row(ConceptSubject subject, UserAccount who, ConceptStance stance, VoterClass voterClass) => new()
+ {
+ SubjectId = subject.Id, UserAccountId = who.Id, VoterKey = "account:" + who.Id.ToString("N"), Stance = stance, VoterClass = voterClass, CastAtUtc = T0
+ };
+ db.ConceptAppraisals.AddRange(Row(both, survivor, ConceptStance.Up, VoterClass.Member), Row(both, folded, ConceptStance.Down, foldedClass), Row(only, folded, ConceptStance.Down, foldedClass));
+ await db.SaveChangesAsync();
+ return (both.Id, only.Id);
+ }
+
+ [Fact]
+ public async Task A_lone_folded_appraisal_is_voided_when_the_survivor_is_not_active()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor", MembershipStatus.PendingApproval);
+ var folded = await world.AccountAsync("folded");
+ var (_, onlyFolded) = await SeedAppraisalsAsync(world, survivor, folded, VoterClass.Member);
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ await using var read = world.Db();
+ var row = await read.ConceptAppraisals.IgnoreQueryFilters().SingleAsync(x => x.SubjectId == onlyFolded);
+ Assert.Equal((merge.Id, folded.Id), (row.VoidedByMergeId, row.UserAccountId));
+ Assert.Equal(0, (await world.Concepts(read).GetTalliesAsync("c", default))["only-folded"].Down);
+ }
+
+ [Fact]
+ public async Task A_moved_appraisal_takes_the_member_class_and_undo_gives_back_the_class_and_key_unless_the_survivor_recast_it()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var (_, onlyFolded) = await SeedAppraisalsAsync(world, survivor, folded, VoterClass.Account);
+ var survivorKey = "account:" + survivor.Id.ToString("N");
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ await using (var read = world.Db())
+ {
+ var moved = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded);
+ Assert.Equal((survivor.Id, survivorKey, VoterClass.Member), (moved.UserAccountId, moved.VoterKey, moved.VoterClass));
+ }
+
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(merge.Id, default);
+ }
+
+ await using (var read = world.Db())
+ {
+ var back = await read.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded);
+ Assert.Equal((folded.Id, "account:" + folded.Id.ToString("N"), VoterClass.Account), (back.UserAccountId, back.VoterKey, back.VoterClass));
+ }
+
+ // Again, but the survivor re-casts the moved appraisal before the undo: it is theirs now and stays.
+ var folded2 = await world.AccountAsync("folded2");
+ await using (var db = world.Db())
+ {
+ db.ConceptAppraisals.Add(new ConceptAppraisal
+ {
+ SubjectId = onlyFolded, UserAccountId = folded2.Id, VoterKey = "account:" + folded2.Id.ToString("N"), Stance = ConceptStance.Down,
+ VoterClass = VoterClass.Account, CastAtUtc = T0
+ });
+ await db.SaveChangesAsync();
+ }
+
+ var second = await world.CommitAsync(await world.MergeAsync(survivor, folded2));
+ world.Clock.Now = T0.AddDays(1);
+ await using (var db = world.Db())
+ {
+ var voter = new VoterIdentity(survivorKey, VoterClass.Member, survivor.Id);
+ Assert.Equal(CastResult.Changed, await world.Concepts(db).CastAsync("c", "only-folded", voter, ConceptStance.Up, null, default));
+ }
+
+ await world.SetStateAsync(second, AccountMergeState.HeimdallReversed);
+ await using (var db = world.Db())
+ {
+ await world.Ledger(db).UndoLocalAsync(second.Id, default);
+ }
+
+ await using var after = world.Db();
+ var kept = await after.ConceptAppraisals.SingleAsync(x => x.SubjectId == onlyFolded && x.UserAccountId == survivor.Id);
+ Assert.Equal((survivorKey, ConceptStance.Up), (kept.VoterKey, kept.Stance));
+ Assert.Contains(await world.JournalAsync(second), e => e is { Kind: AccountMergeEntryKind.ConceptAppraisal, Action: AccountMergeEntryAction.KeptAfterUndo });
+ }
+
+ [Fact]
+ public async Task Closed_motions_keep_their_votes_with_their_owners_and_journal_nothing_for_them()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var closed = await world.MotionAsync(status: MotionStatus.Passed);
+ await world.VoteAsync(closed, survivor, VoteChoice.For, 1m);
+ await world.VoteAsync(closed, folded, VoteChoice.For, 2m);
+ var lone = await world.MotionAsync(status: MotionStatus.Failed);
+ await world.VoteAsync(lone, folded, VoteChoice.Against, 2m);
+
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ Assert.Equal(new[] { folded.Id, survivor.Id }.Order(), (await world.AllVotesAsync(closed)).Select(x => x.UserAccountId).Order());
+ var loneVote = Assert.Single(await world.AllVotesAsync(lone));
+ Assert.Equal((folded.Id, 2m), (loneVote.UserAccountId, loneVote.Weight)); // not re-pointed, not re-weighed
+ Assert.DoesNotContain(await world.JournalAsync(merge), e => e.Kind == AccountMergeEntryKind.Vote);
+ }
+
+ [Theory]
+ [InlineData(AccountMergeState.Committed)]
+ [InlineData(AccountMergeState.Final)]
+ public async Task Commit_on_a_landed_merge_returns_the_receipt_and_writes_nothing(AccountMergeState state)
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var merge = await world.MergeAsync(survivor, folded, state);
+
+ var receipt = await world.CommitAsync(merge);
+
+ Assert.Equal((merge.Id, state), (receipt.Id, receipt.State));
+ Assert.Empty(await world.JournalAsync(merge));
+ Assert.Equal(MembershipStatus.Active, (await world.MembershipOfAsync(folded)).Status);
+ }
+
+ [Fact]
+ public async Task Undo_is_refused_for_a_merge_that_was_ever_finalized()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+ await using (var db = world.Db())
+ {
+ var row = await db.AccountMerges.SingleAsync(x => x.Id == merge.Id);
+ row.State = AccountMergeState.HeimdallReversed;
+ row.FinalizedUtc = T0.AddDays(8);
+ await db.SaveChangesAsync();
+ }
+
+ await using var undo = world.Db();
+ await Assert.ThrowsAsync(() => world.Ledger(undo).UndoLocalAsync(merge.Id, default));
+ Assert.Equal(MembershipStatus.Merged, (await world.MembershipOfAsync(folded)).Status);
+ }
+
+ [Fact]
+ public async Task A_vote_and_an_appraisal_from_an_actor_resolved_before_the_account_froze_write_nothing()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ var staleActor = await world.ActorAsync(folded.Id); // a request resolved this before the merge was confirmed
+ await using (var db = world.Db())
+ {
+ db.ConceptSubjects.Add(new ConceptSubject { Collection = "c", Key = "k", Title = "K", RegisteredAtUtc = T0 });
+ await db.SaveChangesAsync();
+ }
+
+ await world.MergeAsync(survivor, folded, AccountMergeState.Confirmed);
+
+ await using (var db = world.Db())
+ {
+ await world.Motions(db).CastVoteAsync(staleActor, motion.Id, VoteChoice.For, null, default);
+ Assert.Equal(CastResult.NoVoter, await world.Concepts(db).CastAsync("c", "k", VoterIdentity.For(staleActor, null), ConceptStance.Up, null, default));
+ }
+
+ Assert.Empty(await world.AllVotesAsync(motion));
+ await using var read = world.Db();
+ Assert.Empty(read.ConceptAppraisals.IgnoreQueryFilters());
+
+ // The survivor, not frozen, still writes.
+ await using var control = world.Db();
+ await world.Motions(control).CastVoteAsync(await world.ActorAsync(survivor.Id), motion.Id, VoteChoice.For, null, default);
+ Assert.Single(await world.AllVotesAsync(motion));
+ }
+
+ [Fact]
+ public async Task A_merged_membership_is_never_rewritten_by_the_bootstrap_promotion_or_by_suspension()
+ {
+ var world = new World();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var admin = await world.AccountAsync("admin", roles: MemberRole.PlatformAdmin);
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ await using (var db = world.Db())
+ {
+ var account = await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleAsync(x => x.Id == folded.Id);
+ Assert.False(ApplicationBootstrapper.TryPromoteBootstrapAdmin(account, T0, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance));
+ Assert.Equal((MembershipStatus.Merged, false), (account.Membership!.Status, account.Membership.IsPlatformAdmin));
+ }
+
+ await using (var db = world.Db())
+ {
+ var suspension = new MembershipSuspensionService(db, new AuditTrailService(db, world.Clock));
+ var actor = await world.ActorAsync(admin.Id);
+ Assert.Equal(SuspensionOutcome.NotApplicable, await suspension.SuspendAsync(actor, folded.Id, "reason", default));
+ Assert.Equal(SuspensionOutcome.NotApplicable, await suspension.UnsuspendAsync(actor, folded.Id, "reason", default));
+ }
+
+ Assert.Equal(MembershipStatus.Merged, (await world.MembershipOfAsync(folded)).Status);
+ }
+
+ [Fact]
+ public async Task The_digest_names_the_survivor_so_two_memberless_survivors_with_identical_records_digest_differently()
+ {
+ // A memberless survivor leaves no entry that mentions it: the plan for (A, folded) and for (C, folded) is the same list of
+ // entries, so only the pair the digest is made for can tell them apart (heimdall-body:finding:cut-merge-saga.s2.digest-pair-binding-unpinned).
+ var world = new World();
+ var folded = await world.AccountAsync("folded");
+ var a = await MemberlessAsync(world, "survivor-a");
+ var c = await MemberlessAsync(world, "survivor-c");
+
+ await using var db = world.Db();
+ var forA = await world.Ledger(db).PlanAsync(a.Id, folded.Id, default);
+ var forC = await world.Ledger(db).PlanAsync(c.Id, folded.Id, default);
+
+ Assert.Empty(forA.Blocks);
+ Assert.Empty(forC.Blocks);
+ Assert.Equal(forA.Entries.Select(x => (x.Kind, x.Action, x.PriorText)), forC.Entries.Select(x => (x.Kind, x.Action, x.PriorText)));
+ Assert.NotEqual(forA.Digest(a.Id, folded.Id), forC.Digest(c.Id, folded.Id));
+ Assert.NotEqual(forA.Digest(a.Id, folded.Id), forA.Digest(c.Id, folded.Id)); // a digest made for one pair does not confirm the other
+ Assert.Equal(forA.Digest(a.Id, folded.Id), (await world.Ledger(db).PlanAsync(a.Id, folded.Id, default)).Digest(a.Id, folded.Id));
+ }
+
+ private static async Task MemberlessAsync(World world, string name)
+ {
+ await using var db = world.Db();
+ var account = new UserAccount
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = name, HeimdallAccountId = $"hd-{name}-{Guid.NewGuid():N}",
+ CreatedAtUtc = T0, LastSeenAtUtc = T0
+ };
+ db.UserAccounts.Add(account);
+ await db.SaveChangesAsync();
+ return account;
+ }
+}
diff --git a/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs b/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs
new file mode 100644
index 0000000..e353e0f
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs
@@ -0,0 +1,981 @@
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Motions;
+using Bifrost.Web.Features.Patronage;
+using Bifrost.Web.Features.Shared;
+using Bifrost.Web.Tests.Support;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using Npgsql;
+
+namespace Bifrost.Web.Tests;
+
+///
+/// The merge tests that need a real server run only when BIFROST_TEST_PG holds a Postgres connection string (no Database=; a role that
+/// may create databases). Every other merge test runs on the in-memory provider, which enforces no unique index, transaction,
+/// concurrency token or trigger, so the rules that rest on those are proven here, on a database each test creates, builds through the
+/// real migrations and the class drops. See AGENTS.md (Live Postgres tests).
+///
+public static class PostgresGate
+{
+ public const string Variable = "BIFROST_TEST_PG";
+
+ public static string? Skip =>
+ string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(Variable))
+ ? $"live Postgres tests: set {Variable} to a connection string without Database= (see AGENTS.md, Live Postgres tests)"
+ : null;
+}
+
+public sealed class PostgresFactAttribute : FactAttribute
+{
+ public PostgresFactAttribute() => Skip = PostgresGate.Skip;
+}
+
+public sealed class PostgresTheoryAttribute : TheoryAttribute
+{
+ public PostgresTheoryAttribute() => Skip = PostgresGate.Skip;
+}
+
+public sealed class MergePostgres : IAsyncLifetime
+{
+ private readonly List _databases = [];
+
+ private static string? Admin => Environment.GetEnvironmentVariable(PostgresGate.Variable);
+
+ public Task InitializeAsync() => Task.CompletedTask;
+
+ /// A fresh database, built by the real migrations, and a world over it.
+ public async Task NewWorldAsync()
+ {
+ var name = $"bifrost_merge_{Guid.NewGuid():N}";
+ await using (var admin = new NpgsqlConnection(Admin))
+ {
+ await admin.OpenAsync();
+ await using var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\"", admin);
+ await create.ExecuteNonQueryAsync();
+ }
+
+ _databases.Add(name);
+ var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString);
+ await using var db = world.Db();
+ await db.Database.MigrateAsync();
+ return world;
+ }
+
+ public async Task DisposeAsync()
+ {
+ if (_databases.Count == 0)
+ {
+ return;
+ }
+
+ NpgsqlConnection.ClearAllPools();
+ await using var admin = new NpgsqlConnection(Admin);
+ await admin.OpenAsync();
+ foreach (var name in _databases)
+ {
+ await using var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", admin);
+ await drop.ExecuteNonQueryAsync();
+ }
+ }
+}
+
+public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFixture
+{
+ private static PostgresException Pg(Exception error)
+ {
+ for (var current = error; current is not null; current = current.InnerException!)
+ {
+ if (current is PostgresException pg)
+ {
+ return pg;
+ }
+ }
+
+ throw new Xunit.Sdk.XunitException($"no PostgresException under {error.GetType().Name}");
+ }
+
+ /// Runs an action once, just before the first save of a context: the rival writer that lands inside a read-then-save window.
+ private sealed class BeforeFirstSave(Func rival) : SaveChangesInterceptor
+ {
+ private int _fired;
+
+ public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ if (Interlocked.Exchange(ref _fired, 1) == 0)
+ {
+ await rival();
+ }
+
+ return result;
+ }
+ }
+
+ /// Holds each of two contexts at its save until both have arrived, so both have read before either writes.
+ private sealed class Rendezvous : SaveChangesInterceptor
+ {
+ private readonly Barrier _barrier = new(2);
+
+ public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ await Task.Run(() => _barrier.SignalAndWait(TimeSpan.FromSeconds(30)), cancellationToken);
+ return result;
+ }
+ }
+
+ private static IEnumerable Chain(Exception error)
+ {
+ for (var current = error; current is not null; current = current.InnerException!)
+ {
+ yield return current;
+ }
+ }
+
+ private static string ConnectionOf(AccountMergeLedgerTests.World world)
+ {
+ using var db = world.Db();
+ return db.Database.GetConnectionString()!;
+ }
+
+ private static async Task ExecuteAsync(AccountMergeLedgerTests.World world, string sql)
+ {
+ await using var db = world.Db();
+ await db.Database.ExecuteSqlRawAsync(sql);
+ }
+
+ // ---- commit atomicity ----
+
+ [PostgresFact]
+ public async Task A_commit_that_fails_midway_leaves_nothing_applied_and_the_retry_commits_once()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, survivor, VoteChoice.For);
+ await world.VoteAsync(motion, folded, VoteChoice.Against);
+ var merge = await world.MergeAsync(survivor, folded);
+ await ExecuteAsync(world, """
+ CREATE FUNCTION fail_merged() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN IF NEW."Status" = 'Merged' THEN RAISE EXCEPTION 'injected fault'; END IF; RETURN NEW; END $$;
+ CREATE TRIGGER fail_merged BEFORE UPDATE ON "Memberships" FOR EACH ROW EXECUTE FUNCTION fail_merged();
+ """);
+
+ var fault = await Assert.ThrowsAsync(() => world.CommitAsync(merge));
+ Assert.Contains("injected fault", Pg(fault).MessageText);
+
+ await using (var check = world.Db())
+ {
+ Assert.Equal(AccountMergeState.HeimdallMoved, (await check.AccountMerges.SingleAsync()).State);
+ Assert.Empty(check.AccountMergeEntries);
+ Assert.All(await check.Votes.IgnoreQueryFilters().ToListAsync(), v => Assert.Null(v.VoidedByMergeId));
+ Assert.Equal(MembershipStatus.Active, (await check.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).Status);
+ }
+
+ await ExecuteAsync(world, "DROP TRIGGER fail_merged ON \"Memberships\"");
+ Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State);
+ var journal = await world.JournalAsync(merge);
+ Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote));
+ Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(merge)).State); // a second commit is a no-op
+ Assert.Equal(journal.Count, (await world.JournalAsync(merge)).Count);
+ }
+
+ [PostgresFact]
+ public async Task The_journal_refuses_a_second_entry_with_the_same_merge_and_seq()
+ {
+ var world = await postgres.NewWorldAsync();
+ var merge = await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"));
+ await using var db = world.Db();
+ AccountMergeEntry Entry() => new() { MergeId = merge.Id, Seq = 1, Kind = AccountMergeEntryKind.Vote, Action = AccountMergeEntryAction.Voided, RecordId = Guid.NewGuid(), AtUtc = AccountMergeLedgerTests.T0 };
+ db.AccountMergeEntries.Add(Entry());
+ await db.SaveChangesAsync();
+ db.AccountMergeEntries.Add(Entry());
+
+ var error = await Assert.ThrowsAsync(() => db.SaveChangesAsync());
+
+ Assert.Equal(("23505", "IX_AccountMergeEntries_MergeId_Seq"), (Pg(error).SqlState, Pg(error).ConstraintName));
+ }
+
+ [PostgresFact]
+ public async Task Two_commits_of_the_same_merge_racing_apply_it_exactly_once()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, survivor, VoteChoice.For);
+ await world.VoteAsync(motion, folded, VoteChoice.Against);
+ var merge = await world.MergeAsync(survivor, folded);
+ var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world));
+
+ async Task TryCommit()
+ {
+ try
+ {
+ await committers.CommitAsync(merge);
+ return null;
+ }
+ catch (Exception error)
+ {
+ return error;
+ }
+ }
+
+ var results = await Task.WhenAll(Task.Run(TryCommit), Task.Run(TryCommit));
+
+ // The second commit waits on the folded account's exclusive lock, then finds the merge landed and returns its receipt.
+ Assert.All(results, e => Assert.Null(e));
+ var journal = await world.JournalAsync(merge);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote));
+ Assert.Single((await world.AllVotesAsync(motion)).Where(v => v.VoidedByMergeId == merge.Id));
+ }
+
+ [PostgresFact]
+ public async Task A_voided_vote_leaves_every_tally_on_a_real_database()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var moderator = await world.AccountAsync("mod", moderator: true);
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, survivor, VoteChoice.Against, 1m);
+ await world.VoteAsync(motion, folded, VoteChoice.For, 3m);
+
+ await world.CommitAsync(await world.MergeAsync(survivor, folded));
+
+ var item = await world.StateOfAsync(motion, moderator);
+ Assert.Equal((0m, 1m), (item.VotesFor, item.VotesAgainst));
+ Assert.Equal(MotionStatus.Failed, await world.CloseAsync(motion, moderator));
+ }
+
+ // ---- the sweeper against the saga ----
+
+ [PostgresFact]
+ public async Task The_sweep_does_not_overwrite_an_UndoRequested_written_after_it_read_the_merge()
+ {
+ var plain = await postgres.NewWorldAsync();
+ var merge = await plain.CommitAsync(await plain.MergeAsync(await plain.AccountAsync("survivor"), await plain.AccountAsync("folded")));
+ var sweeper = AccountMergeLedgerTests.World.OnPostgres(
+ ConnectionOf(plain), new BeforeFirstSave(() => plain.SetStateAsync(merge, AccountMergeState.UndoRequested)));
+
+ await using (var db = sweeper.Db())
+ {
+ Assert.Equal(0, await sweeper.Ledger(db).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default));
+ }
+
+ await using var read = plain.Db();
+ var row = await read.AccountMerges.SingleAsync();
+ Assert.Equal(AccountMergeState.UndoRequested, row.State);
+ Assert.Null(row.FinalizedUtc);
+ }
+
+ [PostgresFact]
+ public async Task An_UndoRequested_written_from_a_stale_Committed_read_cannot_overwrite_Final()
+ {
+ var world = await postgres.NewWorldAsync();
+ var merge = await world.CommitAsync(await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded")));
+ await using var saga = world.Db();
+ var stale = await saga.AccountMerges.SingleAsync(x => x.Id == merge.Id); // the saga read Committed
+
+ await using (var sweep = world.Db())
+ {
+ Assert.Equal(1, await world.Ledger(sweep).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default));
+ }
+
+ stale.State = AccountMergeState.UndoRequested;
+ await Assert.ThrowsAsync(() => saga.SaveChangesAsync());
+ await using var read = world.Db();
+ Assert.Equal(AccountMergeState.Final, (await read.AccountMerges.SingleAsync()).State);
+ }
+
+ [PostgresFact]
+ public async Task A_sweep_that_loses_one_merge_to_the_saga_still_finalizes_the_others()
+ {
+ var plain = await postgres.NewWorldAsync();
+ var survivor = await plain.AccountAsync("survivor");
+ await plain.CommitAsync(await plain.MergeAsync(survivor, await plain.AccountAsync("folded-a")));
+ await plain.CommitAsync(await plain.MergeAsync(survivor, await plain.AccountAsync("folded-b")));
+ var sweeper = AccountMergeLedgerTests.World.OnPostgres(
+ ConnectionOf(plain), new BeforeFirstSave(async () =>
+ {
+ // Whichever merge the sweep saves first, the saga takes one of the two before it does.
+ await using var rival = plain.Db();
+ var taken = await rival.AccountMerges.Where(x => x.State == AccountMergeState.Committed).OrderBy(x => x.Id).FirstAsync();
+ taken.State = AccountMergeState.UndoRequested;
+ await rival.SaveChangesAsync();
+ }));
+
+ await using (var db = sweeper.Db())
+ {
+ Assert.Equal(1, await sweeper.Ledger(db).FinalizeDueAsync(AccountMergeLedgerTests.T0.AddDays(8), default));
+ }
+
+ await using var read = plain.Db();
+ Assert.Equal([AccountMergeState.Final, AccountMergeState.UndoRequested], (await read.AccountMerges.ToListAsync()).Select(x => x.State).Order());
+ }
+
+ // ---- overlapping merges, refused by the database ----
+
+ [PostgresFact]
+ public async Task A_second_live_merge_folding_the_same_account_is_refused_and_a_finished_one_frees_it()
+ {
+ var world = await postgres.NewWorldAsync();
+ var s1 = await world.AccountAsync("acct-s1");
+ var s2 = await world.AccountAsync("acct-s2");
+ var folded = await world.AccountAsync("folded");
+
+ var second = await world.MergeAsync(s2, folded, AccountMergeState.Proposed); // proposals may coexist
+ var first = await world.MergeAsync(s1, folded, AccountMergeState.Confirmed);
+
+ var refused = await Assert.ThrowsAsync(() => world.SetStateAsync(second, AccountMergeState.Confirmed));
+ Assert.Equal(("23505", "UX_AccountMerges_FoldedUserAccountId_Live"), (Pg(refused).SqlState, Pg(refused).ConstraintName));
+ var inserted = await Assert.ThrowsAsync(() => world.MergeAsync(s2, folded, AccountMergeState.Final));
+ Assert.Equal("23505", Pg(inserted).SqlState);
+
+ await world.SetStateAsync(first, AccountMergeState.Undone);
+ await world.SetStateAsync(second, AccountMergeState.Confirmed); // the slot is free again
+ }
+
+ [PostgresTheory]
+ [InlineData(AccountMergeState.Confirmed, AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Final, AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.Committed, AccountMergeState.HeimdallMoved)]
+ public async Task A_chain_is_refused_in_either_arrival_order_and_the_same_survivor_twice_is_fine(AccountMergeState earlier, AccountMergeState later)
+ {
+ var world = await postgres.NewWorldAsync();
+ foreach (var survivorFirst in new[] { true, false })
+ {
+ var tag = survivorFirst ? "a" : "b";
+ var s = await world.AccountAsync("acct-s" + tag);
+ var f = await world.AccountAsync("acct-f" + tag);
+ var g = await world.AccountAsync("acct-g" + tag);
+ var other = await world.AccountAsync("other" + tag);
+
+ await world.MergeAsync(s, other, AccountMergeState.Confirmed); // one survivor may carry two folded accounts
+ await world.MergeAsync(s, f, earlier);
+ // f survives a live merge and folds into g, or s folds into g while it survives one: both are chains.
+ var chain = await Assert.ThrowsAsync(() => survivorFirst ? world.MergeAsync(f, g, later) : world.MergeAsync(g, s, later));
+ Assert.Equal("23P01", Pg(chain).SqlState);
+ }
+ }
+
+ [PostgresFact]
+ public async Task Two_transactions_racing_to_chain_the_same_account_cannot_both_commit()
+ {
+ var world = await postgres.NewWorldAsync();
+ var s = await world.AccountAsync("acct-s");
+ var f = await world.AccountAsync("acct-f");
+ var g = await world.AccountAsync("acct-g");
+ await using var first = world.Db();
+ await using var firstTransaction = await first.Database.BeginTransactionAsync();
+ first.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = s.Id, FoldedUserAccountId = f.Id, State = AccountMergeState.Confirmed, CreatedUtc = AccountMergeLedgerTests.T0 });
+ await first.SaveChangesAsync();
+
+ await using var second = world.Db();
+ await using var secondTransaction = await second.Database.BeginTransactionAsync();
+ second.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = f.Id, FoldedUserAccountId = g.Id, State = AccountMergeState.Confirmed, CreatedUtc = AccountMergeLedgerTests.T0 });
+ var racing = second.SaveChangesAsync();
+
+ await Task.Delay(1500);
+ Assert.False(racing.IsCompleted); // it waits on the first, which holds the lock on f
+ await firstTransaction.CommitAsync();
+
+ var refused = await Assert.ThrowsAsync(() => racing.WaitAsync(TimeSpan.FromSeconds(30)));
+ Assert.Equal("23P01", Pg(refused).SqlState);
+ }
+
+ // ---- rollback ----
+
+ [PostgresFact]
+ public async Task Reverting_the_migration_is_refused_while_any_merge_exists_even_one_that_voided_nothing_and_allowed_after()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ await world.CommitAsync(await world.MergeAsync(survivor, folded)); // moves and voids nothing: only the Merged membership remains
+
+ await using (var db = world.Db())
+ {
+ var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials"));
+ Assert.Contains("roll-forward only", Pg(error).MessageText);
+ // The acks migration reverts first (it holds only acks); the saga migration is the one that refuses.
+ Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last());
+ }
+
+ await ExecuteAsync(world, "DELETE FROM \"AccountMergeEntries\"; DELETE FROM \"AccountMerges\"");
+ await using var down = world.Db();
+ await down.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials");
+ Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
+ await down.GetService().MigrateAsync(); // and up again, trigger and index and all
+ Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await down.Database.GetAppliedMigrationsAsync()).Last());
+ }
+
+ // ---- restage and intake journal ----
+
+ [PostgresFact]
+ public async Task Two_merges_into_one_survivor_restaging_at_once_leave_one_current_patron_snapshot_and_the_loser_commits_on_retry()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var first = await world.AccountAsync("first");
+ var second = await world.AccountAsync("second");
+ await using (var db = world.Db())
+ {
+ foreach (var who in new[] { first, second })
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m,
+ SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0
+ });
+ }
+
+ await db.SaveChangesAsync();
+ }
+
+ var one = await world.MergeAsync(survivor, first);
+ var two = await world.MergeAsync(survivor, second);
+ var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new Rendezvous());
+
+ async Task TryCommit(AccountMerge merge)
+ {
+ try
+ {
+ await committers.CommitAsync(merge);
+ return null;
+ }
+ catch (Exception error)
+ {
+ return error;
+ }
+ }
+
+ var results = await Task.WhenAll(Task.Run(() => TryCommit(one)), Task.Run(() => TryCommit(two)));
+
+ Assert.Equal(1, results.Count(x => x is null));
+ Assert.All(results.OfType(), e => Assert.Contains(Chain(e), x => x is PostgresException { SqlState: "23505", ConstraintName: "UX_TierSnapshots_MembershipId_CurrentPatron" }));
+ var loser = results[0] is null ? two : one;
+ Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(loser)).State);
+ await using var read = world.Db();
+ var membership = await read.Memberships.Include(x => x.TierSnapshots).SingleAsync(x => x.UserAccountId == survivor.Id);
+ Assert.Single(membership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent);
+ Assert.All(await read.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId));
+ }
+
+ [PostgresFact]
+ public async Task A_patron_refresh_that_loses_the_restage_race_reads_the_winners_snapshot_and_derives_again()
+ {
+ var world = await postgres.NewWorldAsync();
+ var patron = await world.AccountAsync("patron");
+ await using (var db = world.Db())
+ {
+ db.PatronSupportEvents.Add(new PatronSupportEvent
+ {
+ UserAccountId = patron.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m,
+ SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0
+ });
+ await db.SaveChangesAsync();
+ }
+
+ var clock = world.Clock;
+ var rival = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world));
+ var loser = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
+ {
+ await using var rivalDb = rival.Db();
+ await new PatronageService(rivalDb, new AuditTrailService(rivalDb, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default);
+ }));
+
+ await using (var db = loser.Db())
+ {
+ var summary = await new PatronageService(db, new AuditTrailService(db, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default);
+ Assert.True(summary.VotingWeight > 0m);
+ }
+
+ await using var read = world.Db();
+ var snapshots = await read.TierSnapshots.Where(x => x.Kind == TierSnapshotKind.Patron).ToListAsync();
+ Assert.Single(snapshots, x => x.IsCurrent);
+ Assert.Equal(2, snapshots.Count); // the winner's, demoted by the retry, and the retry's own
+ }
+
+ [PostgresFact]
+ public async Task The_migration_keeps_only_the_newest_of_duplicate_current_patron_snapshots_before_it_builds_the_index()
+ {
+ var world = await postgres.NewWorldAsync();
+ var patron = await world.AccountAsync("patron");
+ await using var db = world.Db();
+ await db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials"); // the index does not exist yet
+ var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == patron.Id);
+ TierSnapshot Snapshot(string label, int minutes) => new()
+ {
+ MembershipId = membership.Id, Kind = TierSnapshotKind.Patron, Label = label, Weight = 1m, IsCurrent = true,
+ EffectiveFromUtc = AccountMergeLedgerTests.T0, CapturedAtUtc = AccountMergeLedgerTests.T0.AddMinutes(minutes)
+ };
+ db.TierSnapshots.AddRange(Snapshot("older", 0), Snapshot("newer", 5));
+ await db.SaveChangesAsync();
+
+ await db.GetService().MigrateAsync();
+
+ await using var read = world.Db();
+ Assert.Equal("newer", (await read.TierSnapshots.SingleAsync(x => x.IsCurrent)).Label);
+ Assert.Equal(2, await read.TierSnapshots.CountAsync());
+ }
+
+ [PostgresFact]
+ public async Task A_journalled_patron_intake_takes_the_next_seq_after_the_commits_entries_and_is_idempotent()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+ var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
+ var committed = (await world.JournalAsync(merge)).Count;
+ Assert.True(committed > 0);
+
+ var events = new[] { $"WH-{Guid.NewGuid():N}", $"WH-{Guid.NewGuid():N}" };
+ foreach (var id in events.Concat(events)) // each twice: the provider retries
+ {
+ await using var db = world.Db();
+ await new PatronageService(db, new AuditTrailService(db, world.Clock), world.Clock).RecordSupportEventAsync(
+ null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, id,
+ string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default);
+ }
+
+ var journal = await world.JournalAsync(merge);
+ Assert.Equal(committed + 2, journal.Count);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ }
+
+ [PostgresTheory]
+ [InlineData(AccountMergeState.Proposed)]
+ [InlineData(AccountMergeState.Confirmed)]
+ [InlineData(AccountMergeState.HeimdallMoved)]
+ [InlineData(AccountMergeState.Final)]
+ [InlineData(AccountMergeState.UndoRequested)]
+ [InlineData(AccountMergeState.HeimdallReversed)]
+ [InlineData(AccountMergeState.Undone)]
+ [InlineData(AccountMergeState.Failed)]
+ public async Task Reverting_the_migration_is_refused_for_a_merge_in_any_state(AccountMergeState state)
+ {
+ var world = await postgres.NewWorldAsync();
+ await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"), state);
+
+ await using var db = world.Db();
+ var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials"));
+ Assert.Contains("roll-forward only", Pg(error).MessageText);
+ }
+
+ // ---- the write gate ----
+
+ [PostgresFact]
+ public async Task A_vote_that_read_no_merge_saves_before_a_merge_can_freeze_the_account_and_the_commit_then_moves_it()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ var actor = await world.ActorAsync(folded.Id);
+ Task? freeze = null;
+ var blocked = false;
+ var voters = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
+ {
+ // The vote has read its standing (none) and is about to save: the freeze lands here and must wait for the save.
+ freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed));
+ await Task.Delay(1500);
+ blocked = !freeze.IsCompleted;
+ }));
+
+ await using (var db = voters.Db())
+ {
+ await voters.Motions(db).CastVoteAsync(actor, motion.Id, VoteChoice.For, null, default);
+ }
+
+ var merge = await freeze!.WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(blocked);
+ await world.SetStateAsync(merge, AccountMergeState.HeimdallMoved);
+ await world.CommitAsync(merge);
+
+ var votes = await world.AllVotesAsync(motion);
+ Assert.Equal(survivor.Id, Assert.Single(votes).UserAccountId); // the commit saw the vote and moved it: no second voice stays on the folded account
+ Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.Vote);
+ }
+
+ [PostgresFact]
+ public async Task A_patron_event_that_read_a_Frozen_account_saves_before_the_commit_reduces_and_the_commit_moves_it()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var merge = await world.MergeAsync(survivor, folded); // HeimdallMoved: the folded account is Frozen
+ Task? commit = null;
+ var blocked = false;
+ var recorders = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
+ {
+ commit = Task.Run(() => world.CommitAsync(merge)); // takes the folded account's exclusive lock before it reduces
+ await Task.Delay(1500);
+ blocked = !commit.IsCompleted;
+ }));
+
+ await using (var db = recorders.Db())
+ {
+ await new PatronageService(db, new AuditTrailService(db, recorders.Clock), recorders.Clock).RecordSupportEventAsync(
+ null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, "WH-frozen",
+ string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default);
+ }
+
+ await commit!.WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(blocked);
+ await using var read = world.Db();
+ Assert.Equal(survivor.Id, (await read.PatronSupportEvents.SingleAsync()).UserAccountId); // the reduction found the event and moved it
+ Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
+ }
+
+ [PostgresFact]
+ public async Task A_sealed_reveal_that_retries_on_a_conflict_keeps_its_lock_so_no_merge_freezes_the_account_between_attempts()
+ {
+ const string salt = "00112233445566778899aabbccddeeff";
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var other = await world.AccountAsync("other");
+ var moderator = await world.AccountAsync("moderator", moderator: true);
+ SealedBallotService Sealed(AccountMergeLedgerTests.World w, BifrostDbContext db) => new(db, new AuditTrailService(db, w.Clock), w.Clock);
+ SealedBallotDocument Doc(Guid motionId, string reason) => new(SealedBallotDocument.SchemaId, motionId, 1, "Ana", reason, salt);
+
+ await using var setup = world.Db();
+ var motionId = (await Sealed(world, setup).OpenAsync(await world.ActorAsync(moderator.Id),
+ new OpenSealedMotionCommand("Who", "Blind.", ["Ana", "Bo"], AccountMergeLedgerTests.T0.AddHours(1), AccountMergeLedgerTests.T0.AddHours(2)), default)).Id;
+ foreach (var (account, reason) in new[] { (folded, "mine"), (other, "theirs") })
+ {
+ await using var db = world.Db();
+ await Sealed(world, db).CommitAsync(await world.ActorAsync(account.Id), motionId, SealedBallotDocument.Commit(Doc(motionId, reason), account.Id), default);
+ }
+
+ Task? freeze = null;
+ var blocked = false;
+ var revealers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
+ {
+ // The first attempt has read its standing (none). A freeze starts and must wait; another member's reveal then lands first,
+ // so this attempt's save conflicts on RevealSeq and the reveal retries while the freeze still waits.
+ freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed));
+ await using var rival = world.Db();
+ world.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90);
+ await Sealed(world, rival).RevealAsync(await world.ActorAsync(other.Id), motionId, Doc(motionId, "theirs"), default);
+ await Task.Delay(1500);
+ blocked = !freeze.IsCompleted;
+ }));
+ revealers.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90);
+ var actor = await world.ActorAsync(folded.Id);
+
+ await using (var db = revealers.Db())
+ {
+ Assert.True((await Sealed(revealers, db).RevealAsync(actor, motionId, Doc(motionId, "mine"), default)).Revealed);
+ }
+
+ await freeze!.WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(blocked);
+ }
+
+ // ---- the saga: races the State token and the live-merge index carry ----
+
+ /// Holds the first save of each of two contexts until both have arrived: both have read, neither has written.
+ private sealed class FirstSaveRendezvous : SaveChangesInterceptor
+ {
+ private readonly Barrier _barrier = new(2);
+ private readonly HashSet _seen = [];
+
+ public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ bool first;
+ lock (_seen)
+ {
+ first = _seen.Add(eventData.Context!.ContextId.InstanceId);
+ }
+
+ if (first)
+ {
+ await Task.Run(() => _barrier.SignalAndWait(TimeSpan.FromSeconds(30)), cancellationToken);
+ }
+
+ return result;
+ }
+ }
+
+ /// The fake Heimdall's account model behind the real move client, one key ring for every saga built over it.
+ private sealed class Heimdall
+ {
+ private readonly EphemeralDataProtectionProvider _keys = new();
+ private readonly HeimdallIdentityMoveClient _mover;
+
+ public Heimdall(AccountMergeLedgerTests.World clockOwner)
+ {
+ Fake = new FakeHeimdall { RequiredAppSecret = HeimdallHost.AppSecret, Now = () => clockOwner.Clock.Now };
+ var options = new HeimdallOptions { BaseUrl = HeimdallShapes.Issuer, AppSecret = HeimdallHost.AppSecret };
+ var client = new HttpClient(Fake);
+ HeimdallAuthService.ConfigureClient(client, options);
+ _mover = new HeimdallIdentityMoveClient(client, Options.Create(options), NullLogger.Instance);
+ }
+
+ public FakeHeimdall Fake { get; }
+
+ public AccountMergeSaga Saga(AccountMergeLedgerTests.World world, BifrostDbContext db) =>
+ new(db, world.Ledger(db), _mover, _keys, new AuditTrailService(db, world.Clock), world.Clock, NullLogger.Instance);
+
+ /// A world account with one login at the fake Heimdall and a weak proof through it.
+ public MergeProof Proof(UserAccount account, string provider) =>
+ new(Fake.Moves.Issue(account.HeimdallAccountId, Fake.Moves.AddLogin(account.HeimdallAccountId, provider)), account.HeimdallAccountId, provider);
+ }
+
+ [PostgresFact]
+ public async Task Two_concurrent_advances_of_one_confirmed_merge_make_one_move_commit_once_and_journal_once()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var motion = await world.MotionAsync();
+ await world.VoteAsync(motion, folded, VoteChoice.For);
+ var heimdall = new Heimdall(world);
+ var survivorProof = heimdall.Proof(survivor, "twitch");
+ var foldedProof = heimdall.Proof(folded, "discord");
+ Guid mergeId;
+ await using (var db = world.Db())
+ {
+ var saga = heimdall.Saga(world, db);
+ var digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id);
+ mergeId = Assert.IsType(await saga.ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, survivorProof, [foldedProof]), default)).MergeId;
+ }
+
+ var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous());
+ async Task Advance()
+ {
+ await using var db = racers.Db();
+ return await heimdall.Saga(racers, db).AdvanceAsync(mergeId, default);
+ }
+
+ var both = await Task.WhenAll(Task.Run(Advance), Task.Run(Advance));
+
+ Assert.All(both, x => Assert.Equal(AccountMergeState.Committed, x.State));
+ Assert.Single(heimdall.Fake.Moves.Stored);
+ var journal = await world.JournalAsync(new AccountMerge { Id = mergeId });
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.Vote);
+ Assert.Equal(survivor.Id, Assert.Single(await world.AllVotesAsync(motion)).UserAccountId);
+ }
+
+ [PostgresFact]
+ public async Task Two_confirms_folding_the_same_account_leave_one_row_and_the_other_is_blocked_by_the_database()
+ {
+ var world = await postgres.NewWorldAsync();
+ var first = await world.AccountAsync("first");
+ var second = await world.AccountAsync("second");
+ var folded = await world.AccountAsync("folded");
+ var heimdall = new Heimdall(world);
+ var proofs = new Dictionary();
+ foreach (var survivor in new[] { first, second })
+ {
+ await using var db = world.Db();
+ proofs[survivor.Id] = (heimdall.Proof(survivor, "twitch"), (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id));
+ }
+
+ var foldedProof = heimdall.Proof(folded, "discord");
+ var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous());
+ async Task Confirm(UserAccount survivor)
+ {
+ await using var db = racers.Db();
+ return await heimdall.Saga(racers, db).ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, proofs[survivor.Id].Digest, proofs[survivor.Id].Survivor, [foldedProof]), default);
+ }
+
+ var results = await Task.WhenAll(Task.Run(() => Confirm(first)), Task.Run(() => Confirm(second)));
+
+ Assert.Single(results.OfType());
+ var blocked = Assert.Single(results.OfType());
+ Assert.Contains(AccountMergeSaga.MergeInFlight, blocked.Codes);
+ await using var check = world.Db();
+ Assert.Equal(1, await check.AccountMerges.CountAsync());
+ }
+
+ [PostgresFact]
+ public async Task Two_merges_cannot_share_a_Heimdall_move_id_or_a_reverse_move_id()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var one = await world.MergeAsync(survivor, await world.AccountAsync("one"), AccountMergeState.Confirmed);
+ var two = await world.MergeAsync(survivor, await world.AccountAsync("two"), AccountMergeState.Confirmed);
+
+ foreach (var column in new[] { "HeimdallMoveId", "HeimdallReverseMoveId" })
+ {
+ await ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"{column}\" = 'shared-0123456789abcdef' WHERE \"Id\" = '{one.Id}'");
+ var error = await Assert.ThrowsAnyAsync(() =>
+ ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"{column}\" = 'shared-0123456789abcdef' WHERE \"Id\" = '{two.Id}'"));
+ Assert.Equal("23505", Pg(error).SqlState);
+ }
+ }
+
+ [PostgresFact]
+ public async Task Confirm_holds_the_actors_write_lock_until_its_row_is_saved()
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var heimdall = new Heimdall(world);
+ var proof = heimdall.Proof(survivor, "twitch");
+ var foldedProof = heimdall.Proof(folded, "discord");
+ string digest;
+ await using (var db = world.Db())
+ {
+ digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id);
+ }
+
+ Task? exclusive = null;
+ var blocked = false;
+ var confirmers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
+ {
+ // A writer that needs the actor's exclusive lock (a commit freezing it) arrives while the confirm is about to save.
+ exclusive = Task.Run(async () =>
+ {
+ await using var connection = new NpgsqlConnection(ConnectionOf(world));
+ await connection.OpenAsync();
+ await using var transaction = await connection.BeginTransactionAsync();
+ await using var command = new NpgsqlCommand("SELECT pg_advisory_xact_lock(hashtextextended(@key, 0))", connection, transaction);
+ command.Parameters.AddWithValue("key", survivor.Id.ToString());
+ await command.ExecuteNonQueryAsync();
+ });
+ await Task.Delay(1500);
+ blocked = !exclusive.IsCompleted;
+ }));
+
+ await using (var db = confirmers.Db())
+ {
+ Assert.IsType(await heimdall.Saga(confirmers, db).ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, proof, [foldedProof]), default));
+ }
+
+ await exclusive!.WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(blocked);
+ }
+
+ /// A Confirmed merge with sealed proofs, stopped on the given outcome, and the operator who will settle it.
+ private async Task<(AccountMergeLedgerTests.World World, Heimdall Heimdall, Guid Id, string MoveId, Guid Operator)> StuckConfirmedAsync(string outcome)
+ {
+ var world = await postgres.NewWorldAsync();
+ var survivor = await world.AccountAsync("survivor");
+ var folded = await world.AccountAsync("folded");
+ var operatorId = (await world.AccountAsync("operator")).Id;
+ var heimdall = new Heimdall(world);
+ Guid id;
+ await using (var db = world.Db())
+ {
+ var digest = (await world.Ledger(db).PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id);
+ id = Assert.IsType(await heimdall.Saga(world, db).ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, heimdall.Proof(survivor, "twitch"), [heimdall.Proof(folded, "discord")]), default)).MergeId;
+ }
+
+ await ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"State\" = 'Confirmed', \"LastOutcome\" = '{outcome}' WHERE \"Id\" = '{id}'");
+ await using var read = world.Db();
+ var merge = await read.AccountMerges.AsNoTracking().SingleAsync();
+ Assert.NotNull(merge.SealedProofs);
+ return (world, heimdall, id, merge.HeimdallMoveId!, operatorId);
+ }
+
+ [PostgresFact]
+ public async Task A_settle_that_loses_to_a_rival_state_write_inside_its_save_window_writes_nothing_and_no_audit_row()
+ {
+ var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("move_id_conflict");
+ var settler = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(() =>
+ ExecuteAsync(world, $"UPDATE \"AccountMerges\" SET \"State\" = 'HeimdallMoved' WHERE \"Id\" = '{id}'")));
+ await using (var db = settler.Db())
+ {
+ Assert.IsType(await heimdall.Saga(settler, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default));
+ }
+
+ await using var read = world.Db();
+ var merge = await read.AccountMerges.AsNoTracking().SingleAsync();
+ Assert.Equal(AccountMergeState.HeimdallMoved, merge.State);
+ Assert.NotNull(merge.SealedProofs);
+ Assert.Equal("move_id_conflict", merge.LastOutcome);
+ Assert.Equal(0, await read.AuditEvents.CountAsync());
+ }
+
+ [PostgresFact]
+ public async Task A_settle_whose_audit_insert_fails_rolls_the_transition_back()
+ {
+ var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("receipt_mismatch");
+ await ExecuteAsync(world, """
+ CREATE FUNCTION fail_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected audit fault'; END $$;
+ CREATE TRIGGER fail_audit BEFORE INSERT ON "AuditEvents" FOR EACH ROW EXECUTE FUNCTION fail_audit();
+ """);
+ await using (var db = world.Db())
+ {
+ await Assert.ThrowsAsync(() => heimdall.Saga(world, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default));
+ }
+
+ await using var read = world.Db();
+ var merge = await read.AccountMerges.AsNoTracking().SingleAsync();
+ Assert.Equal(AccountMergeState.Confirmed, merge.State);
+ Assert.NotNull(merge.SealedProofs);
+ Assert.Equal("receipt_mismatch", merge.LastOutcome);
+ Assert.Equal(0, await read.AuditEvents.CountAsync());
+ }
+
+ [PostgresFact]
+ public async Task Two_concurrent_settles_of_one_stuck_merge_settle_once_lose_once_and_audit_once()
+ {
+ var (world, heimdall, id, moveId, operatorId) = await StuckConfirmedAsync("proofs_unreadable");
+ var racers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new FirstSaveRendezvous());
+ async Task Settle()
+ {
+ await using var db = racers.Db();
+ return await heimdall.Saga(racers, db).SettleStuckAsync(id, SettleChoice.FailForward, moveId, operatorId, default);
+ }
+
+ var both = await Task.WhenAll(Task.Run(Settle), Task.Run(Settle));
+
+ Assert.Single(both.OfType());
+ Assert.Single(both.OfType());
+ await using var read = world.Db();
+ Assert.Equal(1, await read.AuditEvents.CountAsync());
+ Assert.Equal(AccountMergeState.Failed, (await read.AccountMerges.AsNoTracking().SingleAsync()).State);
+ }
+
+ [PostgresFact]
+ public async Task The_saga_migration_adds_and_drops_its_columns_and_keys_and_its_Down_is_refused_while_any_merge_exists()
+ {
+ var world = await postgres.NewWorldAsync();
+ await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"), AccountMergeState.Confirmed);
+ await using (var db = world.Db())
+ {
+ var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261114120000_AddAccountMerges"));
+ Assert.Contains("AddAccountMergeSaga cannot be reverted", Pg(error).MessageText);
+ // The acks migration reverts first (it holds only acks); the saga migration is the one that refuses.
+ Assert.Equal("20261114130000_AddAccountMergeSaga", (await db.Database.GetAppliedMigrationsAsync()).Last());
+ }
+
+ await ExecuteAsync(world, "DELETE FROM \"AccountMerges\"");
+ await using var down = world.Db();
+ await down.GetService().MigrateAsync("20261114120000_AddAccountMerges");
+ Assert.Equal(0, await ScalarAsync(world, "SELECT count(*) FROM information_schema.columns WHERE table_name = 'AccountMerges' AND column_name IN ('HeimdallMoveId','SealedProofs','Attempts')"));
+ Assert.Equal(0, await ScalarAsync(world, "SELECT count(*) FROM pg_indexes WHERE tablename = 'AccountMerges' AND indexname LIKE 'IX_AccountMerges_Heimdall%'"));
+ await down.GetService().MigrateAsync();
+ Assert.Equal(3, await ScalarAsync(world, "SELECT count(*) FROM information_schema.columns WHERE table_name = 'AccountMerges' AND column_name IN ('HeimdallMoveId','SealedProofs','Attempts')"));
+ Assert.Equal(2, await ScalarAsync(world, "SELECT count(*) FROM pg_indexes WHERE tablename = 'AccountMerges' AND indexname LIKE 'IX_AccountMerges_Heimdall%'"));
+ }
+
+ private static async Task ScalarAsync(AccountMergeLedgerTests.World world, string sql)
+ {
+ await using var connection = new NpgsqlConnection(ConnectionOf(world));
+ await connection.OpenAsync();
+ await using var command = new NpgsqlCommand(sql, connection);
+ return (long)(await command.ExecuteScalarAsync())!;
+ }
+}
diff --git a/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs
new file mode 100644
index 0000000..0e73216
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeSagaTests.cs
@@ -0,0 +1,732 @@
+using System.Net;
+using System.Text.Json;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Tests.Support;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Bifrost.Web.Tests;
+
+///
+/// The merge saga from its consumers' side: a request scope of the real host (DI, the move client's HttpClient, Data Protection, the shared
+/// TestClock) driving Confirm, Advance and RequestUndo against the fake Heimdall's account model (Heimdall 4fe367a's contract). Every
+/// operation takes a fresh scope, as a request or a sweeper tick would, so what survives is only what was saved.
+///
+public sealed class AccountMergeSagaTests
+{
+ private const string Passkey = "bifrost-passkey";
+
+ internal sealed record Party(Guid Id, string HeimdallId, IReadOnlyDictionary Logins);
+
+ /// A host plus the helpers every test needs: accounts with logins at the fake Heimdall, proofs, a scope per operation.
+ internal sealed class Rig(bool realSessions = false, bool accountMerge = false, string? chatNoticesToken = null) : IDisposable
+ {
+ public HeimdallHost Host { get; } = new(realSessions: realSessions, accountMerge: accountMerge, chatNoticesToken: chatNoticesToken);
+
+ public FakeMoves Moves => Host.Heimdall.Moves;
+
+ public TestClock Clock => Host.Clock;
+
+ public void Dispose() => Host.Dispose();
+
+ public async Task AccountAsync(string name, params string[] providers)
+ {
+ var heimdallId = HeimdallShapes.NewAccountId();
+ var logins = providers.ToDictionary(x => x, x => Moves.AddLogin(heimdallId, x));
+ using var scope = Host.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var account = new UserAccount
+ {
+ DisplayName = name, BifrostIdentity = name, NormalizedBifrostIdentity = BifrostIdentityService.NormalizeIdentity(name),
+ HeimdallAccountId = heimdallId, CreatedAtUtc = Clock.Now, LastSeenAtUtc = Clock.Now,
+ MemberProfile = new MemberProfile { Nickname = name, Headline = "seed", UpdatedAtUtc = Clock.Now }
+ };
+ account.Membership = new Membership { UserAccountId = account.Id, Status = MembershipStatus.Active };
+ db.UserAccounts.Add(account);
+ await db.SaveChangesAsync();
+ return new Party(account.Id, heimdallId, logins);
+ }
+
+ /// A fresh sign-in through the login of : a weak proof of that login only.
+ public MergeProof Weak(Party who, string provider) => new(Moves.Issue(who.HeimdallId, who.Logins[provider]), who.HeimdallId, provider);
+
+ /// A fresh sign-in of through a login that came from (a login the merge moved to it).
+ public MergeProof Moved(Party holder, Party origin, string provider) => new(Moves.Issue(holder.HeimdallId, origin.Logins[provider]), holder.HeimdallId, provider);
+
+ /// A passkey assertion: a strong proof that speaks for the whole account.
+ public MergeProof Strong(Party who) => new(Moves.Issue(who.HeimdallId, stepUpMethod: Passkey), who.HeimdallId, "passkey");
+
+ public async Task InScopeAsync(Func> work)
+ {
+ using var scope = Host.Services.CreateScope();
+ return await work(scope.ServiceProvider);
+ }
+
+ public async Task DigestAsync(Party survivor, Party folded) =>
+ await InScopeAsync(async sp => (await sp.GetRequiredService().PlanAsync(survivor.Id, folded.Id, default)).Digest(survivor.Id, folded.Id));
+
+ public async Task ConfirmAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs)
+ {
+ var digest = await DigestAsync(survivor, folded);
+ return await InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, digest, survivorProof, foldedProofs), default));
+ }
+
+ public async Task ConfirmedAsync(Party survivor, Party folded, MergeProof survivorProof, params MergeProof[] foldedProofs) =>
+ Assert.IsType(await ConfirmAsync(survivor, folded, survivorProof, foldedProofs)).MergeId;
+
+ public Task AdvanceAsync(Guid id) => InScopeAsync(sp => sp.GetRequiredService().AdvanceAsync(id, default));
+
+ public Task AdvanceDueAsync() => InScopeAsync(sp => sp.GetRequiredService().AdvanceDueAsync(Clock.Now, default));
+
+ public Task MergeAsync(Guid id) =>
+ InScopeAsync(sp => sp.GetRequiredService().AccountMerges.AsNoTracking().SingleAsync(x => x.Id == id));
+
+ public Task> JournalAsync(Guid id) =>
+ InScopeAsync(sp => sp.GetRequiredService().AccountMergeEntries.Where(x => x.MergeId == id).ToListAsync());
+
+ public Task StandingAsync(Party who) =>
+ InScopeAsync(sp => sp.GetRequiredService().StandingAsync(who.Id, default));
+
+ public Task MergeCountAsync() => InScopeAsync(sp => sp.GetRequiredService().AccountMerges.CountAsync());
+
+ public async Task MotionAsync(Party author)
+ {
+ using var scope = Host.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var motion = new Motion
+ {
+ CreatedByUserAccountId = author.Id, Title = "m", Status = MotionStatus.Open, Kind = MotionKind.Standard, OpensAtUtc = Clock.Now,
+ ClosesAtUtc = Clock.Now.AddDays(3), CreatedAtUtc = Clock.Now, ApprovalThreshold = 0.5m
+ };
+ db.Motions.Add(motion);
+ await db.SaveChangesAsync();
+ return motion;
+ }
+
+ public async Task VoteAsync(Motion motion, Party who, VoteChoice choice)
+ {
+ using var scope = Host.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.Votes.Add(new Vote { MotionId = motion.Id, UserAccountId = who.Id, Choice = choice, Weight = 1m, CastAtUtc = Clock.Now.AddHours(1) });
+ await db.SaveChangesAsync();
+ }
+
+ public Task SeenMoveIdsAsync() =>
+ Task.FromResult(Moves.Requests.Select(x => JsonDocument.Parse(x.Body).RootElement.GetProperty("moveId").GetString()!).ToArray());
+ }
+
+ // ---- the happy path and the stored move id ----
+
+ [Fact]
+ public async Task Two_weak_folded_proofs_and_a_survivor_proof_confirm_and_advance_to_committed_with_a_seven_day_grace_and_one_stored_move()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord", "patreon");
+
+ var digest = await rig.DigestAsync(survivor, folded);
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"), rig.Weak(folded, "patreon"));
+ var confirmed = await rig.MergeAsync(id);
+ Assert.Equal(AccountMergeState.Confirmed, confirmed.State);
+ Assert.Equal(survivor.Id, confirmed.ConfirmedByUserAccountId);
+ Assert.Equal(rig.Clock.Now, confirmed.ConfirmedUtc);
+ Assert.Equal("twitch", confirmed.SurvivorProofProvider);
+ Assert.Equal("discord,patreon", confirmed.FoldedProofProviders);
+ Assert.Equal(digest, confirmed.PreviewDigest);
+ Assert.NotNull(confirmed.SealedProofs);
+ Assert.Matches("^[0-9a-f]{32}$", confirmed.HeimdallMoveId!);
+ Assert.Empty(rig.Moves.Requests); // confirm calls no Heimdall
+ Assert.IsType(await rig.StandingAsync(folded));
+
+ var done = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Committed, done.State);
+ Assert.Equal(done.CommittedUtc + AccountMergeLedger.Grace, done.GraceEndsUtc);
+ var stored = Assert.Single(rig.Moves.Stored);
+ Assert.Equal(confirmed.HeimdallMoveId, stored.MoveId);
+ var final = await rig.MergeAsync(id);
+ Assert.Null(final.SealedProofs);
+ Assert.Equal("weak", final.ProofFromTier);
+ Assert.Equal("weak", final.ProofToTier);
+ Assert.Equal(folded.Logins.Values.Order(), JsonSerializer.Deserialize(final.MovedIdentityIds!)!.Order());
+ Assert.IsType(await rig.StandingAsync(folded));
+ Assert.Equal(["twitch", "discord", "patreon"], rig.Moves.Logins[survivor.HeimdallId].Select(x => x.Provider));
+ }
+
+ [Fact]
+ public async Task A_vote_on_the_same_open_motion_from_both_accounts_counts_only_the_survivors_after_the_saga_lands()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var motion = await rig.MotionAsync(survivor);
+ await rig.VoteAsync(motion, survivor, VoteChoice.For);
+ await rig.VoteAsync(motion, folded, VoteChoice.Against);
+
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ await rig.AdvanceAsync(id);
+
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ Assert.Equal(survivor.Id, (await db.Votes.SingleAsync(x => x.MotionId == motion.Id)).UserAccountId);
+ var all = await db.Votes.IgnoreQueryFilters().Where(x => x.MotionId == motion.Id).ToListAsync();
+ Assert.Equal(id, Assert.Single(all, x => x.UserAccountId == folded.Id).VoidedByMergeId);
+ return 0;
+ });
+ }
+
+ [Fact]
+ public async Task Heimdall_sees_the_move_id_stored_on_the_row_and_it_is_not_derived_from_the_merge_id()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ Assert.NotEqual(id.ToString("N"), (await rig.MergeAsync(id)).HeimdallMoveId);
+ const string overwritten = "overwritten0123456789abcdef0123456789";
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ (await db.AccountMerges.SingleAsync(x => x.Id == id)).HeimdallMoveId = overwritten;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ await rig.AdvanceAsync(id);
+
+ Assert.Equal(overwritten, Assert.Single(rig.Moves.Stored).MoveId);
+ }
+
+ // ---- crashes and lost answers ----
+
+ [Fact]
+ public async Task A_lost_answer_leaves_the_merge_confirmed_and_a_fresh_scope_after_the_proofs_expired_settles_it_by_replay()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ rig.Moves.MoveApplyThenFail = HttpStatusCode.InternalServerError;
+
+ var lost = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Confirmed, lost.State);
+ Assert.Equal(1, lost.Attempts);
+ Assert.Equal(rig.Clock.Now + TimeSpan.FromSeconds(15), lost.NextAttemptUtc);
+ Assert.Equal("HTTP 500", lost.LastOutcome);
+ Assert.Single(rig.Moves.Stored);
+ rig.Moves.MoveApplyThenFail = null;
+ rig.Clock.Advance(TimeSpan.FromSeconds(601)); // every proof is stale and the bearers expired by now; Heimdall answers a replay first
+
+ Assert.Equal(1, await rig.AdvanceDueAsync());
+
+ Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State);
+ Assert.Single(rig.Moves.Stored);
+ Assert.Equal(2, (await rig.SeenMoveIdsAsync()).Length);
+ }
+
+ [Fact]
+ public async Task A_crash_on_the_save_that_writes_HeimdallMoved_is_resumed_with_the_same_move_id_and_one_stored_move()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ rig.Host.Fault.When = db => db.ChangeTracker.Entries().Any(x => x.Entity.State == AccountMergeState.HeimdallMoved);
+
+ await Assert.ThrowsAsync(() => rig.AdvanceAsync(id));
+ rig.Host.Fault.When = null;
+ Assert.Equal(AccountMergeState.Confirmed, (await rig.MergeAsync(id)).State);
+ Assert.NotNull((await rig.MergeAsync(id)).SealedProofs);
+
+ Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State);
+
+ var seen = await rig.SeenMoveIdsAsync();
+ Assert.Equal(2, seen.Length);
+ Assert.Single(seen.Distinct());
+ Assert.Single(rig.Moves.Stored);
+ Assert.Equal(seen[0], (await rig.MergeAsync(id)).HeimdallMoveId);
+ }
+
+ [Fact]
+ public async Task A_crash_on_the_Committed_save_leaves_HeimdallMoved_and_the_next_advance_commits_once_without_calling_Heimdall_again()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var motion = await rig.MotionAsync(survivor);
+ await rig.VoteAsync(motion, folded, VoteChoice.For);
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ rig.Host.Fault.When = db => db.ChangeTracker.Entries().Any(x => x.Entity.State == AccountMergeState.Committed);
+
+ await Assert.ThrowsAsync(() => rig.AdvanceAsync(id));
+ rig.Host.Fault.When = null;
+ var moved = await rig.MergeAsync(id);
+ Assert.Equal(AccountMergeState.HeimdallMoved, moved.State);
+ Assert.Null(moved.SealedProofs);
+ Assert.Empty(await rig.JournalAsync(id));
+
+ Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State);
+ Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State);
+
+ Assert.Single(rig.Moves.Requests);
+ var journal = await rig.JournalAsync(id);
+ Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
+ Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.Vote);
+ }
+
+ [Fact]
+ public async Task The_sweepers_own_loop_resumes_a_confirmed_merge_after_a_restart_and_finalizes_it_after_the_grace()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+
+ await RunOneSweepAsync(rig);
+ Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State);
+
+ rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1));
+ await RunOneSweepAsync(rig);
+ Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State);
+ }
+
+ /// Starts the production sweeper (its first pass runs at once, before its 30 s timer) and stops it once the pass is over.
+ private static async Task RunOneSweepAsync(Rig rig)
+ {
+ var sweeper = new AccountMergeSweeper(rig.Host.Services.GetRequiredService(), rig.Clock, NullLogger.Instance);
+ await sweeper.StartAsync(default);
+ var before = rig.Clock.Now;
+ var deadline = DateTime.UtcNow.AddSeconds(20);
+ while (DateTime.UtcNow < deadline && sweeper.ExecuteTask is { IsCompleted: false } && await rig.InScopeAsync(async sp =>
+ await sp.GetRequiredService().AccountMerges.AnyAsync(x =>
+ x.State == AccountMergeState.Confirmed || x.State == AccountMergeState.HeimdallMoved || (x.State == AccountMergeState.Committed && x.GraceEndsUtc <= before))))
+ {
+ await Task.Delay(50);
+ }
+
+ await sweeper.StopAsync(default);
+ }
+
+ // ---- refusals ----
+
+ [Theory]
+ [InlineData("proof_stale")]
+ [InlineData("identity_not_proved")]
+ [InlineData("provider_conflict")]
+ [InlineData("already_moved")]
+ public async Task A_coded_refusal_fails_the_merge_wipes_the_proofs_and_changes_nothing_in_Bifrost(string code)
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", code == "provider_conflict" ? ["discord"] : ["twitch"]);
+ var folded = await rig.AccountAsync("folded", "discord", "patreon");
+ var motion = await rig.MotionAsync(survivor);
+ await rig.VoteAsync(motion, folded, VoteChoice.For);
+ MergeProof[] foldedProofs = code == "identity_not_proved"
+ ? [rig.Weak(folded, "discord")] // the patreon login is not proved: no partial move
+ : [rig.Weak(folded, "discord"), rig.Weak(folded, "patreon")];
+ var survivorProof = rig.Weak(survivor, code == "provider_conflict" ? "discord" : "twitch");
+ if (code == "already_moved")
+ {
+ // Heimdall already moved the folded account elsewhere; Bifrost's merge does not know.
+ var elsewhere = await rig.AccountAsync("elsewhere", "twitch2");
+ var move = new HeimdallMoveRequest("preexisting-move-0000", [rig.Strong(folded).AccessToken], rig.Weak(elsewhere, "twitch2").AccessToken);
+ Assert.IsType(await rig.InScopeAsync(sp => sp.GetRequiredService().MoveAsync(move, default)));
+ foldedProofs = [rig.Strong(folded)];
+ }
+
+ var id = await rig.ConfirmedAsync(survivor, folded, survivorProof, foldedProofs);
+ if (code == "proof_stale")
+ {
+ rig.Clock.Advance(TimeSpan.FromSeconds(400));
+ }
+
+ var failed = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Failed, failed.State);
+ Assert.Equal(code, failed.FailureCode);
+ Assert.Equal(rig.Clock.Now, failed.FailedUtc);
+ var stored = await rig.MergeAsync(id);
+ Assert.Null(stored.SealedProofs);
+ Assert.Empty(await rig.JournalAsync(id));
+ Assert.Null(await rig.StandingAsync(folded));
+ await rig.InScopeAsync(async sp =>
+ {
+ var vote = await sp.GetRequiredService().Votes.SingleAsync();
+ Assert.Equal(folded.Id, vote.UserAccountId);
+ return 0;
+ });
+ Assert.DoesNotContain(rig.Moves.Stored, x => x.MoveId == stored.HeimdallMoveId);
+ }
+
+ // ---- confirm's consent checks ----
+
+ [Fact]
+ public async Task Confirm_refuses_a_third_party_a_changed_plan_a_proof_of_another_account_and_a_blocked_pair_and_writes_no_row()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var stranger = await rig.AccountAsync("stranger", "github");
+ var digest = await rig.DigestAsync(survivor, folded);
+ var good = rig.Weak(survivor, "twitch");
+ var foldedProof = rig.Weak(folded, "discord");
+
+ Task Confirm(Guid actor, string digestSeen, MergeProof survivorProof, params MergeProof[] proofs) =>
+ rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(
+ new ConfirmMergeRequest(actor, survivor.Id, folded.Id, digestSeen, survivorProof, proofs), default));
+
+ Assert.IsType(await Confirm(stranger.Id, digest, good, foldedProof));
+ Assert.IsType(await Confirm(survivor.Id, digest, rig.Weak(stranger, "github"), foldedProof));
+ Assert.IsType(await Confirm(survivor.Id, digest, good, rig.Weak(survivor, "twitch")));
+ var motion = await rig.MotionAsync(survivor);
+ await rig.VoteAsync(motion, folded, VoteChoice.For); // the plan the member saw is no longer the plan
+ Assert.IsType(await Confirm(survivor.Id, digest, good, foldedProof));
+ Assert.Equal(0, await rig.MergeCountAsync());
+
+ var blocked = Assert.IsType(await rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(
+ new ConfirmMergeRequest(survivor.Id, survivor.Id, survivor.Id, "x", good, [good]), default)));
+ Assert.Contains("same_account", blocked.Codes);
+ Assert.Equal(0, await rig.MergeCountAsync());
+
+ // a second confirm of the same fold, after the first
+ var fresh = await rig.DigestAsync(survivor, folded);
+ Assert.IsType(await Confirm(survivor.Id, fresh, good, foldedProof));
+ var second = Assert.IsType(await Confirm(survivor.Id, fresh, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord")));
+ Assert.Contains(AccountMergeSaga.MergeInFlight, second.Codes);
+ Assert.Equal(1, await rig.MergeCountAsync());
+ }
+
+ [Fact]
+ public async Task A_malformed_confirm_throws_before_any_row_and_neither_the_message_nor_the_proof_text_carry_a_token()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ const string canary = "CANARY-bearer-9f3a";
+ var proof = new MergeProof(canary, folded.HeimdallId, "discord");
+ Assert.DoesNotContain(canary, proof.ToString());
+ Assert.DoesNotContain(folded.HeimdallId, proof.ToString());
+ var request = new ConfirmMergeRequest(survivor.Id, survivor.Id, folded.Id, "d", new MergeProof(canary, survivor.HeimdallId, "twitch"), [proof]);
+ Assert.DoesNotContain(canary, request.ToString());
+
+ var nine = Enumerable.Repeat(proof, 9).ToList();
+ var tooMany = await Assert.ThrowsAsync(() =>
+ rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(request with { FoldedProofs = nine }, default)));
+ var tooLong = await Assert.ThrowsAsync(() =>
+ rig.InScopeAsync(sp => sp.GetRequiredService().ConfirmAsync(
+ request with { FoldedProofs = [proof with { AccessToken = canary + new string('x', HeimdallIdentityMoveClient.MaxProofLength) }] }, default)));
+
+ Assert.DoesNotContain(canary, tooMany.ToString());
+ Assert.DoesNotContain(canary, tooLong.ToString());
+ Assert.Equal(0, await rig.MergeCountAsync());
+ }
+
+ // ---- sealing ----
+
+ [Fact]
+ public async Task Sealed_proofs_never_hold_a_bearer_in_the_clear_are_wiped_at_each_final_answer_and_no_log_carries_a_bearer_or_an_account()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var survivorProof = rig.Weak(survivor, "twitch");
+ var foldedProof = rig.Weak(folded, "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, survivorProof, foldedProof);
+ var sealedText = (await rig.MergeAsync(id)).SealedProofs!;
+ Assert.DoesNotContain(survivorProof.AccessToken, sealedText);
+ Assert.DoesNotContain(foldedProof.AccessToken, sealedText);
+ Assert.DoesNotContain("bearer", sealedText);
+
+ await rig.AdvanceAsync(id);
+ Assert.Null((await rig.MergeAsync(id)).SealedProofs);
+
+ var undoProof = rig.Moved(survivor, folded, "discord"); // the moved login now lives on the survivor
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, undoProof));
+ var requested = (await rig.MergeAsync(id)).SealedProofs!;
+ Assert.DoesNotContain(undoProof.AccessToken, requested);
+ await rig.AdvanceAsync(id);
+ Assert.Null((await rig.MergeAsync(id)).SealedProofs);
+
+ var log = string.Join('\n', rig.Host.Logs.Lines);
+ foreach (var secret in new[] { survivorProof.AccessToken, foldedProof.AccessToken, undoProof.AccessToken, survivor.HeimdallId, folded.HeimdallId }
+ .Concat(folded.Logins.Values).Concat(survivor.Logins.Values))
+ {
+ Assert.DoesNotContain(secret, log);
+ }
+
+ Assert.Contains(id.ToString(), log);
+ }
+
+ private static Task RequestUndoAsync(Rig rig, Guid id, Party actor, params MergeProof[] proofs) =>
+ rig.InScopeAsync(sp => sp.GetRequiredService().RequestUndoAsync(id, actor.Id, proofs, default));
+
+ [Fact]
+ public async Task Unreadable_sealed_proofs_change_no_state_and_retry_in_an_hour_and_the_error_log_names_only_the_merge()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ (await db.AccountMerges.SingleAsync(x => x.Id == id)).SealedProofs = "CfDJ8-not-a-protected-payload";
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ var stuck = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Confirmed, stuck.State);
+ Assert.Equal(AccountMergeSaga.ProofsUnreadable, stuck.LastOutcome);
+ Assert.Equal(rig.Clock.Now + TimeSpan.FromHours(1), stuck.NextAttemptUtc);
+ Assert.Empty(rig.Moves.Requests);
+ Assert.Contains(rig.Host.Logs.Lines, x => x.Contains(id.ToString()) && x.Contains("unreadable"));
+ Assert.Equal(0, await rig.AdvanceDueAsync()); // not due for an hour
+ }
+
+ [Fact]
+ public async Task A_receipt_for_another_account_is_recorded_wipes_the_proofs_and_is_never_retried()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ (await db.UserAccounts.SingleAsync(x => x.Id == survivor.Id)).HeimdallAccountId = HeimdallShapes.NewAccountId(); // Bifrost's own link drifted
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ var stuck = await rig.AdvanceAsync(id);
+ var again = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Confirmed, stuck.State);
+ Assert.Equal(AccountMergeSaga.ReceiptMismatch, stuck.LastOutcome);
+ // The answer stays what Heimdall gave: a later sweep does not turn it into an hourly "proofs unreadable" retry.
+ Assert.Equal(AccountMergeSaga.ReceiptMismatch, again.LastOutcome);
+ Assert.Null(again.NextAttemptUtc);
+ Assert.Null((await rig.MergeAsync(id)).SealedProofs);
+ Assert.Single(rig.Moves.Requests);
+ Assert.IsType(await rig.StandingAsync(folded));
+ }
+
+ // ---- Heimdall down ----
+
+ [Fact]
+ public async Task While_Heimdall_is_down_the_merge_stays_confirmed_and_the_folded_account_frozen_then_commits_when_it_answers()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Strong(survivor), rig.Strong(folded)); // strong proofs outlive the outage below
+ rig.Moves.MoveDown = new HttpRequestException("down");
+
+ Assert.Equal(1, await rig.AdvanceDueAsync());
+ Assert.Equal(0, await rig.AdvanceDueAsync()); // backed off 15 s
+ rig.Clock.Advance(TimeSpan.FromSeconds(16));
+ Assert.Equal(1, await rig.AdvanceDueAsync());
+ rig.Clock.Advance(TimeSpan.FromSeconds(61));
+ Assert.Equal(1, await rig.AdvanceDueAsync());
+
+ var down = await rig.MergeAsync(id);
+ Assert.Equal(AccountMergeState.Confirmed, down.State);
+ Assert.Equal(3, down.Attempts);
+ Assert.Equal(rig.Clock.Now + TimeSpan.FromMinutes(5), down.NextAttemptUtc);
+ Assert.IsType(await rig.StandingAsync(folded));
+ Assert.Empty(rig.Moves.Stored);
+
+ rig.Moves.MoveDown = null;
+ rig.Clock.Advance(TimeSpan.FromMinutes(5));
+ Assert.Equal(1, await rig.AdvanceDueAsync());
+
+ Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State);
+ }
+
+ // ---- undo ----
+
+ [Fact]
+ public async Task Undo_with_survivor_proofs_of_the_moved_logins_reverses_the_move_and_ends_Undone()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord", "patreon");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"), rig.Weak(folded, "patreon"));
+ await rig.AdvanceAsync(id);
+ var forward = (await rig.MergeAsync(id)).HeimdallMoveId;
+
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Moved(survivor, folded, "discord"), rig.Moved(survivor, folded, "patreon")));
+ var requested = await rig.MergeAsync(id);
+ Assert.Equal(AccountMergeState.UndoRequested, requested.State);
+ Assert.Matches("^[0-9a-f]{32}$", requested.HeimdallReverseMoveId!);
+ Assert.NotEqual(forward, requested.HeimdallReverseMoveId);
+ Assert.IsType(await rig.StandingAsync(folded));
+
+ var done = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Undone, done.State);
+ Assert.NotNull((await rig.MergeAsync(id)).ReversedUtc);
+ Assert.Equal(2, rig.Moves.Stored.Count);
+ var reversal = Assert.Single(rig.Moves.Stored, x => x.ReversesMoveId is not null);
+ Assert.Equal(forward, reversal.ReversesMoveId);
+ Assert.Equal(requested.HeimdallReverseMoveId, reversal.MoveId);
+ Assert.Equal(["discord", "patreon"], rig.Moves.Logins[folded.HeimdallId].Select(x => x.Provider).Order());
+ Assert.Null(await rig.StandingAsync(folded));
+ }
+
+ [Fact]
+ public async Task A_refused_undo_returns_the_merge_to_Committed_with_the_proofs_wiped_and_the_sweep_finalizes_it_after_the_grace()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ var committed = await rig.AdvanceAsync(id);
+ rig.Moves.Logins[survivor.HeimdallId].RemoveAll(x => x.Provider == "discord"); // the survivor unlinked a moved login
+
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
+ var back = await rig.AdvanceAsync(id);
+
+ Assert.Equal(AccountMergeState.Committed, back.State);
+ var stored = await rig.MergeAsync(id);
+ Assert.Equal("undo_not_reversible", stored.LastOutcome);
+ Assert.Null(stored.SealedProofs);
+ Assert.Equal(committed.GraceEndsUtc, stored.GraceEndsUtc);
+ Assert.IsType(await rig.StandingAsync(folded));
+
+ rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromMinutes(1));
+ await rig.InScopeAsync(async sp =>
+ {
+ await sp.GetRequiredService().AdvanceDueAsync(rig.Clock.Now, default);
+ return await sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default);
+ });
+ Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State);
+ }
+
+ [Fact]
+ public async Task Undo_is_requested_only_inside_the_grace_only_by_the_survivor_and_only_from_Committed()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
+ Assert.IsType(await RequestUndoAsync(rig, Guid.NewGuid(), survivor, rig.Weak(survivor, "twitch")));
+ await rig.AdvanceAsync(id);
+
+ Assert.IsType(await RequestUndoAsync(rig, id, folded, rig.Weak(folded, "discord")));
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(folded, "discord")));
+ Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(id)).State);
+
+ var proof = rig.Weak(survivor, "twitch");
+ rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromSeconds(1));
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, proof)); // Committed, but the grace ended
+ await rig.InScopeAsync(sp => sp.GetRequiredService().FinalizeDueAsync(rig.Clock.Now, default));
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, proof)); // Final
+ Assert.Equal(AccountMergeState.Final, (await rig.MergeAsync(id)).State);
+ }
+
+ [Fact]
+ public async Task A_suspended_folded_account_into_a_memberless_survivor_confirms_on_the_digest_the_member_saw_and_commits()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ db.Memberships.Remove(await db.Memberships.SingleAsync(x => x.UserAccountId == survivor.Id)); // the chat tier holds no membership
+ (await db.Memberships.SingleAsync(x => x.UserAccountId == folded.Id)).Status = MembershipStatus.Suspended;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+
+ // The member is shown a plan and confirms it: the same unchanged world must show the same digest.
+ Assert.Equal(await rig.DigestAsync(survivor, folded), await rig.DigestAsync(survivor, folded));
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+
+ Assert.Equal(AccountMergeState.Committed, (await rig.AdvanceAsync(id)).State);
+ var carried = await rig.InScopeAsync(sp => sp.GetRequiredService().Memberships.SingleAsync(x => x.UserAccountId == survivor.Id));
+ Assert.Equal(MembershipStatus.Suspended, carried.Status);
+ }
+
+ [Fact]
+ public async Task Undo_is_refused_at_the_exact_instant_the_grace_ends_and_allowed_a_second_before()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ await rig.AdvanceAsync(id);
+ var ends = (await rig.MergeAsync(id)).GraceEndsUtc!.Value;
+
+ rig.Clock.Advance(ends - rig.Clock.Now);
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
+ rig.Clock.Advance(TimeSpan.FromSeconds(-1));
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Weak(survivor, "twitch")));
+ }
+
+ [Fact]
+ public void The_sealed_proofs_record_prints_no_bearer()
+ {
+ var seal = typeof(AccountMergeSaga).GetNestedType("ProofSeal", System.Reflection.BindingFlags.NonPublic)!;
+ var instance = Activator.CreateInstance(seal, new List { "bearer-folded-secret" }, "bearer-survivor-secret")!;
+
+ var text = instance.ToString()!;
+
+ Assert.DoesNotContain("secret", text);
+ }
+
+ [Fact]
+ public async Task An_unknown_answer_to_the_reversal_is_replayed_under_the_same_reverse_id_even_past_the_grace()
+ {
+ using var rig = new Rig();
+ var survivor = await rig.AccountAsync("survivor", "twitch");
+ var folded = await rig.AccountAsync("folded", "discord");
+ var id = await rig.ConfirmedAsync(survivor, folded, rig.Weak(survivor, "twitch"), rig.Weak(folded, "discord"));
+ await rig.AdvanceAsync(id);
+ Assert.IsType(await RequestUndoAsync(rig, id, survivor, rig.Moved(survivor, folded, "discord")));
+ rig.Moves.MoveApplyThenFail = HttpStatusCode.BadGateway;
+
+ Assert.Equal(AccountMergeState.UndoRequested, (await rig.AdvanceAsync(id)).State);
+ rig.Moves.MoveApplyThenFail = null;
+ rig.Clock.Advance(AccountMergeLedger.Grace + TimeSpan.FromDays(1));
+ await rig.AdvanceDueAsync();
+
+ Assert.Equal(AccountMergeState.Undone, (await rig.MergeAsync(id)).State);
+ var seen = (await rig.SeenMoveIdsAsync()).Skip(1).ToArray();
+ Assert.Equal(2, seen.Length);
+ Assert.Single(seen.Distinct());
+ Assert.Equal(2, rig.Moves.Stored.Count);
+ }
+
+ // ---- the wiring ----
+
+ [Fact]
+ public void The_host_registers_exactly_one_merge_loop_in_production_and_the_saga_beside_the_ledger()
+ {
+ var program = File.ReadAllText(Path.Combine(RepoRoot(), "src", "Bifrost.Web", "Program.cs"));
+ Assert.Single(System.Text.RegularExpressions.Regex.Matches(program, @"AddHostedService<.*Merge"));
+ Assert.Contains("AddScoped", program);
+ }
+
+ private static string RepoRoot()
+ {
+ var dir = new DirectoryInfo(AppContext.BaseDirectory);
+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Bifrost.slnx")))
+ {
+ dir = dir.Parent;
+ }
+
+ return dir?.FullName ?? throw new InvalidOperationException("repo root not found");
+ }
+}
diff --git a/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs
new file mode 100644
index 0000000..5337eb8
--- /dev/null
+++ b/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs
@@ -0,0 +1,160 @@
+using System.Net;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Tests.Support;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using static Bifrost.Web.Tests.AccountMergeSagaTests;
+using static Bifrost.Web.Tests.AccountMergeSettleTests;
+
+namespace Bifrost.Web.Tests;
+
+/// The operator's page for stuck merges, from browser sessions of the real host: admin only, the stored move id shown as the confirmation, results by closed code.
+public sealed class AccountMergeSettlePageTests
+{
+ private const string Url = "/App/Merges";
+
+ private sealed class World : IDisposable
+ {
+ public Rig Rig { get; } = new(realSessions: true);
+
+ public Party Admin { get; private set; } = null!;
+
+ public string AdminSession { get; private set; } = string.Empty;
+
+ public string MemberSession { get; private set; } = string.Empty;
+
+ public Stuck Forward { get; private set; } = null!;
+
+ public static async Task Make()
+ {
+ var world = new World();
+ var rig = world.Rig;
+ world.Admin = await rig.AccountAsync("operator", "github");
+ var member = await rig.AccountAsync("member", "github");
+ await rig.InScopeAsync(async sp =>
+ {
+ var db = sp.GetRequiredService();
+ var membership = await db.Memberships.SingleAsync(x => x.UserAccountId == world.Admin.Id);
+ membership.IsPlatformAdmin = true;
+ await db.SaveChangesAsync();
+ return 0;
+ });
+ world.AdminSession = await rig.Host.SignInSessionAsync(world.Admin.HeimdallId);
+ world.MemberSession = await rig.Host.SignInSessionAsync(member.HeimdallId);
+ world.Forward = await ConfirmedStuckAsync(rig, AccountMergeSaga.ReceiptMismatch);
+ return world;
+ }
+
+ public void Dispose() => Rig.Dispose();
+
+ public Task<(HttpResponseMessage Response, string Html)> Get(string session, string query = "") => MergePage.GetAsync(Rig.Host, session, query, Url);
+
+ public async Task