diff --git a/.env.local.example b/.env.local.example
index 8a63878..ad0e597 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -4,5 +4,3 @@
COMPOSE_PROJECT_NAME=bifrost-local
BIFROST_ROOT_VERSE=asgard
BIFROST_MACHINE_ID=yggdrasil
-
-BIFROST_PERSONA_FEEDBACK_PRIVATE_STORE=.bifrost/persona-feedback-private.cc
diff --git a/AGENTS.md b/AGENTS.md
index 0b17617..ea3c489 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,7 +33,7 @@
- UI: Razor Pages
- database: PostgreSQL
- hosting target: `bifrost.gamecult.org` on Yggdrasil
-- deployment pattern: nginx + systemd + localhost-only Postgres, matching `E:\Projects\gamecult-ops`
+- deployment pattern: nginx + systemd + localhost-only Postgres, matching `F:\Projects\gamecult-ops`
## Naming Defaults
@@ -43,7 +43,7 @@
## Ops Assumptions
-- follow the GameCult ops pattern already documented in `E:\Projects\gamecult-ops`
+- follow the GameCult ops pattern already documented in `F:\Projects\gamecult-ops`
- prefer one web app process for v1
- keep Postgres bound to localhost on the host
- add deployment runbooks to `gamecult-ops` when app work begins
@@ -57,26 +57,3 @@
- If a question is about trust, accountability, or payout fairness, prefer auditability over automation.
- If a question is about public work crossing GitHub, Discord, Reddit, CultNet/CultCache intake, or future collaboration surfaces, prefer Bifrost-owned requests, receipts, and routing over local helper sprawl.
- Before debugging UI/layout, inspect the live DOM and computed styles instead of guessing from templates or CSS intent.
-
-## Starting Point For The Next Session
-
-Read these files first:
-
-1. `AGENTS.md`
-2. `README.md`
-3. `docs/jurisdiction-map.md`
-4. `docs/bridge.md`
-5. `docs/agent-transport.md`
-6. `docs/reddit.md`
-7. `docs/bifrost-mvp-plan.md`
-8. `docs/full-implementation-strategy.md`
-9. `docs/context.md`
-
-Then start the first implementation milestone:
-
-- GitHub auth
-- membership gating
-- project and member models
-- work items
-- motions
-- ledgers
diff --git a/README.md b/README.md
index 4994f86..f7f69fd 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
@@ -89,13 +90,12 @@ 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`
- provider advertisement commands require explicit `BIFROST_ROOT_VERSE` and
`BIFROST_MACHINE_ID` deployment identity
-- inspect the interactive Motion Verse surface at `/eve/governance/surface` while signed in as an active member
- container smoke test with `docker compose -f compose.local.yaml up --build`
- container smoke tests may hit `/healthz` and `/readyz` as product probes.
Provider advertisements, Docker health, and deploy gates must come from
@@ -106,13 +106,13 @@ For the full staged roadmap, including contribution points, revenue share, patro
Before implementation work starts in a new session, read these files in order:
-1. [AGENTS.md](E:\Projects\Bifrost\AGENTS.md)
-2. [docs/bifrost-mvp-plan.md](E:\Projects\Bifrost\docs\bifrost-mvp-plan.md)
-3. [docs/jurisdiction-map.md](E:\Projects\Bifrost\docs\jurisdiction-map.md)
-4. [docs/bridge.md](E:\Projects\Bifrost\docs\bridge.md)
-5. [docs/verse-service-contract.md](E:\Projects\Bifrost\docs\verse-service-contract.md)
-6. [docs/agent-transport.md](E:\Projects\Bifrost\docs\agent-transport.md)
-7. [docs/reddit.md](E:\Projects\Bifrost\docs\reddit.md)
-8. [docs/paypal-patronage.md](E:\Projects\Bifrost\docs\paypal-patronage.md)
-9. [docs/full-implementation-strategy.md](E:\Projects\Bifrost\docs\full-implementation-strategy.md)
-10. [docs/context.md](E:\Projects\Bifrost\docs\context.md)
+1. [AGENTS.md](AGENTS.md)
+2. [docs/bifrost-mvp-plan.md](docs/bifrost-mvp-plan.md)
+3. [docs/jurisdiction-map.md](docs/jurisdiction-map.md)
+4. [docs/bridge.md](docs/bridge.md)
+5. [docs/verse-service-contract.md](docs/verse-service-contract.md)
+6. [docs/agent-transport.md](docs/agent-transport.md)
+7. [docs/reddit.md](docs/reddit.md)
+8. [docs/paypal-patronage.md](docs/paypal-patronage.md)
+9. [docs/full-implementation-strategy.md](docs/full-implementation-strategy.md)
+10. [docs/context.md](docs/context.md)
diff --git a/docs/bridge.md b/docs/bridge.md
index d66f9a5..52f51a4 100644
--- a/docs/bridge.md
+++ b/docs/bridge.md
@@ -206,7 +206,7 @@ A client asks for the facts by the kind it polls with: `gamecult.persona.chat_pe
| Field | Type | Meaning |
|---|---|---|
-| 12 `basis` | `"direct"`, `"tag"`, `"reply"`, `"room"` 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. |
+| 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.
@@ -253,6 +253,19 @@ A line a delivery already shows and a room she cannot speak in change nothing he
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`.
@@ -267,25 +280,6 @@ The answer is `[persona, deliveries, tail, tail_gaps]` exactly as v3; each deliv
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.
-
-`tools/persona-feedback.mjs enroll-identity` creates the Bifrost service's Ed25519 seed with exclusive creation and mode `0600`, then exports its public MessagePack trust anchor. The private seed belongs under Bifrost's service-private state (default `/var/lib/gamecult/bifrost/persona-feedback/persona-feedback-ed25519.seed`) and is checked for regular-file type, exact Unix mode, and service-user ownership every time it signs. VoidBot publishes pending observations only; it neither pumps admission nor receives the signing path.
-
-The public trust-anchor artifact is a Rust-compatible six-element MessagePack tuple in `HostIdentityTrustAnchorEntry` declaration order: schema version, identity id, 32-byte public key, assurance, identity creation time, and source-record digest. It contains no private material.
-
-The same seed also exposes a separately domain-derived `gamecult.provider_health_identity.trust_anchor.v1` through `export-provider-health-anchor` (or `--provider-health-trust-anchor-out` during first enrollment). This works with the already-enrolled service key and creates the public artifact without replacing an existing file. Persona-feedback health uses that provider-health identity, not the feedback host identity. One `serve` process owns one UUID incarnation and a strictly increasing sequence. Each pulse is the exact 17-field `idunn.signed_daemon_health.v1` tuple, signed over its empty-signature canonical MessagePack form with the `gamecult.provider-health.signature.v1` domain and `idunn.signed_daemon_health.v1` purpose. It carries only the closed provider state and a bounded generic reason. The temporary `idunn.daemon_health` dual publication is explicitly tagged and sourced as an unsigned diagnostic; it cannot substitute for signed admission and can be removed after the deployed Idunn trust binding is live.
-
-The signed `bifrost.persona_feedback.delivery.v0` document matches Epiphany's `BifrostPersonaFeedbackAdmission`: its packet digest is `sha256-` plus SHA-256 of the Rust field-order MessagePack packet tuple, and Ed25519 signs the Epiphany host-identity domain message for purpose `bifrost.persona-feedback.delivery.v0` over the exact admission tuple. The observation provenance is `sourceObserverId=bifrost-discord`; the admission provider is separately and explicitly `provider=bifrost`. Authority is `feedback_only`, and the canonical Epiphany repository target is `GameCult/Epiphany`.
-
-Each binding selects a dedicated provider-owned CultCache store containing only signed delivery documents. The canonical Epiphany path is `/srv/bifrost/persona-feedback/deliveries.cc`; Windows development defaults to `.bifrost/epiphany-persona-feedback.cc`. Observation inbox, Bifrost-private provider state, and delivery store must have distinct canonical paths and distinct existing file identities. Publication is crash-replayable, not cross-store transactional: the signed delivery is inserted idempotently first, then Bifrost records its private delivery copy and immutable receipt. A crash between those writes leaves the source observation unchanged and eligible for replay. Epiphany may consume the delivery store read-only without gaining access to bindings, actor links, receipts, or signing state. CultNet snapshot export remains available.
-
-The Bifrost service runs `tools/persona-feedback.mjs serve` with separate `--observation-store`, private `--store`, private-key, and public `--delivery-store` paths. This bounded resident pump scans immutable source events in observation order, derives unprocessed state solely from absence of an immutable Bifrost receipt, processes each through the same exact binding/signing primitive, and sleeps for `--interval-ms` (default five seconds). Failed events remain eligible for retry; admitted events are never rewritten, deleted, or re-granted. VoidBot does not invoke this mode and requires no read access to Bifrost's private provider state. `--once true` exists for service probes and fixtures.
-
-The deploy contract is one ordinary Bifrost sidecar process with Node.js and the built CultLib CultCache/CultMesh/CultNet runtimes. Provision three separately owned paths: a VoidBot-writable/Bifrost-readable observation inbox, a Bifrost-only private provider store, and the Bifrost-writable/Epiphany-readable delivery store at `/srv/bifrost/persona-feedback/deliveries.cc`. Enroll the Bifrost-only seed once, export its six-field public trust-anchor tuple for Epiphany, create exact target bindings (including visibility, data classification, and delivery path), then start `serve`. The service needs no Discord credential and no Eve surface; it transforms typed organizational feedback observations into authenticated cognition pressure.
-
-`tools/persona-feedback.mjs status` is the non-actuating container readiness probe. It loads the runtime, checks store path and existing-file identity separation, verifies the service-owned key identity, reads bindings without modifying them, and checks each binding's delivery parent/write posture. It emits `bifrost.persona_feedback.readiness.v0` with provider identity, binding count, readiness status, reasons, and `privateStateExposed=false`. It never processes an observation and is not deployment admission.
-
Discord should become a native Bifrost interface for Bifrost-scoped work, not just an output pipe.
The intended shape:
@@ -298,6 +292,22 @@ 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.
+### Send requests (`chat_send_request.v1`, `.v2`, `.v3`)
+
+A send is one `PUT /rooms/{room}/send/m.room.message/{request_id}`: the request id is the Matrix transaction id, so a repeat under the same id is idempotent at the homeserver (Synapse dedupes a transaction id per access token for at least 30 minutes and returns the original event id).
+
+| Kind | Tuple | Answer |
+| --- | --- | --- |
+| `gamecult.persona.chat_send_request.v1` | `[request_id, persona, room_alias, text]` | `chat_send_receipt.v1` `[request_id, event_id, refusal]` |
+| `gamecult.persona.chat_send_request.v2` | the v1 tuple, then `basis`: nil or `[seen_event_id or nil, since_unix_ms]` | `chat_send_receipt.v2` `[request_id, event_id, refusal, newer]` |
+| `gamecult.persona.chat_send_request.v3` | the v2 tuple, then `resend`: a boolean | `chat_send_receipt.v2`, whose refusal may be `RoomMoved`, `ResendUnknown` or `NotSent` |
+
+A v2 or v3 send with a `basis` is checked inside the room gate: if messages that move the room are newer than what she saw, the mouth makes no PUT and answers `RoomMoved` with their ids (`newer`, oldest first, at most 50).
+
+**`NotSent` and `SendFailed`** (v2 receipt) say whether a PUT was attempted. `NotSent`: the mouth attempted no PUT and posted nothing, because something failed before it (the room join or start, the room-head read for the basis check); the request id is not remembered, so the caller sends the line again as a first send (`resend` false). A resend of that id is answered `ResendUnknown`, which is why it must not be sent as a resend. `SendFailed`: a PUT was attempted and its outcome is unknown (a timeout, a 5xx, a dropped connection); the id is remembered, and the caller may repeat it with `resend` true. A resend that itself fails before its PUT is `SendFailed`, not `NotSent`, because the try it repeats may have posted. A v1 caller has no word for `NotSent` and is answered `SendFailed`.
+
+**`resend`** is true when the request repeats an earlier send by the same caller under the same `request_id`, for instance after `SendFailed` (the mouth's 10 s send timeout fires although the homeserver may still persist the event). The mouth honours it only for a request id it attempted itself (the id, the room and the time of the first PUT attempt, in memory, at most 500 per Persona, the oldest forgotten first), for the same Persona and room, less than 25 minutes after that first attempt (inside Synapse's 30 minute minimum txn dedupe window; a repeat does not renew it). It then skips the basis check, because her decision was made against the original basis, and PUTs under the same transaction id. The homeserver's answer is the receipt: the original event id if the first try posted, a new one if it did not. Every other resend is answered `ResendUnknown` (v2 receipt only) and posts nothing: the mouth cannot vouch for the earlier send, because it does not remember the id, the id is older than 25 minutes, it was attempted for another room, or the mouth restarted since. The caller must treat the line as not known to have gone out. `PersonaMismatch`, `Brake`, `EmptyText`, `UnknownRoom` and the room gate apply as for any send. `basis` stays in the tuple for shape uniformity and is ignored on a resend. A request that does not repeat an earlier send must send `resend` false, and a retry that does not say it is a resend is checked as a new send and may be answered `RoomMoved`. Golden bytes: `tests/fixtures/persona-chat-v2/` (`chat_send_request.v3.first-try`, `.resend`).
+
### 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`.
diff --git a/docs/concept-mill-votes-target.md b/docs/concept-mill-votes-target.md
index 30a523e..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
diff --git a/docs/deploy-main-to-live.md b/docs/deploy-main-to-live.md
index 88997ec..61ed1ca 100644
--- a/docs/deploy-main-to-live.md
+++ b/docs/deploy-main-to-live.md
@@ -54,9 +54,16 @@ permits, windows and `MaxTrackedKeys`.
New since the live release, and not read by the validator:
-- **`Heimdall__AppSecret`**: required for Discord and Patreon sign-in. Without it `HeimdallOptions.IsDiscordConfigured` and
- `IsPatreonConfigured` are false and those sign-ins stop working (GitHub sign-in is unaffected); startup does not fail,
- so a missing key shows only at the live check. The value is Heimdall's app secret for slug `bifrost`
+- **`Heimdall__AppSecretFile`**: the preferred way to give Bifrost the app secret below. A path to a file holding it (one
+ trailing newlines are trimmed), for example `%d/heimdall-app-secret` under systemd `LoadCredential=`, so the secret never
+ rides in the process environment. When set, the file wins over `Heimdall__AppSecret`; a missing, unreadable or empty file
+ stops startup in every environment, with a message that names the option and path and never the value. Ops steps:
+ `docs/heimdall-app-secret-file.md`.
+- **`Heimdall__AppSecret`** (deprecated; use `Heimdall__AppSecretFile`; startup logs a warning when it is set): required for
+ Discord and Patreon sign-in. Outside Development and Testing startup fails when neither this nor
+ `Heimdall__AppSecretFile` supplies a non-blank secret (the message names both options, never a value), because
+ `HeimdallOptions.IsDiscordConfigured` and `IsPatreonConfigured` would otherwise be false and those sign-ins silently
+ stop working (GitHub sign-in is unaffected). The value is Heimdall's app secret for slug `bifrost`
(`GC_ACCESS_APP_BIFROST_SHARED_SECRET` on the Heimdall side). Bifrost sends it as `x-heimdall-app-secret`, redacted
from logs.
- **`Bifrost__Oidc__*`**: optional. Absent, the OIDC issuer is not mapped and discovery answers 404. Present, it must be
@@ -129,7 +136,7 @@ All must hold before step 1. A missing one means the window is not used.
not a workstation.
6. **Env diff done.** Every row of the Configuration table is marked present by the reader, `ConceptVotes__NetworkTagSecret`
included and at least 32 characters (a count, not the value), and the `Heimdall__AppSecret` line is in `bifrost.env`
- (mode 600, owner `bifrost`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
+ (mode 600, owner `bifrost`; a build with the empty-secret refusal does not start without it or `Heimdall__AppSecretFile`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
7. **Quiet.** No motion closing and no known vote in flight inside the window. Check the motions page. Members told that
everyone is signed out once (see "What moves").
8. **Watchdog.** `bifrost-watchdog-notice.timer` fires one minute after boot and one minute after each run
@@ -232,6 +239,44 @@ Rollback signs members out again (the old release reads the old cookie names); s
`pg_restore` from it, then `shred -u` the copy and `rmdir $S`; readback `test ! -e $S`. The dump itself stays root-only.
6. Leave the failed release directory for diagnosis; do not delete it in the window.
+## Rolling back the chat invite release
+
+Release `hands/bifrost-chat-invite` drops `MembershipInvitations` and adds `ChatInvites` and `UserAccounts.ChatInvitedAtUtc`
+(migration `20261127120000_AddChatInvites`). So the symlink move above is **not enough** after it has migrated: the previous
+binary reads `MembershipInvitations` on every GitHub sign-in and throws. Roll back the schema with the binary.
+
+The host has no `dotnet ef`, so the migration's `Down` is applied as the SQL below, by the `postgres` superuser against the
+`bifrost` database, with the service stopped. It recreates the old table empty and removes the new ones, in one transaction.
+**It discards every minted invite and every redemption**, and the invited fact on each account; the operator mints
+the invites again on the next release.
+
+```sql
+BEGIN;
+DROP TABLE "ChatInvites";
+ALTER TABLE "UserAccounts" DROP COLUMN "ChatInvitedAtUtc";
+CREATE TABLE "MembershipInvitations" (
+ "Id" uuid NOT NULL,
+ "GitHubLogin" character varying(120) NOT NULL,
+ "NormalizedGitHubLogin" character varying(120) NOT NULL,
+ "IssuedByUserAccountId" uuid NULL,
+ "AcceptedByUserAccountId" uuid NULL,
+ "IssuedAtUtc" timestamp with time zone NOT NULL,
+ "AcceptedAtUtc" timestamp with time zone NULL,
+ "RevokedAtUtc" timestamp with time zone NULL,
+ "Notes" text NOT NULL,
+ CONSTRAINT "PK_MembershipInvitations" PRIMARY KEY ("Id"),
+ CONSTRAINT "FK_MembershipInvitations_UserAccounts_AcceptedByUserAccountId" FOREIGN KEY ("AcceptedByUserAccountId") REFERENCES "UserAccounts" ("Id") ON DELETE SET NULL,
+ CONSTRAINT "FK_MembershipInvitations_UserAccounts_IssuedByUserAccountId" FOREIGN KEY ("IssuedByUserAccountId") REFERENCES "UserAccounts" ("Id") ON DELETE SET NULL
+);
+CREATE INDEX "IX_MembershipInvitations_AcceptedByUserAccountId" ON "MembershipInvitations" ("AcceptedByUserAccountId");
+CREATE INDEX "IX_MembershipInvitations_IssuedByUserAccountId" ON "MembershipInvitations" ("IssuedByUserAccountId");
+CREATE UNIQUE INDEX "IX_MembershipInvitations_NormalizedGitHubLogin" ON "MembershipInvitations" ("NormalizedGitHubLogin");
+DELETE FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261127120000_AddChatInvites';
+COMMIT;
+```
+
+Then point `/srv/bifrost/app/current` at the previous release and start it, as in Rollback. Note: `20261203120000_DropAccountMergeTables` is a one-way teardown migration (`Down` throws `NotSupportedException`) once applied.
+
## What this plan does not do
It does not deploy, does not add an Idunn recipe, and does not touch `bifrost-watchdog-notice.timer`. The
diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md
new file mode 100644
index 0000000..188ca98
--- /dev/null
+++ b/docs/guest-accounts.md
@@ -0,0 +1,294 @@
+# Guest accounts
+
+Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifrost-guest-accounts` under
+`eureka-body:ruling:guest-arrival-bifrost` (Meta: guests need no Matrix account of their own; they get a GameCult
+account through Bifrost with a guest role, and move to member, user or patron on the same account seamlessly),
+building on `eureka-body:ruling:bifrost-owns-accounts-invite-only`. I could not `view` either ruling from the
+Heimdall mind, so their text here is the follow-up brief's wording. Eureka's review (PR comment, 2026-11-07) checked
+it against the rulings and found guest-arrival matches; the conflicts it found are folded in below. First guest:
+sletz (Faust developer). Aqua decides on `#aquasynth` access, so the first grant list is hers to name.
+
+Read at Bifrost `bf8ff62` (`src/Bifrost.Web/Domain/BifrostModels.cs`, `Features/Membership`, `Features/Heimdall`,
+`Features/Oidc`, `Features/Motions`, `Features/ConceptVotes`, `Pages/App/Members`) and Heimdall `575be9c`
+(`src/app-profiles.ts`, `docs/app-profiles/bifrost.md`). File and line references re-read at Bifrost main `e58e953` and Heimdall main
+`afa1b74` on 2026-11-12; where main moved the subject, the text says so. Nothing in this design has landed on main.
+
+## Rulings of the steward (Heimdall, 2026-11-12)
+
+These four are the Bifrost steward's; they replace the recommendations further down. Eureka's, Aqua's and Meta's items are not ruled here.
+
+1. **Name and shape: a stored `Membership.Role` (enum `AccountRole`), not a boolean.** One stored field is one reading, and an account with no role is denied by default (least privilege). `MemberRole` keeps its name and meaning; renaming it is not needed, and nothing existing is removed.
+2. **Invite: a single-use code redeemed from a form, never a token in a URL.** The issuer is shown the code once; the guest pastes it into `POST /invite/guest` (a body, not a path or query), so it reaches no log, referrer or browser history. Hashed at rest, seven days, one use, receipted on issue, accept and revoke. The issuer may bind `ExpectedProvider` (optional, narrows the invite). The sign-in return path carries only the Heimdall attempt, never the code.
+3. **Provider lists: Bifrost narrows to the intersection with Heimdall's `bifrost` profile, `discord, patreon, google`; no widening.** Twitch cannot start in Heimdall and has been removed from Bifrost's `AllowedProviders`. Google is a sign-in provider too: a Google start carrying a live invite asks Heimdall for an invite grant, and Heimdall mints an account only under it (Bifrost PR #93). Which provider sletz uses is still the issuer's to learn.
+4. **Collector: a guest has no `member_id` and none of their messages are collected.** A sender with no linked member is already dropped (`docs/answer-collector-consent.md` l.197 in Heimdall). A `member_id`, and a consent record under it, exists only on promotion to `member`.
+
+## The shape in one paragraph
+
+A guest is a `UserAccount` like any other: same `Id` (the OIDC `sub`), same `NormalizedBifrostIdentity` (the Matrix
+localpart, minted once). What is new is one field, `Membership.Role`, with four values: `guest`, `user`, `patron`,
+`member`. Role is the single place that says what an account may do. A role change rewrites that field and writes a
+receipt; it never creates a second account, never re-mints the identity, so chat history, grants and the Matrix
+user stay attached.
+
+## What exists today
+
+- `UserAccount.Id` is the OIDC subject; `NormalizedBifrostIdentity` is `preferred_username` and, through MAS, the
+ Matrix localpart (`docs/oidc-issuer.md`). `HeimdallAccountId` is only an authenticator handle.
+- `Membership.Status` is `Authenticated | PendingApproval | Active | Suspended`. `CurrentBifrostActor.IsActiveMember`
+ (`CurrentBifrostActor.cs:17`, `Status == Active`) is the one test behind `/App`, motion votes
+ (`Membership.EffectiveVotingWeight`, `BifrostModels.cs:361`, read at `MotionGovernanceService.cs:72`), concept votes (`VoterIdentity.For`,
+ `VoterIdentity.cs:20`, member versus account class), Mind moderation (`MindIntakeService.cs:241`) and the fork desk's subject check
+ (`OidcEndpoints.ActiveMemberIdAsync`, `OidcEndpoints.cs:183-194`). The OIDC chat tier is not behind it: main lets any account that is
+ not `Suspended` and holds a live training-notice receipt sign in to chat (`OidcEndpoints.cs:55-65` and `ChatRefusalAsync`, `:164-180`,
+ called at `:127` and `:144`; `docs/oidc-issuer.md` l.72-77), and the back-channel logout reconciler (`OidcLogoutReconciler.cs`, 30 s
+ interval, l.34) ends sessions of suspended or deleted subjects, never of a chat-tier account for lacking membership.
+- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability
+ roles a member holds in addition. They are not the new field.
+- Chat invites are `ChatInvite` (see `oidc-issuer.md`, Chat invites), not keyed to any login;
+ a guest may have no GitHub login at all.
+- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an
+ identity-only account at `Authenticated`; with member access it creates `Active`.
+- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research
+ only, `docs/charter-amendment-proposal.md`).
+
+## Decision: one role field, status stays lifecycle
+
+Two authorities cannot both say "may this account vote". Today `Status == Active` says it. The cut:
+
+- `Membership.Status` keeps its meaning as lifecycle of the account: may it hold a session. Add `Left` and
+ `Erased` (see Leave and erase). `Active` means admitted and in good standing, for any role.
+- `Membership.Role` (new, non-null, enum `AccountRole`) decides rights. `IsActiveMember` becomes
+ `Status == Active && Role == Member`, and is the only place that expression exists. Every current
+ `IsActiveMember` caller keeps working unchanged and a guest fails all of them without a per-site edit.
+- OIDC needs no change for guests: main already admits any non-`Suspended` account with a live training-notice receipt to chat (see
+ What exists today), so a guest, user or patron holds a chat session, and a member demoted to `Suspended` loses it. The change this
+ design owes is the two new statuses: `Left` and `Erased` must be refused at the same three places (`OidcEndpoints.cs:62`,
+ `ChatRefusalAsync` `:174`) and ended by the reconciler, which today looks for `Suspended` only. That is the line to review.
+- Backfill: `Active` becomes `member`; `Authenticated` and `PendingApproval` become `user`; an account with a
+ current `Patron` tier snapshot and not `Active` becomes `patron`. Nobody starts as `guest`.
+
+Naming risk: `MemberRole` already exists for capability roles. If the collision bites, call the new field
+`Class`; the published field below follows whichever name is chosen. I use `Role` because that is the ruling's word.
+
+Alternative considered and not recommended: a boolean `IsGuest` on `Membership` with guests kept at `Active`.
+Smaller to land, but `user` and `patron` stay implicit in status and tier snapshots, so "the role field Personas
+read" would have to be derived in three places. One stored field is one reading.
+
+## Invite shape
+
+New table `GuestInvitation`, separate from `ChatInvite` (which leads to chat, and
+not to a guest). Fields:
+
+| field | rule |
+|---|---|
+| `Id` | Guid. |
+| `CodeHash` | SHA-256 of a 256-bit random code. The code itself is shown to the issuer once and never stored. |
+| `IntendedIdentity` | the localpart the issuer picks (for example `sletz`), validated by `BifrostIdentityService.NormalizeIdentity`, reserved while the invite is open. Minted once on accept; a collision gets the usual `-2` suffix. |
+| `Label` | free note for the issuer ("sletz, Faust developer"). |
+| `RoomGrants` | the rooms to grant on accept (below), as a list of grant requests. |
+| `IssuedByUserAccountId`, `IssuedAtUtc` | issuer must be a platform admin (`CanManageMembership`), as for member invites. |
+| `ExpiresAtUtc` | default seven days. |
+| `AcceptedByUserAccountId`, `AcceptedAtUtc`, `RevokedAtUtc` | one use; revoke before accept ends it. |
+
+The code is a bearer: whoever redeems it first is the guest. That is the cost of not needing sletz's
+provider handle in advance, and it is why the code is single-use and short-lived and why the accept is shown
+to the issuer. Ruled over binding the invite to a provider handle (which needs a Discord or Google id the
+issuer may not have); the issuer may still set `ExpectedProvider` (see Rulings). It is carried in a form body, never in a URL.
+
+## Sign-in via Heimdall
+
+1. Guest opens `/invite/guest`, pastes the code, and posts it. Bifrost checks hash, expiry, unused, unrevoked, and stores the invite id in
+ the existing Heimdall attempt (`HeimdallAuthService` protects attempt state with the data protector).
+2. Bifrost starts Heimdall sign-in with `requireMemberAccess = false` (identity only, no entitlement policy).
+ Heimdall authenticates; it does not issue the identity (`docs/jurisdiction-map.md`).
+3. On the callback, in one transaction: resolve `HeimdallAccountId`.
+ - No account: create `UserAccount` with `IntendedIdentity`, `Membership { Status = Active, Role = Guest }`, write
+ the room grants, mark the invite accepted, write the receipt.
+ - Account exists: the invite never lowers an account. A `member`, `patron` or `user` keeps their role; the grants
+ are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse.
+4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client.
+
+Bifrost's `AllowedProviders` is `discord, patreon, google` (`HeimdallAuthService.cs`), matching Heimdall's `bifrost` app profile (`app-profiles.ts`, `bifrostProfile`). A Google start carrying a live invite asks Heimdall for an invite grant (Bifrost PR #93); Google also stays the explicit link by a signed-in member (`HeimdallAttemptPurpose.LinkAwaitGoogle`, PRs #81 and #82). Which provider sletz uses is unknown; the issuer learns it before the first invite.
+
+## Guest rights
+
+A guest may: sign in, hold a Bifrost cookie, hold a chat session through OIDC (after accepting the training notice, as any chat account does on main, `ConsentEndpoints.HasLiveReceiptAsync`, `ConsentEndpoints.cs:146`), see and edit their own profile
+(`MemberProfile`), be in the rooms granted to them, and leave or erase (below). A guest may not:
+
+- vote on motions: `EffectiveVotingWeight` is `0` for any role but `member` (today it is `Max(1, ...)` for
+ `Active` (`BifrostModels.cs:361-363`), which would give every guest weight 1; that line must read the role);
+- cast concept-mill appraisals: `VoterIdentity.For` returns no voter for a guest (not even `VoterClass.Account`);
+- appear on any estate roll or in any tally. The charter proposal snapshots each estate's roll at notice (A6);
+ `guest` is on no roll, so a guest cannot be counted, cannot make a quorum, and reclassifying a guest after a
+ snapshot changes nothing for that snapshot;
+- use bridge transport, claim or log work, earn points or ledger credit, or hold tier snapshots (those make them
+ a patron or member by changing role, not by decorating a guest);
+- hold a `MemberRole` or any of the `CanManage*` flags;
+- invite anyone.
+
+This list is enforced by role in one place (`CurrentBifrostActor`), not by a check at each use.
+
+## Per-room grants
+
+Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, so a grant is Bifrost state:
+
+`GuestRoomGrant { Id, UserAccountId, RoomRef, GrantedByUserAccountId, GrantedAtUtc, ExpiresAtUtc?, RevokedAtUtc? }`
+
+`RoomRef` is a room id or alias as chat names it. Aqua's `#aquasynth` is the first one if she says yes.
+
+**Scope (per `guest-room-moderation-ruled`, `guest-room-authority-ruled`).** Project rooms are public-join and
+hand-moderated by the steward, with Eureka as backstop, so a guest who can reach a public room needs no grant. A
+grant exists only for a room its steward chooses to keep closed, and its grantor is that room's steward, not a
+platform admin (the invite itself is still issued by a platform admin; `GrantedByUserAccountId` records the
+steward). Room entry for public rooms is not Bifrost's decision.
+
+The grant has to reach Matrix to mean anything. Today Bifrost's only Matrix writer is the Persona mouth, with
+per-Persona access tokens (`docs/bridge.md`), and it holds no admin or invite right.
+
+Gap (largest in this doc): something must perform "invite this Matrix user to that room" on a grant and "remove
+them" on revoke or expiry. Candidates: a Bifrost-owned bot user that is a member with invite power in the granted
+rooms (reuses the Matrix client API, no Synapse admin credential), or the Synapse admin API. I recommend the bot
+user: narrower credential, and the room's power levels remain the real gate. Until it exists, the grant is a
+record, a human invites the guest by hand, and the receipt says `delivered_by: manual`. Whether the closed rooms a
+steward keeps are invite-only in Synapse is a chat configuration fact I have not verified.
+
+What Matrix takes from the Bifrost account is exactly this effector: invite or remove on a grant, and the power
+level the effector sets on invite. Role never enters OIDC, so Matrix reads no role from the issuer
+(`bifrost-owns-accounts-invite-only`: grants flow from the account through the effector, not through claims).
+
+**Guest DMs (`guest-dms-ruled`) conflict, open.** The mouth declines invites from other servers and accepts
+same-server DM invites (`tools/persona-matrix-mouth.mjs` `answerInvites`). The ruling's decline-for-now assumed
+federated guests; a Bifrost guest is a local `@sletz:`, so the mouth would accept their DM. Either the mouth
+declines DMs from role `guest` (using the account document below), or the ruling is revisited. That is Eureka's and
+the ruling's owner's call, not this doc's; until it is made, the mouth's behaviour is the ruling's opposite for local
+guests.
+
+Second gap: a guest has a full Matrix account once MAS provisions the localpart, so Matrix itself will let them
+create rooms or DM unless Synapse's room-creation and invite settings (`room_list_publication_rules`,
+`allow_public_rooms_*`, a spam-checker or module) say otherwise. These are global in Synapse, not per user, so a
+guest limit may have to be power levels in every room they are in. I did not find a per-user switch.
+
+## Role change on the same account id, with a receipt
+
+`ChangeRole(accountId, to, actor, reason)` is the only writer of `Membership.Role`. It runs in one transaction:
+
+1. refuse `Erased` and `Left`; refuse a no-op;
+2. write `Role`, and for `member` also set `Status = Active`, `ApprovedAtUtc`, and the default `StandardMember`
+ capability role (the same effects as `OnPostApproveAsync`); for `patron`, nothing beyond the role (tier
+ snapshots come from support events as before);
+3. write `AccountRoleReceipt { Id, UserAccountId, From, To, ChangedAtUtc, ChangedByUserAccountId, Reason }`;
+4. leave `UserAccount.Id`, `NormalizedBifrostIdentity`, `HeimdallAccountId`, grants and profile untouched.
+
+Who may change: a platform admin (`CanManageMembership`). Promoting to `member` is the existing approve path;
+this design routes it through `ChangeRole` so one writer exists. Promoting to `member` also applies whatever the
+charter says about joining an estate (not decided; see Questions). Demotion (member to guest) is allowed and
+receipted; it also removes the `MemberRole`s and capability flags in the same transaction.
+
+The receipt is a Postgres row today, like `AuditEvent`. Bifrost's rule is that durable state has a CultCache `.cc`
+witness (`docs/jurisdiction-map.md`, Design Rules); the witness is owed (Gaps).
+
+Seamless means: the guest's session cookie, OIDC subject, Matrix id, display name and room memberships do not
+change on promotion. A cookie issued before promotion carries identity claims only, never the role, so it needs
+no refresh; the actor is read from the database each request (`CurrentBifrostActorAccessor`).
+
+## Leave and erase
+
+Neither exists in Bifrost today. Two different acts:
+
+**Leave** (guest or any role, self-service): sets `Status = Left`, revokes every grant, and expels the account
+from granted rooms through the same effector as grants. Once the reconciler and the chat refusals name `Left` (see Decision),
+it ends the MAS session within its 30 s interval, and the token and userinfo endpoints refuse. The account row and
+`Id` stay, so a later invite can restore it (a `Left` account re-accepting is a role change from itself, receipted).
+Nothing else about the person is deleted by leaving.
+
+**Erase** (self-service, or admin on request): irreversible. In one transaction: blank `DisplayName`, `AvatarUrl`,
+`MemberProfile`, `GitHubLogin`/`GitHubUserId`, clear `HeimdallAccountId` (the authenticator link), set
+`Status = Erased`, keep `Id` and `NormalizedBifrostIdentity` as a tombstone so the localpart is never reissued to
+someone else (OIDC says it is minted once), keep receipts but with names stripped. The reason to keep a tombstone
+row is that receipts and audit events point at the id.
+
+An erasing guest has no votes, ledger entries or points, because guests cannot create them. A member or patron
+who erases does, and those are accounting records: their erase is a separate question (Questions). Guest erase
+is the case this design covers.
+
+Outside Bifrost, erase is incomplete without two effectors:
+
+- Matrix: Synapse's deactivate-with-erase admin call and MAS deactivation for the user. Federation is disabled in
+ the chat map (`gamecult-ops/docs/gamecult-chat-map.md`: federation paths 404), which helps: messages are
+ not copied to other servers. Other members' clients, and any export or training copy, are not reached by an
+ erase. Whether chat content is training data is `heimdall-body`'s consent rulings (Heimdall PR #6), which already
+ define exit by redaction; a guest's messages follow whatever that doc says, not this one.
+- Heimdall: I found no account-delete or unlink path in Heimdall `src`. Clearing `HeimdallAccountId` on the Bifrost
+ side leaves the Heimdall account and its provider link alive. Heimdall needs an erase call keyed by the account id
+ before "erased" is true end to end.
+
+## What Eureka reads
+
+Personas read the role, not the account. Do not put it in OIDC: the issuer promises "no membership detail leaves
+Bifrost" (`docs/oidc-issuer.md`) and chat does not need it. Publish a typed CultMesh document under the
+`gamecult.bifrost.governance` family (the nearest existing schema namespace, `verse-service-contract.md` l.60), id
+`gamecult.bifrost.account.v1`, key = account id:
+
+| field | type | note |
+|---|---|---|
+| `account_id` | uuid | OIDC `sub`; never changes. |
+| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart. |
+| `matrix_id` | string | the full mxid `@:`, server name taken from MAS config at publish time so no reader assumes it. The lookup key for a Persona, which holds the Matrix sender id and not the account uuid. |
+| `display_name` | string | blank once erased. |
+| `role` | `guest` \| `user` \| `patron` \| `member` | the field Personas read. |
+| `status` | `authenticated` \| `pending_approval` \| `active` \| `suspended` \| `left` \| `erased` | |
+| `role_since` | UTC ms | from the latest `AccountRoleReceipt`. |
+| `rooms` | list of room refs | only for `guest`: the live grants. Others get rooms by estate. |
+
+Contract the document carries, not left to each reader:
+
+- **Lookup.** The document is queryable by `matrix_id`.
+- **Absence is `unknown`.** A sender with no document is not a Bifrost account (a bridge ghost or an unlinked user).
+ Readers must treat it as `unknown`, never default it to `guest`, `user` or `member`. This reverses today's Persona
+ reading (everyone unlisted is `member`), which narrows to the Bifrost `member` role.
+- **Status gates the role.** Only `status = active` yields a usable role; `suspended`, `left`, `erased`,
+ `authenticated` and `pending_approval` yield none.
+- **Not Bifrost accounts.** Operator, the Persona's own id and Minds are typed by the reader's config, which takes
+ precedence over the document. Minds are not Bifrost accounts and must not fall to `unknown`.
+- **Freshness.** A reader loads the document when it builds each turn, never once at start, so a role change
+ applies from the next message; past messages keep the role they were read under. `role_since` lets a trace say
+ which role was read. Publisher bound: a role or status change is published within 30 seconds, the same bound the
+ OIDC reconciler already keeps for a non-`active` subject. No publisher exists, so this is the requirement it is
+ built to, not a measurement.
+
+Bifrost does not decide Persona behavior; it states the role.
+
+No such publisher or witness exists; Bifrost has no `.cc` export for accounts today.
+
+## Cut sequence (not specs)
+
+1. `Membership.Role`, backfill, `IsActiveMember` and the OIDC tests moved to the new reading, vote and concept-vote
+ exclusions, with tests that fail if a guest gets weight or a voter key.
+2. `GuestInvitation`, the accept path, the Heimdall provider list aligned.
+3. `AccountRoleReceipt` and `ChangeRole`, with `OnPostApproveAsync` routed through it.
+4. `GuestRoomGrant` and the Matrix effector.
+5. Leave, then erase (Bifrost side), then the Matrix and Heimdall effectors.
+6. The account document and its `.cc` witness.
+
+## Gaps, plainly
+
+- The Matrix effector for grants, leave and erase does not exist, and no credential for it is provisioned.
+- Synapse cannot cap what a guest does per user; room-creation and invite limits are global (unverified: I did not
+ read the live Synapse config).
+- Heimdall has no erase path (re-checked at `afa1b74`: no account-delete or unlink route in `src`, and `docs/answer-collector-consent.md`, merged as Heimdall PR #6, redacts by exit and says nothing of guests).
+- No `.cc` witness or CultMesh publisher for accounts or receipts. Bifrost's account state is Postgres only.
+- Matrix id shape (`@:`) depends on MAS importing `preferred_username` as localpart; the OIDC doc
+ says so, I did not check the deployed MAS.
+- Tie to the answer-collector consent doc (Heimdall PR #6, merged; `docs/answer-collector-consent.md`): a guest posting in a room may be posting to a sample
+ collector. That doc keys on `member_id`, and says a sender with no linked member is dropped (l.197). Whether a guest has a
+ `member_id`, and so whether their answers are collected at all, is not decided here. Default: not collected.
+- Erase for member and patron roles (ledger and vote records) is unmapped.
+
+## Questions for the deciders
+
+1. **Name and shape**: ruled (stored `Role`), see Rulings.
+2. **Bearer link or provider-bound invite?** Ruled (single-use code from a form), see Rulings.
+3. **Which Heimdall provider will sletz sign in with?** The lists are ruled (see Rulings); this is the issuer's to learn before the first invite.
+4. **`member_id` for the answer collector**: ruled (none for a guest), see Rulings.
+5. **Does promotion to member join the Members estate immediately**, or does the charter's notice and snapshot
+ rule apply to the roll? The charter text is a proposal, not in force.
diff --git a/docs/heimdall-app-secret-file.md b/docs/heimdall-app-secret-file.md
new file mode 100644
index 0000000..bee017c
--- /dev/null
+++ b/docs/heimdall-app-secret-file.md
@@ -0,0 +1,18 @@
+# Heimdall app secret from a file
+
+`Heimdall:AppSecret` (`Heimdall__AppSecret`) is Bifrost's app secret for Heimdall slug `bifrost`; it is sent as the
+`x-heimdall-app-secret` header. Set through the environment it rides in the process environment. `Heimdall:AppSecretFile`
+(`Heimdall__AppSecretFile`) names a file holding it instead.
+
+- File set: Bifrost reads it once at startup and trailing newlines are trimmed. The file wins over `Heimdall__AppSecret`.
+- File set but missing, unreadable, a directory, or empty: startup fails in every environment. The message names
+ `Heimdall:AppSecretFile` and the path, never the secret.
+- Only `Heimdall__AppSecret` set: still works; startup logs a deprecation warning (without the value).
+- Neither set: startup fails outside Development and Testing, naming `Heimdall:AppSecretFile` and `Heimdall:AppSecret`
+ (`StartupConfigurationValidator`). Development and Testing still start, with Discord and Patreon sign-in off.
+
+Under systemd, pass the file with `LoadCredential=heimdall-app-secret:` and
+`Environment=Heimdall__AppSecretFile=%d/heimdall-app-secret`.
+
+Code: `HeimdallOptions.ResolveAppSecret` (`src/Bifrost.Web/Configuration/HeimdallOptions.cs`), wired in `Program.cs`, forced at
+startup by `StartupConfigurationValidator.Validate`. Tests: `tests/Bifrost.Web.Tests/HeimdallAppSecretFileTests.cs`.
diff --git a/docs/jurisdiction-map.md b/docs/jurisdiction-map.md
index a251b00..ede5294 100644
--- a/docs/jurisdiction-map.md
+++ b/docs/jurisdiction-map.md
@@ -105,6 +105,8 @@ This keeps Reddit useful without making subreddit mechanics the secret constitut
Heimdall authenticates; it does not issue GameCult identity. Bifrost owns the identity (`UserAccount.Id`, `NormalizedBifrostIdentity`) and issues it to chat as an OIDC provider (`docs/oidc-issuer.md`). `HeimdallAccountId` is an authenticator handle that links a Heimdall account to a Bifrost identity.
+A member's provider logins are Heimdall's (`linked_identities`); Bifrost shows, links and unlinks them on `/Membership/LinkedAccounts` by calling Heimdall's member routes with a bearer from a fresh Heimdall sign-in, and keeps none (`docs/linked-accounts.md`). Strong proof for an unlink is a Bifrost-verified passkey (WebAuthn, RP ID the Bifrost host) that Bifrost asserts to Heimdall through its app-asserted step-up route; Bifrost owns the credential store and the ceremonies, Heimdall owns the unlink gate (`docs/passkeys.md`).
+
Bifrost consumes Heimdall claims. It does not become the key vault. The split is bridge versus gate: Heimdall decides who may cross under which grant; Bifrost moves authorized work across public protocols and records where it landed.
### Patron Collection Crossing
diff --git a/docs/linked-accounts.md b/docs/linked-accounts.md
new file mode 100644
index 0000000..4f99d2c
--- /dev/null
+++ b/docs/linked-accounts.md
@@ -0,0 +1,68 @@
+# Linked accounts
+
+`/Membership/LinkedAccounts` (`src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml[.cs]`) is where a signed-in member sees the provider logins attached to their Heimdall account, links another one, and unlinks one. Heimdall owns the logins and every rule about them; this page starts the flows and shows what Heimdall answered. A member reaches it from the membership status page. A session with no Heimdall account (a Bifrost-native GitHub sign-in) gets a note instead of controls.
+
+## What it does
+
+| Action | What Bifrost does | Heimdall call |
+|---|---|---|
+| Show my logins | A fresh ordinary Heimdall sign-in as the session's account, through the proof provider (below); inside its completion, the list | `GET /v1/me/identities` with that sign-in's bearer |
+| Link Discord, Patreon or Google | The same fresh sign-in as proof, then the link start for the chosen provider with its bearer. Needs a current list. Discord and Patreon attach in Heimdall's callback and return a link completion; Google writes a pending link, and a second fresh sign-in confirms it | `POST /v1/oauth/{provider}/start` `mode: "link"`, then for Google `POST /v1/apps/bifrost/links/confirm` |
+| Unlink | A sign-in through Google with `stepUp: true` (app secret); inside its completion, the unlink | `POST /v1/me/identities/{id}/unlink` with that sign-in's bearer |
+| Unlink with a passkey (an account with a strong passkey) | A WebAuthn assertion verified at Bifrost, then a fresh ordinary sign-in as the account; inside its completion, Heimdall's app-asserted step-up, then the unlink with the token it returns | `POST /v1/apps/bifrost/step-up` `{method: "bifrost-passkey", nonce}`, then `POST /v1/me/identities/{id}/unlink` |
+| Add or revoke a passkey | Enrolment needs a fresh Heimdall sign-in first and cools off 48 hours; revoking needs no proof | none |
+
+The linkable providers are the ones Heimdall's `bifrost` profile admits (`identityProviders` in Heimdall `src/app-profiles.ts`): Discord, Patreon, Google.
+
+## How the bearer is kept: it is not
+
+Bifrost keeps no Heimdall token. Each action is an attempt: a Data Protection cookie (`__Host-bifrost_heimdall_`, HttpOnly, Secure, ten minutes) holding a purpose (`ListProof`, `UnlinkProof`, `LinkStart`, `LinkAwaitGoogle`, `LinkConfirm`, `LinkAwaitDirect`), the account the session must be, and a target (the provider to link, or the identity to unlink). The browser returns from Heimdall to `/auth/heimdall/complete`; Bifrost redeems the code, verifies the token, requires that the proven account is the attempt's account and that the browser's session is that same account, calls Heimdall with the bearer inside that one request, and drops it. The bearer is never stored, logged, put in a cookie or a redirect, or rendered. Heimdall's member routes go through an HTTP client that carries no app secret (`HeimdallMemberClient`), so a Bifrost fault cannot call them without a member present.
+
+The list is kept for five minutes in this process only (`LinkedAccountsSnapshots`), keyed by the Heimdall account id, so the page can render after the completion's redirect: identity id, provider, display name (or username when there is none) and link date. Never the bearer, the email, the provider user id or the scopes. It is not given to the browser. A restart or the five minutes empties it and the page offers "Show my linked logins" again.
+
+Every action is a POST with antiforgery; a GET starts nothing. The completion route's answers are `Cache-Control: no-store`. The page and every redirect carry only a code from a closed set (`HeimdallLinkOutcomes`, `?result=`); the wording is Bifrost's, never Heimdall's text or the query's.
+
+## Which provider proves the account
+
+An ordinary proof sign-in through Discord or Patreon when the account no longer holds that login makes Heimdall mint a new, unrelated account that holds it (those providers are `mints_account`), and the freed login then answers `identity_linked_elsewhere` when the member tries to link it back. Google is `requires_link`: Heimdall refuses a Google sign-in for a login no account holds (`identity_not_linked`) and mints only under an invite grant, which a proof never asks for. So Bifrost never guesses a provider, and it does not use the "provider you signed in with" claim in the session (that records how you signed in once, not what the account holds now). This guarantee covers this page's proofs only: the older anonymous `GET /auth/heimdall/{provider}` still starts an ordinary sign-in through any named provider, and can overwrite an in-flight attempt slot; that route is unchanged here.
+
+- With a current list (the five-minute snapshot), the proof goes through a provider on it: Discord, else Patreon, else Google.
+- With no list (first visit, five minutes passed, a restart), the page offers only "Show my logins through Google (cannot create an account) / Discord / Patreon" and says plainly that Bifrost cannot tell what the account holds, so the member picks a login they know it holds. A named Discord or Patreon the account turns out not to hold still mints at Heimdall: that is the member's choice and the page says so beforehand. A refresh with no list and no named provider starts nothing (`provider_needed`).
+- Link buttons appear only with a current list; a posted link with none starts nothing (`list_expired`). Unlink needs the list too. After an unlink whose result is not a definitive refusal (a 500, a lost or malformed answer, not found) the list is dropped, since Heimdall may have applied it; only `403 step_up_required`, `409 last_identity` and `401` leave it.
+
+## The proof limit
+
+Passkeys (`docs/passkeys.md`) are the strong proof: an account with a passkey past its cooling-off unlinks with it, and the Google step-up below is then closed (`passkey_required`). The rest of this section is the Google proof, which stays for an account with no strong passkey.
+
+Unlinking needs fresh proof: Heimdall refuses `403 step_up_required` unless the access token carries `step_up_at` from a step-up sign-in within 600 seconds (`docs/service-contract.md`, `POST /v1/me/identities/{identityId}/unlink`, in the Heimdall repository). Only Google can give that to a `bifrost` sign-in: Discord and Patreon have no re-authentication parameter (an open provider session completes without credentials), and Twitch and YouTube, which do, are not in the `bifrost` profile. So:
+
+- An account with no Google login linked and no strong passkey cannot unlink anything from here. The page says what it can do (add a passkey; the time a cooling-off one becomes strong) and shows no Unlink button; a posted unlink starts nothing.
+- Heimdall answers `503 provider_not_configured` for Google until a Google OAuth client is configured on the Heimdall host (follow-up `heimdall-body:follow_up:google-console-client-registration`; not set live as of 2026-11-13). The step-up start is then refused and the page says fresh proof could not be started. Nothing loops: the refusal sets no attempt cookie.
+- Linking Google needs the same client. Until then the Google link button ends in "That could not be completed. Nothing was changed."
+- A Google step-up proof is as strong as Google's `prompt=login`; Heimdall says "asked", not "verified" (`stepUpRequested`).
+
+The unlink completion must also say a step-up was requested (`stepUpRequested`, set by Heimdall when the start asked for one); one that does not is refused without calling Heimdall. Heimdall's other answers are shown as plain outcomes with nothing changed: `409 last_identity` (the last login is never removed), `404 identity_not_found` (the list is dropped as stale), `401 sign_in_required`, `403 step_up_required`, and any failure to reach Heimdall.
+
+A link refused because the login already belongs to another account (`409 identity_linked_elsewhere` from `links/confirm`; for Discord and Patreon the callback's `link_initiator_mismatch`, carried on by the complete page as a fixed result) is shown as "That login belongs to another account." The other account is never named.
+
+## Not here
+
+- Merging two accounts. A refused link ends there; nothing is moved or merged.
+- Step-up through Discord, Patreon or Twitch. Heimdall does not offer it to the `bifrost` profile.
+- Linking Twitch or GitHub: not admitted by the `bifrost` profile, and Heimdall's GitHub runtime is not implemented.
+- A list of other apps' logins, grants or consent receipts (Heimdall's grants page).
+
+## Where the code is
+
+- `Pages/Membership/LinkedAccounts.cshtml[.cs]`: the page and its three POST handlers.
+- `Features/Heimdall/HeimdallAuthService.cs`: the attempt machinery (`StartListAsync`, `StartLinkAsync`, `StartUnlinkAsync`, `ContinueLinkAsync`), shared with sign-in.
+- `Features/Heimdall/HeimdallMemberClient.cs`: the two member calls and their outcome mapping.
+- `Features/Passkeys/`, `wwwroot/js/passkeys.js`: the passkey ceremonies (`docs/passkeys.md`).
+- `Features/Heimdall/LinkedAccountsSnapshots.cs`: the five-minute list.
+- Tests: `tests/Bifrost.Web.Tests/LinkedAccountsTests.cs`, `HeimdallGoogleLinkTests.cs`, `PasskeyTests.cs`, with the fake Heimdall in `Support/HeimdallTestKit.cs`.
+
+## Known leftover
+
+Several exits leave the held attempt cookie (`__Host-bifrost_heimdall_`, HttpOnly, so script cannot clear it) in the browser until its ten minutes end: the complete page's redirect when Discord or Patreon refuses a link because the login belongs to another account, every other `heimdall_status=error` redirect, and a return with no code or no attempt. The script redirects without posting anything; clearing the cookie would need a server route reached by GET or a post from the failure path, which the hardened script deliberately does not do.
+
+A start takes a free slot, else overwrites the slot that expires first, live or dead (`ChooseSlot`, two slots). So three member starts within ten minutes can cost a still-live older attempt, which then finds no cookie and is refused; the member starts again.
diff --git a/docs/oidc-issuer.md b/docs/oidc-issuer.md
index df357ee..2dffee5 100644
--- a/docs/oidc-issuer.md
+++ b/docs/oidc-issuer.md
@@ -71,7 +71,11 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
the return path carries only a short `request_uri`, so `LocalReturnPath.MaxLength` stays 256.
- Signed in, membership `Suspended`: redirect to the client's `redirect_uri` with `error=access_denied` and
`error_description=The account is suspended.`
-- Signed in with no membership, `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
+- Signed in, not suspended, with no `ChatInvitedAtUtc` and a membership that is not `Active` (the chat tier before an invite):
+ `error=access_denied` with `error_description=Chat is by invitation. Open an invite link, then sign in, to chat.`
+ (`OidcEndpoints.NotInvitedDescription`). This follows the suspension and identity refusals and comes before the consent redirect,
+ so an uninvited account is never invited to agree. A desk token (every scope a desk scope) asks no invite.
+- Signed in, invited or `Active`, with no membership or `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
sign-in to chat and nothing else. The token carries the same `openid profile` claims; the issuer writes no membership,
role or vote, and every member or governance surface (`/App`, `/eve/governance`, `/api/sealed-motions`, the fork desk)
still asks for `Active` itself, so neither the session nor the token opens them.
@@ -97,9 +101,29 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
(this path does not revoke the token; the back-channel reconciler below does, when it is configured). There is no refresh token, so refresh needs no gate.
The logout reconciler ends the sessions of those same accounts; a chat-tier account is never logged out for lacking membership.
+## Chat invites
+
+Who may chat is decided here, by the issuer, and nowhere else: an account holding `UserAccount.ChatInvitedAtUtc` or an `Active`
+membership. "Invited" is derived at token time (authorize, token, userinfo, the logout reconciler: `ChatRefusalAsync`) and is never
+copied to MAS or Synapse. Native registration and Heimdall sign-in create accounts that can use the Mill and the member pages; they do not
+reach chat on their own.
+
+- A member with `CanManageMembership` mints an invite on the Members page with a note. The link `https:///invite#` is shown
+ once, on the response to the mint. The token is 32 random bytes; only its SHA-256 (`ChatInvite.TokenHash`) is stored. An invite is valid
+ for 14 days, single use, and can be revoked until redeemed. The audit trail records `chat.invite.minted`, `chat.invite.redeemed` and
+ `chat.invite.revoked`. The payment ledger will later mint the same record through `ChatInviteService.MintAsync`.
+- `GET /invite` serves a page that reads the token from the URL fragment (never sent to a server, so in no request line, access log, error log or Referer) and posts it to `POST /invite`. A live invite sets a one-hour `HttpOnly`, `Secure`, `SameSite=Lax` cookie (`__Host-bifrost_chat_invite`) holding
+ the token and redirects to the sign-in chooser. Anything else (unknown, expired, revoked, redeemed) gets one page, `This link is not valid`,
+ with status 404 and no cookie.
+- Redemption has one owner, `ChatInviteService.RedeemCarriedAsync`, called after the Heimdall completion signs in and after native
+ registration signs in. A request carrying the cookie spends the invite onto the signed-in account (`ChatInvitedAtUtc`, `RedeemedByUserAccountId`)
+ in one save conditioned on the invite still being unredeemed and unrevoked, so of two accounts racing for one link one loses. The cookie
+ is cleared either way. An account that is already invited, or `Active`, keeps the invite unspent. GitHub OAuth sign-in redeems nothing, so `/auth/sign-in?provider=github` answers 409 with the sign-ins that do while the cookie is carried.
+- Sessions that were open for an uninvited, non-`Active` account end at the logout reconciler's next pass, as for any refusal read by `ChatRefusalAsync`.
+
## Chat needs a receipt
-The issuer is the chat tier: every token it issues is a chat token. Ruled by Meta, 2026-11-11: speaking in chat needs agreement
+The issuer is the chat tier: every token it issues is a chat token. Ruled by Meta, 2026-11-11: speaking in chat needs an invite (above) and agreement
to the training notice, and nothing else does. A live `ConsentReceipt` for `TrainingNotice.Version` is required (the same
reading as the consent page's "agreed", `ConsentEndpoints.HasLiveReceiptAsync`); account sign-in, the members page and votes need no
receipt. A member with no receipt keeps all of those and loses only the chat token until they agree on the consent page.
diff --git a/docs/passkeys.md b/docs/passkeys.md
new file mode 100644
index 0000000..6a04d07
--- /dev/null
+++ b/docs/passkeys.md
@@ -0,0 +1,133 @@
+# Passkeys: strong proof for unlinking a login
+
+A Heimdall-backed member can enrol WebAuthn passkeys on `/Membership/LinkedAccounts` and use one as the strong proof that unlinking a provider login needs. Bifrost verifies the passkey; Heimdall accepts Bifrost's word through its app-asserted step-up route (`POST /v1/apps/bifrost/step-up`, Heimdall `docs/service-contract.md`, `docs/app-profiles/bifrost.md`). Scoping and the option comparison are in the handoff `strong-proof-scoping-20261113.md` (option 1a with the S1 sink).
+
+## Scope
+
+- Accounts that have a `HeimdallAccountId`: the accounts that can unlink at all. A Bifrost-native-only account (a native `BifrostIdentity` or GitHub sign-in) has no logins to unlink and gets no passkeys from this cut; the page shows it nothing.
+- Unlink only. A passkey is not a sign-in method here.
+
+## The library: Fido2NetLib (`Fido2` 4.3.3)
+
+Decision: use `Fido2` 4.3.3 (NuGet id `Fido2`, repository `passwordless-lib/fido2-net-lib`) for every byte of WebAuthn parsing and verification. Bifrost hand-rolls no CBOR, COSE or signature code.
+
+What was checked on 2026-11-13, against the package and the repository, not from memory:
+
+| Question | Finding |
+|---|---|
+| Licence | MIT, in the nuspec (`MIT`) and in the repository's `LICENSE.txt` (GitHub reports `MIT`). Its closure: `Fido2.Models` MIT; `NSec.Cryptography` 25.4.0 MIT; `libsodium` 1.0.20.1 ISC; `System.Formats.Cbor` 9.0.24, `Microsoft.IdentityModel.JsonWebTokens` 8.2.0, `Microsoft.Extensions.Http` 9.0.0, `Microsoft.Bcl.Memory` 9.0.14 all Microsoft MIT. All open source. |
+| Maintained | Not archived; repository pushed 2026-11-11; 4.3.3 released 2026-11-11 and 4.3.2 on 2026-10-29; about 1,460 stars. |
+| net8.0 | The 4.3.3 nuspec has a `net8.0` dependency group (and `net10.0`); it targets the framework this project targets. |
+| Packed attestation | `Src/Fido2/AttestationFormat/` holds `Packed`, `None`, `FidoU2f`, `Tpm`, `AndroidKey`, `AndroidSafetyNet`, `Apple`, `AppleAppAttest`. Bifrost asks for `none` attestation and does not use a metadata service, so it does not depend on any of them being trusted; a client that sends another format still has it parsed and its statement verified structurally by the library. |
+| What verification covers | Read in `AuthenticatorAssertionResponse.cs`: challenge, origin (against `Fido2Configuration.Origins`), `webauthn.get` type, RP ID hash, user-present and user-verified flags (when required), signature over `authData || SHA-256(clientDataJSON)` with the stored COSE key, user handle ownership, and the sign count (see "Sign count" below). Enrolment verifies the attestation, the credential id and the key. |
+| Transitive weight | Heavier than the repository's other packages: `Microsoft.Extensions.Http` 9.0.0 pulls `Microsoft.Extensions.*` 9.0.0, so existing 8.x entries move to 9.0.0 (seven in `src/Bifrost.Web/packages.lock.json`; twelve `Microsoft.Extensions.*` entries plus `System.Diagnostics.DiagnosticSource` in the test project's lockfile, which sees them too; app-local on top of the net8 shared framework, a supported combination), and the lockfiles gain `Fido2`, `Fido2.Models`, `Microsoft.Bcl.Memory`, `Microsoft.Extensions.Http`, `Microsoft.Extensions.Diagnostics[.Abstractions]`, `Microsoft.Extensions.Configuration[.Binder]`, `System.Diagnostics.DiagnosticSource`, `Microsoft.Extensions.Options.ConfigurationExtensions`, `NSec.Cryptography`, `System.Formats.Cbor` and the native `libsodium` package (the Linux x64 glibc and musl binaries ship in the package's `runtimes/`). `Microsoft.IdentityModel.JsonWebTokens` is requested at 8.2.0 and already resolved to 8.19.2 (through OpenIddict) before this change; it still does. `packages.lock.json` in both projects is regenerated and committed. |
+| Alternatives | Not needed: the candidate passed. |
+
+Not verified: that the 9.0.0 `Microsoft.Extensions.*` assemblies behave on the live host's ASP.NET Core 8 runtime beyond the test host (the suite runs the real app under it); that `libsodium` loads on Yggdrasil (the EdDSA test loads it here, on Debian x64).
+
+The library is used through four calls: `RequestNewCredential`, `MakeNewCredentialAsync`, `GetAssertionOptions`, `MakeAssertionAsync`. `PasskeyRelyingParty` builds it from `Host:PublicBaseUrl`.
+
+## Sign count
+
+The stored sign count is updated on every successful assertion, and the library refuses a counter that does not increase once either side is non-zero. Authenticators that always report zero (most synced passkeys) are accepted every time and get no clone detection from this: both counters stay zero. An authenticator that reported a non-zero count and then reports zero is refused. Clone detection is therefore real only for hardware keys and other counting authenticators.
+
+## Relying party
+
+RP ID is the host of `Host:PublicBaseUrl`, the one origin is its scheme, host and port. They come from configuration and from nothing the browser sends. Passkeys are unavailable, with a warning logged once at start, when `Host:PublicBaseUrl` is not https or its host is not `Host:ExpectedHost`: the page offers none and every ceremony endpoint refuses (`passkeys_unavailable`). `PasskeyRelyingParty` is resolved at startup, so a misconfiguration is logged once at boot (not at the first ceremony). `Host:ExpectedHost` must be a bare host name: one with a port (`host:443`) or an IP address (`[::1]`, `127.0.0.1`) makes passkeys unavailable and is reported, because an IP address is not a valid RP ID and a port is not part of it. No new configuration key exists.
+
+If passkeys are unavailable while an account holds a strong passkey, the page shows no unlink form and says so: unlinking needs the passkey, the Google route stays closed (`passkey_required`), and the member can revoke their passkeys on the page (revoking does not need the relying party) to fall back to the Google proof, or wait for the operator to fix the server. This is a lockout until the operator or the member acts; it fails closed.
+
+## State
+
+- `PasskeyCredentials` (migration `20261113120000_AddPasskeyCredentials`, additive, applied at boot like the others): per `UserAccount` id, `CredentialId` (unique), `PublicKey`, `SignCount`, `Transports`, `AaGuid`, `Label`, `CreatedUtc`, `StrongFromUtc` (`CreatedUtc` + 48 h), `RevokedUtc`, `LastUsedUtc`. No secret exists to store: the private key never leaves the authenticator. Rows cascade with the account.
+- `PasskeyCeremonies` (in memory, this process only, like the Linked accounts list): the short-lived single-use records of the flows, each bound to a Heimdall account id and a kind (and to an identity id for unlink). A restart empties it and every flow is begun again; with more than one Bifrost instance a flow must finish on the instance that began it, otherwise it is refused and begun again. Both fail closed (a lost ticket, challenge or fact refuses; it never grants). It is chosen over a sealed cookie because a cookie cannot be spent: a copied cookie would replay.
+
+| Kind | Lifetime | Spent |
+|---|---|---|
+| enrolment ticket | 5 min | by the registration post |
+| enrolment challenge | 2 min | by the registration post |
+| unlink challenge | 2 min | by the assertion post (success or not) |
+| unlink assertion fact | 5 min | by the completion that asks Heimdall for the step-up |
+
+A challenge kind has one live record per account: a newer one replaces the older. The table holds at most 2048 records and refuses past that.
+
+A caller's own preconditions are checked before anything is spent. A registration needs the live ticket cookie (a session thief has none), a decodable body and room under the cap; an assertion needs a decodable body naming one of the session account's own strong, un-revoked credentials. Only then are the verification permit, the challenge and (for enrolment) the ticket taken. An assertion also needs a live challenge for that account and identity before a permit is spent. So junk posted by someone who holds only the session, naming no credential of the account or arriving with no live challenge, spends nothing. Junk naming one of the account's own credentials (the id is in `allowCredentials`) spends one verification permit per challenge that was asked for, because the first such post takes the challenge; it cannot drain the 20 permits per 10 minutes in one go. It can still burn that challenge once, and a session holder who keeps asking for challenges (an options permit each) and posting junk can exhaust both budgets: a lockout the same session already has through revoking passkeys, not a bypass. A junk post naming no credential of the account costs two cheap database lookups and no permit; that is accepted rather than spending an options-style permit on it. Both budgets are per process: with more than one instance each has its own. Asking for options spends a separate options budget (20 per 10 minutes), which a session holder can exhaust: that blocks new options for a while and nothing else. A session holder can also replace the member's pending challenge by asking for new options, which makes the member's assertion answer `passkey_expired` and the member tries again; that session can already revoke passkeys, so it is not a new capability. The member whose challenge was burned retries with a new one.
+
+## Enrolment
+
+1. The member is on the page with a current list (Bifrost will not guess a proof provider) and presses "Sign in again to add a passkey". Bifrost starts a fresh ordinary Heimdall sign-in through a provider the account holds (an attempt with purpose `EnrolProof`, the same machinery as the list and link proofs, `ExpectedAccountId` the session's account).
+2. In that sign-in's completion, when the proven account is the session's own, Bifrost issues an enrolment ticket and sets its id in `__Host-bifrost_passkey_ticket` (HttpOnly, Secure, 5 minutes). The ticket exists only because a fresh sign-in completed in this browser: a stolen session cookie alone has no ticket and cannot get registration options.
+3. The page's script asks for creation options (antiforgery header), calls `navigator.credentials.create` (user verification required, resident key preferred, `none` attestation, existing credentials excluded) and posts the base64url result. Bifrost spends the ticket and the challenge, verifies, and stores the credential with `StrongFromUtc` = now + 48 hours.
+
+A label is limited to 40 text elements (cut by rune and grapheme, never inside a surrogate pair) and loses control and format characters (bidi overrides, joiners, zero-width marks).
+
+Cap: five un-revoked passkeys per account (`passkey_limit`; a sixth starts no sign-in). Every options request, enrolment, assertion and enrolment start spends a permit of one `FixedWindowBudget` per account (20 per 10 minutes, `rate_limited`).
+
+## Cooling-off
+
+A passkey is strong from `StrongFromUtc` (at that instant and after), until revoked. Until then it is listed on the page with its time and cannot unlink anything. So someone who controls both a member's session and a provider login long enough to add a key of their own still waits 48 hours with the key visible, and the member can revoke it from the page. Revoking needs no strong proof (it only removes capability) and is shown.
+
+## Unlink with a passkey
+
+When the account has a strong passkey, the page's Unlink button runs a WebAuthn assertion instead of the Google step-up, and the Google route (`Unlink` handler) answers `passkey_required` and starts nothing: a member who holds a strong passkey is not offered the weaker proof. With no strong passkey the Google step-up stays as it was, and when neither exists the page says what to do (add a passkey, with the time a cooling-off one becomes strong).
+
+1. The script asks for request options for the chosen identity (`allowCredentials` is the account's strong passkeys; user verification required). One live challenge per account, bound to the identity.
+2. The browser's assertion is posted. Bifrost spends the challenge, requires the credential to be the session account's own, not revoked and past `StrongFromUtc`, and has the library verify origin, RP ID, challenge, user verification, signature and sign count. On success it records the new sign count and last use, and issues the single-use fact "passkey assertion verified" for this account and this identity (5 minutes; no credential, no bearer).
+3. Bifrost starts a fresh ordinary Heimdall sign-in for the account (attempt purpose `UnlinkPasskeyProof`; proof provider as on the page: one the current list shows, never a guess). The attempt carries the fact's id.
+4. In the completion, which is the only place the bearer exists: the fact is taken (missing, expired, spent, for another account or identity: no Heimdall step-up call and `passkey_expired`); the credential the fact was made with must still be the account's own, un-revoked and strong (a passkey revoked since the assertion: no step-up call, `passkey_failed`); the app secret, the bearer and `{method: "bifrost-passkey", nonce}` go to `POST /v1/apps/bifrost/step-up` (nonce: 32 fresh random bytes, base64url, 43 characters); the returned `accessToken` goes to the existing unlink call; everything is dropped. The bearer and the minted token are never stored, logged, put in a cookie or a redirect, or rendered.
+
+Heimdall's refusals are shown as closed codes and nothing is retried in the flow: `401 sign_in_required` is `sign_in_required`; `403`/`400`/`401 app_auth_required` is `step_up_unavailable`; `409 step_up_nonce_replayed` is `step_up_replayed`; `429` is `step_up_rate_limited`; anything else, or Heimdall down, is `error`. A member whose attempt ends this way starts the unlink again (a new assertion).
+
+## Abuse cases and what stops them
+
+Each is a test in `tests/Bifrost.Web.Tests/PasskeyTests.cs` unless noted.
+
+| Case | Defence |
+|---|---|
+| Stolen session cookie tries to enrol | No ticket without a fresh Heimdall sign-in completed in the victim's own browser. A ticket is per account, spent once, expires in 5 minutes, and is held by id in an HttpOnly cookie |
+| Stolen session tries to unlink | Needs an assertion by a strong passkey of the account; the Google route is closed while one exists; no step-up is asked of Heimdall without the fact |
+| Attacker who controls the provider session enrols their own key | Cooling-off: 48 hours before it counts, shown on the page, revocable by the member |
+| Replay of an assertion, double submit | The challenge is single-use; two concurrent posts start one sign-in |
+| Assertion for another account or identity | The credential must belong to the session's account; the challenge, the fact and the attempt are bound to the account and the chosen identity |
+| Phishing site | The library checks origin and RP ID hash against the configured values; a registration or assertion with another origin or RP ID is refused |
+| Cloned authenticator | A sign count that does not increase is refused; the stored count is updated on every use |
+| Cooling-off boundary | Strong at exactly `StrongFromUtc`, not one second before |
+| Revoked credential | Never strong; a revoke between challenge and assertion also refuses, and so does one between the assertion and the completion |
+| Junk from a session thief | Preconditions first, nothing spent before they hold (see State) |
+| No user verification | Required at enrolment and at assertion |
+| Cross-site POST | Antiforgery on every page POST including the JSON option requests |
+| Bearer anywhere | Only in the completion request's stack; tests look in logs (with HttpClient trace logging on), cookies, redirects, the page and the decrypted attempt |
+| Reused or replayed step-up | A fresh nonce each call; Heimdall's 409 is shown, not retried |
+| Brute force of ceremonies | One `FixedWindowBudget` per account |
+
+## Account-scoped lookup and the allow list
+
+An assertion is accepted only for a credential of the session's own account (strong, un-revoked), and the user handle, when the authenticator sends one, must be that account's id. The request options also carry the account's strong credentials as `allowCredentials`, which the library enforces, so a credential of another account is refused twice. The test for the account-scoped lookup (`The_credential_lookup_is_scoped_to_the_session_account_even_when_the_allow_list_is_empty`) takes the allow list out of the other account's challenge through the in-process ceremony store, which production code cannot do, so the lookup is exercised alone without weakening the server.
+
+## Content Security Policy
+
+Bifrost sends no `Content-Security-Policy` header (nothing in the application sets one; this predates passkeys). The passkey script is first-party and external so that a policy of `script-src 'self'` would admit it, but nothing enforces that today.
+
+## The script
+
+`wwwroot/js/passkeys.js` is first-party, loaded by the page with an external `src` (nothing inline, no third-party asset, no `eval`, no `innerHTML`). It asks for options with the antiforgery header, calls `navigator.credentials`, and submits a same-origin form of base64url strings (`id`, `rawId`, `attestationObject` or `authenticatorData`, `clientDataJson`, `signature`, `userHandle`, `transports`). On any failure it navigates to this page with a result code from a closed set; nothing from a response is shown. `PasskeyScriptTests` runs it under Node against a simulated browser and pins what it posts.
+
+## What it does not do
+
+- No passkey sign-in; passkeys prove an already signed-in session only.
+- No native-only accounts (no Heimdall account, nothing to unlink).
+- No recovery without mail: a member who loses every passkey revokes them and falls back to the Google step-up if a Google login is linked, or waits for the mail gate (`docs/registration-gates.md`) and the email-code factor that follows it. The email code is not built.
+- Named limit and next hardening: enrolling a second passkey should require an assertion by an existing strong passkey, and enrolment should use a Google step-up when a Google login is held. Today enrolment needs only the fresh ordinary sign-in and the cooling-off, so an attacker who controls a provider session can add a key that becomes strong after 48 hours unless the member sees and revokes it. Not built; a follow-up is filed.
+- A revoke between the completion's check and its unlink does not stop that unlink: the window is the few milliseconds of the two Heimdall calls and is inherent to checking before acting.
+- Revoking needs no strong proof, so a stolen session can revoke a member's passkeys and fall back to the Google proof: no weaker than the account was before it had a passkey.
+- A passkey synced through a cloud account the attacker also controls is a residual risk, as in the scoping note.
+- Heimdall cannot tell that a passkey was checked: `bifrost-passkey` is Bifrost's word, gated by the app secret and a live bearer (Heimdall `docs/app-profiles/bifrost.md`).
+- Not verified here: a real authenticator or browser. Tests use a software authenticator built from the WebAuthn specification and the script runs under Node against a simulated browser.
+
+## Where the code is
+
+- `Features/Passkeys/PasskeyService.cs`: enrol, assert, revoke, list; `PasskeyCeremonies.cs`: the single-use records and the rate limit; `PasskeyRelyingParty.cs`: RP ID, origin, library construction.
+- `Features/Heimdall/HeimdallAuthService.cs`: the `EnrolProof` and `UnlinkPasskeyProof` attempts, `StepUpAsync`.
+- `Pages/Membership/LinkedAccounts.cshtml[.cs]`, `wwwroot/js/passkeys.js`.
+- `Domain/BifrostModels.cs` (`PasskeyCredential`), `Data/Migrations/20261113120000_AddPasskeyCredentials.cs`.
+- Tests: `PasskeyTests.cs`, `PasskeyScriptTests.cs`, `Support/SoftwareAuthenticator.cs`, and the step-up route of the fake Heimdall in `Support/HeimdallTestKit.cs`.
diff --git a/src/Bifrost.Web/Bifrost.Web.csproj b/src/Bifrost.Web/Bifrost.Web.csproj
index f69b885..a9c77cf 100644
--- a/src/Bifrost.Web/Bifrost.Web.csproj
+++ b/src/Bifrost.Web/Bifrost.Web.csproj
@@ -7,11 +7,14 @@
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
+
diff --git a/src/Bifrost.Web/Configuration/BridgeOptions.cs b/src/Bifrost.Web/Configuration/BridgeOptions.cs
deleted file mode 100644
index 2d90eae..0000000
--- a/src/Bifrost.Web/Configuration/BridgeOptions.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace Bifrost.Web.Configuration;
-
-public sealed class BridgeOptions
-{
- public const string SectionName = "Bridge";
-
- public string LocalBridgeToken { get; init; } = string.Empty;
-
- public bool HasLocalBridgeToken => !string.IsNullOrWhiteSpace(LocalBridgeToken);
-}
diff --git a/src/Bifrost.Web/Configuration/HeimdallOptions.cs b/src/Bifrost.Web/Configuration/HeimdallOptions.cs
index 01eaec9..2dda782 100644
--- a/src/Bifrost.Web/Configuration/HeimdallOptions.cs
+++ b/src/Bifrost.Web/Configuration/HeimdallOptions.cs
@@ -14,7 +14,11 @@ public sealed class HeimdallOptions
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
- public string AppSecret { get; init; } = string.Empty;
+ /// Deprecated: rides in the process environment. Use ; the file wins when both are set.
+ public string AppSecret { get; set; } = string.Empty;
+
+ /// Path of a file holding the app secret (systemd LoadCredential style: %d/heimdall-app-secret).
+ public string AppSecretFile { get; init; } = string.Empty;
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
@@ -39,4 +43,37 @@ public sealed class HeimdallOptions
IsConfigured &&
EnablePatronSupportIntake &&
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
+
+ ///
+ /// Resolves once, when the options are built. A set must be a
+ /// readable, non-empty file, or startup fails; the message names the option and path, never a secret.
+ ///
+ public static void ResolveAppSecret(HeimdallOptions options, ILogger logger)
+ {
+ if (!string.IsNullOrWhiteSpace(options.AppSecret))
+ {
+ logger.LogWarning("Heimdall:AppSecret is deprecated: it rides in the process environment. Use Heimdall:AppSecretFile, which wins when both are set.");
+ }
+
+ if (!string.IsNullOrWhiteSpace(options.AppSecretFile))
+ {
+ string secret;
+ try
+ {
+ secret = File.ReadAllText(options.AppSecretFile).TrimEnd('\r', '\n');
+ }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ throw new InvalidOperationException(
+ $"Heimdall:AppSecretFile must name a readable file; '{options.AppSecretFile}' could not be read ({error.GetType().Name}).");
+ }
+
+ if (string.IsNullOrWhiteSpace(secret))
+ {
+ throw new InvalidOperationException($"Heimdall:AppSecretFile '{options.AppSecretFile}' is empty.");
+ }
+
+ options.AppSecret = secret;
+ }
+ }
}
diff --git a/src/Bifrost.Web/Data/BifrostDbContext.cs b/src/Bifrost.Web/Data/BifrostDbContext.cs
index d227c42..21c4f40 100644
--- a/src/Bifrost.Web/Data/BifrostDbContext.cs
+++ b/src/Bifrost.Web/Data/BifrostDbContext.cs
@@ -19,7 +19,7 @@ public sealed class BifrostDbContext(DbContextOptions options)
public DbSet TierSnapshots => Set();
- public DbSet MembershipInvitations => Set();
+ public DbSet ChatInvites => Set();
public DbSet Projects => Set();
@@ -45,6 +45,7 @@ public sealed class BifrostDbContext(DbContextOptions options)
public DbSet ConsentReceipts => Set();
public DbSet MindKeys => Set();
+ public DbSet PasskeyCredentials => Set();
public DbSet MindNonces => Set();
@@ -136,23 +137,30 @@ public sealed class BifrostDbContext(DbContextOptions options)
entity.Property(x => x.Label).HasMaxLength(120);
entity.Property(x => x.Weight).HasPrecision(18, 2);
entity.HasIndex(x => new { x.MembershipId, x.Kind, x.IsCurrent });
+ entity.HasIndex(x => x.MembershipId)
+ .IsUnique()
+ .HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
+ .HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
entity.HasOne(x => x.Membership)
.WithMany(x => x.TierSnapshots)
.HasForeignKey(x => x.MembershipId);
});
- modelBuilder.Entity(entity =>
+ modelBuilder.Entity(entity =>
{
- entity.HasIndex(x => x.NormalizedGitHubLogin).IsUnique();
- entity.Property(x => x.GitHubLogin).HasMaxLength(120);
- entity.Property(x => x.NormalizedGitHubLogin).HasMaxLength(120);
- entity.HasOne(x => x.IssuedByUserAccount)
+ entity.HasIndex(x => x.TokenHash).IsUnique();
+ entity.Property(x => x.TokenHash).HasMaxLength(64);
+ entity.Property(x => x.Note).HasMaxLength(500);
+ // The single-use fact: a redemption saves `WHERE RedeemedAtUtc IS NULL`, so of two racing accounts one save loses.
+ entity.Property(x => x.RedeemedAtUtc).IsConcurrencyToken();
+ entity.Property(x => x.RevokedAtUtc).IsConcurrencyToken();
+ entity.HasOne()
.WithMany()
.HasForeignKey(x => x.IssuedByUserAccountId)
.OnDelete(DeleteBehavior.SetNull);
- entity.HasOne(x => x.AcceptedByUserAccount)
+ entity.HasOne()
.WithMany()
- .HasForeignKey(x => x.AcceptedByUserAccountId)
+ .HasForeignKey(x => x.RedeemedByUserAccountId)
.OnDelete(DeleteBehavior.SetNull);
});
@@ -333,6 +341,16 @@ public sealed class BifrostDbContext(DbContextOptions options)
.OnDelete(DeleteBehavior.Cascade);
});
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasIndex(x => x.CredentialId).IsUnique();
+ entity.HasIndex(x => x.UserAccountId);
+ entity.HasOne(x => x.UserAccount)
+ .WithMany()
+ .HasForeignKey(x => x.UserAccountId)
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
modelBuilder.Entity(entity =>
{
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
diff --git a/src/Bifrost.Web/Data/Migrations/20261113120000_AddPasskeyCredentials.cs b/src/Bifrost.Web/Data/Migrations/20261113120000_AddPasskeyCredentials.cs
new file mode 100644
index 0000000..fd1c2e0
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261113120000_AddPasskeyCredentials.cs
@@ -0,0 +1,48 @@
+using System;
+using Bifrost.Web.Data;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ // Hand-written like AddConsentReceipts: no dotnet-ef on the authoring host; the snapshot was edited to match. Additive only.
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261113120000_AddPasskeyCredentials")]
+ public partial class AddPasskeyCredentials : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "PasskeyCredentials",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ UserAccountId = table.Column(type: "uuid", nullable: false),
+ CredentialId = table.Column(type: "bytea", nullable: false),
+ PublicKey = table.Column(type: "bytea", nullable: false),
+ SignCount = table.Column(type: "bigint", nullable: false),
+ Transports = table.Column(type: "text", nullable: false),
+ AaGuid = table.Column(type: "uuid", nullable: true),
+ Label = table.Column(type: "text", nullable: false),
+ CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ StrongFromUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ RevokedUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ LastUsedUtc = table.Column(type: "timestamp with time zone", nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_PasskeyCredentials", x => x.Id);
+ table.ForeignKey("FK_PasskeyCredentials_UserAccounts_UserAccountId", x => x.UserAccountId, "UserAccounts", "Id", onDelete: ReferentialAction.Cascade);
+ });
+ migrationBuilder.CreateIndex(name: "IX_PasskeyCredentials_CredentialId", table: "PasskeyCredentials", column: "CredentialId", unique: true);
+ migrationBuilder.CreateIndex(name: "IX_PasskeyCredentials_UserAccountId", table: "PasskeyCredentials", column: "UserAccountId");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(name: "PasskeyCredentials");
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/20261114120000_AddAccountMerges.cs b/src/Bifrost.Web/Data/Migrations/20261114120000_AddAccountMerges.cs
new file mode 100644
index 0000000..7cd6143
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261114120000_AddAccountMerges.cs
@@ -0,0 +1,216 @@
+using System;
+using Bifrost.Web.Data;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ // Scaffolded by IMigrationsScaffolder against the previous snapshot (no dotnet-ef on the authoring host), the designer file dropped and
+ // the snapshot edited by hand to match, like AddPasskeyCredentials. Additive only; Down drops what Up adds.
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261114120000_AddAccountMerges")]
+ public partial class AddAccountMerges : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "VoidedByMergeId",
+ table: "Votes",
+ type: "uuid",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "VoidedUtc",
+ table: "Votes",
+ type: "timestamp with time zone",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "VoidedByMergeId",
+ table: "ConceptAppraisals",
+ type: "uuid",
+ nullable: true);
+
+ migrationBuilder.AddColumn(
+ name: "VoidedUtc",
+ table: "ConceptAppraisals",
+ type: "timestamp with time zone",
+ nullable: true);
+
+ migrationBuilder.CreateTable(
+ name: "AccountMerges",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ State = table.Column(type: "character varying(24)", maxLength: 24, nullable: false),
+ SurvivorUserAccountId = table.Column(type: "uuid", nullable: false),
+ FoldedUserAccountId = table.Column(type: "uuid", nullable: false),
+ CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ CommittedUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ GraceEndsUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ FinalizedUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ UndoneUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ FailedUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ FailureCode = table.Column(type: "character varying(64)", maxLength: 64, nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_AccountMerges", x => x.Id);
+ table.ForeignKey(
+ name: "FK_AccountMerges_UserAccounts_FoldedUserAccountId",
+ column: x => x.FoldedUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ table.ForeignKey(
+ name: "FK_AccountMerges_UserAccounts_SurvivorUserAccountId",
+ column: x => x.SurvivorUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "AccountMergeEntries",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ MergeId = table.Column(type: "uuid", nullable: false),
+ Seq = table.Column(type: "integer", nullable: false),
+ Kind = table.Column(type: "character varying(24)", maxLength: 24, nullable: false),
+ RecordId = table.Column(type: "uuid", nullable: false),
+ Action = table.Column(type: "character varying(24)", maxLength: 24, nullable: false),
+ PriorUserAccountId = table.Column(type: "uuid", nullable: true),
+ PriorText = table.Column(type: "character varying(120)", maxLength: 120, nullable: true),
+ PriorAtUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ AtUtc = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_AccountMergeEntries", x => x.Id);
+ table.ForeignKey(
+ name: "FK_AccountMergeEntries_AccountMerges_MergeId",
+ column: x => x.MergeId,
+ principalTable: "AccountMerges",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMergeEntries_MergeId_Seq",
+ table: "AccountMergeEntries",
+ columns: new[] { "MergeId", "Seq" },
+ unique: true);
+
+ migrationBuilder.CreateIndex(
+ name: "UX_AccountMerges_FoldedUserAccountId_Live",
+ table: "AccountMerges",
+ column: "FoldedUserAccountId",
+ unique: true,
+ filter: "\"State\" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMerges_FoldedUserAccountId_State",
+ table: "AccountMerges",
+ columns: new[] { "FoldedUserAccountId", "State" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMerges_State_GraceEndsUtc",
+ table: "AccountMerges",
+ columns: new[] { "State", "GraceEndsUtc" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMerges_SurvivorUserAccountId_State",
+ table: "AccountMerges",
+ columns: new[] { "SurvivorUserAccountId", "State" });
+
+ // One current Patron snapshot per membership: two restages racing (two merges into one survivor, a merge and an intake) would
+ // each demote the old row and add their own, and EffectiveVotingWeight sums the current ones. A pre-existing duplicate keeps
+ // only its newest row current so the index can be built.
+ migrationBuilder.Sql(@"
+UPDATE ""TierSnapshots"" t SET ""IsCurrent"" = false
+WHERE t.""Kind"" = 'Patron' AND t.""IsCurrent"" AND EXISTS (
+ SELECT 1 FROM ""TierSnapshots"" o
+ WHERE o.""MembershipId"" = t.""MembershipId"" AND o.""Kind"" = 'Patron' AND o.""IsCurrent""
+ AND (o.""CapturedAtUtc"" > t.""CapturedAtUtc"" OR (o.""CapturedAtUtc"" = t.""CapturedAtUtc"" AND o.""Id"" > t.""Id"")));");
+
+ migrationBuilder.CreateIndex(
+ name: "UX_TierSnapshots_MembershipId_CurrentPatron",
+ table: "TierSnapshots",
+ column: "MembershipId",
+ unique: true,
+ filter: "\"Kind\" = 'Patron' AND \"IsCurrent\"");
+
+ // The cross-role guard no single unique index can express: a live merge's survivor is never another live merge's folded
+ // account (no chains), whichever order they arrive in. Advisory locks on both accounts, taken in a fixed order, serialise two
+ // transactions racing over the same account, so the second one's check sees the first's committed row.
+ migrationBuilder.Sql(@"
+CREATE FUNCTION ""AccountMerges_refuse_chain""() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF NEW.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed') THEN
+ PERFORM pg_advisory_xact_lock(hashtextextended(LEAST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
+ PERFORM pg_advisory_xact_lock(hashtextextended(GREATEST(NEW.""SurvivorUserAccountId""::text, NEW.""FoldedUserAccountId""::text), 0));
+ IF EXISTS (
+ SELECT 1 FROM ""AccountMerges"" m
+ WHERE m.""Id"" <> NEW.""Id""
+ AND m.""State"" IN ('Confirmed', 'HeimdallMoved', 'Committed', 'Final', 'UndoRequested', 'HeimdallReversed')
+ AND (m.""SurvivorUserAccountId"" = NEW.""FoldedUserAccountId"" OR m.""FoldedUserAccountId"" = NEW.""SurvivorUserAccountId""))
+ THEN
+ RAISE EXCEPTION 'account merge chain refused' USING ERRCODE = '23P01';
+ END IF;
+ END IF;
+ RETURN NEW;
+END
+$$;
+CREATE TRIGGER ""AccountMerges_refuse_chain"" BEFORE INSERT OR UPDATE OF ""State"", ""SurvivorUserAccountId"", ""FoldedUserAccountId"" ON ""AccountMerges""
+ FOR EACH ROW EXECUTE FUNCTION ""AccountMerges_refuse_chain""();");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ // Roll-forward only (heimdall-body:ruling:merge-roll-forward-only): once any merge exists the Merged membership status
+ // cannot be read by an older build, and voided votes and appraisals would be counted again. Refuse while any merge row
+ // exists; see docs/account-merge.md (Rollback).
+ migrationBuilder.Sql(@"
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM ""AccountMerges"") THEN
+ RAISE EXCEPTION 'AddAccountMerges cannot be reverted once an account merge exists: Bifrost is roll-forward only';
+ END IF;
+END
+$$;");
+
+ migrationBuilder.DropIndex(
+ name: "UX_TierSnapshots_MembershipId_CurrentPatron",
+ table: "TierSnapshots");
+
+ migrationBuilder.Sql(@"DROP TRIGGER ""AccountMerges_refuse_chain"" ON ""AccountMerges""; DROP FUNCTION ""AccountMerges_refuse_chain""();");
+
+ migrationBuilder.DropTable(
+ name: "AccountMergeEntries");
+
+ migrationBuilder.DropTable(
+ name: "AccountMerges");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedByMergeId",
+ table: "Votes");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedUtc",
+ table: "Votes");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedByMergeId",
+ table: "ConceptAppraisals");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedUtc",
+ table: "ConceptAppraisals");
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/20261114130000_AddAccountMergeSaga.cs b/src/Bifrost.Web/Data/Migrations/20261114130000_AddAccountMergeSaga.cs
new file mode 100644
index 0000000..cb0b5fb
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261114130000_AddAccountMergeSaga.cs
@@ -0,0 +1,78 @@
+using System;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ // Hand-written like AddAccountMerges, the snapshot edited to match. Additive: the saga's columns on AccountMerges. Down is
+ // roll-forward only, like AddAccountMerges: it drops the Heimdall idempotency keys and the consent record, so it refuses while
+ // any merge row exists (heimdall-body:ruling:merge-roll-forward-only).
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261114130000_AddAccountMergeSaga")]
+ public partial class AddAccountMergeSaga : Migration
+ {
+ private static readonly string[] Columns =
+ [
+ "HeimdallMoveId", "HeimdallReverseMoveId", "SealedProofs", "PreviewDigest", "ConfirmedByUserAccountId", "ConfirmedUtc",
+ "SurvivorProofProvider", "FoldedProofProviders", "ProofFromTier", "ProofToTier", "MovedIdentityIds", "Attempts",
+ "NextAttemptUtc", "LastOutcome", "UndoRequestedUtc", "ReversedUtc"
+ ];
+
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(name: "HeimdallMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
+ migrationBuilder.AddColumn(name: "HeimdallReverseMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
+ migrationBuilder.AddColumn(name: "SealedProofs", table: "AccountMerges", type: "text", nullable: true);
+ migrationBuilder.AddColumn(name: "PreviewDigest", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
+ migrationBuilder.AddColumn(name: "ConfirmedByUserAccountId", table: "AccountMerges", type: "uuid", nullable: true);
+ migrationBuilder.AddColumn(name: "ConfirmedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
+ migrationBuilder.AddColumn(name: "SurvivorProofProvider", table: "AccountMerges", type: "character varying(32)", maxLength: 32, nullable: false, defaultValue: "");
+ migrationBuilder.AddColumn(name: "FoldedProofProviders", table: "AccountMerges", type: "character varying(120)", maxLength: 120, nullable: false, defaultValue: "");
+ migrationBuilder.AddColumn(name: "ProofFromTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
+ migrationBuilder.AddColumn(name: "ProofToTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
+ migrationBuilder.AddColumn(name: "MovedIdentityIds", table: "AccountMerges", type: "text", nullable: true);
+ migrationBuilder.AddColumn(name: "Attempts", table: "AccountMerges", type: "integer", nullable: false, defaultValue: 0);
+ migrationBuilder.AddColumn(name: "NextAttemptUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
+ migrationBuilder.AddColumn(name: "LastOutcome", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
+ migrationBuilder.AddColumn(name: "UndoRequestedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
+ migrationBuilder.AddColumn(name: "ReversedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMerges_HeimdallMoveId",
+ table: "AccountMerges",
+ column: "HeimdallMoveId",
+ unique: true,
+ filter: "\"HeimdallMoveId\" IS NOT NULL");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_AccountMerges_HeimdallReverseMoveId",
+ table: "AccountMerges",
+ column: "HeimdallReverseMoveId",
+ unique: true,
+ filter: "\"HeimdallReverseMoveId\" IS NOT NULL");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.Sql(@"
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM ""AccountMerges"") THEN
+ RAISE EXCEPTION 'AddAccountMergeSaga cannot be reverted once an account merge exists: Bifrost is roll-forward only';
+ END IF;
+END
+$$;");
+
+ migrationBuilder.DropIndex(name: "IX_AccountMerges_HeimdallMoveId", table: "AccountMerges");
+ migrationBuilder.DropIndex(name: "IX_AccountMerges_HeimdallReverseMoveId", table: "AccountMerges");
+ foreach (var column in Columns)
+ {
+ migrationBuilder.DropColumn(name: column, table: "AccountMerges");
+ }
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/20261114140000_AddAccountMergeNoticeAcks.cs b/src/Bifrost.Web/Data/Migrations/20261114140000_AddAccountMergeNoticeAcks.cs
new file mode 100644
index 0000000..20e53c7
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261114140000_AddAccountMergeNoticeAcks.cs
@@ -0,0 +1,45 @@
+using System;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ // Hand-written like AddAccountMergeSaga (no dotnet-ef on the authoring host), the snapshot edited to match. Additive: one table of
+ // acks, the only fact a notice reader adds; the notices themselves are derived from AccountMerges. Down may drop it: it holds only acks.
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261114140000_AddAccountMergeNoticeAcks")]
+ public partial class AddAccountMergeNoticeAcks : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "AccountMergeNoticeAcks",
+ columns: table => new
+ {
+ MergeId = table.Column(type: "uuid", nullable: false),
+ Kind = table.Column(type: "character varying(16)", maxLength: 16, nullable: false),
+ Target = table.Column(type: "character varying(16)", maxLength: 16, nullable: false),
+ AckedUtc = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_AccountMergeNoticeAcks", x => new { x.MergeId, x.Kind, x.Target });
+ table.ForeignKey(
+ name: "FK_AccountMergeNoticeAcks_AccountMerges_MergeId",
+ column: x => x.MergeId,
+ principalTable: "AccountMerges",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(name: "AccountMergeNoticeAcks");
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/20261127120000_AddChatInvites.cs b/src/Bifrost.Web/Data/Migrations/20261127120000_AddChatInvites.cs
new file mode 100644
index 0000000..576770c
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261127120000_AddChatInvites.cs
@@ -0,0 +1,105 @@
+using System;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ // Hand-written like AddAccountMergeNoticeAcks (no dotnet-ef on the authoring host), the snapshot edited to match.
+ // MembershipInvitations (keyed to a GitHub login, matched only on a GitHub sign-in) is dropped: the live table held zero rows
+ // when this was written (read 2026-11-27 on the production database), so nothing is carried over. Down recreates the empty table.
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261127120000_AddChatInvites")]
+ public partial class AddChatInvites : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(name: "MembershipInvitations");
+
+ migrationBuilder.AddColumn(
+ name: "ChatInvitedAtUtc",
+ table: "UserAccounts",
+ type: "timestamp with time zone",
+ nullable: true);
+
+ migrationBuilder.CreateTable(
+ name: "ChatInvites",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ TokenHash = table.Column(type: "character varying(64)", maxLength: 64, nullable: false),
+ Note = table.Column(type: "character varying(500)", maxLength: 500, nullable: false),
+ IssuedByUserAccountId = table.Column(type: "uuid", nullable: true),
+ IssuedAtUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ ExpiresAtUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ RedeemedByUserAccountId = table.Column(type: "uuid", nullable: true),
+ RedeemedAtUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ RevokedAtUtc = table.Column(type: "timestamp with time zone", nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ChatInvites", x => x.Id);
+ table.ForeignKey(
+ name: "FK_ChatInvites_UserAccounts_IssuedByUserAccountId",
+ column: x => x.IssuedByUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.SetNull);
+ table.ForeignKey(
+ name: "FK_ChatInvites_UserAccounts_RedeemedByUserAccountId",
+ column: x => x.RedeemedByUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.SetNull);
+ });
+
+ migrationBuilder.CreateIndex(name: "IX_ChatInvites_IssuedByUserAccountId", table: "ChatInvites", column: "IssuedByUserAccountId");
+ migrationBuilder.CreateIndex(name: "IX_ChatInvites_RedeemedByUserAccountId", table: "ChatInvites", column: "RedeemedByUserAccountId");
+ migrationBuilder.CreateIndex(name: "IX_ChatInvites_TokenHash", table: "ChatInvites", column: "TokenHash", unique: true);
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(name: "ChatInvites");
+ migrationBuilder.DropColumn(name: "ChatInvitedAtUtc", table: "UserAccounts");
+
+ migrationBuilder.CreateTable(
+ name: "MembershipInvitations",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ GitHubLogin = table.Column(type: "character varying(120)", maxLength: 120, nullable: false),
+ NormalizedGitHubLogin = table.Column(type: "character varying(120)", maxLength: 120, nullable: false),
+ IssuedByUserAccountId = table.Column(type: "uuid", nullable: true),
+ AcceptedByUserAccountId = table.Column(type: "uuid", nullable: true),
+ IssuedAtUtc = table.Column(type: "timestamp with time zone", nullable: false),
+ AcceptedAtUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ RevokedAtUtc = table.Column(type: "timestamp with time zone", nullable: true),
+ Notes = table.Column(type: "text", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_MembershipInvitations", x => x.Id);
+ table.ForeignKey(
+ name: "FK_MembershipInvitations_UserAccounts_AcceptedByUserAccountId",
+ column: x => x.AcceptedByUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.SetNull);
+ table.ForeignKey(
+ name: "FK_MembershipInvitations_UserAccounts_IssuedByUserAccountId",
+ column: x => x.IssuedByUserAccountId,
+ principalTable: "UserAccounts",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.SetNull);
+ });
+
+ migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_AcceptedByUserAccountId", table: "MembershipInvitations", column: "AcceptedByUserAccountId");
+ migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_IssuedByUserAccountId", table: "MembershipInvitations", column: "IssuedByUserAccountId");
+ migrationBuilder.CreateIndex(name: "IX_MembershipInvitations_NormalizedGitHubLogin", table: "MembershipInvitations", column: "NormalizedGitHubLogin", unique: true);
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/20261203120000_DropAccountMergeTables.cs b/src/Bifrost.Web/Data/Migrations/20261203120000_DropAccountMergeTables.cs
new file mode 100644
index 0000000..4ba5e21
--- /dev/null
+++ b/src/Bifrost.Web/Data/Migrations/20261203120000_DropAccountMergeTables.cs
@@ -0,0 +1,56 @@
+using System;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Bifrost.Web.Data.Migrations
+{
+ [DbContext(typeof(BifrostDbContext))]
+ [Migration("20261203120000_DropAccountMergeTables")]
+ public partial class DropAccountMergeTables : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.Sql(@"
+DO $$
+DECLARE
+ has_rows boolean;
+BEGIN
+ IF to_regclass('public.""AccountMerges""') IS NOT NULL THEN
+ EXECUTE 'SELECT EXISTS (SELECT 1 FROM ""AccountMerges"")' INTO has_rows;
+ IF has_rows THEN
+ RAISE EXCEPTION 'DropAccountMergeTables refused: AccountMerges is non-empty';
+ END IF;
+ DROP TRIGGER IF EXISTS ""AccountMerges_refuse_chain"" ON ""AccountMerges"";
+ END IF;
+END
+$$;
+DROP TABLE IF EXISTS ""AccountMergeNoticeAcks"", ""AccountMergeEntries"", ""AccountMerges"";
+DROP FUNCTION IF EXISTS ""AccountMerges_refuse_chain""();");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedByMergeId",
+ table: "Votes");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedUtc",
+ table: "Votes");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedByMergeId",
+ table: "ConceptAppraisals");
+
+ migrationBuilder.DropColumn(
+ name: "VoidedUtc",
+ table: "ConceptAppraisals");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ throw new NotSupportedException("AccountMerge teardown is one-way (heimdall-body:ruling:manual-merges-teardown-saga).");
+ }
+ }
+}
diff --git a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs
index 042e2f0..177f21c 100644
--- a/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs
+++ b/src/Bifrost.Web/Data/Migrations/BifrostDbContextModelSnapshot.cs
@@ -835,51 +835,52 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("Memberships");
});
- modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
+ modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
{
b.Property("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
- b.Property("AcceptedAtUtc")
+ b.Property("ExpiresAtUtc")
.HasColumnType("timestamp with time zone");
- b.Property("AcceptedByUserAccountId")
- .HasColumnType("uuid");
-
- b.Property("GitHubLogin")
- .IsRequired()
- .HasMaxLength(120)
- .HasColumnType("character varying(120)");
-
b.Property("IssuedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property("IssuedByUserAccountId")
.HasColumnType("uuid");
- b.Property("NormalizedGitHubLogin")
+ b.Property("Note")
.IsRequired()
- .HasMaxLength(120)
- .HasColumnType("character varying(120)");
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)");
- b.Property("Notes")
- .IsRequired()
- .HasColumnType("text");
+ b.Property("RedeemedAtUtc")
+ .IsConcurrencyToken()
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("RedeemedByUserAccountId")
+ .HasColumnType("uuid");
b.Property("RevokedAtUtc")
+ .IsConcurrencyToken()
.HasColumnType("timestamp with time zone");
+ b.Property("TokenHash")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("character varying(64)");
+
b.HasKey("Id");
- b.HasIndex("AcceptedByUserAccountId");
-
b.HasIndex("IssuedByUserAccountId");
- b.HasIndex("NormalizedGitHubLogin")
+ b.HasIndex("RedeemedByUserAccountId");
+
+ b.HasIndex("TokenHash")
.IsUnique();
- b.ToTable("MembershipInvitations");
+ b.ToTable("ChatInvites");
});
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
@@ -1336,6 +1337,11 @@ namespace Bifrost.Web.Data.Migrations
b.HasIndex("MembershipId", "Kind", "IsCurrent");
+ b.HasIndex("MembershipId")
+ .IsUnique()
+ .HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
+ .HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
+
b.ToTable("TierSnapshots");
});
@@ -1355,6 +1361,9 @@ namespace Bifrost.Web.Data.Migrations
.HasMaxLength(120)
.HasColumnType("character varying(120)");
+ b.Property("ChatInvitedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
b.Property("CreatedAtUtc")
.HasColumnType("timestamp with time zone");
@@ -1470,6 +1479,59 @@ namespace Bifrost.Web.Data.Migrations
b.ToTable("ConsentReceipts");
});
+ modelBuilder.Entity("Bifrost.Web.Domain.PasskeyCredential", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AaGuid")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CredentialId")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property("Label")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("LastUsedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("PublicKey")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property("RevokedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("SignCount")
+ .HasColumnType("bigint");
+
+ b.Property("StrongFromUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Transports")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("UserAccountId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CredentialId")
+ .IsUnique();
+
+ b.HasIndex("UserAccountId");
+
+ b.ToTable("PasskeyCredentials");
+ });
+
modelBuilder.Entity("Bifrost.Web.Domain.MindKey", b =>
{
b.Property("Id")
@@ -2183,6 +2245,17 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("UserAccount");
});
+ modelBuilder.Entity("Bifrost.Web.Domain.PasskeyCredential", b =>
+ {
+ b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
+ .WithMany()
+ .HasForeignKey("UserAccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("UserAccount");
+ });
+
modelBuilder.Entity("Bifrost.Web.Domain.MemberProfile", b =>
{
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
@@ -2205,21 +2278,17 @@ namespace Bifrost.Web.Data.Migrations
b.Navigation("UserAccount");
});
- modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
+ modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
{
- b.HasOne("Bifrost.Web.Domain.UserAccount", "AcceptedByUserAccount")
- .WithMany()
- .HasForeignKey("AcceptedByUserAccountId")
- .OnDelete(DeleteBehavior.SetNull);
-
- b.HasOne("Bifrost.Web.Domain.UserAccount", "IssuedByUserAccount")
+ b.HasOne("Bifrost.Web.Domain.UserAccount", null)
.WithMany()
.HasForeignKey("IssuedByUserAccountId")
.OnDelete(DeleteBehavior.SetNull);
- b.Navigation("AcceptedByUserAccount");
-
- b.Navigation("IssuedByUserAccount");
+ b.HasOne("Bifrost.Web.Domain.UserAccount", null)
+ .WithMany()
+ .HasForeignKey("RedeemedByUserAccountId")
+ .OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
diff --git a/src/Bifrost.Web/Domain/BifrostModels.cs b/src/Bifrost.Web/Domain/BifrostModels.cs
index 00e3f9c..d3c0f5e 100644
--- a/src/Bifrost.Web/Domain/BifrostModels.cs
+++ b/src/Bifrost.Web/Domain/BifrostModels.cs
@@ -264,6 +264,9 @@ public sealed class UserAccount
public DateTimeOffset LastSeenAtUtc { get; set; }
+ /// When a chat invite was redeemed onto this account. Bifrost's OIDC issuer reads it (or Active membership) to decide who gets a chat token.
+ public DateTimeOffset? ChatInvitedAtUtc { get; set; }
+
public MemberProfile? MemberProfile { get; set; }
public Membership? Membership { get; set; }
@@ -407,29 +410,30 @@ public sealed class TierSnapshot
public Membership Membership { get; set; } = null!;
}
-public sealed class MembershipInvitation
+///
+/// An operator-minted, single-use invitation to chat. The link carries a 32-byte random token; only its SHA-256 is stored.
+/// Redeemed onto the account that signs in carrying it (UserAccount.ChatInvitedAtUtc); Bifrost's OIDC issuer reads that fact.
+///
+public sealed class ChatInvite
{
public Guid Id { get; set; } = Guid.NewGuid();
- public string GitHubLogin { get; set; } = string.Empty;
+ /// Lowercase hex SHA-256 of the token; the token itself is shown once at minting and never stored.
+ public string TokenHash { get; set; } = string.Empty;
- public string NormalizedGitHubLogin { get; set; } = string.Empty;
+ public string Note { get; set; } = string.Empty;
public Guid? IssuedByUserAccountId { get; set; }
- public Guid? AcceptedByUserAccountId { get; set; }
-
public DateTimeOffset IssuedAtUtc { get; set; }
- public DateTimeOffset? AcceptedAtUtc { get; set; }
+ public DateTimeOffset ExpiresAtUtc { get; set; }
+
+ public Guid? RedeemedByUserAccountId { get; set; }
+
+ public DateTimeOffset? RedeemedAtUtc { get; set; }
public DateTimeOffset? RevokedAtUtc { get; set; }
-
- public string Notes { get; set; } = string.Empty;
-
- public UserAccount? IssuedByUserAccount { get; set; }
-
- public UserAccount? AcceptedByUserAccount { get; set; }
}
public sealed class Project
@@ -1177,6 +1181,41 @@ public sealed class ConsentReceipt
public UserAccount? UserAccount { get; set; }
}
+///
+/// A WebAuthn passkey a Heimdall-backed member enrolled (docs/passkeys.md). Holds only what verifying an assertion needs:
+/// the credential id, the public key and the sign count. No secret exists to hold. It counts as strong proof only from
+/// (the cooling-off after enrolment) and only while not revoked.
+///
+public sealed class PasskeyCredential
+{
+ public Guid Id { get; set; } = Guid.NewGuid();
+
+ public Guid UserAccountId { get; set; }
+
+ public byte[] CredentialId { get; set; } = [];
+
+ public byte[] PublicKey { get; set; } = [];
+
+ public long SignCount { get; set; }
+
+ // Comma-separated WebAuthn transport hints the authenticator reported at enrolment; a hint for the browser, never trusted.
+ public string Transports { get; set; } = string.Empty;
+
+ public Guid? AaGuid { get; set; }
+
+ public string Label { get; set; } = string.Empty;
+
+ public DateTimeOffset CreatedUtc { get; set; }
+
+ public DateTimeOffset StrongFromUtc { get; set; }
+
+ public DateTimeOffset? RevokedUtc { get; set; }
+
+ public DateTimeOffset? LastUsedUtc { get; set; }
+
+ public UserAccount? UserAccount { get; set; }
+}
+
/// A Mind's registered Ed25519 public key. Bifrost never holds a private key.
public sealed class MindKey
{
diff --git a/src/Bifrost.Web/Features/Bridge/AgentDispatchRunService.cs b/src/Bifrost.Web/Features/Bridge/AgentDispatchRunService.cs
deleted file mode 100644
index 36d0b64..0000000
--- a/src/Bifrost.Web/Features/Bridge/AgentDispatchRunService.cs
+++ /dev/null
@@ -1,271 +0,0 @@
-using Bifrost.Web.Data;
-using Bifrost.Web.Domain;
-using Bifrost.Web.Features.Shared;
-using Microsoft.EntityFrameworkCore;
-
-namespace Bifrost.Web.Features.Bridge;
-
-public sealed class AgentDispatchRunService(
- BifrostDbContext dbContext,
- AuditTrailService auditTrailService,
- TimeProvider timeProvider)
-{
- public async Task StartAsync(
- AgentDispatchRunStartRequest request,
- Guid? startedByUserAccountId,
- CancellationToken cancellationToken)
- {
- ValidateStartRequest(request);
- await EnsureLinkedTransportRequestAsync(request, cancellationToken);
-
- var now = timeProvider.GetUtcNow();
- var run = new AgentDispatchRun
- {
- RequestId = NormalizeText(request.RequestId),
- TargetRepoName = NormalizeText(request.TargetRepoName),
- TargetRepositoryFullName = NormalizeText(request.TargetRepositoryFullName),
- TargetAgentIdentity = NormalizeText(request.TargetAgentIdentity),
- LaunchMode = NormalizeText(request.LaunchMode),
- Status = AgentDispatchRunStatus.Started,
- StartedByUserAccountId = startedByUserAccountId,
- WorkerProcessId = request.WorkerProcessId,
- ThreadId = NormalizeText(request.ThreadId),
- TurnId = NormalizeText(request.TurnId),
- LogPath = NormalizeText(request.LogPath),
- ResultPath = NormalizeText(request.ResultPath),
- Note = NormalizeText(request.Note),
- StartedAtUtc = now,
- UpdatedAtUtc = now
- };
-
- dbContext.AgentDispatchRuns.Add(run);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- startedByUserAccountId,
- nameof(AgentDispatchRun),
- run.Id,
- "agent-dispatch.started",
- $"Dispatch run started for request {run.RequestId}.",
- cancellationToken);
-
- return AgentDispatchRunResult.From(run);
- }
-
- public Task CompleteAsync(
- Guid runId,
- AgentDispatchRunCompletionRequest request,
- Guid? startedByUserAccountId,
- CancellationToken cancellationToken) =>
- UpdateAsync(
- runId,
- startedByUserAccountId,
- "agent-dispatch.completed",
- run =>
- {
- var now = timeProvider.GetUtcNow();
- run.Status = request.Status;
- run.Note = NormalizeText(request.Note);
- run.Error = string.Empty;
- run.ThreadId = string.IsNullOrWhiteSpace(request.ThreadId) ? run.ThreadId : NormalizeText(request.ThreadId);
- run.TurnId = string.IsNullOrWhiteSpace(request.TurnId) ? run.TurnId : NormalizeText(request.TurnId);
- run.ResultPath = string.IsNullOrWhiteSpace(request.ResultPath) ? run.ResultPath : NormalizeText(request.ResultPath);
- run.UpdatedAtUtc = now;
- run.CompletedAtUtc = now;
- return $"Dispatch run {run.RequestId} completed as {run.Status}.";
- },
- cancellationToken);
-
- public Task FailAsync(
- Guid runId,
- AgentDispatchRunFailureRequest request,
- Guid? startedByUserAccountId,
- CancellationToken cancellationToken) =>
- UpdateAsync(
- runId,
- startedByUserAccountId,
- "agent-dispatch.failed",
- run =>
- {
- var now = timeProvider.GetUtcNow();
- run.Status = AgentDispatchRunStatus.Failed;
- run.Note = NormalizeText(request.Note);
- run.Error = NormalizeText(request.Error);
- run.ThreadId = string.IsNullOrWhiteSpace(request.ThreadId) ? run.ThreadId : NormalizeText(request.ThreadId);
- run.TurnId = string.IsNullOrWhiteSpace(request.TurnId) ? run.TurnId : NormalizeText(request.TurnId);
- run.ResultPath = string.IsNullOrWhiteSpace(request.ResultPath) ? run.ResultPath : NormalizeText(request.ResultPath);
- run.UpdatedAtUtc = now;
- run.CompletedAtUtc = now;
- return string.IsNullOrWhiteSpace(run.Error)
- ? $"Dispatch run {run.RequestId} failed."
- : run.Error;
- },
- cancellationToken);
-
- private async Task UpdateAsync(
- Guid runId,
- Guid? startedByUserAccountId,
- string auditAction,
- Func update,
- CancellationToken cancellationToken)
- {
- var run = await dbContext.AgentDispatchRuns
- .SingleOrDefaultAsync(x => x.Id == runId, cancellationToken);
-
- if (run is null)
- {
- return null;
- }
-
- var detail = update(run);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- startedByUserAccountId,
- nameof(AgentDispatchRun),
- run.Id,
- auditAction,
- detail,
- cancellationToken);
-
- return AgentDispatchRunResult.From(run);
- }
-
- private async Task EnsureLinkedTransportRequestAsync(
- AgentDispatchRunStartRequest request,
- CancellationToken cancellationToken)
- {
- var linkedReceipt = await dbContext.AgentTransportReceipts
- .AsNoTracking()
- .Where(x => x.RequestId == request.RequestId)
- .OrderByDescending(x => x.OccurredAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (linkedReceipt is null)
- {
- throw new AgentDispatchRunException(
- $"Dispatch runs require an existing request-lane receipt for request {request.RequestId}.");
- }
-
- EnsureSameIdentity(
- "dispatch run target repo",
- request.TargetRepoName,
- "request-lane target repo",
- linkedReceipt.TargetRepoName);
- EnsureSameIdentity(
- "dispatch run target repository",
- request.TargetRepositoryFullName,
- "request-lane target repository",
- linkedReceipt.TargetRepositoryFullName);
- EnsureSameIdentity(
- "dispatch run target agent",
- request.TargetAgentIdentity,
- "request-lane target agent",
- linkedReceipt.TargetAgentIdentity);
- }
-
- private static void ValidateStartRequest(AgentDispatchRunStartRequest request)
- {
- if (string.IsNullOrWhiteSpace(request.RequestId))
- {
- throw new AgentDispatchRunException("Dispatch runs require a request id.");
- }
-
- if (string.IsNullOrWhiteSpace(request.TargetRepoName))
- {
- throw new AgentDispatchRunException("Dispatch runs require a target repo name.");
- }
-
- if (string.IsNullOrWhiteSpace(request.LaunchMode))
- {
- throw new AgentDispatchRunException("Dispatch runs require a launch mode.");
- }
- }
-
- private static void EnsureSameIdentity(
- string currentLabel,
- string currentValue,
- string linkedLabel,
- string linkedValue)
- {
- var normalizedCurrent = NormalizeText(currentValue);
- var normalizedLinked = NormalizeText(linkedValue);
- if (string.IsNullOrWhiteSpace(normalizedCurrent) || string.IsNullOrWhiteSpace(normalizedLinked))
- {
- return;
- }
-
- if (!string.Equals(normalizedCurrent, normalizedLinked, StringComparison.OrdinalIgnoreCase))
- {
- throw new AgentDispatchRunException($"{currentLabel} does not match the linked {linkedLabel}.");
- }
- }
-
- private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
-}
-
-public sealed record AgentDispatchRunStartRequest(
- string RequestId,
- string TargetRepoName,
- string TargetRepositoryFullName,
- string TargetAgentIdentity,
- string LaunchMode,
- int? WorkerProcessId,
- string ThreadId,
- string TurnId,
- string LogPath,
- string ResultPath,
- string Note);
-
-public sealed record AgentDispatchRunCompletionRequest(
- AgentDispatchRunStatus Status,
- string ThreadId,
- string TurnId,
- string ResultPath,
- string Note);
-
-public sealed record AgentDispatchRunFailureRequest(
- string ThreadId,
- string TurnId,
- string ResultPath,
- string Note,
- string Error);
-
-public sealed record AgentDispatchRunResult(
- Guid Id,
- string RequestId,
- string TargetRepoName,
- string TargetRepositoryFullName,
- string TargetAgentIdentity,
- string LaunchMode,
- AgentDispatchRunStatus Status,
- int? WorkerProcessId,
- string ThreadId,
- string TurnId,
- string LogPath,
- string ResultPath,
- string Note,
- string Error,
- DateTimeOffset StartedAtUtc,
- DateTimeOffset UpdatedAtUtc,
- DateTimeOffset? CompletedAtUtc)
-{
- public static AgentDispatchRunResult From(AgentDispatchRun run) => new(
- run.Id,
- run.RequestId,
- run.TargetRepoName,
- run.TargetRepositoryFullName,
- run.TargetAgentIdentity,
- run.LaunchMode,
- run.Status,
- run.WorkerProcessId,
- run.ThreadId,
- run.TurnId,
- run.LogPath,
- run.ResultPath,
- run.Note,
- run.Error,
- run.StartedAtUtc,
- run.UpdatedAtUtc,
- run.CompletedAtUtc);
-}
-
-public sealed class AgentDispatchRunException(string message) : InvalidOperationException(message);
diff --git a/src/Bifrost.Web/Features/Bridge/AgentTransportReceiptService.cs b/src/Bifrost.Web/Features/Bridge/AgentTransportReceiptService.cs
deleted file mode 100644
index 1564cd6..0000000
--- a/src/Bifrost.Web/Features/Bridge/AgentTransportReceiptService.cs
+++ /dev/null
@@ -1,194 +0,0 @@
-using Bifrost.Web.Data;
-using Bifrost.Web.Domain;
-using Bifrost.Web.Features.Shared;
-using Microsoft.EntityFrameworkCore;
-
-namespace Bifrost.Web.Features.Bridge;
-
-public sealed class AgentTransportReceiptService(
- BifrostDbContext dbContext,
- AuditTrailService auditTrailService,
- TimeProvider timeProvider)
-{
- public async Task RecordAsync(
- AgentTransportReceiptRequest request,
- Guid? actorUserAccountId,
- CancellationToken cancellationToken)
- {
- ValidateRequest(request);
- await EnsureConsistentIdentityAsync(request, cancellationToken);
-
- var receipt = new AgentTransportReceipt
- {
- RequestId = NormalizeText(request.RequestId),
- Title = NormalizeText(request.Title),
- TargetRepoName = NormalizeText(request.TargetRepoName),
- TargetRepositoryFullName = NormalizeText(request.TargetRepositoryFullName),
- TargetAgentIdentity = NormalizeText(request.TargetAgentIdentity),
- ActivityKind = request.ActivityKind,
- Status = NormalizeText(request.Status),
- ActorUserAccountId = actorUserAccountId,
- ActorName = NormalizeText(request.ActorName),
- Note = NormalizeText(request.Note),
- OccurredAtUtc = timeProvider.GetUtcNow()
- };
-
- dbContext.AgentTransportReceipts.Add(receipt);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- actorUserAccountId,
- nameof(AgentTransportReceipt),
- receipt.Id,
- $"agent-transport.{receipt.ActivityKind.ToString().ToLowerInvariant()}",
- BuildAuditDetail(receipt),
- cancellationToken);
-
- return AgentTransportReceiptResult.From(receipt);
- }
-
- private async Task EnsureConsistentIdentityAsync(
- AgentTransportReceiptRequest request,
- CancellationToken cancellationToken)
- {
- var priorReceipt = await dbContext.AgentTransportReceipts
- .AsNoTracking()
- .Where(x => x.RequestId == request.RequestId)
- .OrderByDescending(x => x.OccurredAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (priorReceipt is not null)
- {
- EnsureSameIdentity(
- "request-lane target repo",
- request.TargetRepoName,
- "prior request-lane target repo",
- priorReceipt.TargetRepoName);
- EnsureSameIdentity(
- "request-lane target repository",
- request.TargetRepositoryFullName,
- "prior request-lane target repository",
- priorReceipt.TargetRepositoryFullName);
- EnsureSameIdentity(
- "request-lane target agent",
- request.TargetAgentIdentity,
- "prior request-lane target agent",
- priorReceipt.TargetAgentIdentity);
- }
-
- var linkedRun = await dbContext.AgentDispatchRuns
- .AsNoTracking()
- .Where(x => x.RequestId == request.RequestId)
- .OrderByDescending(x => x.StartedAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (linkedRun is not null)
- {
- EnsureSameIdentity(
- "request-lane target repo",
- request.TargetRepoName,
- "dispatch-run target repo",
- linkedRun.TargetRepoName);
- EnsureSameIdentity(
- "request-lane target repository",
- request.TargetRepositoryFullName,
- "dispatch-run target repository",
- linkedRun.TargetRepositoryFullName);
- EnsureSameIdentity(
- "request-lane target agent",
- request.TargetAgentIdentity,
- "dispatch-run target agent",
- linkedRun.TargetAgentIdentity);
- }
- }
-
- private static void ValidateRequest(AgentTransportReceiptRequest request)
- {
- if (string.IsNullOrWhiteSpace(request.RequestId))
- {
- throw new AgentTransportReceiptException("Request-lane receipts require a request id.");
- }
-
- if (string.IsNullOrWhiteSpace(request.Title))
- {
- throw new AgentTransportReceiptException("Request-lane receipts require a title.");
- }
-
- if (string.IsNullOrWhiteSpace(request.TargetRepoName))
- {
- throw new AgentTransportReceiptException("Request-lane receipts require a target repo name.");
- }
-
- if (string.IsNullOrWhiteSpace(request.ActorName))
- {
- throw new AgentTransportReceiptException("Request-lane receipts require an actor name.");
- }
- }
-
- private static void EnsureSameIdentity(
- string currentLabel,
- string currentValue,
- string linkedLabel,
- string linkedValue)
- {
- var normalizedCurrent = NormalizeText(currentValue);
- var normalizedLinked = NormalizeText(linkedValue);
- if (string.IsNullOrWhiteSpace(normalizedCurrent) || string.IsNullOrWhiteSpace(normalizedLinked))
- {
- return;
- }
-
- if (!string.Equals(normalizedCurrent, normalizedLinked, StringComparison.OrdinalIgnoreCase))
- {
- throw new AgentTransportReceiptException($"{currentLabel} does not match the linked {linkedLabel}.");
- }
- }
-
- private static string BuildAuditDetail(AgentTransportReceipt receipt)
- {
- var actorName = string.IsNullOrWhiteSpace(receipt.ActorName) ? "unknown actor" : receipt.ActorName;
- var repoName = string.IsNullOrWhiteSpace(receipt.TargetRepoName) ? "unknown repo" : receipt.TargetRepoName;
- return $"{actorName} recorded {receipt.ActivityKind} for request {receipt.RequestId} in {repoName} as {receipt.Status}.";
- }
-
- private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
-}
-
-public sealed record AgentTransportReceiptRequest(
- string RequestId,
- string Title,
- string TargetRepoName,
- string TargetRepositoryFullName,
- string TargetAgentIdentity,
- AgentTransportReceiptKind ActivityKind,
- string Status,
- string ActorName,
- string Note);
-
-public sealed record AgentTransportReceiptResult(
- Guid Id,
- string RequestId,
- string Title,
- string TargetRepoName,
- string TargetRepositoryFullName,
- string TargetAgentIdentity,
- AgentTransportReceiptKind ActivityKind,
- string Status,
- string ActorName,
- string Note,
- DateTimeOffset OccurredAtUtc)
-{
- public static AgentTransportReceiptResult From(AgentTransportReceipt receipt) => new(
- receipt.Id,
- receipt.RequestId,
- receipt.Title,
- receipt.TargetRepoName,
- receipt.TargetRepositoryFullName,
- receipt.TargetAgentIdentity,
- receipt.ActivityKind,
- receipt.Status,
- receipt.ActorName,
- receipt.Note,
- receipt.OccurredAtUtc);
-}
-
-public sealed class AgentTransportReceiptException(string message) : InvalidOperationException(message);
diff --git a/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs b/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs
deleted file mode 100644
index d58ea27..0000000
--- a/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs
+++ /dev/null
@@ -1,629 +0,0 @@
-using Bifrost.Web.Data;
-using Bifrost.Web.Domain;
-using Bifrost.Web.Features.Membership;
-using Bifrost.Web.Features.Shared;
-using Microsoft.EntityFrameworkCore;
-
-namespace Bifrost.Web.Features.Bridge;
-
-public sealed class BridgeActionService(
- BifrostDbContext dbContext,
- AuditTrailService auditTrailService,
- TimeProvider timeProvider)
-{
- private const string AgentTransportRequestSourceKind = "bifrost_agent_transport_request";
- private const string GovernanceTopicSourceKind = "bifrost_governance_topic";
- private const string LegacyGovernanceTopicSourceKind = "governance_topic";
-
- public async Task RequestAsync(
- BridgeActionRequest request,
- BridgeCaller caller,
- CancellationToken cancellationToken)
- {
- var now = timeProvider.GetUtcNow();
- var normalizedRequest = request.Normalize(caller);
- var policy = await EvaluatePolicyAsync(normalizedRequest, caller, cancellationToken);
-
- var action = new BridgeAction
- {
- ActorKind = normalizedRequest.ActorKind,
- ActorUserAccountId = caller.UserAccountId,
- ActorName = normalizedRequest.ActorName,
- TargetSurface = normalizedRequest.TargetSurface,
- ActionKind = normalizedRequest.ActionKind,
- Status = policy.Allowed ? BridgeActionStatus.Authorized : BridgeActionStatus.Denied,
- WorkItemId = normalizedRequest.WorkItemId,
- MotionId = normalizedRequest.MotionId,
- TargetRepositoryFullName = NormalizeRepository(normalizedRequest.TargetRepositoryFullName),
- TargetLocator = NormalizeText(normalizedRequest.TargetLocator),
- TargetSurfaceName = NormalizeSurfaceName(normalizedRequest.TargetSurfaceName),
- SourceKind = NormalizeText(normalizedRequest.SourceKind),
- SourceId = NormalizeText(normalizedRequest.SourceId),
- AuthorityReference = NormalizeText(normalizedRequest.AuthorityReference),
- BifrostIdentity = NormalizeText(normalizedRequest.BifrostIdentity),
- HeimdallCapabilityReference = NormalizeText(normalizedRequest.HeimdallCapabilityReference),
- EpiphanyRunId = NormalizeText(normalizedRequest.EpiphanyRunId),
- EpiphanyLaneId = NormalizeText(normalizedRequest.EpiphanyLaneId),
- EpiphanyAgentIdentity = NormalizeText(normalizedRequest.EpiphanyAgentIdentity),
- PolicyDecision = policy.Decision,
- Title = NormalizeText(normalizedRequest.Title),
- Summary = NormalizeText(normalizedRequest.Summary),
- RequestedAtUtc = now,
- UpdatedAtUtc = now
- };
-
- dbContext.BridgeActions.Add(action);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- caller.UserAccountId,
- nameof(BridgeAction),
- action.Id,
- policy.Allowed ? "bridge.authorized" : "bridge.denied",
- policy.Decision,
- cancellationToken);
-
- return BridgeActionResult.From(action);
- }
-
- public Task StartAsync(
- Guid actionId,
- BridgeCaller caller,
- CancellationToken cancellationToken) =>
- UpdateAsync(
- actionId,
- caller,
- "bridge.started",
- action =>
- {
- if (action.Status is not BridgeActionStatus.Authorized)
- {
- throw new BridgeActionException("Only authorized bridge actions can be started.");
- }
-
- var now = timeProvider.GetUtcNow();
- action.Status = BridgeActionStatus.InProgress;
- action.StartedAtUtc = now;
- action.UpdatedAtUtc = now;
- return "Bridge action started.";
- },
- cancellationToken);
-
- public Task CompleteAsync(
- Guid actionId,
- BridgeActionReceiptRequest request,
- BridgeCaller caller,
- CancellationToken cancellationToken) =>
- UpdateAsync(
- actionId,
- caller,
- "bridge.completed",
- action =>
- {
- if (action.Status is not (BridgeActionStatus.Authorized or BridgeActionStatus.InProgress))
- {
- throw new BridgeActionException("Only authorized or in-progress bridge actions can be completed.");
- }
-
- if (string.IsNullOrWhiteSpace(request.ReceiptUrl) &&
- string.IsNullOrWhiteSpace(request.ExternalReceiptId) &&
- string.IsNullOrWhiteSpace(request.ReceiptPayload))
- {
- throw new BridgeActionException("A completed bridge action must include a receipt URL, external receipt id, or receipt payload.");
- }
-
- var now = timeProvider.GetUtcNow();
- action.Status = BridgeActionStatus.Completed;
- action.ReceiptUrl = NormalizeText(request.ReceiptUrl);
- action.ExternalReceiptId = NormalizeText(request.ExternalReceiptId);
- action.ReceiptPayload = NormalizeText(request.ReceiptPayload);
- action.CompletedAtUtc = now;
- action.UpdatedAtUtc = now;
- return "Bridge action completed with receipt.";
- },
- cancellationToken);
-
- public Task FailAsync(
- Guid actionId,
- BridgeActionFailureRequest request,
- BridgeCaller caller,
- CancellationToken cancellationToken) =>
- UpdateAsync(
- actionId,
- caller,
- "bridge.failed",
- action =>
- {
- var now = timeProvider.GetUtcNow();
- action.Status = BridgeActionStatus.Failed;
- action.FailureReason = NormalizeText(request.FailureReason);
- action.UpdatedAtUtc = now;
- action.CompletedAtUtc = now;
- return string.IsNullOrWhiteSpace(action.FailureReason)
- ? "Bridge action failed."
- : action.FailureReason;
- },
- cancellationToken);
-
- private async Task UpdateAsync(
- Guid actionId,
- BridgeCaller caller,
- string auditAction,
- Func update,
- CancellationToken cancellationToken)
- {
- var action = await dbContext.BridgeActions
- .SingleOrDefaultAsync(x => x.Id == actionId, cancellationToken);
-
- if (action is null)
- {
- return null;
- }
-
- if (!caller.CanOperate(action))
- {
- throw new UnauthorizedAccessException("Caller cannot operate this bridge action.");
- }
-
- var detail = update(action);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- caller.UserAccountId,
- nameof(BridgeAction),
- action.Id,
- auditAction,
- detail,
- cancellationToken);
-
- return BridgeActionResult.From(action);
- }
-
- private async Task EvaluatePolicyAsync(
- BridgeActionRequest request,
- BridgeCaller caller,
- CancellationToken cancellationToken)
- {
- if (!caller.IsAllowedTransport)
- {
- return BridgePolicyDecision.Reject("Bridge actions require an active member session or a configured local bridge token.");
- }
-
- if (request.TargetSurface == BridgeTargetSurface.GitHub &&
- string.IsNullOrWhiteSpace(request.TargetRepositoryFullName))
- {
- return BridgePolicyDecision.Reject("GitHub bridge actions must name a target repository.");
- }
-
- if (request.ActorKind is BridgeActorKind.Agent or BridgeActorKind.Persona or BridgeActorKind.Service)
- {
- var hasProvenance =
- !string.IsNullOrWhiteSpace(request.AuthorityReference) ||
- (!string.IsNullOrWhiteSpace(request.SourceKind) && !string.IsNullOrWhiteSpace(request.SourceId)) ||
- request.WorkItemId is not null ||
- request.MotionId is not null;
-
- if (!hasProvenance)
- {
- return BridgePolicyDecision.Reject("Agent and Persona bridge actions must cite an authority reference, source object, work item, or motion.");
- }
- }
-
- if (RequiresExternalAccountCapability(request))
- {
- if (string.IsNullOrWhiteSpace(request.BifrostIdentity))
- {
- return BridgePolicyDecision.Reject("Persona and agent outside-world bridge actions must carry a Bifrost identity.");
- }
-
- var identityResult = await ResolveRegisteredBifrostIdentityAsync(request.BifrostIdentity, cancellationToken);
- if (identityResult.Decision is not null)
- {
- return identityResult.Decision;
- }
-
- if (string.IsNullOrWhiteSpace(request.HeimdallCapabilityReference))
- {
- return BridgePolicyDecision.Reject("Persona and agent outside-world bridge actions must carry a Heimdall-backed capability or account reference.");
- }
-
- var capabilityDecision = EvaluateHeimdallCapabilityReference(request, identityResult.UserAccount!);
- if (capabilityDecision is not null)
- {
- return capabilityDecision;
- }
- }
-
- if (request.WorkItemId is not null)
- {
- var workItem = await dbContext.WorkItems
- .Include(x => x.Project)
- .SingleOrDefaultAsync(x => x.Id == request.WorkItemId, cancellationToken);
-
- if (workItem is null)
- {
- return BridgePolicyDecision.Reject("Referenced work item does not exist.");
- }
-
- var targetRepository = NormalizeRepository(request.TargetRepositoryFullName);
- var projectRepository = NormalizeRepository(workItem.Project.GitHubRepository);
- if (!string.IsNullOrWhiteSpace(targetRepository) &&
- !string.IsNullOrWhiteSpace(projectRepository) &&
- targetRepository != projectRepository)
- {
- return BridgePolicyDecision.Reject("GitHub target repository does not match the referenced work item's project.");
- }
- }
-
- if (request.MotionId is not null &&
- !await dbContext.Motions.AnyAsync(x => x.Id == request.MotionId, cancellationToken))
- {
- return BridgePolicyDecision.Reject("Referenced motion does not exist.");
- }
-
- var provenanceDecision = await EvaluateBifrostOwnedProvenanceAsync(request, cancellationToken);
- if (provenanceDecision is not null)
- {
- return provenanceDecision;
- }
-
- return BridgePolicyDecision.Permit(
- caller.IsLocalBridge
- ? "Authorized through the configured local Bifrost bridge token and Bifrost policy."
- : "Authorized for an active Bifrost member through Bifrost policy.");
- }
-
- private async Task ResolveRegisteredBifrostIdentityAsync(
- string bifrostIdentity,
- CancellationToken cancellationToken)
- {
- string normalizedIdentity;
- try
- {
- normalizedIdentity = BifrostIdentityService.NormalizeIdentity(bifrostIdentity);
- }
- catch (BifrostIdentityException exception)
- {
- return new RegisteredBifrostIdentityResult(null, BridgePolicyDecision.Reject(exception.Message));
- }
-
- var userAccount = await dbContext.UserAccounts.SingleOrDefaultAsync(
- x => x.NormalizedBifrostIdentity == normalizedIdentity,
- cancellationToken);
- if (userAccount is null)
- {
- return new RegisteredBifrostIdentityResult(
- null,
- BridgePolicyDecision.Reject("Persona and agent outside-world bridge actions must carry a registered Bifrost identity."));
- }
-
- return new RegisteredBifrostIdentityResult(userAccount, null);
- }
-
- private static BridgePolicyDecision? EvaluateHeimdallCapabilityReference(
- BridgeActionRequest request,
- UserAccount userAccount)
- {
- if (string.IsNullOrWhiteSpace(userAccount.HeimdallAccountId))
- {
- return BridgePolicyDecision.Reject("Persona and agent outside-world bridge actions require the Bifrost identity to be linked to a Heimdall account.");
- }
-
- var capabilityReference = NormalizeText(request.HeimdallCapabilityReference);
- if (!capabilityReference.StartsWith("heimdall:", StringComparison.OrdinalIgnoreCase))
- {
- return BridgePolicyDecision.Reject("Persona and agent outside-world bridge actions must carry a Heimdall-backed capability or account reference.");
- }
-
- var expectedSurface = request.TargetSurface switch
- {
- BridgeTargetSurface.Discord => "discord",
- BridgeTargetSurface.Reddit => "reddit",
- BridgeTargetSurface.Other => NormalizeSurfaceName(request.TargetSurfaceName),
- _ => string.Empty
- };
- if (request.TargetSurface is BridgeTargetSurface.Other &&
- string.IsNullOrWhiteSpace(expectedSurface))
- {
- return BridgePolicyDecision.Reject("Future outside-world bridge actions must name the requested target surface.");
- }
-
- if (!string.IsNullOrWhiteSpace(expectedSurface) &&
- !capabilityReference.Contains($":{expectedSurface}:", StringComparison.OrdinalIgnoreCase))
- {
- return BridgePolicyDecision.Reject("Heimdall capability reference does not match the requested bridge target surface.");
- }
-
- return null;
- }
-
- private async Task EvaluateBifrostOwnedProvenanceAsync(
- BridgeActionRequest request,
- CancellationToken cancellationToken)
- {
- var sourceKind = NormalizeText(request.SourceKind);
- if (string.IsNullOrWhiteSpace(sourceKind))
- {
- return null;
- }
-
- if (string.Equals(sourceKind, AgentTransportRequestSourceKind, StringComparison.OrdinalIgnoreCase))
- {
- if (string.IsNullOrWhiteSpace(request.SourceId))
- {
- return BridgePolicyDecision.Reject("Bifrost request-backed bridge actions must cite the request id as sourceId.");
- }
-
- var linkedReceipt = await dbContext.AgentTransportReceipts
- .AsNoTracking()
- .Where(x => x.RequestId == request.SourceId)
- .OrderByDescending(x => x.OccurredAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (linkedReceipt is null)
- {
- return BridgePolicyDecision.Reject($"Bifrost request-backed bridge action references unknown request {request.SourceId}.");
- }
-
- var repoMismatch = LinkedRepositoryMismatch(
- request.TargetRepositoryFullName,
- linkedReceipt.TargetRepositoryFullName,
- linkedReceipt.TargetRepoName);
- if (repoMismatch is not null)
- {
- return BridgePolicyDecision.Reject(repoMismatch);
- }
-
- return null;
- }
-
- if (string.Equals(sourceKind, GovernanceTopicSourceKind, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(sourceKind, LegacyGovernanceTopicSourceKind, StringComparison.OrdinalIgnoreCase))
- {
- if (string.IsNullOrWhiteSpace(request.SourceId))
- {
- return BridgePolicyDecision.Reject("Bifrost governance-backed bridge actions must cite the topic id as sourceId.");
- }
-
- var linkedReceipt = await dbContext.GovernanceActivityReceipts
- .AsNoTracking()
- .Where(x => x.TopicId == request.SourceId)
- .OrderByDescending(x => x.OccurredAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (linkedReceipt is null)
- {
- return BridgePolicyDecision.Reject($"Bifrost governance-backed bridge action references unknown topic {request.SourceId}.");
- }
-
- var repoMismatch = LinkedRepositoryMismatch(
- request.TargetRepositoryFullName,
- string.Empty,
- linkedReceipt.JurisdictionRepoName);
- if (repoMismatch is not null)
- {
- return BridgePolicyDecision.Reject(repoMismatch);
- }
-
- if (request.TargetSurface == BridgeTargetSurface.GitHub &&
- !await dbContext.GovernanceActivityReceipts
- .AsNoTracking()
- .AnyAsync(
- x => x.TopicId == request.SourceId &&
- (x.ActivityKind == GovernanceActivityReceiptKind.TopicApproved ||
- x.ActivityKind == GovernanceActivityReceiptKind.TopicPromoted),
- cancellationToken))
- {
- return BridgePolicyDecision.Reject(
- $"GitHub bridge action references governance topic {request.SourceId}, but that topic has not been approved or promoted.");
- }
- }
-
- return null;
- }
-
- private static string? LinkedRepositoryMismatch(
- string targetRepositoryFullName,
- string linkedTargetRepositoryFullName,
- string linkedRepoName)
- {
- var normalizedTargetRepository = NormalizeRepository(targetRepositoryFullName);
- var normalizedLinkedRepository = NormalizeRepository(linkedTargetRepositoryFullName);
- if (!string.IsNullOrWhiteSpace(normalizedTargetRepository) &&
- !string.IsNullOrWhiteSpace(normalizedLinkedRepository) &&
- !string.Equals(normalizedTargetRepository, normalizedLinkedRepository, StringComparison.OrdinalIgnoreCase))
- {
- return "GitHub target repository does not match the linked Bifrost provenance.";
- }
-
- var targetRepoShortName = ShortRepositoryName(normalizedTargetRepository);
- var normalizedLinkedRepoName = NormalizeText(linkedRepoName);
- if (!string.IsNullOrWhiteSpace(targetRepoShortName) &&
- !string.IsNullOrWhiteSpace(normalizedLinkedRepoName) &&
- !string.Equals(targetRepoShortName, normalizedLinkedRepoName, StringComparison.OrdinalIgnoreCase))
- {
- return "GitHub target repository does not match the linked Bifrost provenance.";
- }
-
- return null;
- }
-
- private static bool RequiresExternalAccountCapability(BridgeActionRequest request) =>
- request.ActorKind is BridgeActorKind.Agent or BridgeActorKind.Persona &&
- request.TargetSurface is BridgeTargetSurface.Discord or BridgeTargetSurface.Reddit or BridgeTargetSurface.Other;
-
- private static string NormalizeRepository(string value) => NormalizeText(value).ToLowerInvariant();
-
- private static string NormalizeSurfaceName(string? value)
- {
- var normalized = NormalizeText(value).ToLowerInvariant();
- if (string.IsNullOrWhiteSpace(normalized))
- {
- return string.Empty;
- }
-
- return normalized.All(character =>
- char.IsAsciiLetterOrDigit(character) ||
- character is '-' or '_' or '.')
- ? normalized
- : string.Empty;
- }
-
- private static string ShortRepositoryName(string normalizedRepositoryFullName)
- {
- if (string.IsNullOrWhiteSpace(normalizedRepositoryFullName))
- {
- return string.Empty;
- }
-
- var slash = normalizedRepositoryFullName.LastIndexOf('/');
- return slash >= 0 && slash < normalizedRepositoryFullName.Length - 1
- ? normalizedRepositoryFullName[(slash + 1)..]
- : normalizedRepositoryFullName;
- }
-
- private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
-}
-
-public sealed record BridgeCaller(
- bool IsActiveMember,
- bool IsLocalBridge,
- Guid? UserAccountId,
- string DisplayName)
-{
- public bool IsAllowedTransport => IsActiveMember || IsLocalBridge;
-
- public bool CanOperate(BridgeAction action) =>
- IsLocalBridge ||
- (IsActiveMember && action.ActorUserAccountId == UserAccountId);
-}
-
-internal sealed record RegisteredBifrostIdentityResult(
- UserAccount? UserAccount,
- BridgePolicyDecision? Decision);
-
-public sealed record BridgeActionRequest(
- BridgeActorKind ActorKind,
- string ActorName,
- BridgeTargetSurface TargetSurface,
- BridgeActionKind ActionKind,
- string TargetRepositoryFullName,
- string TargetLocator,
- string TargetSurfaceName,
- string SourceKind,
- string SourceId,
- string AuthorityReference,
- string BifrostIdentity,
- string HeimdallCapabilityReference,
- string EpiphanyRunId,
- string EpiphanyLaneId,
- string EpiphanyAgentIdentity,
- string Title,
- string Summary,
- Guid? WorkItemId = null,
- Guid? MotionId = null)
-{
- public BridgeActionRequest Normalize(BridgeCaller caller) =>
- this with
- {
- ActorKind = ActorKind == default && caller.IsActiveMember ? BridgeActorKind.Member : ActorKind,
- ActorName = string.IsNullOrWhiteSpace(ActorName) && caller.IsActiveMember
- ? caller.DisplayName
- : NormalizeText(ActorName),
- TargetRepositoryFullName = NormalizeText(TargetRepositoryFullName),
- TargetLocator = NormalizeText(TargetLocator),
- TargetSurfaceName = NormalizeSurfaceName(TargetSurfaceName),
- SourceKind = NormalizeText(SourceKind),
- SourceId = NormalizeText(SourceId),
- AuthorityReference = NormalizeText(AuthorityReference),
- BifrostIdentity = NormalizeText(BifrostIdentity),
- HeimdallCapabilityReference = NormalizeText(HeimdallCapabilityReference),
- EpiphanyRunId = NormalizeText(EpiphanyRunId),
- EpiphanyLaneId = NormalizeText(EpiphanyLaneId),
- EpiphanyAgentIdentity = NormalizeText(EpiphanyAgentIdentity),
- Title = NormalizeText(Title),
- Summary = NormalizeText(Summary)
- };
-
- private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
-
- private static string NormalizeSurfaceName(string? value)
- {
- var normalized = NormalizeText(value).ToLowerInvariant();
- if (string.IsNullOrWhiteSpace(normalized))
- {
- return string.Empty;
- }
-
- return normalized.All(character =>
- char.IsAsciiLetterOrDigit(character) ||
- character is '-' or '_' or '.')
- ? normalized
- : string.Empty;
- }
-}
-
-public sealed record BridgeActionReceiptRequest(
- string ReceiptUrl,
- string ExternalReceiptId,
- string ReceiptPayload);
-
-public sealed record BridgeActionFailureRequest(string FailureReason);
-
-public sealed record BridgeActionResult(
- Guid Id,
- BridgeActorKind ActorKind,
- string ActorName,
- BridgeTargetSurface TargetSurface,
- BridgeActionKind ActionKind,
- BridgeActionStatus Status,
- string TargetRepositoryFullName,
- string TargetLocator,
- string TargetSurfaceName,
- string SourceKind,
- string SourceId,
- string AuthorityReference,
- string BifrostIdentity,
- string HeimdallCapabilityReference,
- string EpiphanyRunId,
- string EpiphanyLaneId,
- string EpiphanyAgentIdentity,
- string PolicyDecision,
- string Title,
- string ReceiptUrl,
- string ExternalReceiptId,
- DateTimeOffset RequestedAtUtc,
- DateTimeOffset UpdatedAtUtc)
-{
- public static BridgeActionResult From(BridgeAction action) => new(
- action.Id,
- action.ActorKind,
- action.ActorName,
- action.TargetSurface,
- action.ActionKind,
- action.Status,
- action.TargetRepositoryFullName,
- action.TargetLocator,
- action.TargetSurfaceName,
- action.SourceKind,
- action.SourceId,
- action.AuthorityReference,
- action.BifrostIdentity,
- action.HeimdallCapabilityReference,
- action.EpiphanyRunId,
- action.EpiphanyLaneId,
- action.EpiphanyAgentIdentity,
- action.PolicyDecision,
- action.Title,
- action.ReceiptUrl,
- action.ExternalReceiptId,
- action.RequestedAtUtc,
- action.UpdatedAtUtc);
-}
-
-public sealed record BridgePolicyDecision(bool Allowed, string Decision)
-{
- public static BridgePolicyDecision Permit(string decision) => new(true, decision);
-
- public static BridgePolicyDecision Reject(string decision) => new(false, decision);
-}
-
-public sealed class BridgeActionException(string message) : InvalidOperationException(message);
diff --git a/src/Bifrost.Web/Features/Bridge/GovernanceActivityReceiptService.cs b/src/Bifrost.Web/Features/Bridge/GovernanceActivityReceiptService.cs
deleted file mode 100644
index ffa1b3e..0000000
--- a/src/Bifrost.Web/Features/Bridge/GovernanceActivityReceiptService.cs
+++ /dev/null
@@ -1,190 +0,0 @@
-using Bifrost.Web.Data;
-using Bifrost.Web.Domain;
-using Bifrost.Web.Features.Shared;
-using Microsoft.EntityFrameworkCore;
-
-namespace Bifrost.Web.Features.Bridge;
-
-public sealed class GovernanceActivityReceiptService(
- BifrostDbContext dbContext,
- AuditTrailService auditTrailService,
- TimeProvider timeProvider)
-{
- public async Task RecordAsync(
- GovernanceActivityReceiptRequest request,
- Guid? actorUserAccountId,
- CancellationToken cancellationToken)
- {
- ValidateRequest(request);
- await EnsureLinkedDispatchRequestAsync(request, cancellationToken);
-
- var receipt = new GovernanceActivityReceipt
- {
- TopicId = NormalizeText(request.TopicId),
- CommentId = NormalizeText(request.CommentId),
- DispatchRequestId = NormalizeText(request.DispatchRequestId),
- Title = NormalizeText(request.Title),
- JurisdictionRepoName = NormalizeText(request.JurisdictionRepoName),
- JurisdictionAgentIdentity = NormalizeText(request.JurisdictionAgentIdentity),
- ActivityKind = request.ActivityKind,
- ActorKind = NormalizeText(request.ActorKind),
- ActorName = NormalizeText(request.ActorName),
- Note = NormalizeText(request.Note),
- ActorUserAccountId = actorUserAccountId,
- OccurredAtUtc = timeProvider.GetUtcNow()
- };
-
- dbContext.GovernanceActivityReceipts.Add(receipt);
- await dbContext.SaveChangesAsync(cancellationToken);
- await auditTrailService.RecordAsync(
- actorUserAccountId,
- nameof(GovernanceActivityReceipt),
- receipt.Id,
- $"governance.{ToAuditSuffix(receipt.ActivityKind)}",
- BuildAuditDetail(receipt),
- cancellationToken);
-
- return GovernanceActivityReceiptResult.From(receipt);
- }
-
- private async Task EnsureLinkedDispatchRequestAsync(
- GovernanceActivityReceiptRequest request,
- CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(request.DispatchRequestId))
- {
- return;
- }
-
- var linkedReceipt = await dbContext.AgentTransportReceipts
- .AsNoTracking()
- .Where(x => x.RequestId == request.DispatchRequestId)
- .OrderByDescending(x => x.OccurredAtUtc)
- .FirstOrDefaultAsync(cancellationToken);
-
- if (linkedReceipt is null)
- {
- throw new GovernanceActivityReceiptException(
- $"Governance receipt references unknown dispatch request {request.DispatchRequestId}.");
- }
-
- EnsureSameIdentity(
- "governance jurisdiction repo",
- request.JurisdictionRepoName,
- "dispatch request repo",
- linkedReceipt.TargetRepoName);
- EnsureSameIdentity(
- "governance jurisdiction agent",
- request.JurisdictionAgentIdentity,
- "dispatch request agent",
- linkedReceipt.TargetAgentIdentity);
- }
-
- private static void ValidateRequest(GovernanceActivityReceiptRequest request)
- {
- if (string.IsNullOrWhiteSpace(request.TopicId))
- {
- throw new GovernanceActivityReceiptException("Governance receipts require a topic id.");
- }
-
- if (string.IsNullOrWhiteSpace(request.Title))
- {
- throw new GovernanceActivityReceiptException("Governance receipts require a title.");
- }
-
- if (string.IsNullOrWhiteSpace(request.JurisdictionRepoName))
- {
- throw new GovernanceActivityReceiptException("Governance receipts require a jurisdiction repo name.");
- }
-
- if (string.IsNullOrWhiteSpace(request.ActorKind))
- {
- throw new GovernanceActivityReceiptException("Governance receipts require an actor kind.");
- }
-
- if (string.IsNullOrWhiteSpace(request.ActorName))
- {
- throw new GovernanceActivityReceiptException("Governance receipts require an actor name.");
- }
- }
-
- private static void EnsureSameIdentity(
- string currentLabel,
- string currentValue,
- string linkedLabel,
- string linkedValue)
- {
- var normalizedCurrent = NormalizeText(currentValue);
- var normalizedLinked = NormalizeText(linkedValue);
- if (string.IsNullOrWhiteSpace(normalizedCurrent) || string.IsNullOrWhiteSpace(normalizedLinked))
- {
- return;
- }
-
- if (!string.Equals(normalizedCurrent, normalizedLinked, StringComparison.OrdinalIgnoreCase))
- {
- throw new GovernanceActivityReceiptException($"{currentLabel} does not match the linked {linkedLabel}.");
- }
- }
-
- private static string ToAuditSuffix(GovernanceActivityReceiptKind activityKind) => activityKind switch
- {
- GovernanceActivityReceiptKind.TopicOpened => "topic-opened",
- GovernanceActivityReceiptKind.TopicCommented => "topic-commented",
- GovernanceActivityReceiptKind.TopicApproved => "topic-approved",
- GovernanceActivityReceiptKind.TopicPromoted => "topic-promoted",
- _ => "activity",
- };
-
- private static string BuildAuditDetail(GovernanceActivityReceipt receipt)
- {
- var actorName = string.IsNullOrWhiteSpace(receipt.ActorName) ? "unknown actor" : receipt.ActorName;
- var topicId = string.IsNullOrWhiteSpace(receipt.TopicId) ? "unknown topic" : receipt.TopicId;
- return $"{actorName} recorded {receipt.ActivityKind} for governance topic {topicId}.";
- }
-
- private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty;
-}
-
-public sealed record GovernanceActivityReceiptRequest(
- string TopicId,
- string CommentId,
- string DispatchRequestId,
- string Title,
- string JurisdictionRepoName,
- string JurisdictionAgentIdentity,
- GovernanceActivityReceiptKind ActivityKind,
- string ActorKind,
- string ActorName,
- string Note);
-
-public sealed record GovernanceActivityReceiptResult(
- Guid Id,
- string TopicId,
- string CommentId,
- string DispatchRequestId,
- string Title,
- string JurisdictionRepoName,
- string JurisdictionAgentIdentity,
- GovernanceActivityReceiptKind ActivityKind,
- string ActorKind,
- string ActorName,
- string Note,
- DateTimeOffset OccurredAtUtc)
-{
- public static GovernanceActivityReceiptResult From(GovernanceActivityReceipt receipt) => new(
- receipt.Id,
- receipt.TopicId,
- receipt.CommentId,
- receipt.DispatchRequestId,
- receipt.Title,
- receipt.JurisdictionRepoName,
- receipt.JurisdictionAgentIdentity,
- receipt.ActivityKind,
- receipt.ActorKind,
- receipt.ActorName,
- receipt.Note,
- receipt.OccurredAtUtc);
-}
-
-public sealed class GovernanceActivityReceiptException(string message) : InvalidOperationException(message);
diff --git a/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs b/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs
index ac96eb8..e629e44 100644
--- a/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs
+++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs
@@ -80,13 +80,31 @@ public sealed class ConceptAppraisalService(
? string.Empty
: NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret);
+ try
+ {
+ return await WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken);
+ }
+ catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation })
+ {
+ dbContext.ChangeTracker.Clear();
+ if (await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken) is null)
+ {
+ throw;
+ }
+
+ return await WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken);
+ }
+ }
+
+ private async Task WriteAppraisalAsync(ConceptSubject subject, VoterIdentity voter, ConceptStance stance, string tag, CancellationToken cancellationToken)
+ {
var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
if (existing is not null)
{
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
}
- var row = new ConceptAppraisal
+ dbContext.ConceptAppraisals.Add(new ConceptAppraisal
{
SubjectId = subject.Id,
VoterKey = voter.Key,
@@ -95,26 +113,9 @@ public sealed class ConceptAppraisalService(
UserAccountId = voter.UserAccountId,
NetworkTag = tag,
CastAtUtc = timeProvider.GetUtcNow()
- };
- dbContext.ConceptAppraisals.Add(row);
-
- try
- {
- await dbContext.SaveChangesAsync(cancellationToken);
- return CastResult.Recorded;
- }
- catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation })
- {
- // A concurrent cast by the same voter won the insert: apply this stance to their row, once.
- dbContext.Entry(row).State = EntityState.Detached;
- var winner = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
- if (winner is null)
- {
- throw;
- }
-
- return await ApplyStanceAsync(winner, stance, tag, cancellationToken);
- }
+ });
+ await dbContext.SaveChangesAsync(cancellationToken);
+ return CastResult.Recorded;
}
public async Task RetractAsync(
diff --git a/src/Bifrost.Web/Features/Desk/DeskDocuments.cs b/src/Bifrost.Web/Features/Desk/DeskDocuments.cs
index 915b3e4..2f9483d 100644
--- a/src/Bifrost.Web/Features/Desk/DeskDocuments.cs
+++ b/src/Bifrost.Web/Features/Desk/DeskDocuments.cs
@@ -4,9 +4,13 @@ using System.Text.Json.Serialization;
namespace Bifrost.Web.Features.Desk;
// The fork-desk documents Bifrost reads or writes, spelled as CultLib's contracts/cultnet/governance/fork-card.md
-// (commit de8a062a) spells them: snake_case keys, every key written (nil where absent), declared in the
+// (commit d3025d3c) spells them: snake_case keys, every key written (nil where absent), declared in the
// contract's key order. Bifrost authors only DeskRefusal and DeskUnavailable. AnswerRequest is the client's body;
-// ForkCard, DeskAnswerDocument and AnswerResult are Huginn's documents, typed here so they pass through unchanged.
+// DeskAnswerDocument, ForkList and AnswerResult are Huginn's documents, typed here so they pass through unchanged.
+// The card (gamecult.fork.card.v0) is deliberately NOT typed: the Huginn door owns what a reader's card holds (the
+// decider view carries ids, the non-decider view withholds them and keeps decider_count), and Bifrost neither reads
+// nor edits it, so it is an opaque JsonElement that keeps every key, key order and integer. The door refuses a float,
+// a binary or an extension value anywhere in a reply (the contract has none), so no number is ever rewritten.
public static class DeskSchemas
{
@@ -53,32 +57,6 @@ public sealed record DeskUnavailable(
[property: JsonPropertyName("error")] string Error,
[property: JsonPropertyName("retryAfterSeconds")] int? RetryAfterSeconds);
-public sealed record ForkOption(
- [property: JsonPropertyName("id")] string Id,
- [property: JsonPropertyName("text")] string Text);
-
-public sealed record ForkRef(
- [property: JsonPropertyName("kind")] string Kind,
- [property: JsonPropertyName("id")] string Id);
-
-public sealed record ForkCard(
- [property: JsonPropertyName("schemaVersion")] string SchemaVersion,
- [property: JsonPropertyName("fork_id")] string ForkId,
- [property: JsonPropertyName("title")] string Title,
- [property: JsonPropertyName("context")] string Context,
- [property: JsonPropertyName("options")] ForkOption[] Options,
- [property: JsonPropertyName("recommendation")] string Recommendation,
- [property: JsonPropertyName("depends")] string[] Depends,
- [property: JsonPropertyName("leans")] string? Leans,
- [property: JsonPropertyName("flag")] string? Flag,
- [property: JsonPropertyName("raised_in")] ForkRef? RaisedIn,
- [property: JsonPropertyName("deciders")] string[] Deciders,
- [property: JsonPropertyName("status")] string Status,
- [property: JsonPropertyName("ruling")] string? Ruling,
- [property: JsonPropertyName("ruled_from")] string[] RuledFrom,
- [property: JsonPropertyName("order")] long Order,
- [property: JsonPropertyName("options_hash")] string OptionsHash);
-
// One stored answer: Counted, Revision, Retraction or Refused, told apart by Outcome and Code.
public sealed record DeskAnswerDocument(
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
@@ -94,7 +72,9 @@ public sealed record DeskAnswerDocument(
[property: JsonPropertyName("answered_at")] string AnsweredAt,
[property: JsonPropertyName("received_at")] string ReceivedAt,
[property: JsonPropertyName("claim_in_future")] bool ClaimInFuture,
- [property: JsonPropertyName("answerer")] string Answerer,
+ // Nil in a non-decider's view (Huginn withholds the ids). The key is required, and the door's wire walker (Closed in
+ // UnixSocketDeskDoor) is the one owner of that: a missing key is a door fault, never a nil Bifrost invented.
+ [property: JsonPropertyName("answerer")] string? Answerer,
[property: JsonPropertyName("authority")] string Authority,
[property: JsonPropertyName("request_id")] string RequestId);
@@ -103,11 +83,12 @@ public sealed record ForkRecord(
[property: JsonPropertyName("fork_id")] string ForkId,
[property: JsonPropertyName("options_hash")] string OptionsHash,
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId,
+ [property: JsonPropertyName("answerer_count")] int AnswererCount,
[property: JsonPropertyName("answers")] DeskAnswerDocument[] Answers);
public sealed record ForkEntry(
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
- [property: JsonPropertyName("card")] ForkCard Card,
+ [property: JsonPropertyName("card")] JsonElement Card,
[property: JsonPropertyName("record")] ForkRecord Record);
public sealed record ForkList(
@@ -122,7 +103,7 @@ public sealed record ForkList(
public sealed record AnswerResult(
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
[property: JsonPropertyName("answer")] DeskAnswerDocument Answer,
- [property: JsonPropertyName("card")] ForkCard? Card,
+ [property: JsonPropertyName("card")] JsonElement? Card,
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId);
// The refusal codes Bifrost itself writes, each with its one status and message (vectors doorRefusals).
diff --git a/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs b/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs
index 2108840..67185cc 100644
--- a/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs
+++ b/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs
@@ -46,6 +46,7 @@ public static class DeskEndpoints
services.TryAddSingleton();
}
+ services.TryAddSingleton(_ => new UnixSocketDeskDoor());
services.AddSingleton(provider => new DeskMindRoutes(provider.GetRequiredService>().Value.Minds));
services.AddCors();
// Exactly the configured origin, no credentials, and only on the routes that require this policy.
diff --git a/src/Bifrost.Web/Features/Desk/DeskPorts.cs b/src/Bifrost.Web/Features/Desk/DeskPorts.cs
index 385f1bb..0769cb2 100644
--- a/src/Bifrost.Web/Features/Desk/DeskPorts.cs
+++ b/src/Bifrost.Web/Features/Desk/DeskPorts.cs
@@ -2,8 +2,9 @@ namespace Bifrost.Web.Features.Desk;
// The two ports the desk stands on. Bifrost owns the edge's order and judgments; these two own what is not
// Bifrost's yet: validating a bearer token (the OIDC validation scheme) and speaking to a Mind's Huginn on the
-// peer-checked door. No production implementation is registered here: with the Desk section configured and a port
-// missing, startup fails (DeskEndpoints.MapDesk) instead of serving.
+// peer-checked door. The door's production implementation is UnixSocketDeskDoor (registered by AddBifrostDesk unless
+// a test or host registered its own); the credential has none registered here, so with the Desk section configured
+// and a port missing, startup fails (DeskEndpoints.MapDesk) instead of serving.
// What a validated bearer token claims. The credential port verifies the token; the desk judges audience, scope and
// membership. A null Subject or Audience means the token did not carry one.
diff --git a/src/Bifrost.Web/Features/Desk/UnixSocketDeskDoor.cs b/src/Bifrost.Web/Features/Desk/UnixSocketDeskDoor.cs
new file mode 100644
index 0000000..6d007c3
--- /dev/null
+++ b/src/Bifrost.Web/Features/Desk/UnixSocketDeskDoor.cs
@@ -0,0 +1,624 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using MessagePack;
+
+namespace Bifrost.Web.Features.Desk;
+
+// The door could not confirm an outcome: no connection, no whole reply in time, or a reply that is not the contract's
+// (an error, a failure, a Mind refusal, an unknown variant). The desk edge maps any exception from the door to 503
+// `unavailable`; this is the one type the client throws for every one of those, so a failure is never an empty page.
+public sealed class DeskDoorException(string message, Exception? inner = null) : Exception(message, inner);
+
+// The production IDeskDoor: a client of Huginn's desk door (Huginn docs/desk-feed-door.md at 232764bf). One new
+// connection per call, one request frame, one reply frame, closed after, all inside one deadline. The client holds no
+// connection state, so a dead socket fails only the calls addressed to that Mind.
+//
+// frame = u32 big-endian length || CultNet message (MessagePack map), at most 65536 bytes each way
+// payload = standard base64 of the named MessagePack of Huginn's externally tagged DeskRequest / DeskResponse
+//
+// The reply is decoded by key, never by position, and strictly: every contract document is a closed map whose keys are
+// all present with the right type (the variants' own maps too: as_of is an unsigned integer, as Huginn's DeskResponse
+// declares), a key written twice anywhere is a failure, and so is a float, a binary or an extension value (the
+// contract has none; integers keep every digit). The card inside an entry is not read beyond
+// being a map: it stays an opaque JsonElement, so whatever keys and integers Huginn wrote leave unchanged.
+public sealed partial class UnixSocketDeskDoor : IDeskDoor
+{
+ public const int MaxFrameBytes = 65536;
+ public static readonly TimeSpan Deadline = TimeSpan.FromSeconds(1);
+
+ private const string ServiceId = "huginn.desk";
+ private const string RequestSchema = "huginn.desk_request.v1";
+ private const string ResponseSchema = "huginn.desk_response.v1";
+ private const string Encoding64 = "messagepack-base64";
+ private const int MaxMessageIdBytes = 256;
+
+ private static readonly UTF8Encoding StrictUtf8 = new(false, true);
+
+ private readonly Func messageIds;
+
+ public UnixSocketDeskDoor()
+ : this(() => Guid.NewGuid().ToString("N"))
+ {
+ }
+
+ public UnixSocketDeskDoor(Func messageIds) => this.messageIds = messageIds;
+
+ public async Task AnswerAsync(
+ string socket, DeskDoorContext context, ReadOnlyMemory body, CancellationToken cancellationToken)
+ {
+ byte[] request;
+ try
+ {
+ // Every key, null and key order of the client's body, as MessagePack.
+ request = MessagePackSerializer.ConvertFromJson(StrictUtf8.GetString(body.Span));
+ }
+ catch (Exception e) when (e is not OperationCanceledException)
+ {
+ throw new DeskDoorException("the answer body does not convert to the request map", e);
+ }
+
+ var payload = Payload("Answer", 5, (ref MessagePackWriter w) =>
+ {
+ w.Write("mind");
+ w.Write(context.Mind);
+ w.Write("subject");
+ w.Write(context.Subject);
+ w.Write("authority");
+ w.Write(context.Authority);
+ w.Write("deciders");
+ Strings(ref w, context.Deciders);
+ w.Write("request");
+ w.WriteRaw(request);
+ });
+
+ var (variant, value) = await ExchangeAsync(socket, "answer", payload, cancellationToken);
+ switch (variant)
+ {
+ case "Answered":
+ Closed(value, "Answered", string.Empty, ("answer", Kind.Map), ("counted_answer_id", Kind.TextOrNull), ("as_of", Kind.Unsigned));
+ var answer = AnswerDocument(value, "answer");
+
+ // Huginn's reply carries no card: a stale_fork answer gets the current card from the edge's read.
+ return new DeskAnswerOutcome.Answered(new AnswerResult(
+ DeskSchemas.AnswerResult, answer, null, OptionalString(value, "counted_answer_id")));
+ case "NotStored":
+ var code = RefusalCode(value);
+ return code is DeskRefusals.ForkTooLarge
+ ? throw new DeskDoorException("fork_too_large is not an answer refusal")
+ : new DeskAnswerOutcome.NotStored(code);
+ default:
+ throw Unexpected(variant);
+ }
+ }
+
+ public async Task ReadAsync(
+ string socket, DeskDoorContext context, string forkId, CancellationToken cancellationToken)
+ {
+ var payload = Payload("Fork", 4, (ref MessagePackWriter w) =>
+ {
+ w.Write("mind");
+ w.Write(context.Mind);
+ w.Write("subject");
+ w.Write(context.Subject);
+ w.Write("deciders");
+ Strings(ref w, context.Deciders);
+ w.Write("fork_id");
+ w.Write(forkId);
+ });
+
+ var (variant, value) = await ExchangeAsync(socket, "fork", payload, cancellationToken);
+ switch (variant)
+ {
+ case "Fork":
+ Closed(value, "Fork", string.Empty, ("entry", Kind.Map), ("as_of", Kind.Unsigned));
+ var entry = Entry(Required(value, "entry"), "entry");
+ // The route asked for one fork. An entry whose card names another is not the answer to it. (That the record
+ // agrees with the card is a rule of the entry, CultLib's validators' and Huginn's, not the door's.)
+ if (!entry.Card.TryGetProperty("fork_id", out var cardFork) || cardFork.ValueKind != JsonValueKind.String
+ || cardFork.GetString() != forkId)
+ {
+ throw new DeskDoorException("the entry is not for the fork asked");
+ }
+
+ return new DeskReadOutcome.Found(entry);
+ case "NotStored":
+ var code = RefusalCode(value);
+ // The route's fork id, never the refusal's informational text.
+ return code == DeskRefusals.ForkTooLarge
+ ? new DeskReadOutcome.ForkTooLarge(forkId)
+ : new DeskReadOutcome.NotFound(code);
+ default:
+ throw Unexpected(variant);
+ }
+ }
+
+ public async Task ListAsync(
+ string socket, DeskDoorContext context, DeskListRequest request, CancellationToken cancellationToken)
+ {
+ var payload = Payload("Forks", 6, (ref MessagePackWriter w) =>
+ {
+ w.Write("mind");
+ w.Write(context.Mind);
+ w.Write("subject");
+ w.Write(context.Subject);
+ w.Write("deciders");
+ Strings(ref w, context.Deciders);
+ w.Write("status");
+ w.Write(request.Status);
+ w.Write("cursor");
+ w.Write(request.Cursor);
+ w.Write("limit");
+ w.Write(request.Limit);
+ });
+
+ var (variant, value) = await ExchangeAsync(socket, "forks", payload, cancellationToken);
+ switch (variant)
+ {
+ case "Forks":
+ Closed(value, "Forks", string.Empty, ("list", Kind.Map), ("as_of", Kind.Unsigned));
+ var list = List(Required(value, "list"));
+ return list.Mind == context.Mind
+ ? new DeskListOutcome.Listed(list)
+ : throw new DeskDoorException("the list is for another Mind");
+ case "NotStored":
+ var code = RefusalCode(value);
+ if (code != DeskRefusals.ForkTooLarge)
+ {
+ return new DeskListOutcome.NotListed(code);
+ }
+
+ // The fork and its order exist only in the informational text; anything but the exact form is a fault.
+ var text = RequiredString(value, "error");
+ var match = ListTooLarge().Match(text);
+ if (!match.Success || !int.TryParse(match.Groups["order"].ValueSpan, NumberStyles.None, CultureInfo.InvariantCulture, out var order))
+ {
+ throw new DeskDoorException("fork_too_large does not name its fork and order in the list form");
+ }
+
+ return new DeskListOutcome.ForkTooLarge(match.Groups["id"].Value, order);
+ default:
+ throw Unexpected(variant);
+ }
+ }
+
+ // fork_too_large: fork at order is past the page budget by itself; ...
+ [GeneratedRegex(@"\Afork_too_large: fork (?\S+) at order (?0|[1-9][0-9]*) is past the page budget(?:[ ;][^\r\n]*)?\z", RegexOptions.CultureInvariant)]
+ private static partial Regex ListTooLarge();
+
+ // ---- strict documents: a closed map, every key present with its type, then bound to the typed record ----
+
+ private enum Kind
+ {
+ Text,
+ TextOrNull,
+ Flag,
+ Count,
+ Unsigned,
+ Map,
+ Items,
+ }
+
+ private static readonly (string, Kind)[] AnswerKeys =
+ [
+ ("schemaVersion", Kind.Text), ("answer_id", Kind.Text), ("fork_id", Kind.Text), ("outcome", Kind.Text),
+ ("of", Kind.TextOrNull), ("retracts", Kind.TextOrNull), ("code", Kind.TextOrNull), ("options_hash", Kind.Text),
+ ("choice", Kind.TextOrNull), ("note", Kind.TextOrNull), ("answered_at", Kind.Text), ("received_at", Kind.Text),
+ ("claim_in_future", Kind.Flag), ("answerer", Kind.TextOrNull), ("authority", Kind.Text), ("request_id", Kind.Text),
+ ];
+
+ private static void Closed(JsonElement map, string what, string schema, params (string Key, Kind Kind)[] keys)
+ {
+ if (map.ValueKind != JsonValueKind.Object || map.EnumerateObject().Count() != keys.Length)
+ {
+ throw new DeskDoorException($"{what} is not a closed map of {keys.Length} keys");
+ }
+
+ foreach (var (key, kind) in keys)
+ {
+ var ok = Property(map, key) is { } v && kind switch
+ {
+ Kind.Text => v.ValueKind == JsonValueKind.String,
+ Kind.TextOrNull => v.ValueKind is JsonValueKind.String or JsonValueKind.Null,
+ Kind.Flag => v.ValueKind is JsonValueKind.True or JsonValueKind.False,
+ Kind.Count => v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n) && n >= 0,
+ Kind.Unsigned => v.ValueKind == JsonValueKind.Number && v.TryGetUInt64(out _),
+ Kind.Map => v.ValueKind == JsonValueKind.Object,
+ _ => v.ValueKind == JsonValueKind.Array,
+ };
+ if (!ok)
+ {
+ throw new DeskDoorException($"{what}.{key} is missing or not the contract's type");
+ }
+ }
+
+ if (schema.Length > 0 && Property(map, "schemaVersion")!.Value.GetString() != schema)
+ {
+ throw new DeskDoorException($"{what} is not {schema}");
+ }
+ }
+
+ private static DeskAnswerDocument AnswerDocument(JsonElement value, string what)
+ {
+ var map = Required(value, what);
+ Closed(map, what, DeskSchemas.DeskAnswer, AnswerKeys);
+ return Bind(map, what);
+ }
+
+ private static ForkEntry Entry(JsonElement map, string what)
+ {
+ Closed(map, what, "gamecult.fork.entry.v0", ("schemaVersion", Kind.Text), ("card", Kind.Map), ("record", Kind.Map));
+ var record = Property(map, "record")!.Value;
+ Closed(record, what + ".record", "gamecult.fork.record.v0",
+ ("schemaVersion", Kind.Text), ("fork_id", Kind.Text), ("options_hash", Kind.Text), ("counted_answer_id", Kind.TextOrNull),
+ ("answerer_count", Kind.Count), ("answers", Kind.Items));
+ foreach (var answer in Property(record, "answers")!.Value.EnumerateArray())
+ {
+ Closed(answer, what + ".record.answers[]", DeskSchemas.DeskAnswer, AnswerKeys);
+ }
+
+ return Bind(map, what);
+ }
+
+ private static ForkList List(JsonElement map)
+ {
+ Closed(map, "list", "gamecult.fork.list.v0",
+ ("schemaVersion", Kind.Text), ("mind", Kind.Text), ("stamp", Kind.Text), ("open_count", Kind.Count),
+ ("recorded_count", Kind.Count), ("forks", Kind.Items), ("next_cursor", Kind.TextOrNull));
+ foreach (var entry in Property(map, "forks")!.Value.EnumerateArray())
+ {
+ Entry(entry, "list.forks[]");
+ }
+
+ return Bind(map, "list");
+ }
+
+ private static T Bind(JsonElement map, string what)
+ {
+ try
+ {
+ return map.Deserialize(DeskJson.Options) ?? throw new DeskDoorException($"{what} does not decode");
+ }
+ catch (JsonException e)
+ {
+ throw new DeskDoorException($"{what} does not decode", e);
+ }
+ }
+
+ private static JsonElement Required(JsonElement map, string name) =>
+ Property(map, name) ?? throw new DeskDoorException($"{name} is missing");
+
+ private static DeskDoorException Unexpected(string variant) =>
+ new($"the door answered with {(variant == "Refused" ? "a Mind refusal" : "a variant this call does not take")}");
+
+ private static string RefusalCode(JsonElement refusal)
+ {
+ Closed(refusal, "the refusal", DeskSchemas.Refusal, ("schemaVersion", Kind.Text), ("code", Kind.Text), ("error", Kind.Text));
+ var code = RequiredString(refusal, "code");
+ return code is DeskRefusals.ForkUnknown or DeskRefusals.BodyInvalid or DeskRefusals.RequestIdConflict or DeskRefusals.ForkTooLarge
+ ? code
+ : throw new DeskDoorException("the refusal code is not one the contract names");
+ }
+
+ // ---- request ----
+
+ private delegate void FieldWriter(ref MessagePackWriter writer);
+
+ private static byte[] Payload(string variant, int fields, FieldWriter write)
+ {
+ var buffer = new ArrayBufferWriter();
+ var w = new MessagePackWriter(buffer);
+ w.WriteMapHeader(1);
+ w.Write(variant);
+ w.WriteMapHeader(fields);
+ write(ref w);
+ w.Flush();
+ return buffer.WrittenSpan.ToArray();
+ }
+
+ private static void Strings(ref MessagePackWriter w, IReadOnlyList values)
+ {
+ w.WriteArrayHeader(values.Count);
+ foreach (var value in values)
+ {
+ w.Write(value);
+ }
+ }
+
+ // Operation messages write their keys sorted, absent optionals omitted.
+ private static byte[] RequestMessage(string messageId, string operation, byte[] payload)
+ {
+ var buffer = new ArrayBufferWriter();
+ var w = new MessagePackWriter(buffer);
+ w.WriteMapHeader(7);
+ w.Write("messageId");
+ w.Write(messageId);
+ w.Write("operation");
+ w.Write(operation);
+ w.Write("payload");
+ w.Write(Convert.ToBase64String(payload));
+ w.Write("payloadEncoding");
+ w.Write(Encoding64);
+ w.Write("payloadSchema");
+ w.Write(RequestSchema);
+ w.Write("schemaVersion");
+ w.Write("cultnet.operation_request.v0");
+ w.Write("serviceId");
+ w.Write(ServiceId);
+ w.Flush();
+ return buffer.WrittenSpan.ToArray();
+ }
+
+ // ---- exchange ----
+
+ private async Task<(string Variant, JsonElement Value)> ExchangeAsync(
+ string socketPath, string operation, byte[] payload, CancellationToken cancellationToken)
+ {
+ var messageId = messageIds();
+ if (messageId.Length == 0 || StrictUtf8.GetByteCount(messageId) > MaxMessageIdBytes)
+ {
+ throw new DeskDoorException("the message id is empty or over 256 bytes");
+ }
+
+ var message = RequestMessage(messageId, operation, payload);
+ if (message.Length > MaxFrameBytes)
+ {
+ throw new DeskDoorException("the request is past the frame bound");
+ }
+
+ var frame = new byte[4 + message.Length];
+ BinaryPrimitives.WriteUInt32BigEndian(frame, (uint)message.Length);
+ message.CopyTo(frame, 4);
+
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(Deadline);
+ byte[] reply;
+ try
+ {
+ using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
+ await socket.ConnectAsync(new UnixDomainSocketEndPoint(socketPath), deadline.Token);
+ for (var sent = 0; sent < frame.Length;)
+ {
+ sent += await socket.SendAsync(frame.AsMemory(sent), SocketFlags.None, deadline.Token);
+ }
+
+ var header = new byte[4];
+ await ReadWholeAsync(socket, header, deadline.Token);
+ var length = BinaryPrimitives.ReadUInt32BigEndian(header);
+ if (length == 0 || length > MaxFrameBytes)
+ {
+ // Refused on the prefix alone: the body is never read.
+ throw new DeskDoorException("the reply's length prefix is outside the frame bound");
+ }
+
+ reply = new byte[length];
+ await ReadWholeAsync(socket, reply, deadline.Token);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new DeskDoorException("no whole reply within the deadline");
+ }
+ catch (Exception e) when (e is SocketException or IOException or ObjectDisposedException or ArgumentException)
+ {
+ throw new DeskDoorException("the desk socket failed", e);
+ }
+
+ return Decode(reply, messageId, operation);
+ }
+
+ // Loops until the buffer is whole: a stream socket may hand it over in pieces. A peer closing early is a failure.
+ private static async Task ReadWholeAsync(Socket socket, byte[] buffer, CancellationToken cancellationToken)
+ {
+ for (var read = 0; read < buffer.Length;)
+ {
+ var count = await socket.ReceiveAsync(buffer.AsMemory(read), SocketFlags.None, cancellationToken);
+ if (count == 0)
+ {
+ throw new DeskDoorException("the peer closed before a whole reply frame");
+ }
+
+ read += count;
+ }
+ }
+
+ // ---- reply ----
+
+ // The envelope judged by key; the payload's one variant returned with its value. Everything else throws.
+ private static (string Variant, JsonElement Value) Decode(byte[] frame, string messageId, string operation)
+ {
+ try
+ {
+ using var envelope = ToJson(frame);
+ var root = envelope.RootElement;
+ if (root.ValueKind != JsonValueKind.Object)
+ {
+ throw new DeskDoorException("the reply is not a map");
+ }
+
+ // A CultNet Error message is not an operation reply (and its keys are not in operation order).
+ if (RequiredString(root, "schemaVersion") != "cultnet.operation_response.v0")
+ {
+ throw new DeskDoorException("the reply is not an operation response");
+ }
+
+ if (RequiredString(root, "serviceId") != ServiceId
+ || RequiredString(root, "operation") != operation
+ || RequiredString(root, "messageId") != messageId)
+ {
+ throw new DeskDoorException("the reply is not for this request");
+ }
+
+ var status = RequiredString(root, "status");
+ if (RequiredString(root, "payloadSchema") != ResponseSchema || RequiredString(root, "payloadEncoding") != Encoding64)
+ {
+ // Including gamecult.cultnet.operation_failure.v1: the envelope or payload did not decode.
+ throw new DeskDoorException("the reply carries no desk response");
+ }
+
+ // Strict standard base64: Convert would skip whitespace, so the text must be the canonical encoding of what it decodes to.
+ var text = RequiredString(root, "payload");
+ byte[] payload;
+ try
+ {
+ payload = Convert.FromBase64String(text);
+ }
+ catch (FormatException e)
+ {
+ throw new DeskDoorException("the payload is not base64", e);
+ }
+
+ if (Convert.ToBase64String(payload) != text)
+ {
+ throw new DeskDoorException("the payload is not strict standard base64");
+ }
+
+ using var body = ToJson(payload);
+ if (body.RootElement.ValueKind != JsonValueKind.Object)
+ {
+ throw new DeskDoorException("the payload is not a tagged variant");
+ }
+
+ var variants = body.RootElement.EnumerateObject().ToList();
+ if (variants.Count != 1)
+ {
+ throw new DeskDoorException("the payload is not a one-key variant");
+ }
+
+ var (variant, expectedStatus) = (variants[0].Name, variants[0].Name switch
+ {
+ "Answered" or "Forks" or "Fork" => "accepted",
+ "NotStored" or "Refused" => "rejected",
+ _ => null,
+ });
+ var takesVariant = operation switch
+ {
+ "answer" => variant == "Answered",
+ "forks" => variant == "Forks",
+ "fork" => variant == "Fork",
+ _ => false,
+ } || variant is "NotStored" or "Refused";
+ if (expectedStatus is null || !takesVariant || status != expectedStatus)
+ {
+ throw new DeskDoorException("the reply's variant or status does not fit the operation");
+ }
+
+ return (variant, variants[0].Value.Clone());
+ }
+ catch (Exception e) when (e is not (DeskDoorException or OperationCanceledException))
+ {
+ throw new DeskDoorException("the reply does not decode", e);
+ }
+ }
+
+ // MessagePack to JSON text by walking the reader: the JSON writer escapes every control character, keys keep their
+ // order, integers keep every digit. A map key that is not text, a key written twice, a float, a binary, an
+ // extension, invalid UTF-8 or nesting past 64 is a failure; none is in the contract.
+ private static JsonDocument ToJson(ReadOnlyMemory messagePack)
+ {
+ var reader = new MessagePackReader(messagePack);
+ var json = new ArrayBufferWriter();
+ using (var writer = new Utf8JsonWriter(json, new JsonWriterOptions { MaxDepth = 64 }))
+ {
+ Walk(ref reader, writer, 0);
+ }
+
+ if (!reader.End)
+ {
+ throw new DeskDoorException("bytes follow the message");
+ }
+
+ return JsonDocument.Parse(json.WrittenMemory, new JsonDocumentOptions { MaxDepth = 64 });
+ }
+
+ private static void Walk(ref MessagePackReader reader, Utf8JsonWriter writer, int depth)
+ {
+ if (depth > 64)
+ {
+ throw new DeskDoorException("the message nests past 64");
+ }
+
+ switch (reader.NextMessagePackType)
+ {
+ case MessagePackType.Nil:
+ reader.ReadNil();
+ writer.WriteNullValue();
+ break;
+ case MessagePackType.Boolean:
+ writer.WriteBooleanValue(reader.ReadBoolean());
+ break;
+ case MessagePackType.Integer:
+ if (reader.NextCode == MessagePackCode.UInt64)
+ {
+ writer.WriteNumberValue(reader.ReadUInt64());
+ }
+ else
+ {
+ writer.WriteNumberValue(reader.ReadInt64());
+ }
+
+ break;
+ case MessagePackType.String:
+ writer.WriteStringValue(Text(ref reader));
+ break;
+ case MessagePackType.Array:
+ var items = reader.ReadArrayHeader();
+ writer.WriteStartArray();
+ for (var i = 0; i < items; i++)
+ {
+ Walk(ref reader, writer, depth + 1);
+ }
+
+ writer.WriteEndArray();
+ break;
+ case MessagePackType.Map:
+ var pairs = reader.ReadMapHeader();
+ var seen = new HashSet(StringComparer.Ordinal);
+ writer.WriteStartObject();
+ for (var i = 0; i < pairs; i++)
+ {
+ if (reader.NextMessagePackType != MessagePackType.String)
+ {
+ throw new DeskDoorException("a map key is not text");
+ }
+
+ var key = Text(ref reader);
+ if (!seen.Add(key))
+ {
+ throw new DeskDoorException($"{key} is written twice");
+ }
+
+ writer.WritePropertyName(key);
+ Walk(ref reader, writer, depth + 1);
+ }
+
+ writer.WriteEndObject();
+ break;
+ default:
+ throw new DeskDoorException("the message holds a float, binary or extension value, which the contract does not use");
+ }
+ }
+
+ private static string Text(ref MessagePackReader reader) =>
+ StrictUtf8.GetString(reader.ReadStringSequence() ?? throw new DeskDoorException("text is nil"));
+
+ // A key's value by name; a key written twice never gets here (the walk refuses it).
+ private static JsonElement? Property(JsonElement map, string name) =>
+ map.ValueKind == JsonValueKind.Object && map.TryGetProperty(name, out var value) ? value : null;
+
+ private static string RequiredString(JsonElement map, string name) =>
+ Property(map, name) is { ValueKind: JsonValueKind.String } value
+ ? value.GetString()!
+ : throw new DeskDoorException($"{name} is missing or not text");
+
+ private static string? OptionalString(JsonElement map, string name) =>
+ Property(map, name) switch
+ {
+ { ValueKind: JsonValueKind.String } value => value.GetString(),
+ { ValueKind: JsonValueKind.Null } => null,
+ _ => throw new DeskDoorException($"{name} is missing or not text"),
+ };
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs
index 8d10b53..7f662d8 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs
@@ -8,6 +8,7 @@ using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Membership;
+using Bifrost.Web.Features.Passkeys;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.WebUtilities;
@@ -20,7 +21,9 @@ namespace Bifrost.Web.Features.Heimdall;
/// Heimdall sign-in. Start issues an attempt that lives only in a Data Protection-protected cookie in the
/// browser that began it. The browser that Heimdall authenticated presents the completion code from its
/// URL fragment; Bifrost redeems it at Heimdall itself and signs in only when that browser holds the
-/// attempt's cookie and the redeemed return target names the same attempt.
+/// attempt's cookie and the redeemed return target names the same attempt. The Linked accounts page's steps (list,
+/// link, unlink) are the same machine with other attempt purposes: each is a fresh Heimdall sign-in whose bearer is
+/// used inside that one request and dropped.
///
public sealed class HeimdallAuthService(
HttpClient httpClient,
@@ -29,7 +32,12 @@ public sealed class HeimdallAuthService(
BifrostIdentityService bifrostIdentityService,
IOptions heimdallOptions,
IDataProtectionProvider dataProtectionProvider,
- TimeProvider timeProvider)
+ TimeProvider timeProvider,
+ HeimdallMemberClient memberClient,
+ LinkedAccountsSnapshots snapshots,
+ PasskeyCeremonies ceremonies,
+ PasskeyService passkeys,
+ Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
{
public const string ErrorRedirect = "/?auth=heimdall-error";
public const string AppSecretHeader = "x-heimdall-app-secret";
@@ -38,9 +46,20 @@ public sealed class HeimdallAuthService(
{
"discord",
"patreon",
- "twitch"
+ "google"
};
+ ///
+ /// The providers that mint no account on their own: Heimdall makes one for them only under a first-login grant
+ /// (docs/service-contract.md, "Invite grant"), so only their sign-in starts may ask for it.
+ ///
+ private static readonly HashSet GrantProviders = new(StringComparer.OrdinalIgnoreCase) { "google" };
+
+ /// The headers HttpClient logging must never write: the app secret and any bearer.
+ public static bool RedactsHeader(string header) =>
+ string.Equals(header, AppSecretHeader, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(header, "Authorization", StringComparison.OrdinalIgnoreCase);
+
private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector("Bifrost.Heimdall.Attempt.v1");
/// Points the client at Heimdall and, when the app has a secret, identifies Bifrost as the app.
@@ -53,15 +72,39 @@ public sealed class HeimdallAuthService(
}
}
+ ///
+ /// Names the HTTP status and, when the body carries one, Heimdall's error code (a short snake_case token only,
+ /// see ), so nothing else from the body reaches a log.
+ ///
+ private static async Task RefusedStartMessageAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ var detail = $"HTTP {(int)response.StatusCode}";
+ if (await HeimdallRefusal.CodeAsync(response, cancellationToken) is { } code)
+ {
+ detail += ", " + code;
+ }
+
+ return $"Heimdall rejected the auth start ({detail}).";
+ }
+
public async Task StartAsync(
string provider,
string callbackBaseUrl,
LocalReturnPath returnPath,
bool requireMemberAccess,
IEnumerable> requestCookies,
- CancellationToken cancellationToken)
+ CancellationToken cancellationToken,
+ HeimdallAttemptPurpose purpose = HeimdallAttemptPurpose.SignIn,
+ string? expectedAccountId = null,
+ string? pendingLinkId = null,
+ string? replaceSlot = null,
+ bool stepUp = false,
+ string? target = null,
+ string? proof = null)
{
- if (!AllowedProviders.Contains(provider))
+ // The public sign-in routes offer AllowedProviders; the proofs of the Linked accounts page may also use Google
+ // (a step-up proof only Google can give a bifrost sign-in, an ordinary one for an account that holds Google).
+ if (!(purpose == HeimdallAttemptPurpose.SignIn ? AllowedProviders : ProofProviders).Contains(provider))
{
throw new HeimdallAuthException("Unsupported Heimdall provider.");
}
@@ -77,21 +120,30 @@ public sealed class HeimdallAuthService(
: null;
var nonce = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
+ // The grant says "Bifrost has invited this person": asked only when this very start carries a live invite. It never
+ // grants membership or chat; ChatInviteService.RedeemCarriedAsync spends the invite after the sign-in completes.
+ var grant = purpose == HeimdallAttemptPurpose.SignIn && GrantProviders.Contains(provider) && await HoldsLiveInviteAsync(requestCookies, cancellationToken)
+ ? "invite"
+ : null;
var request = new HeimdallStartRequest(
options.AppSlug,
"sign_in",
ToAttemptReturnUrl(callbackBaseUrl, nonce),
new HeimdallHandoff("browser_completion"),
- entitlementPolicy);
+ entitlementPolicy,
+ stepUp ? true : null,
+ grant);
- var response = await httpClient.PostAsJsonAsync(
- $"/v1/oauth/{provider}/start",
- request,
- cancellationToken);
+ // Headers only: a refusal body is read through RefusedStartMessageAsync's own 4 KiB bound, not buffered whole.
+ using var startMessage = new HttpRequestMessage(HttpMethod.Post, $"/v1/oauth/{provider}/start")
+ {
+ Content = JsonContent.Create(request)
+ };
+ using var response = await SendStartAsync(startMessage, cancellationToken);
if (!response.IsSuccessStatusCode)
{
- throw new HeimdallAuthException("Heimdall rejected the auth start.");
+ throw new HeimdallAuthException(await RefusedStartMessageAsync(response, cancellationToken));
}
var payload = await response.Content.ReadFromJsonAsync(cancellationToken);
@@ -105,11 +157,171 @@ public sealed class HeimdallAuthService(
provider,
requireMemberAccess,
returnPath,
- timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime);
+ timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime,
+ purpose,
+ expectedAccountId,
+ pendingLinkId,
+ target,
+ proof);
return new HeimdallAuthStartResult(
- new Uri(payload.AuthorizationUrl, UriKind.Absolute), ChooseSlot(requestCookies), Protect(attempt));
+ new Uri(payload.AuthorizationUrl, UriKind.Absolute), replaceSlot ?? ChooseSlot(requestCookies), Protect(attempt));
}
+ /// True when the cookie names a live invite, read through ChatInviteService, the one owner of invites.
+ private async Task HoldsLiveInviteAsync(IEnumerable> requestCookies, CancellationToken cancellationToken)
+ {
+ foreach (var (name, value) in requestCookies)
+ {
+ if (name == Bifrost.Web.Features.Invites.ChatInviteService.CookieName)
+ {
+ return value.Length is > 0 and <= 200 && await chatInvites.IsLiveAsync(value, cancellationToken);
+ }
+ }
+
+ return false;
+ }
+
+ /// A start that cannot reach Heimdall is a refusal like any other, never a 500.
+ private async Task SendStartAsync(HttpRequestMessage message, CancellationToken cancellationToken)
+ {
+ try
+ {
+ return await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ }
+ catch (Exception error) when (error is HttpRequestException or TaskCanceledException && !cancellationToken.IsCancellationRequested)
+ {
+ throw new HeimdallAuthException("Heimdall could not be reached for the auth start.");
+ }
+ }
+
+ ///
+ /// The provider an ordinary proof sign-in uses, or null when none is safe. A sign-in through a provider the account no
+ /// longer holds makes Heimdall mint an unrelated account that holds that login (Discord and Patreon; Google refuses instead), so it is never guessed: with the account's
+ /// current list, the first held one of the person's choice, Discord, Patreon, Google; with no list, only a provider the
+ /// member named (), who is the one who knows what they hold. The session's provider claim is not
+ /// consulted: it records how they signed in once, not what the account holds now.
+ ///
+ public static string? ProofProvider(IReadOnlyCollection? held, string? via)
+ {
+ var chosen = via is not null && ProofProviders.Contains(via) ? via.ToLowerInvariant() : null;
+ if (held is null)
+ {
+ return chosen;
+ }
+
+ return new[] { chosen, "discord", "patreon", "google" }
+ .FirstOrDefault(x => x is not null && held.Contains(x, StringComparer.OrdinalIgnoreCase));
+ }
+
+ private string ProofProviderFor(string accountId, string? via) =>
+ ProofProvider(snapshots.Get(accountId)?.Select(x => x.Provider).ToArray(), via)
+ ?? throw new HeimdallAuthException("No provider the account is known to hold can prove it.");
+
+ ///
+ /// The page's proof sign-ins. Each is a Heimdall sign-in for the account already signed in here, kept as an attempt
+ /// that says what it is the proof for (list, link, unlink) and which person it must prove. The session is never replaced.
+ ///
+ private Task StartProofAsync(
+ HeimdallAttemptPurpose purpose,
+ string provider,
+ string sessionAccountId,
+ string callbackBaseUrl,
+ IEnumerable> requestCookies,
+ bool stepUp,
+ string? target,
+ CancellationToken cancellationToken,
+ string? proof = null) =>
+ StartAsync(
+ provider,
+ callbackBaseUrl,
+ LocalReturnPath.Parse(LinkReturnPath),
+ requireMemberAccess: false,
+ requestCookies,
+ cancellationToken,
+ purpose,
+ sessionAccountId,
+ stepUp: stepUp,
+ target: target,
+ proof: proof);
+
+ ///
+ /// Reads the account's logins: an ordinary sign-in, then GET /v1/me/identities inside its completion. Through a provider on
+ /// the current list, or, when there is none, the one the member names in .
+ ///
+ public Task StartListAsync(
+ string sessionAccountId, string? via, string callbackBaseUrl,
+ IEnumerable> requestCookies, CancellationToken cancellationToken) =>
+ StartProofAsync(
+ HeimdallAttemptPurpose.ListProof, ProofProviderFor(sessionAccountId, via),
+ sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
+
+ ///
+ /// Links another provider: an ordinary sign-in as proof through a provider on the account's current list (there is no
+ /// guessing without one), then the link start for with its bearer.
+ ///
+ public Task StartLinkAsync(
+ string sessionAccountId, string targetProvider, string callbackBaseUrl,
+ IEnumerable> requestCookies, CancellationToken cancellationToken)
+ {
+ if (!LinkableProviders.Contains(targetProvider))
+ {
+ throw new HeimdallAuthException("Unsupported provider to link.");
+ }
+
+ return StartProofAsync(
+ HeimdallAttemptPurpose.LinkStart, ProofProviderFor(sessionAccountId, null),
+ sessionAccountId, callbackBaseUrl, requestCookies, false, targetProvider.ToLowerInvariant(), cancellationToken);
+ }
+
+ ///
+ /// Unlinks one login: a step-up sign-in through Google, then POST /v1/me/identities/{id}/unlink with its bearer. The
+ /// identity must be on the account's current snapshot and the account must hold Google; otherwise no proof can be had
+ /// and Heimdall is not asked.
+ ///
+ public Task StartUnlinkAsync(
+ string sessionAccountId, string identityId, string callbackBaseUrl,
+ IEnumerable> requestCookies, CancellationToken cancellationToken) =>
+ StartProofAsync(
+ HeimdallAttemptPurpose.UnlinkProof, StepUpProvider, sessionAccountId, callbackBaseUrl, requestCookies, true, identityId, cancellationToken);
+
+ ///
+ /// The fresh sign-in that earns an enrolment ticket (docs/passkeys.md): an ordinary sign-in through a provider the account
+ /// holds, proving the account to this browser's session. Its completion issues the ticket; no passkey exists before it.
+ ///
+ public Task StartEnrolProofAsync(
+ string sessionAccountId, string callbackBaseUrl,
+ IEnumerable> requestCookies, CancellationToken cancellationToken) =>
+ StartProofAsync(
+ HeimdallAttemptPurpose.EnrolProof, ProofProviderFor(sessionAccountId, null),
+ sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
+
+ ///
+ /// Unlinks one login on a verified passkey assertion: an ordinary fresh sign-in as the account (never a guessed provider), and
+ /// inside its completion, with that bearer, Heimdall's app-asserted step-up and then the unlink. is the
+ /// id of the single-use assertion fact; the attempt carries it and nothing else about the passkey.
+ ///
+ public Task StartUnlinkPasskeyAsync(
+ string sessionAccountId, string identityId, string factId, string callbackBaseUrl,
+ IEnumerable> requestCookies, CancellationToken cancellationToken) =>
+ StartProofAsync(
+ HeimdallAttemptPurpose.UnlinkPasskeyProof, ProofProviderFor(sessionAccountId, null),
+ sessionAccountId, callbackBaseUrl, requestCookies, false, identityId, cancellationToken, factId);
+
+ ///
+ /// The providers Heimdall's bifrost profile admits (src/app-profiles.ts, identityProviders): a link or a proof can use them.
+ ///
+ public static readonly IReadOnlyList LinkableProviders = ["discord", "patreon", "google"];
+
+ private static readonly HashSet ProofProviders = new(LinkableProviders, StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// The one provider whose step-up a bifrost sign-in can use (docs/service-contract.md, step-up: Discord and Patreon cannot
+ /// re-authenticate, Twitch and YouTube are not in the bifrost profile). Heimdall answers 503 until a Google client is configured.
+ ///
+ public const string StepUpProvider = "google";
+
+ public const string LinkReturnPath = "/Membership/LinkedAccounts";
+
///
/// The slot the new attempt's cookie takes: the first slot that holds no live attempt, else the one whose
/// attempt expires first. Parallel starts carry the same request cookies, so they choose the same slot and
@@ -156,15 +368,13 @@ public sealed class HeimdallAuthService(
return null;
}
- public async Task CompleteAsync(
- string callbackBaseUrl,
- string? nonce,
- string? cookieValue,
- string? code,
- CancellationToken cancellationToken)
+ /// What the attempt this browser holds for the nonce is for, or null when it holds none.
+ public HeimdallAttemptPurpose? PurposeOf(string? cookieValue, string? nonce) => Unprotect(cookieValue, nonce)?.Purpose;
+
+ /// Redeems the code of an attempt and verifies the token it carries. The token is returned to the caller's stack frame and nowhere else.
+ private async Task<(HeimdallVerifiedIdentity Identity, string AccessToken, HeimdallRedeemResponse Redeemed)> RedeemVerifiedAsync(
+ string callbackBaseUrl, HeimdallAttempt attempt, string? code, CancellationToken cancellationToken)
{
- var attempt = Unprotect(cookieValue, nonce)
- ?? throw new HeimdallAuthException("Heimdall completion has no attempt for this browser.");
if (string.IsNullOrWhiteSpace(code))
{
throw new HeimdallAuthException("Heimdall completion carried no code.");
@@ -182,6 +392,24 @@ public sealed class HeimdallAuthService(
}
var identity = await tokenVerifier.VerifyAsync(redeemed.AccessToken, redeemed.Account?.Id, cancellationToken);
+ return (identity, redeemed.AccessToken, redeemed);
+ }
+
+ public async Task CompleteAsync(
+ string callbackBaseUrl,
+ string? nonce,
+ string? cookieValue,
+ string? code,
+ CancellationToken cancellationToken)
+ {
+ var attempt = Unprotect(cookieValue, nonce)
+ ?? throw new HeimdallAuthException("Heimdall completion has no attempt for this browser.");
+ if (attempt.Purpose != HeimdallAttemptPurpose.SignIn)
+ {
+ throw new HeimdallAuthException("Heimdall completion is not a sign-in attempt.");
+ }
+
+ var (identity, _, _) = await RedeemVerifiedAsync(callbackBaseUrl, attempt, code, cancellationToken);
if (attempt.RequiresMemberAccess && !identity.HasMemberAccess)
{
throw new HeimdallAuthException("Heimdall did not grant Bifrost member access.");
@@ -197,6 +425,323 @@ public sealed class HeimdallAuthService(
attempt.ReturnPath);
}
+ ///
+ /// One step of a Linked accounts action, chosen by the purpose of the attempt this browser holds. The browser's session
+ /// must be the account the action was begun for, checked before Heimdall is asked anything and again against the identity
+ /// the fresh sign-in proves. Each step consumes the held attempt: the next step is a new attempt in the same slot, or none.
+ /// The bearer a step redeems is used inside the step and dropped.
+ ///
+ public async Task ContinueLinkAsync(
+ string callbackBaseUrl,
+ string? nonce,
+ string cookieName,
+ string? cookieValue,
+ string? code,
+ string? pendingLinkId,
+ string? sessionAccountId,
+ CancellationToken cancellationToken)
+ {
+ var attempt = Unprotect(cookieValue, nonce)
+ ?? throw new HeimdallAuthException("Heimdall link has no attempt for this browser.");
+ if (string.IsNullOrEmpty(attempt.ExpectedAccountId)
+ || !string.Equals(sessionAccountId, attempt.ExpectedAccountId, StringComparison.Ordinal))
+ {
+ throw new HeimdallAuthException("Heimdall link belongs to another session.");
+ }
+
+ switch (attempt.Purpose)
+ {
+ case HeimdallAttemptPurpose.LinkStart:
+ {
+ var (_, bearer) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ var authorizationUrl = await StartLinkProviderAsync(callbackBaseUrl, attempt, bearer, cancellationToken);
+ return new HeimdallLinkStep(authorizationUrl.Url, cookieName, authorizationUrl.CookieValue, null);
+ }
+
+ case HeimdallAttemptPurpose.LinkAwaitGoogle:
+ {
+ if (string.IsNullOrWhiteSpace(pendingLinkId))
+ {
+ throw new HeimdallAuthException("Heimdall link carried no pending link.");
+ }
+
+ var next = await StartAsync(
+ attempt.Provider,
+ callbackBaseUrl,
+ attempt.ReturnPath,
+ requireMemberAccess: false,
+ [],
+ cancellationToken,
+ HeimdallAttemptPurpose.LinkConfirm,
+ attempt.ExpectedAccountId,
+ pendingLinkId,
+ replaceSlot: cookieName);
+ return new HeimdallLinkStep(next.AuthorizationUrl, next.CookieName, next.CookieValue, null);
+ }
+
+ case HeimdallAttemptPurpose.LinkConfirm:
+ {
+ var (identity, bearer) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ var outcome = await ConfirmLinkAsync(attempt.PendingLinkId!, bearer, cancellationToken);
+ if (outcome == HeimdallLinkOutcome.Linked)
+ {
+ // Membership follows the verified identity exactly as at sign-in; the session principal is not replaced.
+ await UpsertUserAccountAsync(identity, attempt.Provider, grantMemberAccess: false, cancellationToken);
+ snapshots.Remove(identity.AccountId);
+ }
+
+ return new HeimdallLinkStep(null, cookieName, null, outcome);
+ }
+
+ case HeimdallAttemptPurpose.LinkAwaitDirect:
+ {
+ // A provider other than Google attaches in Heimdall's callback; the browser returns with a link completion.
+ var (identity, _, redeemed) = await RedeemOwnerWithBodyAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ if (redeemed.Mode != "link" || !string.Equals(redeemed.Provider, attempt.Target, StringComparison.Ordinal))
+ {
+ throw new HeimdallAuthException("Heimdall completion is not this link.");
+ }
+
+ await UpsertUserAccountAsync(identity, attempt.Target!, grantMemberAccess: false, cancellationToken);
+ snapshots.Remove(identity.AccountId);
+ return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.Linked);
+ }
+
+ case HeimdallAttemptPurpose.ListProof:
+ {
+ var (identity, bearer) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ var listed = await memberClient.ListAsync(bearer, cancellationToken);
+ if (listed.Call == HeimdallMemberCall.Ok)
+ {
+ snapshots.Put(identity.AccountId, listed.Identities!);
+ }
+
+ return new HeimdallLinkStep(null, cookieName, null, listed.Call == HeimdallMemberCall.Ok ? HeimdallLinkOutcome.Listed : OutcomeOf(listed.Call));
+ }
+
+ case HeimdallAttemptPurpose.UnlinkProof:
+ {
+ var (identity, bearer, redeemed) = await RedeemOwnerWithBodyAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ if (redeemed.StepUpRequested != true)
+ {
+ // Heimdall reports "asked" on a step-up completion; one that does not was not a step-up sign-in.
+ return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.StepUpRequired);
+ }
+
+ return new HeimdallLinkStep(null, cookieName, null, await UnlinkAsync(identity.AccountId, bearer, attempt.Target, cancellationToken));
+ }
+
+ case HeimdallAttemptPurpose.EnrolProof:
+ {
+ // A fresh ordinary sign-in as the session's own account: the one thing a stolen session cookie cannot produce.
+ // It earns a short-lived single-use ticket, handed to this browser in a cookie; no passkey exists yet.
+ var (identity, _) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ var ticket = ceremonies.Issue(CeremonyKind.EnrolTicket, identity.AccountId, null, null, PasskeyCeremonies.TicketLifetime);
+ return new HeimdallLinkStep(
+ null, cookieName, null, ticket is null ? HeimdallLinkOutcome.Error : HeimdallLinkOutcome.EnrolReady, ticket);
+ }
+
+ case HeimdallAttemptPurpose.UnlinkPasskeyProof:
+ {
+ // The assertion fact is spent before anything else: missing, expired, spent, or for another account or identity
+ // means no step-up is asked of Heimdall and nothing is unlinked.
+ var fact = ceremonies.Take(CeremonyKind.UnlinkProof, attempt.ExpectedAccountId, attempt.Target, attempt.Proof);
+ var (identity, bearer) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ if (fact is null)
+ {
+ return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.PasskeyExpired);
+ }
+
+ // A passkey revoked since the assertion no longer proves anything: Heimdall is not asked.
+ if (!await passkeys.StillStrongAsync(identity.AccountId, fact.Data, cancellationToken))
+ {
+ return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.PasskeyFailed);
+ }
+
+ var asserted = await StepUpAsync(bearer, cancellationToken);
+ if (asserted.Refusal is { } refusal)
+ {
+ return new HeimdallLinkStep(null, cookieName, null, refusal);
+ }
+
+ // The returned token is this request's alone: it goes to the one unlink and is dropped.
+ return new HeimdallLinkStep(null, cookieName, null, await UnlinkAsync(identity.AccountId, asserted.AccessToken!, attempt.Target, cancellationToken));
+ }
+
+ default:
+ throw new HeimdallAuthException("Heimdall completion is not a link attempt.");
+ }
+ }
+
+ ///
+ /// Heimdall's unlink with a bearer that carries fresh proof, and what the list becomes. Only Heimdall's definitive refusals leave
+ /// the account as the list showed it. Any other end (not found, a lost answer, a 500, a malformed 200) may have applied the
+ /// unlink, so the list is dropped rather than trusted.
+ ///
+ private async Task UnlinkAsync(string accountId, string bearer, string? identityId, CancellationToken cancellationToken)
+ {
+ var unlinked = await memberClient.UnlinkAsync(bearer, identityId ?? string.Empty, cancellationToken);
+ if (unlinked.Call == HeimdallMemberCall.Ok)
+ {
+ snapshots.Put(accountId, unlinked.Identities!);
+ }
+ else if (unlinked.Call is not (HeimdallMemberCall.SignInRequired or HeimdallMemberCall.StepUpRequired or HeimdallMemberCall.LastIdentity))
+ {
+ snapshots.Remove(accountId);
+ }
+
+ return unlinked.Call == HeimdallMemberCall.Ok ? HeimdallLinkOutcome.Unlinked : OutcomeOf(unlinked.Call);
+ }
+
+ /// The method label Heimdall's bifrost profile admits for an app-asserted passkey proof.
+ public const string PasskeyStepUpMethod = "bifrost-passkey";
+
+ ///
+ /// POST /v1/apps/{app}/step-up (Heimdall docs/service-contract.md): the app secret, the member's live bearer and a fresh random
+ /// nonce; Heimdall answers a token for the same session that carries the proof. Called only from the completion that holds the
+ /// bearer, after a verified passkey assertion fact was spent. Each refusal is a closed outcome; nothing is retried here.
+ ///
+ private async Task<(HeimdallLinkOutcome? Refusal, string? AccessToken)> StepUpAsync(string bearer, CancellationToken cancellationToken)
+ {
+ var nonce = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
+ try
+ {
+ using var message = new HttpRequestMessage(
+ HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/step-up")
+ {
+ Content = JsonContent.Create(new HeimdallStepUpRequest(PasskeyStepUpMethod, nonce))
+ };
+ message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearer);
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ if (response.StatusCode == HttpStatusCode.Created)
+ {
+ var minted = await response.Content.ReadFromJsonAsync(cancellationToken);
+ return string.IsNullOrWhiteSpace(minted?.AccessToken) ? (HeimdallLinkOutcome.Error, null) : (null, minted.AccessToken);
+ }
+
+ var error = await HeimdallRefusal.CodeAsync(response, cancellationToken);
+ return ((int)response.StatusCode, error) switch
+ {
+ (401, "sign_in_required") => (HeimdallLinkOutcome.SignInRequired, null),
+ (429, _) => (HeimdallLinkOutcome.StepUpRateLimited, null),
+ (409, "step_up_nonce_replayed") => (HeimdallLinkOutcome.StepUpReplayed, null),
+ (401 or 403 or 400, _) => (HeimdallLinkOutcome.StepUpUnavailable, null),
+ _ => (HeimdallLinkOutcome.Error, null)
+ };
+ }
+ catch (Exception exception) when (exception is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException
+ && !cancellationToken.IsCancellationRequested)
+ {
+ return (HeimdallLinkOutcome.Error, null);
+ }
+ }
+
+ private static HeimdallLinkOutcome OutcomeOf(HeimdallMemberCall call) => call switch
+ {
+ HeimdallMemberCall.SignInRequired => HeimdallLinkOutcome.SignInRequired,
+ HeimdallMemberCall.StepUpRequired => HeimdallLinkOutcome.StepUpRequired,
+ HeimdallMemberCall.IdentityNotFound => HeimdallLinkOutcome.IdentityNotFound,
+ HeimdallMemberCall.LastIdentity => HeimdallLinkOutcome.LastIdentity,
+ _ => HeimdallLinkOutcome.Error
+ };
+
+ /// Redeems a link attempt's code and requires it to prove the account the link was begun for.
+ private async Task<(HeimdallVerifiedIdentity Identity, string AccessToken)> RedeemOwnerAsync(
+ string callbackBaseUrl, HeimdallAttempt attempt, string? code, CancellationToken cancellationToken)
+ {
+ var (identity, bearer, _) = await RedeemOwnerWithBodyAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ return (identity, bearer);
+ }
+
+ private async Task<(HeimdallVerifiedIdentity Identity, string AccessToken, HeimdallRedeemResponse Redeemed)> RedeemOwnerWithBodyAsync(
+ string callbackBaseUrl, HeimdallAttempt attempt, string? code, CancellationToken cancellationToken)
+ {
+ var proven = await RedeemVerifiedAsync(callbackBaseUrl, attempt, code, cancellationToken);
+ if (!string.Equals(proven.Identity.AccountId, attempt.ExpectedAccountId, StringComparison.Ordinal))
+ {
+ throw new HeimdallAuthException("Heimdall link was proven by another account.");
+ }
+
+ return proven;
+ }
+
+ ///
+ /// Starts the link to the attempt's target provider with the member's bearer. Google attaches in two phases (the
+ /// callback writes a pending link, a second fresh sign-in confirms it); the other admitted providers attach in the callback.
+ /// A cookie written before the target existed names no provider and is a Google link.
+ ///
+ private async Task<(Uri Url, string CookieValue)> StartLinkProviderAsync(
+ string callbackBaseUrl, HeimdallAttempt attempt, string bearer, CancellationToken cancellationToken)
+ {
+ var target = attempt.Target ?? "google";
+ if (!LinkableProviders.Contains(target))
+ {
+ throw new HeimdallAuthException("Unsupported provider to link.");
+ }
+
+ var options = heimdallOptions.Value;
+ var nonce = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
+ using var message = new HttpRequestMessage(HttpMethod.Post, $"/v1/oauth/{target}/start")
+ {
+ Content = JsonContent.Create(new HeimdallStartRequest(
+ options.AppSlug, "link", ToAttemptReturnUrl(callbackBaseUrl, nonce), new HeimdallHandoff("browser_completion"), null, null))
+ };
+ message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearer);
+ using var response = await SendStartAsync(message, cancellationToken);
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HeimdallAuthException(await RefusedStartMessageAsync(response, cancellationToken));
+ }
+
+ var payload = await response.Content.ReadFromJsonAsync(cancellationToken);
+ if (payload is null || string.IsNullOrWhiteSpace(payload.AuthorizationUrl))
+ {
+ throw new HeimdallAuthException("Heimdall link start returned no authorization URL.");
+ }
+
+ var awaiting = new HeimdallAttempt(
+ nonce,
+ attempt.Provider,
+ false,
+ attempt.ReturnPath,
+ timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime,
+ target == "google" ? HeimdallAttemptPurpose.LinkAwaitGoogle : HeimdallAttemptPurpose.LinkAwaitDirect,
+ attempt.ExpectedAccountId,
+ null,
+ target);
+ return (new Uri(payload.AuthorizationUrl, UriKind.Absolute), Protect(awaiting));
+ }
+
+ private async Task ConfirmLinkAsync(string pendingLinkId, string bearer, CancellationToken cancellationToken)
+ {
+ try
+ {
+ using var message = new HttpRequestMessage(
+ HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/links/confirm")
+ {
+ Content = JsonContent.Create(new HeimdallConfirmLinkRequest(pendingLinkId))
+ };
+ message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearer);
+ using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ switch (response.StatusCode)
+ {
+ case HttpStatusCode.Created:
+ var linked = await response.Content.ReadFromJsonAsync(cancellationToken);
+ return linked?.Status == "linked" ? HeimdallLinkOutcome.Linked : HeimdallLinkOutcome.Error;
+ case HttpStatusCode.Conflict:
+ return HeimdallLinkOutcome.IdentityLinkedElsewhere;
+ case HttpStatusCode.Gone:
+ return HeimdallLinkOutcome.Expired;
+ default:
+ return HeimdallLinkOutcome.Error;
+ }
+ }
+ catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException && !cancellationToken.IsCancellationRequested)
+ {
+ return HeimdallLinkOutcome.Error;
+ }
+ }
+
private async Task RedeemAsync(string code, CancellationToken cancellationToken)
{
try
@@ -221,7 +766,8 @@ public sealed class HeimdallAuthService(
private string Protect(HeimdallAttempt attempt) =>
_protector.Protect(JsonSerializer.Serialize(new AttemptWire(
- attempt.Nonce, attempt.Provider, attempt.RequiresMemberAccess, attempt.ReturnPath.Value, attempt.ExpiresAt)));
+ attempt.Nonce, attempt.Provider, attempt.RequiresMemberAccess, attempt.ReturnPath.Value, attempt.ExpiresAt,
+ attempt.Purpose, attempt.ExpectedAccountId, attempt.PendingLinkId, attempt.Target, attempt.Proof)));
/// The live attempt a cookie value protects when it belongs to this nonce, else null.
private HeimdallAttempt? Unprotect(string? cookieValue, string? nonce) =>
@@ -238,13 +784,14 @@ public sealed class HeimdallAuthService(
try
{
var wire = JsonSerializer.Deserialize(_protector.Unprotect(cookieValue));
- if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow())
+ if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow() || !Enum.IsDefined(wire.Purpose))
{
return null;
}
return new HeimdallAttempt(
- wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt);
+ wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt,
+ wire.Purpose, wire.ExpectedAccountId, wire.PendingLinkId, wire.Target, wire.Proof);
}
catch (Exception error) when (error is CryptographicException or JsonException or FormatException)
{
@@ -257,7 +804,12 @@ public sealed class HeimdallAuthService(
string Provider,
bool RequiresMemberAccess,
string ReturnPath,
- DateTimeOffset ExpiresAt);
+ DateTimeOffset ExpiresAt,
+ HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
+ string? ExpectedAccountId = null,
+ string? PendingLinkId = null,
+ string? Target = null,
+ string? Proof = null);
private async Task UpsertUserAccountAsync(
HeimdallVerifiedIdentity identity,
@@ -314,11 +866,13 @@ public sealed class HeimdallAuthService(
Headline = $"Verified through Heimdall {provider}",
UpdatedAtUtc = now
};
- userAccount.Membership ??= new Bifrost.Web.Domain.Membership
+ if (userAccount.Membership is null)
{
- UserAccountId = userAccount.Id,
- CreatedAtUtc = now
- };
+ // Added explicitly: a row with a preset key assigned to a tracked account is taken for an existing one and the save fails.
+ userAccount.Membership = new Bifrost.Web.Domain.Membership { UserAccountId = userAccount.Id, CreatedAtUtc = now };
+ dbContext.Memberships.Add(userAccount.Membership);
+ }
+
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it.
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended)
{
@@ -333,10 +887,10 @@ public sealed class HeimdallAuthService(
userAccount,
displayName,
cancellationToken);
- if (grantMemberAccess && userAccount.Membership!.Status == MembershipStatus.Active)
+ if (grantMemberAccess && userAccount.Membership is { Status: MembershipStatus.Active })
{
ApplicationBootstrapper.EnsureRole(
- userAccount.Membership!,
+ userAccount.Membership,
MemberRole.StandardMember,
null,
now,
@@ -344,6 +898,7 @@ public sealed class HeimdallAuthService(
}
await dbContext.SaveChangesAsync(cancellationToken);
+
return userAccount;
}
@@ -409,7 +964,151 @@ public sealed record HeimdallAttempt(
string Provider,
bool RequiresMemberAccess,
LocalReturnPath ReturnPath,
- DateTimeOffset ExpiresAt);
+ DateTimeOffset ExpiresAt,
+ HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
+ string? ExpectedAccountId = null,
+ string? PendingLinkId = null,
+ string? Target = null,
+ string? Proof = null);
+
+///
+/// What a held attempt is for. SignIn is the default, so a cookie written before purposes existed reads as a sign-in.
+/// The other purposes belong to the Linked accounts page: the fresh sign-ins that prove an account for a list, a link or
+/// an unlink, and the provider round trips of a link. Values are persisted in cookies: append only.
+///
+public enum HeimdallAttemptPurpose
+{
+ SignIn = 0,
+ LinkStart = 1,
+ LinkAwaitGoogle = 2,
+ LinkConfirm = 3,
+ ListProof = 4,
+ UnlinkProof = 5,
+ LinkAwaitDirect = 6,
+ EnrolProof = 7,
+ UnlinkPasskeyProof = 8
+}
+
+/// How a Linked accounts action ended. is its closed wire form.
+public enum HeimdallLinkOutcome
+{
+ Linked,
+ IdentityLinkedElsewhere,
+ Expired,
+ Error,
+ Listed,
+ Unlinked,
+ LastIdentity,
+ StepUpRequired,
+ IdentityNotFound,
+ SignInRequired,
+ ProofUnavailable,
+ ListExpired,
+ ProviderNeeded,
+ EnrolReady,
+ EnrolNeedsSignIn,
+ PasskeyAdded,
+ PasskeyRevoked,
+ PasskeyLimit,
+ PasskeyExpired,
+ PasskeyFailed,
+ PasskeyRequired,
+ PasskeysUnavailable,
+ RateLimited,
+ StepUpUnavailable,
+ StepUpReplayed,
+ StepUpRateLimited
+}
+
+///
+/// Where a Linked accounts step sends the browser: to with a new attempt cookie in the held
+/// slot, or, when the action is finished, back to the page with the outcome's code in ?result=.
+///
+public static class HeimdallLinkOutcomes
+{
+ public const string ResultParameter = "result";
+
+ /// Back to the Linked accounts page with the outcome's code.
+ public static string Redirect(HeimdallLinkOutcome outcome) =>
+ HeimdallAuthService.LinkReturnPath + "?" + ResultParameter + "=" + Code(outcome);
+
+ public static string Code(HeimdallLinkOutcome outcome) => outcome switch
+ {
+ HeimdallLinkOutcome.Linked => "linked",
+ HeimdallLinkOutcome.IdentityLinkedElsewhere => "identity_linked_elsewhere",
+ HeimdallLinkOutcome.Expired => "expired",
+ HeimdallLinkOutcome.Listed => "listed",
+ HeimdallLinkOutcome.Unlinked => "unlinked",
+ HeimdallLinkOutcome.LastIdentity => "last_identity",
+ HeimdallLinkOutcome.StepUpRequired => "step_up_required",
+ HeimdallLinkOutcome.IdentityNotFound => "identity_not_found",
+ HeimdallLinkOutcome.SignInRequired => "sign_in_required",
+ HeimdallLinkOutcome.ProofUnavailable => "proof_unavailable",
+ HeimdallLinkOutcome.ListExpired => "list_expired",
+ HeimdallLinkOutcome.ProviderNeeded => "provider_needed",
+ HeimdallLinkOutcome.EnrolReady => "enrol_ready",
+ HeimdallLinkOutcome.EnrolNeedsSignIn => "enrol_needs_sign_in",
+ HeimdallLinkOutcome.PasskeyAdded => "passkey_added",
+ HeimdallLinkOutcome.PasskeyRevoked => "passkey_revoked",
+ HeimdallLinkOutcome.PasskeyLimit => "passkey_limit",
+ HeimdallLinkOutcome.PasskeyExpired => "passkey_expired",
+ HeimdallLinkOutcome.PasskeyFailed => "passkey_failed",
+ HeimdallLinkOutcome.PasskeyRequired => "passkey_required",
+ HeimdallLinkOutcome.PasskeysUnavailable => "passkeys_unavailable",
+ HeimdallLinkOutcome.RateLimited => "rate_limited",
+ HeimdallLinkOutcome.StepUpUnavailable => "step_up_unavailable",
+ HeimdallLinkOutcome.StepUpReplayed => "step_up_replayed",
+ HeimdallLinkOutcome.StepUpRateLimited => "step_up_rate_limited",
+ _ => "error"
+ };
+
+ /// The words for an outcome code: a closed set, never Heimdall's text and never the query's. Anything else gets none.
+ public static string? Wording(string? code) => code switch
+ {
+ "linked" => "The login is now linked to your Heimdall account.",
+ "identity_linked_elsewhere" => "That login belongs to another account. Nothing was linked.",
+ "expired" => "The link expired before it was confirmed. Nothing was linked; start the link again.",
+ "listed" => null,
+ "unlinked" => "The login was unlinked.",
+ "last_identity" => "That is the last login on your account, and Heimdall will not remove it. Nothing was changed.",
+ "step_up_required" => "Heimdall did not accept the sign-in as fresh proof. Nothing was changed; try again.",
+ "identity_not_found" => "That login is no longer on your account. Nothing was changed; the list below is read again when you ask.",
+ "sign_in_required" => "Heimdall no longer accepts that sign-in. Nothing was changed; try again.",
+ "proof_unavailable" => "Fresh proof could not be started, so nothing was changed. Unlinking needs a fresh Google sign-in, and it is not available right now.",
+ "provider_needed" => "Bifrost does not know which logins this account holds right now, so it will not guess. Pick one you know it holds to read the list. Nothing was changed.",
+ "enrol_ready" => "You signed in again. Add the passkey below within five minutes.",
+ "enrol_needs_sign_in" => "Adding a passkey needs a fresh sign-in first, and none is current. Start again with \"Sign in again to add a passkey\". Nothing was added.",
+ "passkey_added" => "The passkey was added. It counts as strong proof after a 48 hour cooling-off; until then it cannot unlink anything.",
+ "passkey_revoked" => "The passkey was revoked.",
+ "passkey_limit" => "This account already has the most passkeys it can hold. Revoke one to add another.",
+ "passkey_expired" => "The passkey check expired or was already used. Nothing was changed; start the unlink again.",
+ "passkey_failed" => "The passkey could not be verified. Nothing was changed.",
+ "passkey_required" => "This account has a passkey, so unlinking needs it. Nothing was changed.",
+ "passkeys_unavailable" => "Passkeys are not available on this server right now. Nothing was changed.",
+ "rate_limited" => "Too many passkey attempts. Nothing was changed; wait a few minutes.",
+ "step_up_unavailable" => "Your passkey was verified, but Heimdall would not take Bifrost's proof. Nothing was changed.",
+ "step_up_replayed" => "Heimdall had already seen that proof. Nothing was changed; start the unlink again.",
+ "step_up_rate_limited" => "Heimdall is limiting proofs for now. Nothing was changed; wait a few minutes and start the unlink again.",
+ "list_expired" => "The list was out of date. Nothing was changed; read your linked logins again.",
+ "error" => "That could not be completed. Nothing was changed.",
+ _ => null
+ };
+}
+
+public sealed record HeimdallLinkStep(Uri? Next, string CookieName, string? CookieValue, HeimdallLinkOutcome? Outcome, string? EnrolTicket = null);
+
+public sealed record HeimdallConfirmLinkRequest(
+ [property: JsonPropertyName("pendingLinkId")] string PendingLinkId);
+
+public sealed record HeimdallStepUpRequest(
+ [property: JsonPropertyName("method")] string Method,
+ [property: JsonPropertyName("nonce")] string Nonce);
+
+public sealed record HeimdallStepUpResponse(
+ [property: JsonPropertyName("accessToken")] string? AccessToken);
+
+public sealed record HeimdallConfirmLinkResponse(
+ [property: JsonPropertyName("status")] string? Status);
public sealed record HeimdallStartRequest(
[property: JsonPropertyName("appSlug")] string AppSlug,
@@ -417,7 +1116,11 @@ public sealed record HeimdallStartRequest(
[property: JsonPropertyName("returnTo")] string ReturnTo,
[property: JsonPropertyName("handoff")] HeimdallHandoff Handoff,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
- [property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy);
+ [property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ [property: JsonPropertyName("stepUp")] bool? StepUp = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ [property: JsonPropertyName("firstLoginGrant")] string? FirstLoginGrant = null);
public sealed record HeimdallHandoff(
[property: JsonPropertyName("kind")] string Kind);
@@ -440,7 +1143,10 @@ public sealed record HeimdallRedeemRequest(
public sealed record HeimdallRedeemResponse(
[property: JsonPropertyName("returnTo")] string? ReturnTo,
[property: JsonPropertyName("accessToken")] string? AccessToken,
- [property: JsonPropertyName("account")] HeimdallAccount? Account);
+ [property: JsonPropertyName("account")] HeimdallAccount? Account,
+ [property: JsonPropertyName("mode")] string? Mode = null,
+ [property: JsonPropertyName("provider")] string? Provider = null,
+ [property: JsonPropertyName("stepUpRequested")] bool? StepUpRequested = null);
public sealed record HeimdallAccount(
[property: JsonPropertyName("id")] string Id);
@@ -477,3 +1183,26 @@ public static class HeimdallAttemptCookie
///
public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path, Secure = true };
}
+
+public static class HeimdallClientServices
+{
+ ///
+ /// Every Heimdall client Bifrost owns. The auth client carries the app secret and the member client only the member's
+ /// bearer; both 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);
+ }
+
+ /// 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) });
+}
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
index 662fb16..08ba617 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
@@ -3,7 +3,8 @@ namespace Bifrost.Web.Features.Heimdall;
///
/// The page Heimdall's "Return to the app" lands on. The completion code arrives in the URL fragment, which
/// the server never sees, so the page's script reads it, drops it from the address bar, and posts it with
-/// the attempt to the same path. The page is static: it never contains a code.
+/// the attempt to the same path. A Google link returns a pending link id the same way instead of a code. The page
+/// is static: it never contains a code or an id.
///
public static class HeimdallCompletePage
{
@@ -22,21 +23,35 @@ public static class HeimdallCompletePage
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..7ce556a 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs
@@ -64,21 +64,18 @@ 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}.");
}
var supportEvent = await patronageService.RecordSupportEventAsync(
@@ -98,7 +95,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..2dde00e
--- /dev/null
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
@@ -0,0 +1,47 @@
+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)
+ {
+ 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)
+ {
+ return code;
+ }
+ }
+ 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;
+}
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/Invites/ChatInviteService.cs b/src/Bifrost.Web/Features/Invites/ChatInviteService.cs
new file mode 100644
index 0000000..387614d
--- /dev/null
+++ b/src/Bifrost.Web/Features/Invites/ChatInviteService.cs
@@ -0,0 +1,143 @@
+using System.Security.Cryptography;
+using System.Text;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Data;
+using Bifrost.Web.Domain;
+using Bifrost.Web.Features.Shared;
+using Microsoft.AspNetCore.WebUtilities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
+
+namespace Bifrost.Web.Features.Invites;
+
+///
+/// The one owner of chat invites. An operator mints a single-use link (; the payment ledger will mint the same record),
+/// a visitor who opens it carries the token in a short cookie through sign-in, and every sign-in path ends in ,
+/// which spends the invite onto the signed-in account. Only the SHA-256 of the token is stored.
+///
+public sealed class ChatInviteService(BifrostDbContext db, AuditTrailService audit, TimeProvider time, IOptions host)
+{
+ public const string CookieName = BifrostCookies.HostPrefix + "bifrost_chat_invite";
+ public const string EntityType = "ChatInvite";
+ public static readonly TimeSpan Lifetime = TimeSpan.FromDays(14);
+ public static readonly TimeSpan CookieLifetime = TimeSpan.FromHours(1);
+
+ /// The link an operator sends: the public base URL plus the invite path.
+ public string LinkFor(string token) => host.Value.PublicBaseUrl.TrimEnd('/') + "/invite#" + token;
+
+ public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))).ToLowerInvariant();
+
+ /// Mints an invite and returns the token, which exists only in this result.
+ public async Task<(ChatInvite Invite, string Token)> MintAsync(Guid issuedBy, string note, CancellationToken cancellationToken)
+ {
+ var token = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
+ var now = time.GetUtcNow();
+ var invite = new ChatInvite
+ {
+ TokenHash = Hash(token),
+ Note = note.Trim(),
+ IssuedByUserAccountId = issuedBy,
+ IssuedAtUtc = now,
+ ExpiresAtUtc = now + Lifetime
+ };
+ db.ChatInvites.Add(invite);
+ await audit.RecordAsync(issuedBy, EntityType, invite.Id, "chat.invite.minted", $"Minted a chat invite: {invite.Note}", cancellationToken);
+ return (invite, token);
+ }
+
+ /// Revokes an unredeemed invite. False when it is absent or already redeemed or revoked.
+ public async Task RevokeAsync(Guid inviteId, Guid revokedBy, CancellationToken cancellationToken)
+ {
+ var invite = await db.ChatInvites.SingleOrDefaultAsync(x => x.Id == inviteId, cancellationToken);
+ if (invite is null || invite.RedeemedAtUtc is not null || invite.RevokedAtUtc is not null)
+ {
+ return false;
+ }
+
+ invite.RevokedAtUtc = time.GetUtcNow();
+ try
+ {
+ await audit.RecordAsync(revokedBy, EntityType, invite.Id, "chat.invite.revoked", $"Revoked a chat invite: {invite.Note}", cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ db.ChangeTracker.Clear();
+ return false;
+ }
+
+ return true;
+ }
+
+ /// The unredeemed, unrevoked invites, newest first (expired ones included, so they can be revoked and seen).
+ public Task> PendingAsync(CancellationToken cancellationToken) =>
+ db.ChatInvites.AsNoTracking()
+ .Where(x => x.RedeemedAtUtc == null && x.RevokedAtUtc == null)
+ .OrderByDescending(x => x.IssuedAtUtc)
+ .ToListAsync(cancellationToken);
+
+ /// True when the token names an invite that is unredeemed, unrevoked and unexpired now.
+ public async Task IsLiveAsync(string token, CancellationToken cancellationToken)
+ {
+ var now = time.GetUtcNow();
+ var hash = Hash(token);
+ var invite = await db.ChatInvites.AsNoTracking().SingleOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
+ return invite is not null && invite.RedeemedAtUtc is null && invite.RevokedAtUtc is null && invite.ExpiresAtUtc > now;
+ }
+
+ ///
+ /// The one reading of "invited", for every decision that asks it (token, userinfo, redemption): a redeemed chat invite
+ /// or an Active membership. Derived at read time, never copied to MAS or Synapse. The account needs its Membership loaded.
+ ///
+ public static bool IsInvited(UserAccount account) =>
+ account.ChatInvitedAtUtc is not null || new CurrentBifrostActor(true, account).IsActiveMember;
+
+ public void Carry(HttpContext http, string token) =>
+ http.Response.Cookies.Append(CookieName, token, CookieOptions(CookieLifetime));
+
+ ///
+ /// The one redemption, called after every sign-in. A request carrying the cookie spends the invite onto this account in one save and
+ /// clears the cookie. An account that is already invited, or an Active member, keeps the invite unspent. A second account with the same
+ /// link is refused: the save is conditional on the invite still being unredeemed, so a race has one winner.
+ ///
+ public async Task RedeemCarriedAsync(HttpContext http, Guid accountId, CancellationToken cancellationToken)
+ {
+ if (!http.Request.Cookies.TryGetValue(CookieName, out var token) || string.IsNullOrEmpty(token))
+ {
+ return;
+ }
+
+ http.Response.Cookies.Delete(CookieName, CookieOptions(null));
+ var now = time.GetUtcNow();
+ var hash = Hash(token);
+ var invite = await db.ChatInvites.SingleOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
+ var account = await db.UserAccounts.Include(x => x.Membership).SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
+ if (invite is null || account is null
+ || invite.RedeemedAtUtc is not null || invite.RevokedAtUtc is not null || invite.ExpiresAtUtc <= now
+ || IsInvited(account))
+ {
+ return;
+ }
+
+ invite.RedeemedByUserAccountId = account.Id;
+ invite.RedeemedAtUtc = now;
+ account.ChatInvitedAtUtc = now;
+ try
+ {
+ await audit.RecordAsync(account.Id, EntityType, invite.Id, "chat.invite.redeemed", $"Redeemed a chat invite: {invite.Note}", cancellationToken);
+ }
+ catch (DbUpdateConcurrencyException)
+ {
+ // Another account spent it first, or it was revoked in between: nothing of this attempt is kept.
+ db.ChangeTracker.Clear();
+ }
+ }
+
+ private static CookieOptions CookieOptions(TimeSpan? maxAge) => new()
+ {
+ HttpOnly = true,
+ Secure = true,
+ SameSite = SameSiteMode.Lax,
+ Path = BifrostCookies.Path,
+ MaxAge = maxAge
+ };
+}
diff --git a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
index 6d41d73..4d4cfc6 100644
--- a/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
+++ b/src/Bifrost.Web/Features/Membership/MembershipSynchronizationService.cs
@@ -36,11 +36,6 @@ public sealed class MembershipSynchronizationService(
.ThenInclude(x => x.TierSnapshots)
.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
- var invitation = await dbContext.MembershipInvitations
- .SingleOrDefaultAsync(
- x => x.NormalizedGitHubLogin == normalizedLogin && x.RevokedAtUtc == null,
- cancellationToken);
-
if (userAccount is null)
{
userAccount = new UserAccount
@@ -60,7 +55,7 @@ public sealed class MembershipSynchronizationService(
},
Membership = new Bifrost.Web.Domain.Membership
{
- Status = invitation is null ? MembershipStatus.Authenticated : MembershipStatus.PendingApproval,
+ Status = MembershipStatus.Authenticated,
CreatedAtUtc = now
}
};
@@ -88,11 +83,6 @@ public sealed class MembershipSynchronizationService(
UserAccountId = userAccount.Id,
CreatedAtUtc = now
};
-
- if (invitation is not null && userAccount.Membership.Status == MembershipStatus.Authenticated)
- {
- userAccount.Membership.Status = MembershipStatus.PendingApproval;
- }
}
if (string.IsNullOrWhiteSpace(userAccount.MemberProfile!.Nickname))
@@ -105,12 +95,6 @@ public sealed class MembershipSynchronizationService(
userAccount.GitHubLogin,
cancellationToken);
- if (invitation is not null && invitation.AcceptedByUserAccountId is null)
- {
- invitation.AcceptedByUserAccountId = userAccount.Id;
- invitation.AcceptedAtUtc = now;
- }
-
MembershipStatus? promotedFrom = null;
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
{
diff --git a/src/Bifrost.Web/Features/Motions/MotionEveSurfaceService.cs b/src/Bifrost.Web/Features/Motions/MotionEveSurfaceService.cs
deleted file mode 100644
index dbe5d96..0000000
--- a/src/Bifrost.Web/Features/Motions/MotionEveSurfaceService.cs
+++ /dev/null
@@ -1,203 +0,0 @@
-using Bifrost.Web.Domain;
-
-namespace Bifrost.Web.Features.Motions;
-
-public sealed class MotionEveSurfaceService
-{
- private const string MotionCommandTarget = "cultmesh://asgard.starfire.bifrost/commands/motion";
-
- public EveSurfaceDocument BuildSurface(MotionGovernanceState state)
- {
- var motionNodes = state.Motions.Count > 0
- ? state.Motions.Select(BuildMotionCard).ToArray()
- : [TextNode("motion-empty", "No motions yet.")];
-
- return new EveSurfaceDocument(
- "gamecult.eve.surface.v1",
- "bifrost-motion-verse",
- "Bifrost Motion Verse",
- new EveNode(
- "bifrost-motion-root",
- "workspace",
- new Dictionary
- {
- ["title"] = "Bifrost Governance",
- ["subtitle"] = "Motions, weighted votes, thresholds, and receipts",
- ["actor"] = state.ActorName,
- ["effectiveVotingWeight"] = state.EffectiveVotingWeight,
- ["canonicalCommandTarget"] = MotionCommandTarget,
- ["commandTransport"] = "cultmesh-command-document",
- ["commandSchema"] = "bifrost.motion_command.v0"
- },
- [
- new EveNode(
- "motion-create",
- "form",
- new Dictionary
- {
- ["title"] = "Open Motion",
- ["command"] = "motion.create",
- ["target"] = MotionCommandTarget,
- ["transport"] = "cultmesh-command-document"
- },
- [
- SelectNode("scope", "Scope", EnumNames()),
- SelectNode("projectId", "Project", state.Projects.Select(x => new EveOption(x.Id.ToString(), x.Name)).Prepend(new EveOption("", "No project scope"))),
- SelectNode("category", "Category", EnumNames()),
- InputNode("title", "Title", "text"),
- InputNode("summary", "Summary", "multiline"),
- InputNode("closesAtUtc", "Close at UTC", "datetime")
- ]),
- new EveNode(
- "vote-ledger",
- "panel",
- new Dictionary
- {
- ["title"] = "Vote Ledger",
- ["effectiveVotingWeight"] = state.EffectiveVotingWeight
- },
- state.CategoryPolicies
- .Select(x => TextNode($"threshold-{Slug(x.Label)}", $"{x.Label}: {x.Threshold:P0} threshold"))
- .ToArray()),
- new EveNode(
- "motions",
- "collection",
- new Dictionary { ["title"] = "Motions" },
- motionNodes)
- ]));
- }
-
- private static EveNode BuildMotionCard(MotionListItem motion)
- {
- var commandNodes = new List();
- foreach (var choice in Enum.GetValues())
- {
- commandNodes.Add(CommandNode(
- $"vote-{motion.Id}-{choice}",
- $"Vote {choice}",
- "motion.vote",
- new Dictionary
- {
- ["motionId"] = motion.Id,
- ["choice"] = choice.ToString(),
- ["comment"] = string.Empty
- },
- motion.CurrentUserVote == choice ? "selected" : "default"));
- }
-
- if (motion.StatusLabel == "Expired")
- {
- commandNodes.Add(CommandNode(
- $"close-{motion.Id}",
- "Close motion",
- "motion.close",
- new Dictionary { ["motionId"] = motion.Id },
- "secondary"));
- }
-
- return new EveNode(
- $"motion-{motion.Id}",
- "card",
- new Dictionary
- {
- ["title"] = motion.Title,
- ["summary"] = motion.Summary,
- ["scope"] = motion.Scope,
- ["category"] = motion.Category,
- ["status"] = motion.StatusLabel,
- ["tone"] = motion.StatusTone,
- ["project"] = motion.ProjectName,
- ["threshold"] = motion.Threshold,
- ["closesAtUtc"] = motion.ClosesAtUtc,
- ["resolutionNote"] = motion.ResolutionNote
- },
- [
- new EveNode(
- $"motion-votes-{motion.Id}",
- "metrics",
- new Dictionary
- {
- ["for"] = motion.VotesFor,
- ["against"] = motion.VotesAgainst,
- ["abstain"] = motion.VotesAbstain,
- ["currentUserVote"] = motion.CurrentUserVote?.ToString() ?? string.Empty
- }),
- new EveNode(
- $"motion-commands-{motion.Id}",
- "commands",
- new Dictionary
- {
- ["target"] = MotionCommandTarget,
- ["transport"] = "cultmesh-command-document"
- },
- commandNodes)
- ]);
- }
-
- private static EveNode CommandNode(
- string id,
- string label,
- string command,
- IReadOnlyDictionary payload,
- string tone) =>
- new(
- id,
- "command",
- new Dictionary
- {
- ["label"] = label,
- ["command"] = command,
- ["target"] = MotionCommandTarget,
- ["transport"] = "cultmesh-command-document",
- ["payload"] = payload,
- ["tone"] = tone
- });
-
- private static EveNode InputNode(string id, string label, string inputKind) =>
- new(
- $"input-{id}",
- "input",
- new Dictionary
- {
- ["name"] = id,
- ["label"] = label,
- ["inputKind"] = inputKind
- });
-
- private static EveNode SelectNode(string id, string label, IEnumerable options) =>
- SelectNode(id, label, options.Select(x => new EveOption(x, x)));
-
- private static EveNode SelectNode(string id, string label, IEnumerable options) =>
- new(
- $"input-{id}",
- "select",
- new Dictionary
- {
- ["name"] = id,
- ["label"] = label,
- ["options"] = options.ToArray()
- });
-
- private static EveNode TextNode(string id, string text) =>
- new(id, "text", new Dictionary { ["text"] = text });
-
- private static IReadOnlyList EnumNames() where TEnum : struct, Enum =>
- Enum.GetNames();
-
- private static string Slug(string value) =>
- value.ToLowerInvariant().Replace(" ", "-", StringComparison.Ordinal);
-}
-
-public sealed record EveSurfaceDocument(
- string Schema,
- string Id,
- string Title,
- EveNode Root);
-
-public sealed record EveNode(
- string Id,
- string Kind,
- IReadOnlyDictionary Props,
- IReadOnlyList