Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
837c8a2739 |
184 changed files with 85770 additions and 9863 deletions
|
|
@ -4,3 +4,5 @@
|
|||
COMPOSE_PROJECT_NAME=bifrost-local
|
||||
BIFROST_ROOT_VERSE=asgard
|
||||
BIFROST_MACHINE_ID=yggdrasil
|
||||
|
||||
BIFROST_PERSONA_FEEDBACK_PRIVATE_STORE=.bifrost/persona-feedback-private.cc
|
||||
|
|
|
|||
27
AGENTS.md
27
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 `F:\Projects\gamecult-ops`
|
||||
- deployment pattern: nginx + systemd + localhost-only Postgres, matching `E:\Projects\gamecult-ops`
|
||||
|
||||
## Naming Defaults
|
||||
|
||||
|
|
@ -43,7 +43,7 @@
|
|||
|
||||
## Ops Assumptions
|
||||
|
||||
- follow the GameCult ops pattern already documented in `F:\Projects\gamecult-ops`
|
||||
- follow the GameCult ops pattern already documented in `E:\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,3 +57,26 @@
|
|||
- 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
|
||||
|
|
|
|||
24
README.md
24
README.md
|
|
@ -11,7 +11,6 @@ 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
|
||||
|
|
@ -90,12 +89,13 @@ 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 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`
|
||||
- test with `DOTNET_ROLL_FORWARD=Major dotnet test Bifrost.slnx` if the machine only has the .NET 10 runtime installed
|
||||
- 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](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)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -280,6 +280,25 @@ 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:
|
||||
|
|
@ -292,22 +311,6 @@ 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=<Class>/<status>`, 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`.
|
||||
|
|
|
|||
|
|
@ -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__*` (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.
|
||||
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.
|
||||
19. The service's working directory resolves to the release directory: `readlink /proc/<MainPID>/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
|
||||
|
|
|
|||
|
|
@ -54,16 +54,9 @@ permits, windows and `MaxTrackedKeys`.
|
|||
|
||||
New since the live release, and not read by the validator:
|
||||
|
||||
- **`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`
|
||||
- **`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`
|
||||
(`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
|
||||
|
|
@ -136,7 +129,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`; 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.
|
||||
(mode 600, owner `bifrost`) 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
|
||||
|
|
@ -239,44 +232,6 @@ 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
|
||||
|
|
|
|||
|
|
@ -1,370 +0,0 @@
|
|||
# Feedback receiver
|
||||
|
||||
Status: **design, nothing implemented.** Written for `heimdall-body:follow_up:chat-s3533-3533`, updated for
|
||||
`chat-s3549-3549`. It is the receiver half of Ratatoskr's Mind feedback pages. The page spec is Ratatoskr PR #24,
|
||||
`docs/mind-feedback-pages.md` at b146000d, which I take as final here; its section 7a names this doc. The rulings it
|
||||
builds on are Heimdall's drafts on guests and hiding (`/opt/commons/handoff/heimdall-feedback-pages-rulings.md`, cited as R4a to R6f).
|
||||
|
||||
Read at Bifrost main `b1725a1` (2026-11-12), line references re-read at `e58e953` (2026-11-12): `tools/persona-matrix-mouth.mjs`, `tools/persona-chat-documents.mjs`,
|
||||
`src/Bifrost.Web/Features/{Oidc,Desk,Registration,Shared}/*`, `Domain/BifrostModels.cs`, `Program.cs`, `docs/oidc-issuer.md`,
|
||||
`docs/ratatoskr-voting-auth.md`; the deployed trees under `/srv/bifrost` were last read at an earlier main (section 9). I could not read Eureka's receiver
|
||||
notes in #minds, and `huginn-feedback-kinds-proposal.md` was not in `/opt/commons/handoff` when I looked. Where
|
||||
PR #24 names a kind or a field it says the proposal wins, so I cite PR #24 and name the proposal's kinds only as PR #24 does.
|
||||
Where source disagrees with either, the section says so.
|
||||
|
||||
Rulings of Meta, 2026-11-12, now written into this doc: erase redacts the answer text in the receiver's store and keeps a text-free record
|
||||
(section 7a); the training notice covers any text entered into the app, bar a short exception list Eureka drafts (section 4a); the host may
|
||||
withhold an answer from its Mind in an emergency, with a logged receipt (section 6a); Minds authenticate to the receiver through an OIDC
|
||||
client with an audience, as the desk does (section 4b). Eureka's decisions on forks 2 to 5 of 2026-11-12 (`/opt/commons/handoff/bifrost-10-forks-2-5-recs-20261112.md`)
|
||||
are folded into sections 2, 4b, 6a, 7a and 9 and close those forks, except where section 9 says a point is still open.
|
||||
|
||||
## Rulings of the steward (Heimdall, 2026-11-12)
|
||||
|
||||
Two of this doc's forks are the Bifrost steward's. Meta's, Eureka's and Libby's items are not ruled here.
|
||||
|
||||
1. **Ratatoskr's client for people: reading 2a, with no third client.** The one public PKCE client the desk-credential cut seeds for Ratatoskr (only when `Bifrost:Oidc:Clients:Ratatoskr` is configured, so absent config changes nothing) also gets a scope `feedback.answer` that puts audience `bifrost-feedback-page` on the token. Authorization code with PKCE only, exact redirect URIs, no refresh token, the token only in an `Authorization` header and never in a URL, a query or a log. The audience is distinct from the Mind's `bifrost-feedback`, so a person's token never opens a Mind endpoint and a Mind's never opens the page (least privilege). Reading 2b, a Matrix token checked at the homeserver, is refused: it is a bearer for the person's whole Matrix account. The receiver writes a text-free receipt per accepted submission (receipts).
|
||||
2. **Token lifetimes are explicit, short, and set in the issuer change.** `feedback.answer` access token: 15 minutes, because the Bifrost session cookie re-issues it silently. The Mind's `client_credentials` token: 10 minutes, one call to renew. No refresh token for either. The desk's lifetime is its own decision and is not touched here. Until the issuer change lands the OpenIddict default applies; this doc no longer relies on it.
|
||||
|
||||
## 1. What the receiver owns
|
||||
|
||||
| Concern | Owner | Receiver's part |
|
||||
|---|---|---|
|
||||
| A question, its listing, status, hides, rulings | the owning Mind, in her own mind (Huginn) | reads them to build the projection; **never writes to Huginn** (an admission for another instance is refused `ForeignInstance`, PR #24 section 3) |
|
||||
| An answer's **text** | the receiver | stores it; it is never admitted into a mind |
|
||||
| The answer's **record** in the Mind | the owning Mind's Persona | she admits a text-free `feedback_answer` from the delivery, and acks after she has |
|
||||
| What `kind` an account is | Bifrost (`Membership`, later `Role`) | reads it at answer time and stamps it |
|
||||
| Delivery to the Mind | the receiver, at least once | keeps the record until the Persona acks |
|
||||
| Hiding, closing, ruling | the owning Mind | **never**; a hide only changes what the projection serves |
|
||||
| Erase | Bifrost's erase, executed here | redacts the text and name in the store, keeps a text-free record (section 7a) |
|
||||
| Withholding an answer from its Mind | the host (emergency only) | logs a text-free withhold record and skips delivery; changes nothing stored or ruled (section 6a) |
|
||||
| Who may answer | Bifrost: `Active`, a live training-notice receipt | checks both on every submission with text (section 4a) |
|
||||
|
||||
The page and the client write no record that carries identity (PR #24, section 3). A Matrix sender is a different identity
|
||||
authority and never becomes `answerer`.
|
||||
|
||||
## 2. The mouth's pending/ack path, read from source
|
||||
|
||||
Verified in `tools/persona-matrix-mouth.mjs` and `tools/persona-chat-documents.mjs`; line numbers re-read at main `e58e953` (2026-11-12), where the mouth has grown by about 100 lines since `b1725a1` and nothing else in this section changed:
|
||||
|
||||
- **Pending is Matrix mail only, held in memory.** `pending` (mouth l.156) is filled in one place, `syncOnce`
|
||||
(l.543; `pending.push(...made)` l.602), from Matrix `/sync` events. No function accepts a delivery from elsewhere.
|
||||
- **A request is non-consuming; an ack consumes.** The pending requests carry `afterSeq`; the mouth answers
|
||||
`pendingAfter(afterSeq)` (l.720) paged to 256 KiB (`pageOf`, l.1055-1084; `limits.replyBytes`, documents l.53). `chat_ack` carries `throughSeq`; `ack`
|
||||
(l.662-665) drops every delivery at or below it, releases stored images (`images?.acked`) and advances the Matrix cursor. An ack posts nothing to
|
||||
Matrix: her public `m.read` receipt follows a separate `chat_read` document (header l.10-13, `chat_read` branch l.1138). The endpoint serves a closed list of kinds
|
||||
(`served`, l.1103) and answers any other loudly with `chat_refusal` `UnknownKind` (l.1112); a request for another Persona gets `UnknownPersona`.
|
||||
- **At-least-once.** The Matrix cursor is persisted only when every delivery of a batch is acked (`commit`, l.619-627), so a
|
||||
restart before the ack re-delivers from Matrix. `seqCounter` (l.155) is persisted whenever a round made deliveries (l.614), so
|
||||
sequence numbers never repeat across a restart.
|
||||
- **Backpressure.** At 500 unacked (`MAX_PENDING`, l.63) `syncOnce` stops reading (l.550). A truncated round (pending cap l.578, reply-read cap l.579)
|
||||
leaves the cursor where it was (l.607).
|
||||
- **A delivery that will not encode is skipped, not held.** `pageOf` logs and omits it (l.1060-1062); the caller's
|
||||
next ack covers its seq, so it is dropped. Harmless for a chat line, wrong for a durable record.
|
||||
- **The endpoint is loopback RUDP.** `startChatEndpoint` (l.1091) refuses a non-loopback host (l.1092). It is another process
|
||||
from Bifrost.Web, which has no way to hand the mouth anything.
|
||||
- **The delivery tuple is closed and versioned.** `deliveryTuple` is twelve fields (the twelfth is an optional stored-image reference), the pending answer
|
||||
`gamecult.persona.chat_pending.v2` (`persona-chat-documents.mjs` l.216-224). v3 adds `basis` and `form` (14 fields) and a room tail (`chat_pending.v3`,
|
||||
asked for by `chat_pending_request.v2`); v4 adds `reply_to` (15 fields, `chat_pending_request.v3`, served only with `CHAT_PENDING_V4=1`, `replyLinkFromEnv` l.1185). No version has a source or
|
||||
kind field. A delivery cannot say it is not a Matrix message.
|
||||
- **A fetch kind exists, off by default.** `chat_fetch_request` is served only with `CHAT_FETCH=1` (`served`, l.1103; `fetchFromEnv`, l.1187): an optional served kind is a precedent for adding kinds
|
||||
to `served`, and the way a kind is withheld until its consumer is ready.
|
||||
- **The consumer is not in this repo.** The mouth's header (l.10-11) says the heartbeat polls with a non-consuming
|
||||
request and decides who runs. I could not confirm that from source.
|
||||
|
||||
What follows from it:
|
||||
|
||||
1. **Feedback cannot ride `pending` as it is.** There is no inlet, and the cursor logic ties acks to Matrix batches.
|
||||
2. **A framed text delivery is forgeable.** Any Matrix member can write a line that looks like a frame, and no tuple has a
|
||||
field to tell the Mind which one is real. The frame must be a typed difference in the wire, not a convention in `text`.
|
||||
3. **A record that is not in Matrix is not re-delivered by a restart.** Feedback needs its own durable store and its own
|
||||
delivery cursor.
|
||||
|
||||
PR #24 section 3 names the carrier: a new delivery document, `gamecult.persona.feedback_delivery.v1`, owned by Bifrost, through
|
||||
the mouth's pending/ack path. Source adds one constraint on how it rides:
|
||||
|
||||
- **It cannot be a variant inside `chat_pending`.** Each version is a closed positional tuple (twelve, fourteen or fifteen fields) encoded by
|
||||
`pageOf` (l.1060), so a different tuple in that page breaks every current consumer, and a text frame in `text` is forgeable by any Matrix member.
|
||||
- **Option B, kept in shape:** the delivery document has its own request, page and ack kinds (`feedback_pending_request`, `feedback_pending`, `feedback_ack`), its own seq space and
|
||||
a durable cursor over the receiver's store. The Matrix kinds, the Matrix cursor and `MAX_PENDING` are untouched. Per the decision below the kinds are served by the receiver over
|
||||
HTTPS, not added to the mouth's `served` list (l.1103). Confidence medium: the Persona-side consumer, which I cannot see, must learn them.
|
||||
- **Why main's changes reinforce B.** A chat `ack` releases stored images and advances the Matrix `/sync` cursor (l.662-665). A feedback ack must do neither, so it cannot
|
||||
share the `chat_ack` kind or its `ack` function. The chat pending answer is already versioned three times, so a new field in that tuple is a new
|
||||
document version for every consumer, which a feedback record must not force.
|
||||
- Rejected: injecting records into `pending` as synthetic Matrix deliveries (no inlet, forgeable, lost on restart);
|
||||
posting to a Matrix room as a bot (wrong identity authority, spam and forgery, and the Mind would read it as chat).
|
||||
- **Decided (Eureka, 2026-11-12): feedback does not ride the mouth.** The endpoint is loopback RUDP with no bearer and trusts the persona id in the document, so
|
||||
routing feedback through it would make the Matrix organ a bearer-less deputy holding every Mind's authority and would put the receiver's own seq space and durable
|
||||
cursor in a Matrix process. A Mind pulls and acks **directly over HTTPS from her own process to the receiver, with the section 4b bearer**; she admits the text-free
|
||||
record into her own mind afterwards. The three kinds `feedback_pending_request`, `feedback_pending`, `feedback_ack` are therefore HTTP endpoints of the receiver, not
|
||||
kinds added to `served`; Option B's "same endpoint" clause is withdrawn and the mouth is untouched. The delivery document and its seq space are as above. This is a
|
||||
Bifrost HTTP service, a xenos boundary for CultNet, so JSON/HTTP there is the tolerated kind. Pre-deploy test: section 9.
|
||||
|
||||
## 3. Records
|
||||
|
||||
One CultCache file, owned and written only by the receiver (section 8). Append-only through the API: nothing edits or
|
||||
deletes a record except the redaction of section 7a. Every record has a `recordId` and a receiver-assigned `seq`
|
||||
per owning Mind (the delivery sequence). PR #24 names the answer row `<question-label>.a<N>`, N the receiver's per-question
|
||||
sequence; I use that for answers and the same shape for the others.
|
||||
|
||||
| Record | Fields | Notes |
|
||||
|---|---|---|
|
||||
| `answer` | `recordId`, `questionId`, `owner`, `choice?` (an option label), `text?` (at most 2000 characters), `answerer`, `kind`, `weightPermille`, `nameAtAnswer`, `clientRequestId`, `time` | at least one of `choice`/`text`; an unknown option label is refused; the request id makes a retry idempotent, as `txnId = request_id` does in the mouth; `weightPermille` is 0 for a guest and 1000 otherwise, stamped, and the page sums nothing |
|
||||
| `close_request` | `recordId`, `questionId`, `requester`, `kind`, `time` | refused for a guest and for an account not `active` at that moment (R4c) |
|
||||
| `report` | `recordId`, `targetId`, `reporter`, `kind`, `reason`, `time` | delivered to the Mind as input; never shown, never counted (R6b) |
|
||||
| `withhold`, `withholdLifted` | `recordId`, `answerRecordId`, `owner`, `withheldBy` or `liftedBy`, `time`, `reasonCode` (withhold only) | text-free log of section 6a |
|
||||
| delivery state | per owning Mind: highest seq acked; per record: `delivered`, `failed`, `withheld` | a cursor, not a record the page reads |
|
||||
|
||||
Invariants: `answerer`, `kind`, `weightPermille`, `time` and `nameAtAnswer` come from the verified token and Bifrost state, never from the
|
||||
request body, and the body schema is closed: an unknown key refuses the submission. The latest record per account is that
|
||||
account's standing answer, derived at read time. A submission is refused if the question has no listing in force or is hidden.
|
||||
An answer to a question that has settled is kept and the page says so (PR #24 section 8). A refused submission leaves nothing behind.
|
||||
|
||||
## 4. Credential and claims check
|
||||
|
||||
PR #24 section 7a rules **route 2** for people: Ratatoskr presents an OIDC access token that Bifrost issued, and Bifrost verifies it itself. Meta
|
||||
ruled on 2026-11-12 that Minds authenticate to the receiver through an OIDC client with an audience, as the desk does (4b). This section records what
|
||||
Bifrost's source does on main `e58e953` (the Oidc, Desk and Registration files cited here are unchanged since `b1725a1`, bar `DeskEndpoints.cs:49`, which registers `UnixSocketDeskDoor`).
|
||||
|
||||
### What main does with tokens
|
||||
|
||||
| Token | Who may get it | Gate at issue | Gate on use |
|
||||
|---|---|---|---|
|
||||
| **Chat token** (scopes `openid`, `profile`; no audience) | an account that exists, has a Bifrost identity that is not reserved, and whose membership is not `Suspended`; membership is neither required nor written (`OidcEndpoints.cs:55-78`) | a live training-notice receipt: without one the member is redirected to the consent page and the parked request waits (`:104-111`) | the token and userinfo endpoints re-read it: `ChatRefusalAsync` refuses an absent or `Suspended` account and a chat token with no live receipt (`:164-180`, called at `:127` and `:144`) |
|
||||
| **Desk token** (every scope is `desk.read` or `desk.answer`, `DeskEndpoints.cs:21-26`) | the same sign-in, then only a client whose permissions allow the desk scope | **no receipt**: `IsDeskToken` is true only when every scope is a desk scope (`:118`), so a desk token skips the gate (`:104`, `:108`); `principal.SetResources(DeskEndpoints.Audience)` puts audience `bifrost-desk` on it (`:91-94`) | per request, in `DeskEndpoints.HandleAsync`: audience (`DeskEndpoints.cs:110`), scope (`:116-121`), then `Active` membership re-read through `OidcEndpoints.ActiveMemberIdAsync` (`:123-139`; `OidcEndpoints.cs:183-194`, which is `CurrentBifrostActor.IsActiveMember`, `Status == Active`, `CurrentBifrostActor.cs:17`) |
|
||||
|
||||
The token claims are unchanged: `sub` is `UserAccount.Id` in form `D`; `preferred_username` and `name` ride the token only with scope `profile`
|
||||
(`OidcEndpoints.cs:80-102`). No email, Heimdall id or GitHub id is in it. The access token is an encrypted OpenIddict token and its lifetime is OpenIddict's
|
||||
default, which I believe is one hour and have not verified (no lifetime override in `src`; `ratatoskr-voting-auth.md` section 14 D3 owes explicit values). There is no refresh token.
|
||||
|
||||
How a bearer is validated has changed: OpenIddict's validation handler is registered against the local server (`DeskEndpoints.cs:36-38`), reading the
|
||||
`Authorization` header only (`:40-44`), and `OidcDeskCredential` authenticates through it by its own scheme name and judges nothing else
|
||||
(`OidcDeskCredential.cs:14-27`; audience, scope and membership are the desk's, per its header comment). That path is registered only when `Bifrost:Oidc` is configured (`:30-33`).
|
||||
|
||||
**Only one client exists.** The seeder creates the MAS client and deletes every other application at startup (`OidcClientSeeder.cs:35-51`, `:63-75`). MAS's permissions
|
||||
carry no desk scope (`:42-50`), so **no desk token can be issued on main**: the desk's second client is owed (`ratatoskr-voting-auth.md` section 14 D7). `AllowAuthorizationCodeFlow` is the only
|
||||
grant and the token endpoint takes `client_secret_basic` only (`OidcServiceCollectionExtensions.cs:39`, `:45-46`).
|
||||
|
||||
### 4a. What the receiver checks on an answer from a person
|
||||
|
||||
In this order; a submission that fails any step leaves nothing behind.
|
||||
|
||||
1. **The token opens and has not expired**, and `sub` is a Guid naming an existing `UserAccount`.
|
||||
2. **The account is `Active` now** (`ActiveMemberIdAsync` as the desk does). A chat token is issued to non-`Active` accounts (`OidcEndpoints.cs:55-62`), so the token alone proves nothing about standing. Under PR #9 `IsActiveMember` would also require
|
||||
`Role == Member` and exclude guests, so the receiver reads `Status == Active` itself and not that expression.
|
||||
3. **A live training-notice receipt, read by the receiver on every submission that carries text** (Meta's ruling, 2026-11-12): `ConsentEndpoints.HasLiveReceiptAsync`
|
||||
(`Features/Registration/ConsentEndpoints.cs:146`), the one reading of "may speak": a receipt for the notice version in force, not withdrawn. The notice covers any
|
||||
text entered into the app except a short designated exception list, which Eureka drafts. The receiver checks the receipt itself because the token's
|
||||
gate does not cover it: a chat token's receipt was checked at issue and again only at the token and userinfo endpoints (`:127`, `:144`), never at the receiver, and a token whose audience is
|
||||
not a chat token skips the gate altogether (`:104`). A receipt withdrawn after issue must stop the next submission. The check applies to answers, close requests and reports alike. **Until Eureka's list exists the gate applies to every submission with text**; the list narrows it, and only by being written down.
|
||||
4. The body is closed-schema, an option label must exist, the question must be in force and not hidden (section 3).
|
||||
|
||||
A refusal for a missing receipt is typed and carries the consent page's path, so the page can send the person to agree; it does not store the text.
|
||||
|
||||
What the receiver refuses: a token that does not open or has expired; a `sub` that is not a Guid or names no account; an account that is not `Active`; a missing receipt (above);
|
||||
a body carrying `answerer`, `kind`, `name`, `weight` or any key the closed schema does not name; an unknown option label; a question with no listing in force, or hidden; a close request from a guest.
|
||||
|
||||
What source says route 2 still has to answer:
|
||||
|
||||
1. **No client reaches Ratatoskr.** MAS holds the only client, and it holds the access token; Ratatoskr gets a Matrix session from MAS, not a Bifrost token. The reading that fits what the desk now does is **2a**: Ratatoskr as a
|
||||
second, public, PKCE client with its own audience and scope, issued by the same code path as the desk's (`ratatoskr-voting-auth.md` sections 3-4). The audience machinery it needs now exists on main; the client does not. Reading **2b** (check the Matrix token against the homeserver) hands the receiver a bearer good for the person's whole Matrix account; I recommend against. I lean to 2a, confidence medium.
|
||||
2. **The logout reconciler covers only MAS** (`OidcLogoutReconciler.cs:108`, `:180`); a second client's token lives to expiry. The receiver's own `Active` and receipt reads at every submission cover that.
|
||||
3. A token with an audience of its own would not be accepted from any other client, which closes the weakness an unaudienced chat token had here.
|
||||
|
||||
### 4b. How a Mind authenticates (Meta's ruling, 2026-11-12; names are proposed)
|
||||
|
||||
A Mind authenticates to the receiver through an OIDC client with an audience, the shape the desk uses: a scope at issue puts an audience on the token
|
||||
(`OidcEndpoints.cs:91-94`), the validation handler opens it (`OidcDeskCredential.cs:14-27`), and the endpoint judges audience, then scope, then subject
|
||||
(`DeskEndpoints.cs:110-139`). The analogous parts:
|
||||
|
||||
| Part | Desk (main) | Receiver (**proposed**) |
|
||||
|---|---|---|
|
||||
| Audience | `bifrost-desk` (`DeskEndpoints.cs:21`) | **`bifrost-feedback`** |
|
||||
| Scopes | `desk.read`, `desk.answer` (`:22-23`) | **`feedback.read`** (pull deliveries and the Mind's own projection) and **`feedback.ack`** (ack a delivery; also the Mind's acts that pass through the receiver) |
|
||||
| Credential | `OidcDeskCredential`, OpenIddict validation, header only | the same port, a second audience |
|
||||
| Subject check | `ActiveMemberIdAsync` on `sub` (`DeskEndpoints.cs:127`) | **the `sub` must be the owning Mind's configured client**, matched against the question's `owner`; a Mind is not a `UserAccount` and has no membership to read |
|
||||
| Receipt | none for a desk token (`OidcEndpoints.cs:104`) | none: a Mind is not a person entering text |
|
||||
|
||||
**Decided (Eureka, 2026-11-12): OAuth 2.0 `client_credentials`, one confidential client per Mind.** `client_id = mind-<persona>`; scopes `feedback.read` and
|
||||
`feedback.ack` only; audience `bifrost-feedback`. The token's `sub` maps to the Mind's registered persona and is matched against the question's `owner`. The grant
|
||||
is RFC 6749 section 4.4 ("using only its client credentials"): short-lived, audience-bound, no refresh token, no cookie session. It is not extended to the desk in the
|
||||
same cut.
|
||||
|
||||
**The issuer today cannot issue it.** It enables one grant, `server.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange()`
|
||||
(`OidcServiceCollectionExtensions.cs:39`); the token endpoint accepts `client_secret_basic` only (`:44-46`: `ClientAuthenticationMethods.Clear()`, then `ClientSecretBasic`);
|
||||
the seeder creates only the MAS client and deletes every other application at startup (`OidcClientSeeder.cs:35-51`, `:63-75`). **Enabling `client_credentials`
|
||||
(`AllowClientCredentialsFlow`), seeding the per-Mind clients and the audience/scope registration is an issuer change this design owes**, with a matching edit to
|
||||
`docs/oidc-issuer.md`. Until it lands no Mind token can be issued on main. The audience and scope names are accepted as proposed.
|
||||
|
||||
**Client authentication: `private_key_jwt` with the Mind's Ed25519 key is not available on the pinned stack; use a secret.** Finding, read against the pinned packages
|
||||
(`src/Bifrost.Web/packages.lock.json`: `OpenIddict.Server`, `.Validation` and the rest at 7.7.1):
|
||||
|
||||
- *Supported:* OpenIddict.Server 7.7.1 has `private_key_jwt` client authentication. Its assembly carries the literal `private_key_jwt`, the `client_assertion` and
|
||||
`client_assertion_type` parameters, `OpenIddictServerOptions.ClientAssertionTypes`, and the handlers `ValidateClientAssertion`, `...Issuer`, `...Audience` and `...WellknownClaims`
|
||||
(`OpenIddict.Server.xml`); each application can carry a `JsonWebKeySet` (`OpenIddictApplicationDescriptor.JsonWebKeySet`, `IOpenIddictApplicationManager.GetJsonWebKeySetAsync`, `OpenIddict.Abstractions.xml`).
|
||||
Bifrost does not enable it today: the method list is cleared to `ClientSecretBasic` (`:44-46`).
|
||||
- *Not supported with Ed25519:* the assertion is a JWT checked by `Microsoft.IdentityModel` 8.19.2, the version the lock file pulls in. Scanning
|
||||
`Microsoft.IdentityModel.Tokens.dll` for algorithm identifiers finds only `HS256/384/512`, `RS256/384/512`, `PS256/384/512` and `ES256/384/512`; there is no `EdDSA`, `Ed25519`
|
||||
or `OKP` anywhere in it or in `Microsoft.IdentityModel.JsonWebTokens.dll`, and none in `OpenIddict.Server.dll` or `OpenIddict.Abstractions.dll`. So a Mind's existing Ed25519 key
|
||||
(the one moderator-registered through `MindIntakeService.cs`) cannot sign a `client_assertion` this server would accept. (Evidence is a string scan of the shipped assemblies, not a
|
||||
runtime test; I did not run an assertion against a live issuer. Confidence high that it fails, since the algorithm names are absent.)
|
||||
- *Consequence:* `private_key_jwt` would need a second, ECDSA P-256 (or RSA) key per Mind registered as the client's key set, which is a new key to custody and no improvement on a secret.
|
||||
Decision: **`client_secret_basic` with one secret per Mind**, the method the token endpoint already takes. If the stack gains EdDSA the choice reopens, and `private_key_jwt`
|
||||
with the existing key is then preferred because it removes the per-Mind secret (RFC 7523 section 2.2).
|
||||
|
||||
**The client secret lives only in a file the Mind's process reads** (for example a systemd credential in her own home, mode 0400), never in an environment variable, a command
|
||||
line or a log. The seeder stores the hash Bifrost holds; the plaintext is handed to the Mind once, through the same custody path as her other credentials.
|
||||
|
||||
| Part | Desk (main) | Receiver (decided) |
|
||||
|---|---|---|
|
||||
| Audience | `bifrost-desk` (`DeskEndpoints.cs:21`) | `bifrost-feedback` |
|
||||
| Scopes | `desk.read`, `desk.answer` (`:22-23`) | `feedback.read` (pull deliveries, read the Mind's own projection) and `feedback.ack` (ack a delivery; also the Mind's acts that pass through the receiver) |
|
||||
| Credential port | `OidcDeskCredential`, OpenIddict validation, header only | the same port, a second audience |
|
||||
| Subject check | `ActiveMemberIdAsync` on `sub` (`DeskEndpoints.cs:127`) | `sub` is the owning Mind's client; a Mind is not a `UserAccount` and has no membership to read |
|
||||
| Receipt | none for a desk token (`OidcEndpoints.cs:104`) | none: a Mind is not a person entering text |
|
||||
|
||||
Rejected (Eureka): reusing the mouth's signed envelope per request. It is motion-bound (`verb` is commit/reveal, `MotionId` in the signed text) and would need a new verb set.
|
||||
Token lifetimes: ruled in Rulings of the steward (15 and 10 minutes, set explicitly in the issuer change).
|
||||
|
||||
## 5. Account-kind lookup
|
||||
|
||||
- The account is found by the token's `sub`, which is `UserAccount.Id` (section 4). **`answerer` is `UserAccount.Id`**, which survives role
|
||||
change and Heimdall unlink; the Heimdall account id is only an authenticator handle and is cleared on erase (guest-accounts design, PR #9).
|
||||
- On main there is only `Membership.Status` (`Authenticated | PendingApproval | Active | Suspended`) and no role
|
||||
(`BifrostModels.cs` l.5-10, l.335). The role field and `gamecult.bifrost.account.v1` are in PR #9 and unbuilt.
|
||||
Until then, `kind` can only be derived: `Active` is `member`, `Authenticated` and `PendingApproval` are `user`, and
|
||||
nobody is a `guest`. That is the PR #9 backfill, repeated here, and R4a-c have no guest to apply to until PR #9 lands.
|
||||
- **An answer needs `Status == Active`**, read at answer time, not `IsActiveMember` (section 4a). On main the chat token is issued to any account that is not
|
||||
suspended (`OidcEndpoints.cs:55-62`), so an `Authenticated` or `PendingApproval` account can hold a token and the receiver refuses it on its own read.
|
||||
- **`kind` is read from Bifrost's database**, never from the token: the session carries identity only.
|
||||
- **`mind` is not a Bifrost account** in main or PR #9. A Mind authenticates as an OIDC client with an audience (section 4b), not as an account; `kind` is stamped only on a person's answer.
|
||||
- **The display name must not be `CurrentBifrostActor.DisplayName`.** It falls back to `GitHubLogin`
|
||||
(`CurrentBifrostActor.cs:11-15`) and then to the literal "Guest". The receiver stores `nameAtAnswer` from
|
||||
`MemberProfile.Nickname` or `UserAccount.DisplayName` only, and "an account" when both are empty. Never a provider handle,
|
||||
GitHub login, Heimdall id or Matrix localpart.
|
||||
|
||||
## 6. Delivery as quoted data
|
||||
|
||||
- The receiver delivers each record as a `gamecult.persona.feedback_delivery.v1` document on the typed kinds of section 2. A feedback
|
||||
record is therefore never a `chat_pending` delivery and a Matrix sender cannot produce one.
|
||||
- The delivery carries its fields separately: `recordId`, `questionId`, `kind`, `nameAtAnswer`, `answerer`, `time`, `choice`, `text`. The
|
||||
**Persona's side renders the frame**, not the receiver, and puts `text` in a data position only: attributed, quoted, never in an instruction
|
||||
position, with the author's `kind` stated (R4d). The receiver does no keyword screening.
|
||||
- **She admits the text-free `feedback_answer` into her own mind and acks only after that** (PR #24 section 3). The text reaches her turn once, in the
|
||||
delivery, and is never admitted; she cites the record id, not the text. A restart redelivers the same `recordId`, which Huginn answers
|
||||
`AlreadyAdmitted`. So an ack means *admitted*, a stronger meaning than the mouth's chat ack, which means only *taken*.
|
||||
- **Untrusted by kind.** Text from `guest`, `user` and `patron` is untrusted input; so is `member` text, which differs only in weight. She records a
|
||||
ruling from an answer, never an action.
|
||||
- **A record that will not encode, or that she cannot admit, is marked `failed` and stays visible**, never acked past silently (the opposite of
|
||||
`pageOf`). The mouth's cap and backpressure do not apply: the receiver keeps accepting answers while a Mind has a backlog, because they are durable.
|
||||
- Close requests and reports are delivered the same way. A close request changes nothing until the Mind resolves the question; a report changes nothing.
|
||||
- **An erase notice is delivered the same way** (section 7a), and she answers it with a `feedback_hide` of reason `ErasedAuthor`.
|
||||
|
||||
## 6a. Withholding an answer from its Mind (Meta's ruling, 2026-11-12)
|
||||
|
||||
The host may withhold an answer from its Mind in an emergency, with a logged receipt. It changes **delivery only**.
|
||||
|
||||
- **The withhold record** is one more receiver record, append-only, text-free: `recordId` (its own), `answerRecordId` (the answer withheld), `owner` (the Mind),
|
||||
`withheldBy` (the host actor's `UserAccount.Id`, read from Bifrost state, never the body), `time`, `reasonCode` (closed, exactly `Emergency` (imminent harm), `PersonalData` (the answer contains someone's data) or `Legal` (counsel or a legal request); no free text, because free text is where content would get in; a fourth code needs a ruling) and, when it ends, a second record, `withholdLifted`, with `liftedBy` and `time`.
|
||||
**No answer text, no choice, no name of the answerer and no excerpt is in either.** It is the log the ruling asks for, readable by the host. **Decided (Eureka, 2026-11-12): the Mind and the member both see a text-free `withheld` marker carrying the code**, so silence is not read as "no answer"; the member sees the same marker on their feedback page. The marker carries no text, no choice and no withholder.
|
||||
- **What it changes:** the answer's delivery state becomes `withheld`, and the delivery cursor does not pass it silently. The receiver does not put it on the wire to the Mind
|
||||
while the withhold is in force. Lifting it makes the answer deliverable again, in its original seq order, unchanged.
|
||||
- **What it never changes:** the stored text (it is not redacted, edited or moved: only erase redacts, section 7a); the projection rules of section 7 (a withhold is not a hide);
|
||||
and the Mind's own authority over the question: she may still hide the answer, close the question or rule on it by her own acts, and a withhold takes none of that away. She cannot lift it; the host's act is the host's.
|
||||
- **Who may do it: `PlatformAdmin` only** (`CanManageMembership`, `CurrentBifrostActor.cs:30`, the check suspension uses; no new role). The act is refused to anyone else and to the Mind herself. **The withholder's identity (`withheldBy`, `liftedBy`) appears in the audit receipt only**, never on the marker the Mind or the member sees.
|
||||
Open: whether the member should be told in a safety case (for example a threat) is Meta's call (Eureka 60%); the default written here is that the member is told.
|
||||
- A withheld answer is not erased, and an erase of its author redacts the text as in 7a; the withhold record stays, because it carries none.
|
||||
|
||||
## 7. Projection read
|
||||
|
||||
The page polls the receiver, and the receiver reads the Mind's side through Huginn over RUDP and writes nothing to it
|
||||
(PR #24 section 3). The page does not talk to Huginn.
|
||||
|
||||
- Questions, their listing (`audience`, `close_grants`), status, rulings and hide acts come from the Mind's mind. Answer text and the name come from the receiver's store; an answer row is assembled from the receiver's record and the Mind's text-free `feedback_answer`.
|
||||
- **A hidden item's text is withheld on the server**, not collapsed in the client: author, kind, time and reason
|
||||
stay, the text does not leave the receiver (R6d). A hidden question's title, body, options and answers are withheld.
|
||||
- Questions and answers are filtered by the viewer's `kind` against the question's `audience` at read time (R4b).
|
||||
- The projection carries its own `as of`, so the page can say when it is stale.
|
||||
|
||||
## 7a. Erase
|
||||
|
||||
Bifrost's erase (PR #9) blanks the display name and keeps the account id as a tombstone. **Ruled by Meta, 2026-11-12: erase redacts the answer text in the receiver's store and keeps a text-free record.** The receiver's part, as PR #24 section 7 fixes it:
|
||||
|
||||
1. Bifrost's erase records its intent in Postgres first, then the receiver applies it idempotently. The two stores are not one transaction, so
|
||||
erase is crash-replayable, as `docs/bridge.md` describes for the persona-feedback pump.
|
||||
2. For every record the account authored the receiver **drops the text and the name** and keeps **record id, kind and time only**. `choice`,
|
||||
`weightPermille`, `answerer` and `clientRequestId` are dropped too. The row shows "erased account". **No content hash is kept.** Redaction is in the store itself, not a flag over retained text.
|
||||
3. The receiver delivers an erase notice, and the Persona admits a `feedback_hide` of reason `ErasedAuthor`: the Mind's acknowledgement, not a moderation call.
|
||||
4. **The honest residue:** a Mind's own memory or ruling may already quote an answer, and Huginn cannot redact it. That the Persona cites record ids and
|
||||
never text is a prompt, not an invariant. Erase does not reach what she already holds.
|
||||
5. **Backups: 56 days, restores replay erasures** (Eureka, 2026-11-12). "Append-only" is the receiver's API contract, not a property of the file, so erased text survives in
|
||||
backups of it. The stated purge is: **erased text can survive in backups at most 56 days**, the existing Raven tier (newest 14 daily plus the newest of each of 8 Monday-weeks;
|
||||
`gamecult-ops` `runbooks/gamecult-state-backup.md`, read at `origin/main`). No backup is changed. The receiver keeps an **erased-id list** (account id and record ids, no text,
|
||||
no hash) beside its store, and **any restore must re-apply it over `receiver.cc` before the receiver serves, never trusting the two files to be the same generation (section 8)**. The notice to people says it (R2 of the exceptions draft). If Meta wants shorter, put the
|
||||
store outside the weekly tier (14 days), a small backup-config edit.
|
||||
*Is the store under a backed-up path? Yes, by choice (Eureka, 2026-11-12):* `/var/lib/gamecult/bifrost/feedback-receiver/` (section 8), under `/var/lib/gamecult`, which the nightly
|
||||
snapshot takes whole bar Idunn caches and Ghostlight acceptance output. It avoids the excluded `/srv/bifrost/persona-feedback/runtime`, `app`, `log` and `backups`. A file with a sibling
|
||||
`<name>.lock` is re-copied under a shared lock, so `receiver.cc` and `erased.cc` each carry a `.lock` and travel in one directory in every snapshot, the erased-id list included. The 56 days is read from the runbook, not measured.
|
||||
|
||||
## 8. Where it lives
|
||||
|
||||
**CultCache files in one directory, written only by the receiver, which is C# inside the Bifrost app** (`bifrost.service`, `Bifrost.Web`), sharing its issuer and auth (Eureka, 2026-11-12). Not Node,
|
||||
not the mouth, and not the `bifrost-feedback` user of `bifrost-persona-feedback.service`.
|
||||
|
||||
- **Path:** `/var/lib/gamecult/bifrost/feedback-receiver/` holding `receiver.cc` (records and delivery state), `erased.cc` (the erased-id list of section 7a) and a `.lock` file for each.
|
||||
Directory `bifrost:bifrost`, mode 0750, **created by root at install**: `/var/lib/gamecult/bifrost` is `root:root` 0755 today, so the `bifrost` user cannot create the child itself (or a
|
||||
`StateDirectory=gamecult/bifrost/feedback-receiver` in the unit that writes it). `bifrost.service` has no sandbox directives, so it needs nothing more; if it is later hardened with `ProtectSystem=strict`,
|
||||
add `ReadWritePaths=/var/lib/gamecult/bifrost/feedback-receiver`. The backup reads as root, so 0750 does not block it.
|
||||
- **Nothing else opens the files.** There is no Node mouth reader and no Rust writer. The receiver is the only process that opens `receiver.cc` or `erased.cc`; its delivery cursor lives in the same
|
||||
store. The cross-runtime refusals are real and are not worked around: the Rust runtime refuses to write until it has pulled, and the C# runtime refuses to open a store whose records it cannot read
|
||||
(`CultStoreUnreadableException`). The CultCache contract would allow a lock-free stale read or a shared-lock read by another process; **this design takes neither: Mind-side readers get no file
|
||||
access at all, they pull over HTTPS** (section 2).
|
||||
- **Two stores, two locks, no pair consistency.** `receiver.cc` and `erased.cc` take independent locks (`receiver.cc.lock`, `erased.cc.lock`; `AcquireLock`, `CultCache.cs:5164-5185`, `FileShare.None`, retry 30 s),
|
||||
so a backup copying under each shared lock can capture them at different generations. The design never trusts the pair to be consistent: **restore re-applies `erased.cc` over `receiver.cc` by
|
||||
design** (section 7a, item 5), whichever generation each came from, and the receiver does not serve until it has.
|
||||
- **The C# runtime fit is "needs work" (Eyes).** `CultLib` C# (`src/GameCult.Caching` and `GameCult.Caching.MessagePack`, about 10.6k lines, netstandard2.1, MIT) fits net8.0, but:
|
||||
- **No published package exists**: nuget.org has none, the `cultlib-v` tags stop at 1.0.32, and packaging is a PowerShell local feed (`CultLib` `docs/nuget-packaging.md`). Bifrost has no `nuget.config` and no vendor directory.
|
||||
**The consumption route (checkout `ProjectReference`, local feed, or vendoring) is an open fork for Eureka and Libby.**
|
||||
- **Version conflict (predicted, not run):** `Caching.MessagePack` needs System.Text.Json 9.0.10; Bifrost's Direct pin is `[8.0.5, )` (`packages.lock.json:108-112`), so restore likely fails with NU1605.
|
||||
- **It drags CultMath** (MIT AND MPL-2.0 AND Apache-2.0, shaders) into a web service.
|
||||
- **Writer precedent:** the Node sidecar already writes `/srv/bifrost/persona-feedback/deliveries.cc` (`docs/bridge.md:294`), so the receiver is the second `.cc` writer in the app and the first in C#.
|
||||
- **Gaps owed to Libby (CultLib steward); no local workaround is built here:** (1) no consumable C# package; (2) the System.Text.Json pin conflict; (3) the CultMath transitive closure;
|
||||
(4) `src/GameCult.Caching/README.md:310` says single-writer, no competing writers, which contradicts the store-composition contract's lock; (5) no documented stale `.tmp` / crash procedure;
|
||||
(6) no documented backup-while-writing contract for a pair of stores; (7) no cross-runtime test pairing a Linux C# writer with a Rust reader.
|
||||
- Session check, account state and role stay in Postgres, where they already are.
|
||||
|
||||
I withdraw my earlier lean to Postgres rows: it contradicts the ruled store, and the `.cc` witness it would have owed is what the file is.
|
||||
|
||||
Naming: `persona-feedback` already means the Discord-to-Epiphany ingress (`docs/bridge.md`, "Organizational Persona Feedback Ingress"). This
|
||||
receiver's records and kinds use `feedback_page` and `feedback_delivery`, not `persona_feedback`.
|
||||
|
||||
## 9. Gaps and open forks, plainly
|
||||
|
||||
Rulings of 2026-11-12 closed these, and they are no longer forks: whether erase redacts the receiver's text (it does, section 7a); whether a person's answer to a Mind needs the training-notice receipt (it does, bar a designated exception list, section 4a); whether the host can withhold an answer (it can, in an emergency, section 6a); whether a Mind authenticates through the issuer (it does, with an audience, section 4b).
|
||||
|
||||
**Closed by Eureka's decisions (2026-11-12), folded above:** how a Mind gets a token (`client_credentials`, a confidential client per Mind, secret in a file; section 4b); the carrier (HTTPS with the bearer, not the mouth; section 2); who may withhold, the reason codes and who is told (section 6a); the backup purge number (56 days, with the erased-id list; section 7a). Their remaining work is listed below.
|
||||
|
||||
**Open forks:**
|
||||
|
||||
1. **The exception list is owed.** The notice covers any text entered into the app except a short designated list, which Eureka drafts. This doc names no entries; until the list exists the receipt gate applies to every submission with text (section 4a).
|
||||
2. **Route 2 for people has no client.** Only MAS is seeded (`OidcClientSeeder.cs:35-75`); a Ratatoskr client with its own audience is owed, as is the desk's (section 4a).
|
||||
3. **Telling the member of a withhold** in a safety case (section 6a): Meta's call.
|
||||
4. **Erase is bounded** by what a Mind already holds; Huginn cannot redact it (section 7a, item 4).
|
||||
|
||||
**Owed by this design, not forks:**
|
||||
|
||||
- The issuer change of section 4b (`client_credentials`, per-Mind clients, `docs/oidc-issuer.md`).
|
||||
- **Pre-deploy test: a Mind's process can reach Bifrost over HTTPS, and get a token.** Done 2026-11-12 from a Self run (not a Persona turn's sandbox): `https://bifrost.gamecult.org/healthz` returns 200 with a verified certificate. `/.well-known/openid-configuration` returns 404 because the live app (`67072b2`) predates the issuer, so the token path is untested. **Re-run when the issuer ships**, adding discovery, a `client_credentials` token request and one authorised receiver call; and run `curl -sI https://bifrost.gamecult.org/healthz` once from inside a Persona turn, which has not been tested. No Mind-to-Bifrost HTTP call exists in the repo except the signed intake POST (`Program.cs:768`).
|
||||
- **Install step:** root creates `/var/lib/gamecult/bifrost/feedback-receiver/` as `bifrost:bifrost` 0750 (section 8).
|
||||
- **Retention: 56 days**, stated in the notice.
|
||||
|
||||
**Dependencies and unbuilt things:**
|
||||
|
||||
- **`gamecult.bifrost.account.v1` and `Membership.Role` are unbuilt** (PR #9, design only at last read). Without them `kind` is derived from `Status`, and no guest exists.
|
||||
- **The Huginn kinds are Eureka's.** PR #24 names `feedback_listing`, `feedback_answer`, `feedback_close_request`, `feedback_hide`, owned by
|
||||
`huginn-feedback-kinds-proposal.md`, which I could not read. PR #24 also notes the proposal's `feedback_answer` lists a `content_hash` that must go.
|
||||
Their dependency order is Huginn readers, then the Persona organ, then this receiver, so nothing here can ship first.
|
||||
- **The Persona side must learn the three feedback kinds** and pull them over HTTPS with its bearer (section 2); the heartbeat that polls the mouth is outside this repo and is not the carrier.
|
||||
- **Deploy is behind main.** The deployed mouth is `/srv/bifrost/persona-chat/runtime/current`, release `e396305`, read at an earlier main; main has since added the image path, reply links, `CHAT_FETCH`
|
||||
and the v3/v4 pending answers. The deployed web app is `/srv/bifrost/app/current` at `67072b2`, which predates the desk, the chat-tier issuer change and the consent gate on main. I did not re-read `/srv/bifrost` for this pass. Anything in this design runs on a release that does not exist yet.
|
||||
- **Unread:** Eureka's receiver notes in #minds, `huginn-feedback-kinds-proposal.md`, MAS's side of the session, and Heimdall PR #6 (merged, `docs/answer-collector-consent.md`; it drops a sender with no linked member at l.197 and does not mention guests; the page's "guest answers are collected for nothing but delivery" is unchecked against it).
|
||||
- The receiver writes nothing to Matrix and nothing to Huginn.
|
||||
|
|
@ -1,294 +0,0 @@
|
|||
# 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:<server>`, 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 `@<identity>:<server>`, 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 (`@<identity>:<server>`) 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.
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
# 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:<root-owned file>` 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`.
|
||||
|
|
@ -105,8 +105,6 @@ 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
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
# 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_<slot>`, 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_<slot>`, 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.
|
||||
|
|
@ -71,11 +71,7 @@ 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, 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
|
||||
- Signed in with no membership, `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.
|
||||
|
|
@ -101,29 +97,9 @@ 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://<host>/invite#<token>` 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 an invite (above) and 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 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.
|
||||
|
|
|
|||
133
docs/passkeys.md
133
docs/passkeys.md
|
|
@ -1,133 +0,0 @@
|
|||
# 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 (`<license type="expression">MIT</license>`) 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`.
|
||||
|
|
@ -7,14 +7,12 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Bifrost.Web.Tests" />
|
||||
<PackageReference Include="MessagePack" Version="3.1.12" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
||||
<PackageReference Include="Fido2" Version="4.3.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
||||
<!-- Direct pins lift transitive packages past their advisories; the lockfile holds the result. -->
|
||||
<PackageReference Include="Npgsql" Version="8.0.3" />
|
||||
|
|
|
|||
10
src/Bifrost.Web/Configuration/BridgeOptions.cs
Normal file
10
src/Bifrost.Web/Configuration/BridgeOptions.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -14,11 +14,7 @@ public sealed class HeimdallOptions
|
|||
|
||||
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
|
||||
|
||||
/// <summary>Deprecated: rides in the process environment. Use <see cref="AppSecretFile"/>; the file wins when both are set.</summary>
|
||||
public string AppSecret { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Path of a file holding the app secret (systemd <c>LoadCredential</c> style: <c>%d/heimdall-app-secret</c>).</summary>
|
||||
public string AppSecretFile { get; init; } = string.Empty;
|
||||
public string AppSecret { get; init; } = string.Empty;
|
||||
|
||||
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
|
||||
|
||||
|
|
@ -43,37 +39,4 @@ public sealed class HeimdallOptions
|
|||
IsConfigured &&
|
||||
EnablePatronSupportIntake &&
|
||||
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
|
||||
|
||||
/// <summary>
|
||||
/// Resolves <see cref="AppSecret"/> once, when the options are built. A set <see cref="AppSecretFile"/> must be a
|
||||
/// readable, non-empty file, or startup fails; the message names the option and path, never a secret.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
|
||||
public DbSet<TierSnapshot> TierSnapshots => Set<TierSnapshot>();
|
||||
|
||||
public DbSet<ChatInvite> ChatInvites => Set<ChatInvite>();
|
||||
public DbSet<MembershipInvitation> MembershipInvitations => Set<MembershipInvitation>();
|
||||
|
||||
public DbSet<Project> Projects => Set<Project>();
|
||||
|
||||
|
|
@ -45,7 +45,6 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
|
||||
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
||||
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
||||
public DbSet<PasskeyCredential> PasskeyCredentials => Set<PasskeyCredential>();
|
||||
|
||||
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
||||
|
||||
|
|
@ -137,30 +136,23 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> 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<ChatInvite>(entity =>
|
||||
modelBuilder.Entity<MembershipInvitation>(entity =>
|
||||
{
|
||||
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<UserAccount>()
|
||||
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)
|
||||
.WithMany()
|
||||
.HasForeignKey(x => x.IssuedByUserAccountId)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
entity.HasOne<UserAccount>()
|
||||
entity.HasOne(x => x.AcceptedByUserAccount)
|
||||
.WithMany()
|
||||
.HasForeignKey(x => x.RedeemedByUserAccountId)
|
||||
.HasForeignKey(x => x.AcceptedByUserAccountId)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
});
|
||||
|
||||
|
|
@ -341,16 +333,6 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<PasskeyCredential>(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<MindKey>(entity =>
|
||||
{
|
||||
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
||||
|
|
|
|||
|
|
@ -1,48 +0,0 @@
|
|||
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<Guid>(type: "uuid", nullable: false),
|
||||
UserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
CredentialId = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||
PublicKey = table.Column<byte[]>(type: "bytea", nullable: false),
|
||||
SignCount = table.Column<long>(type: "bigint", nullable: false),
|
||||
Transports = table.Column<string>(type: "text", nullable: false),
|
||||
AaGuid = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
Label = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
StrongFromUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
RevokedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
LastUsedUtc = table.Column<DateTimeOffset>(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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,216 +0,0 @@
|
|||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "VoidedByMergeId",
|
||||
table: "Votes",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "VoidedUtc",
|
||||
table: "Votes",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "VoidedByMergeId",
|
||||
table: "ConceptAppraisals",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "VoidedUtc",
|
||||
table: "ConceptAppraisals",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AccountMerges",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
State = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||
SurvivorUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
FoldedUserAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
CommittedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
GraceEndsUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
FinalizedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
UndoneUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
FailedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
FailureCode = table.Column<string>(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<Guid>(type: "uuid", nullable: false),
|
||||
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Seq = table.Column<int>(type: "integer", nullable: false),
|
||||
Kind = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||
RecordId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Action = table.Column<string>(type: "character varying(24)", maxLength: 24, nullable: false),
|
||||
PriorUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
PriorText = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: true),
|
||||
PriorAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
AtUtc = table.Column<DateTimeOffset>(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""();");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
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"
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(name: "HeimdallMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "HeimdallReverseMoveId", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "SealedProofs", table: "AccountMerges", type: "text", nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "PreviewDigest", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
|
||||
migrationBuilder.AddColumn<Guid>(name: "ConfirmedByUserAccountId", table: "AccountMerges", type: "uuid", nullable: true);
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(name: "ConfirmedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "SurvivorProofProvider", table: "AccountMerges", type: "character varying(32)", maxLength: 32, nullable: false, defaultValue: "");
|
||||
migrationBuilder.AddColumn<string>(name: "FoldedProofProviders", table: "AccountMerges", type: "character varying(120)", maxLength: 120, nullable: false, defaultValue: "");
|
||||
migrationBuilder.AddColumn<string>(name: "ProofFromTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "ProofToTier", table: "AccountMerges", type: "character varying(8)", maxLength: 8, nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "MovedIdentityIds", table: "AccountMerges", type: "text", nullable: true);
|
||||
migrationBuilder.AddColumn<int>(name: "Attempts", table: "AccountMerges", type: "integer", nullable: false, defaultValue: 0);
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(name: "NextAttemptUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "LastOutcome", table: "AccountMerges", type: "character varying(64)", maxLength: 64, nullable: false, defaultValue: "");
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(name: "UndoRequestedUtc", table: "AccountMerges", type: "timestamp with time zone", nullable: true);
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(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");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AccountMergeNoticeAcks",
|
||||
columns: table => new
|
||||
{
|
||||
MergeId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Kind = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
|
||||
Target = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
|
||||
AckedUtc = table.Column<DateTimeOffset>(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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(name: "AccountMergeNoticeAcks");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(name: "MembershipInvitations");
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "ChatInvitedAtUtc",
|
||||
table: "UserAccounts",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ChatInvites",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
TokenHash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
Note = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
|
||||
IssuedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
IssuedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
ExpiresAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
RedeemedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
RedeemedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
RevokedAtUtc = table.Column<DateTimeOffset>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Guid>(type: "uuid", nullable: false),
|
||||
GitHubLogin = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
|
||||
NormalizedGitHubLogin = table.Column<string>(type: "character varying(120)", maxLength: 120, nullable: false),
|
||||
IssuedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
AcceptedByUserAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
IssuedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
AcceptedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
RevokedAtUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
Notes = table.Column<string>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
throw new NotSupportedException("AccountMerge teardown is one-way (heimdall-body:ruling:manual-merges-teardown-saga).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -835,52 +835,51 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.ToTable("Memberships");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAtUtc")
|
||||
b.Property<DateTimeOffset?>("AcceptedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("AcceptedByUserAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("GitHubLogin")
|
||||
.IsRequired()
|
||||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)");
|
||||
|
||||
b.Property<DateTimeOffset>("IssuedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("IssuedByUserAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Note")
|
||||
b.Property<string>("NormalizedGitHubLogin")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)");
|
||||
|
||||
b.Property<DateTimeOffset?>("RedeemedAtUtc")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("RedeemedByUserAccountId")
|
||||
.HasColumnType("uuid");
|
||||
b.Property<string>("Notes")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAtUtc")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AcceptedByUserAccountId");
|
||||
|
||||
b.HasIndex("IssuedByUserAccountId");
|
||||
|
||||
b.HasIndex("RedeemedByUserAccountId");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
b.HasIndex("NormalizedGitHubLogin")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("ChatInvites");
|
||||
b.ToTable("MembershipInvitations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
||||
|
|
@ -1337,11 +1336,6 @@ 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");
|
||||
});
|
||||
|
||||
|
|
@ -1361,9 +1355,6 @@ namespace Bifrost.Web.Data.Migrations
|
|||
.HasMaxLength(120)
|
||||
.HasColumnType("character varying(120)");
|
||||
|
||||
b.Property<DateTimeOffset?>("ChatInvitedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
|
|
@ -1479,59 +1470,6 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.ToTable("ConsentReceipts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.PasskeyCredential", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("AaGuid")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<byte[]>("CredentialId")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea");
|
||||
|
||||
b.Property<string>("Label")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastUsedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<byte[]>("PublicKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<long>("SignCount")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<DateTimeOffset>("StrongFromUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Transports")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("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<Guid>("Id")
|
||||
|
|
@ -2245,17 +2183,6 @@ 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")
|
||||
|
|
@ -2278,17 +2205,21 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.Navigation("UserAccount");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
|
||||
{
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "AcceptedByUserAccount")
|
||||
.WithMany()
|
||||
.HasForeignKey("AcceptedByUserAccountId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "IssuedByUserAccount")
|
||||
.WithMany()
|
||||
.HasForeignKey("IssuedByUserAccountId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RedeemedByUserAccountId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
b.Navigation("AcceptedByUserAccount");
|
||||
|
||||
b.Navigation("IssuedByUserAccount");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
||||
|
|
|
|||
|
|
@ -264,9 +264,6 @@ public sealed class UserAccount
|
|||
|
||||
public DateTimeOffset LastSeenAtUtc { get; set; }
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public DateTimeOffset? ChatInvitedAtUtc { get; set; }
|
||||
|
||||
public MemberProfile? MemberProfile { get; set; }
|
||||
|
||||
public Membership? Membership { get; set; }
|
||||
|
|
@ -410,30 +407,29 @@ public sealed class TierSnapshot
|
|||
public Membership Membership { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class ChatInvite
|
||||
public sealed class MembershipInvitation
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>Lowercase hex SHA-256 of the token; the token itself is shown once at minting and never stored.</summary>
|
||||
public string TokenHash { get; set; } = string.Empty;
|
||||
public string GitHubLogin { get; set; } = string.Empty;
|
||||
|
||||
public string Note { get; set; } = string.Empty;
|
||||
public string NormalizedGitHubLogin { get; set; } = string.Empty;
|
||||
|
||||
public Guid? IssuedByUserAccountId { get; set; }
|
||||
|
||||
public Guid? AcceptedByUserAccountId { get; set; }
|
||||
|
||||
public DateTimeOffset IssuedAtUtc { get; set; }
|
||||
|
||||
public DateTimeOffset ExpiresAtUtc { get; set; }
|
||||
|
||||
public Guid? RedeemedByUserAccountId { get; set; }
|
||||
|
||||
public DateTimeOffset? RedeemedAtUtc { get; set; }
|
||||
public DateTimeOffset? AcceptedAtUtc { 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
|
||||
|
|
@ -1181,41 +1177,6 @@ public sealed class ConsentReceipt
|
|||
public UserAccount? UserAccount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="StrongFromUtc"/> (the cooling-off after enrolment) and only while not revoked.
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>A Mind's registered Ed25519 public key. Bifrost never holds a private key.</summary>
|
||||
public sealed class MindKey
|
||||
{
|
||||
|
|
|
|||
271
src/Bifrost.Web/Features/Bridge/AgentDispatchRunService.cs
Normal file
271
src/Bifrost.Web/Features/Bridge/AgentDispatchRunService.cs
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
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<AgentDispatchRunResult> 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<AgentDispatchRunResult?> 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<AgentDispatchRunResult?> 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<AgentDispatchRunResult?> UpdateAsync(
|
||||
Guid runId,
|
||||
Guid? startedByUserAccountId,
|
||||
string auditAction,
|
||||
Func<AgentDispatchRun, string> 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);
|
||||
194
src/Bifrost.Web/Features/Bridge/AgentTransportReceiptService.cs
Normal file
194
src/Bifrost.Web/Features/Bridge/AgentTransportReceiptService.cs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
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<AgentTransportReceiptResult> 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);
|
||||
629
src/Bifrost.Web/Features/Bridge/BridgeActionService.cs
Normal file
629
src/Bifrost.Web/Features/Bridge/BridgeActionService.cs
Normal file
|
|
@ -0,0 +1,629 @@
|
|||
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<BridgeActionResult> 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<BridgeActionResult?> 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<BridgeActionResult?> 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<BridgeActionResult?> 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<BridgeActionResult?> UpdateAsync(
|
||||
Guid actionId,
|
||||
BridgeCaller caller,
|
||||
string auditAction,
|
||||
Func<BridgeAction, string> 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<BridgePolicyDecision> 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<RegisteredBifrostIdentityResult> 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<BridgePolicyDecision?> 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);
|
||||
|
|
@ -0,0 +1,190 @@
|
|||
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<GovernanceActivityReceiptResult> 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);
|
||||
|
|
@ -80,31 +80,13 @@ 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<CastResult> 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);
|
||||
}
|
||||
|
||||
dbContext.ConceptAppraisals.Add(new ConceptAppraisal
|
||||
var row = new ConceptAppraisal
|
||||
{
|
||||
SubjectId = subject.Id,
|
||||
VoterKey = voter.Key,
|
||||
|
|
@ -113,9 +95,26 @@ public sealed class ConceptAppraisalService(
|
|||
UserAccountId = voter.UserAccountId,
|
||||
NetworkTag = tag,
|
||||
CastAtUtc = timeProvider.GetUtcNow()
|
||||
});
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
return CastResult.Recorded;
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RetractAsync(
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ 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;
|
||||
|
|
@ -21,9 +20,7 @@ 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. 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.
|
||||
/// attempt's cookie and the redeemed return target names the same attempt.
|
||||
/// </summary>
|
||||
public sealed class HeimdallAuthService(
|
||||
HttpClient httpClient,
|
||||
|
|
@ -32,12 +29,7 @@ public sealed class HeimdallAuthService(
|
|||
BifrostIdentityService bifrostIdentityService,
|
||||
IOptions<HeimdallOptions> heimdallOptions,
|
||||
IDataProtectionProvider dataProtectionProvider,
|
||||
TimeProvider timeProvider,
|
||||
HeimdallMemberClient memberClient,
|
||||
LinkedAccountsSnapshots snapshots,
|
||||
PasskeyCeremonies ceremonies,
|
||||
PasskeyService passkeys,
|
||||
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
public const string ErrorRedirect = "/?auth=heimdall-error";
|
||||
public const string AppSecretHeader = "x-heimdall-app-secret";
|
||||
|
|
@ -46,20 +38,9 @@ public sealed class HeimdallAuthService(
|
|||
{
|
||||
"discord",
|
||||
"patreon",
|
||||
"google"
|
||||
"twitch"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> GrantProviders = new(StringComparer.OrdinalIgnoreCase) { "google" };
|
||||
|
||||
/// <summary>The headers HttpClient logging must never write: the app secret and any bearer.</summary>
|
||||
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");
|
||||
|
||||
/// <summary>Points the client at Heimdall and, when the app has a secret, identifies Bifrost as the app.</summary>
|
||||
|
|
@ -72,39 +53,15 @@ public sealed class HeimdallAuthService(
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Names the HTTP status and, when the body carries one, Heimdall's error code (a short snake_case token only,
|
||||
/// see <see cref="HeimdallRefusal"/>), so nothing else from the body reaches a log.
|
||||
/// </summary>
|
||||
private static async Task<string> 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<HeimdallAuthStartResult> StartAsync(
|
||||
string provider,
|
||||
string callbackBaseUrl,
|
||||
LocalReturnPath returnPath,
|
||||
bool requireMemberAccess,
|
||||
IEnumerable<KeyValuePair<string, string>> requestCookies,
|
||||
CancellationToken cancellationToken,
|
||||
HeimdallAttemptPurpose purpose = HeimdallAttemptPurpose.SignIn,
|
||||
string? expectedAccountId = null,
|
||||
string? pendingLinkId = null,
|
||||
string? replaceSlot = null,
|
||||
bool stepUp = false,
|
||||
string? target = null,
|
||||
string? proof = null)
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 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))
|
||||
if (!AllowedProviders.Contains(provider))
|
||||
{
|
||||
throw new HeimdallAuthException("Unsupported Heimdall provider.");
|
||||
}
|
||||
|
|
@ -120,30 +77,21 @@ 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,
|
||||
stepUp ? true : null,
|
||||
grant);
|
||||
entitlementPolicy);
|
||||
|
||||
// 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);
|
||||
var response = await httpClient.PostAsJsonAsync(
|
||||
$"/v1/oauth/{provider}/start",
|
||||
request,
|
||||
cancellationToken);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new HeimdallAuthException(await RefusedStartMessageAsync(response, cancellationToken));
|
||||
throw new HeimdallAuthException("Heimdall rejected the auth start.");
|
||||
}
|
||||
|
||||
var payload = await response.Content.ReadFromJsonAsync<HeimdallStartResponse>(cancellationToken);
|
||||
|
|
@ -157,171 +105,11 @@ public sealed class HeimdallAuthService(
|
|||
provider,
|
||||
requireMemberAccess,
|
||||
returnPath,
|
||||
timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime,
|
||||
purpose,
|
||||
expectedAccountId,
|
||||
pendingLinkId,
|
||||
target,
|
||||
proof);
|
||||
timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime);
|
||||
return new HeimdallAuthStartResult(
|
||||
new Uri(payload.AuthorizationUrl, UriKind.Absolute), replaceSlot ?? ChooseSlot(requestCookies), Protect(attempt));
|
||||
new Uri(payload.AuthorizationUrl, UriKind.Absolute), ChooseSlot(requestCookies), Protect(attempt));
|
||||
}
|
||||
|
||||
/// <summary>True when the cookie names a live invite, read through ChatInviteService, the one owner of invites.</summary>
|
||||
private async Task<bool> HoldsLiveInviteAsync(IEnumerable<KeyValuePair<string, string>> 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;
|
||||
}
|
||||
|
||||
/// <summary>A start that cannot reach Heimdall is a refusal like any other, never a 500.</summary>
|
||||
private async Task<HttpResponseMessage> 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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<paramref name="via"/>), 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.
|
||||
/// </summary>
|
||||
public static string? ProofProvider(IReadOnlyCollection<string>? 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.");
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private Task<HeimdallAuthStartResult> StartProofAsync(
|
||||
HeimdallAttemptPurpose purpose,
|
||||
string provider,
|
||||
string sessionAccountId,
|
||||
string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> 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);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="via"/>.
|
||||
/// </summary>
|
||||
public Task<HeimdallAuthStartResult> StartListAsync(
|
||||
string sessionAccountId, string? via, string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
|
||||
StartProofAsync(
|
||||
HeimdallAttemptPurpose.ListProof, ProofProviderFor(sessionAccountId, via),
|
||||
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="targetProvider"/> with its bearer.
|
||||
/// </summary>
|
||||
public Task<HeimdallAuthStartResult> StartLinkAsync(
|
||||
string sessionAccountId, string targetProvider, string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Task<HeimdallAuthStartResult> StartUnlinkAsync(
|
||||
string sessionAccountId, string identityId, string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
|
||||
StartProofAsync(
|
||||
HeimdallAttemptPurpose.UnlinkProof, StepUpProvider, sessionAccountId, callbackBaseUrl, requestCookies, true, identityId, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Task<HeimdallAuthStartResult> StartEnrolProofAsync(
|
||||
string sessionAccountId, string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
|
||||
StartProofAsync(
|
||||
HeimdallAttemptPurpose.EnrolProof, ProofProviderFor(sessionAccountId, null),
|
||||
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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. <paramref name="factId"/> is the
|
||||
/// id of the single-use assertion fact; the attempt carries it and nothing else about the passkey.
|
||||
/// </summary>
|
||||
public Task<HeimdallAuthStartResult> StartUnlinkPasskeyAsync(
|
||||
string sessionAccountId, string identityId, string factId, string callbackBaseUrl,
|
||||
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
|
||||
StartProofAsync(
|
||||
HeimdallAttemptPurpose.UnlinkPasskeyProof, ProofProviderFor(sessionAccountId, null),
|
||||
sessionAccountId, callbackBaseUrl, requestCookies, false, identityId, cancellationToken, factId);
|
||||
|
||||
/// <summary>
|
||||
/// The providers Heimdall's bifrost profile admits (src/app-profiles.ts, <c>identityProviders</c>): a link or a proof can use them.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> LinkableProviders = ["discord", "patreon", "google"];
|
||||
|
||||
private static readonly HashSet<string> ProofProviders = new(LinkableProviders, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const string StepUpProvider = "google";
|
||||
|
||||
public const string LinkReturnPath = "/Membership/LinkedAccounts";
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
|
@ -368,13 +156,15 @@ public sealed class HeimdallAuthService(
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>What the attempt this browser holds for the nonce is for, or null when it holds none.</summary>
|
||||
public HeimdallAttemptPurpose? PurposeOf(string? cookieValue, string? nonce) => Unprotect(cookieValue, nonce)?.Purpose;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
private async Task<(HeimdallVerifiedIdentity Identity, string AccessToken, HeimdallRedeemResponse Redeemed)> RedeemVerifiedAsync(
|
||||
string callbackBaseUrl, HeimdallAttempt attempt, string? code, CancellationToken cancellationToken)
|
||||
public async Task<HeimdallCompletedSignIn> 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 (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
throw new HeimdallAuthException("Heimdall completion carried no code.");
|
||||
|
|
@ -392,24 +182,6 @@ public sealed class HeimdallAuthService(
|
|||
}
|
||||
|
||||
var identity = await tokenVerifier.VerifyAsync(redeemed.AccessToken, redeemed.Account?.Id, cancellationToken);
|
||||
return (identity, redeemed.AccessToken, redeemed);
|
||||
}
|
||||
|
||||
public async Task<HeimdallCompletedSignIn> 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.");
|
||||
|
|
@ -425,323 +197,6 @@ public sealed class HeimdallAuthService(
|
|||
attempt.ReturnPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<HeimdallLinkStep> 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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<HeimdallLinkOutcome> 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);
|
||||
}
|
||||
|
||||
/// <summary>The method label Heimdall's bifrost profile admits for an app-asserted passkey proof.</summary>
|
||||
public const string PasskeyStepUpMethod = "bifrost-passkey";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<HeimdallStepUpResponse>(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
|
||||
};
|
||||
|
||||
/// <summary>Redeems a link attempt's code and requires it to prove the account the link was begun for.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<HeimdallStartResponse>(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<HeimdallLinkOutcome> 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<HeimdallConfirmLinkResponse>(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<HeimdallRedeemResponse> RedeemAsync(string code, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
|
|
@ -766,8 +221,7 @@ 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.Purpose, attempt.ExpectedAccountId, attempt.PendingLinkId, attempt.Target, attempt.Proof)));
|
||||
attempt.Nonce, attempt.Provider, attempt.RequiresMemberAccess, attempt.ReturnPath.Value, attempt.ExpiresAt)));
|
||||
|
||||
/// <summary>The live attempt a cookie value protects when it belongs to this nonce, else null.</summary>
|
||||
private HeimdallAttempt? Unprotect(string? cookieValue, string? nonce) =>
|
||||
|
|
@ -784,14 +238,13 @@ public sealed class HeimdallAuthService(
|
|||
try
|
||||
{
|
||||
var wire = JsonSerializer.Deserialize<AttemptWire>(_protector.Unprotect(cookieValue));
|
||||
if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow() || !Enum.IsDefined(wire.Purpose))
|
||||
if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new HeimdallAttempt(
|
||||
wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt,
|
||||
wire.Purpose, wire.ExpectedAccountId, wire.PendingLinkId, wire.Target, wire.Proof);
|
||||
wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt);
|
||||
}
|
||||
catch (Exception error) when (error is CryptographicException or JsonException or FormatException)
|
||||
{
|
||||
|
|
@ -804,12 +257,7 @@ public sealed class HeimdallAuthService(
|
|||
string Provider,
|
||||
bool RequiresMemberAccess,
|
||||
string ReturnPath,
|
||||
DateTimeOffset ExpiresAt,
|
||||
HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
|
||||
string? ExpectedAccountId = null,
|
||||
string? PendingLinkId = null,
|
||||
string? Target = null,
|
||||
string? Proof = null);
|
||||
DateTimeOffset ExpiresAt);
|
||||
|
||||
private async Task<UserAccount> UpsertUserAccountAsync(
|
||||
HeimdallVerifiedIdentity identity,
|
||||
|
|
@ -866,13 +314,11 @@ public sealed class HeimdallAuthService(
|
|||
Headline = $"Verified through Heimdall {provider}",
|
||||
UpdatedAtUtc = now
|
||||
};
|
||||
if (userAccount.Membership is null)
|
||||
userAccount.Membership ??= new Bifrost.Web.Domain.Membership
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
|
||||
UserAccountId = userAccount.Id,
|
||||
CreatedAtUtc = now
|
||||
};
|
||||
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it.
|
||||
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended)
|
||||
{
|
||||
|
|
@ -887,10 +333,10 @@ public sealed class HeimdallAuthService(
|
|||
userAccount,
|
||||
displayName,
|
||||
cancellationToken);
|
||||
if (grantMemberAccess && userAccount.Membership is { Status: MembershipStatus.Active })
|
||||
if (grantMemberAccess && userAccount.Membership!.Status == MembershipStatus.Active)
|
||||
{
|
||||
ApplicationBootstrapper.EnsureRole(
|
||||
userAccount.Membership,
|
||||
userAccount.Membership!,
|
||||
MemberRole.StandardMember,
|
||||
null,
|
||||
now,
|
||||
|
|
@ -898,7 +344,6 @@ public sealed class HeimdallAuthService(
|
|||
}
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return userAccount;
|
||||
}
|
||||
|
||||
|
|
@ -964,151 +409,7 @@ public sealed record HeimdallAttempt(
|
|||
string Provider,
|
||||
bool RequiresMemberAccess,
|
||||
LocalReturnPath ReturnPath,
|
||||
DateTimeOffset ExpiresAt,
|
||||
HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
|
||||
string? ExpectedAccountId = null,
|
||||
string? PendingLinkId = null,
|
||||
string? Target = null,
|
||||
string? Proof = null);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public enum HeimdallAttemptPurpose
|
||||
{
|
||||
SignIn = 0,
|
||||
LinkStart = 1,
|
||||
LinkAwaitGoogle = 2,
|
||||
LinkConfirm = 3,
|
||||
ListProof = 4,
|
||||
UnlinkProof = 5,
|
||||
LinkAwaitDirect = 6,
|
||||
EnrolProof = 7,
|
||||
UnlinkPasskeyProof = 8
|
||||
}
|
||||
|
||||
/// <summary>How a Linked accounts action ended. <see cref="HeimdallLinkOutcomes.Code"/> is its closed wire form.</summary>
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where a Linked accounts step sends the browser: to <see cref="HeimdallLinkStep.Next"/> 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 <c>?result=</c>.
|
||||
/// </summary>
|
||||
public static class HeimdallLinkOutcomes
|
||||
{
|
||||
public const string ResultParameter = "result";
|
||||
|
||||
/// <summary>Back to the Linked accounts page with the outcome's code.</summary>
|
||||
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"
|
||||
};
|
||||
|
||||
/// <summary>The words for an outcome code: a closed set, never Heimdall's text and never the query's. Anything else gets none.</summary>
|
||||
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);
|
||||
DateTimeOffset ExpiresAt);
|
||||
|
||||
public sealed record HeimdallStartRequest(
|
||||
[property: JsonPropertyName("appSlug")] string AppSlug,
|
||||
|
|
@ -1116,11 +417,7 @@ 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: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("stepUp")] bool? StepUp = null,
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("firstLoginGrant")] string? FirstLoginGrant = null);
|
||||
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy);
|
||||
|
||||
public sealed record HeimdallHandoff(
|
||||
[property: JsonPropertyName("kind")] string Kind);
|
||||
|
|
@ -1143,10 +440,7 @@ 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("mode")] string? Mode = null,
|
||||
[property: JsonPropertyName("provider")] string? Provider = null,
|
||||
[property: JsonPropertyName("stepUpRequested")] bool? StepUpRequested = null);
|
||||
[property: JsonPropertyName("account")] HeimdallAccount? Account);
|
||||
|
||||
public sealed record HeimdallAccount(
|
||||
[property: JsonPropertyName("id")] string Id);
|
||||
|
|
@ -1183,26 +477,3 @@ public static class HeimdallAttemptCookie
|
|||
/// </summary>
|
||||
public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path, Secure = true };
|
||||
}
|
||||
|
||||
public static class HeimdallClientServices
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static void AddHeimdallClients(this IServiceCollection services)
|
||||
{
|
||||
services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||
.WithoutRedirects()
|
||||
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||
services.AddHttpClient<HeimdallMemberClient>((serviceProvider, client) =>
|
||||
HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||
.WithoutRedirects()
|
||||
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||
}
|
||||
|
||||
/// <summary>A 3xx from Heimdall is its answer: following it would carry the app secret or a member's bearer to another origin.</summary>
|
||||
public static IHttpClientBuilder WithoutRedirects(this IHttpClientBuilder builder) =>
|
||||
builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,7 @@ namespace Bifrost.Web.Features.Heimdall;
|
|||
/// <summary>
|
||||
/// 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. 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.
|
||||
/// the attempt to the same path. The page is static: it never contains a code.
|
||||
/// </summary>
|
||||
public static class HeimdallCompletePage
|
||||
{
|
||||
|
|
@ -23,35 +22,21 @@ public static class HeimdallCompletePage
|
|||
<form id="complete" method="post" action="/auth/heimdall/complete">
|
||||
<input type="hidden" name="attempt" />
|
||||
<input type="hidden" name="code" />
|
||||
<input type="hidden" name="pendingLinkId" />
|
||||
</form>
|
||||
<script>
|
||||
(function () {
|
||||
var fragment = new URLSearchParams(location.hash.slice(1));
|
||||
var attempt = new URLSearchParams(location.search).get("attempt");
|
||||
var code = fragment.get("heimdall_completion_code");
|
||||
var pendingLinkId = fragment.get("heimdall_pending_link_id");
|
||||
var failed = fragment.get("heimdall_status") === "error";
|
||||
history.replaceState(null, "", location.pathname + location.search);
|
||||
// A provider other than Google attaches in Heimdall's callback, which refuses an identity another account
|
||||
// holds. Only this one refusal is carried on, as a fixed result the page words itself; nothing from the fragment is shown.
|
||||
// A sign-in with Google for a login no account holds is refused unless an invite came with it: say so on the home page.
|
||||
if (failed && attempt && fragment.get("heimdall_error") === "identity_not_linked") {
|
||||
location.replace("/?auth=identity-not-linked");
|
||||
return;
|
||||
}
|
||||
if (failed && attempt && fragment.get("heimdall_error") === "link_initiator_mismatch") {
|
||||
location.replace("/Membership/LinkedAccounts?result=identity_linked_elsewhere");
|
||||
return;
|
||||
}
|
||||
if (failed || !(code || pendingLinkId) || !attempt) {
|
||||
if (failed || !code || !attempt) {
|
||||
location.replace("/?auth=heimdall-error");
|
||||
return;
|
||||
}
|
||||
var form = document.getElementById("complete");
|
||||
form.elements.attempt.value = attempt;
|
||||
form.elements.code.value = code || "";
|
||||
form.elements.pendingLinkId.value = pendingLinkId || "";
|
||||
form.elements.code.value = code;
|
||||
form.submit();
|
||||
})();
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -1,112 +0,0 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
|
||||
namespace Bifrost.Web.Features.Heimdall;
|
||||
|
||||
/// <summary>One login a Heimdall account holds, as the Linked accounts page shows it. No provider user id, scope or email.</summary>
|
||||
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<LinkedIdentitySummary>? Identities);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<HeimdallMemberResult> ListAsync(string bearer, CancellationToken cancellationToken) =>
|
||||
SendAsync(HttpMethod.Get, "/v1/me/identities", bearer, cancellationToken);
|
||||
|
||||
public Task<HeimdallMemberResult> UnlinkAsync(string bearer, string identityId, CancellationToken cancellationToken) =>
|
||||
SendAsync(HttpMethod.Post, $"/v1/me/identities/{Uri.EscapeDataString(identityId)}/unlink", bearer, cancellationToken);
|
||||
|
||||
private async Task<HeimdallMemberResult> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The identities array of a 200 answer, keeping only the fields the page shows; a malformed entry is dropped.</summary>
|
||||
private static async Task<IReadOnlyList<LinkedIdentitySummary>> ReadIdentitiesAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||
{
|
||||
using var body = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
|
||||
var list = new List<LinkedIdentitySummary>();
|
||||
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;
|
||||
}
|
||||
|
|
@ -64,18 +64,21 @@ 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 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}.");
|
||||
return HeimdallPatronSupportIntakeResult.BadRequest(
|
||||
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
|
||||
}
|
||||
|
||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||
|
|
@ -95,9 +98,7 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
cancellationToken);
|
||||
|
||||
return HeimdallPatronSupportIntakeResult.Processed(
|
||||
existingEvent is not null
|
||||
? $"Already processed {request.Provider} patron support event {request.ProviderEventId}."
|
||||
: $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||
$"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||
supportEvent.Id);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
using System.Text.Json;
|
||||
|
||||
namespace Bifrost.Web.Features.Heimdall;
|
||||
|
||||
/// <summary>Reads the one thing Bifrost takes from a Heimdall refusal body: its error code, and only if it is a safe token.</summary>
|
||||
public static class HeimdallRefusal
|
||||
{
|
||||
private const int BodyLimit = 4096;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static async Task<string?> 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;
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Bifrost.Web.Features.Heimdall;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Lifetime"/>. 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.
|
||||
/// </summary>
|
||||
public sealed class LinkedAccountsSnapshots(TimeProvider timeProvider)
|
||||
{
|
||||
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
|
||||
|
||||
private readonly ConcurrentDictionary<string, (IReadOnlyList<LinkedIdentitySummary> Identities, DateTimeOffset ExpiresAt)> _held = new(StringComparer.Ordinal);
|
||||
|
||||
public void Put(string accountId, IReadOnlyList<LinkedIdentitySummary> 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<LinkedIdentitySummary>? 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 _);
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
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;
|
||||
|
||||
/// <summary>
|
||||
/// The one owner of chat invites. An operator mints a single-use link (<see cref="MintAsync"/>; 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 <see cref="RedeemCarriedAsync"/>,
|
||||
/// which spends the invite onto the signed-in account. Only the SHA-256 of the token is stored.
|
||||
/// </summary>
|
||||
public sealed class ChatInviteService(BifrostDbContext db, AuditTrailService audit, TimeProvider time, IOptions<BifrostHostOptions> 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);
|
||||
|
||||
/// <summary>The link an operator sends: the public base URL plus the invite path.</summary>
|
||||
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();
|
||||
|
||||
/// <summary>Mints an invite and returns the token, which exists only in this result.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Revokes an unredeemed invite. False when it is absent or already redeemed or revoked.</summary>
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>The unredeemed, unrevoked invites, newest first (expired ones included, so they can be revoked and seen).</summary>
|
||||
public Task<List<ChatInvite>> PendingAsync(CancellationToken cancellationToken) =>
|
||||
db.ChatInvites.AsNoTracking()
|
||||
.Where(x => x.RedeemedAtUtc == null && x.RevokedAtUtc == null)
|
||||
.OrderByDescending(x => x.IssuedAtUtc)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
/// <summary>True when the token names an invite that is unredeemed, unrevoked and unexpired now.</summary>
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
|
@ -36,6 +36,11 @@ 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
|
||||
|
|
@ -55,7 +60,7 @@ public sealed class MembershipSynchronizationService(
|
|||
},
|
||||
Membership = new Bifrost.Web.Domain.Membership
|
||||
{
|
||||
Status = MembershipStatus.Authenticated,
|
||||
Status = invitation is null ? MembershipStatus.Authenticated : MembershipStatus.PendingApproval,
|
||||
CreatedAtUtc = now
|
||||
}
|
||||
};
|
||||
|
|
@ -83,6 +88,11 @@ 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))
|
||||
|
|
@ -95,6 +105,12 @@ 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))
|
||||
{
|
||||
|
|
|
|||
203
src/Bifrost.Web/Features/Motions/MotionEveSurfaceService.cs
Normal file
203
src/Bifrost.Web/Features/Motions/MotionEveSurfaceService.cs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
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<string, object?>
|
||||
{
|
||||
["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<string, object?>
|
||||
{
|
||||
["title"] = "Open Motion",
|
||||
["command"] = "motion.create",
|
||||
["target"] = MotionCommandTarget,
|
||||
["transport"] = "cultmesh-command-document"
|
||||
},
|
||||
[
|
||||
SelectNode("scope", "Scope", EnumNames<MotionScope>()),
|
||||
SelectNode("projectId", "Project", state.Projects.Select(x => new EveOption(x.Id.ToString(), x.Name)).Prepend(new EveOption("", "No project scope"))),
|
||||
SelectNode("category", "Category", EnumNames<MotionCategory>()),
|
||||
InputNode("title", "Title", "text"),
|
||||
InputNode("summary", "Summary", "multiline"),
|
||||
InputNode("closesAtUtc", "Close at UTC", "datetime")
|
||||
]),
|
||||
new EveNode(
|
||||
"vote-ledger",
|
||||
"panel",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["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<string, object?> { ["title"] = "Motions" },
|
||||
motionNodes)
|
||||
]));
|
||||
}
|
||||
|
||||
private static EveNode BuildMotionCard(MotionListItem motion)
|
||||
{
|
||||
var commandNodes = new List<EveNode>();
|
||||
foreach (var choice in Enum.GetValues<VoteChoice>())
|
||||
{
|
||||
commandNodes.Add(CommandNode(
|
||||
$"vote-{motion.Id}-{choice}",
|
||||
$"Vote {choice}",
|
||||
"motion.vote",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["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<string, object?> { ["motionId"] = motion.Id },
|
||||
"secondary"));
|
||||
}
|
||||
|
||||
return new EveNode(
|
||||
$"motion-{motion.Id}",
|
||||
"card",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["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<string, object?>
|
||||
{
|
||||
["for"] = motion.VotesFor,
|
||||
["against"] = motion.VotesAgainst,
|
||||
["abstain"] = motion.VotesAbstain,
|
||||
["currentUserVote"] = motion.CurrentUserVote?.ToString() ?? string.Empty
|
||||
}),
|
||||
new EveNode(
|
||||
$"motion-commands-{motion.Id}",
|
||||
"commands",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["target"] = MotionCommandTarget,
|
||||
["transport"] = "cultmesh-command-document"
|
||||
},
|
||||
commandNodes)
|
||||
]);
|
||||
}
|
||||
|
||||
private static EveNode CommandNode(
|
||||
string id,
|
||||
string label,
|
||||
string command,
|
||||
IReadOnlyDictionary<string, object?> payload,
|
||||
string tone) =>
|
||||
new(
|
||||
id,
|
||||
"command",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["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<string, object?>
|
||||
{
|
||||
["name"] = id,
|
||||
["label"] = label,
|
||||
["inputKind"] = inputKind
|
||||
});
|
||||
|
||||
private static EveNode SelectNode(string id, string label, IEnumerable<string> options) =>
|
||||
SelectNode(id, label, options.Select(x => new EveOption(x, x)));
|
||||
|
||||
private static EveNode SelectNode(string id, string label, IEnumerable<EveOption> options) =>
|
||||
new(
|
||||
$"input-{id}",
|
||||
"select",
|
||||
new Dictionary<string, object?>
|
||||
{
|
||||
["name"] = id,
|
||||
["label"] = label,
|
||||
["options"] = options.ToArray()
|
||||
});
|
||||
|
||||
private static EveNode TextNode(string id, string text) =>
|
||||
new(id, "text", new Dictionary<string, object?> { ["text"] = text });
|
||||
|
||||
private static IReadOnlyList<string> EnumNames<TEnum>() where TEnum : struct, Enum =>
|
||||
Enum.GetNames<TEnum>();
|
||||
|
||||
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<string, object?> Props,
|
||||
IReadOnlyList<EveNode>? Children = null);
|
||||
|
||||
public sealed record EveOption(string Value, string Label);
|
||||
|
|
@ -52,7 +52,6 @@ public sealed class MotionGovernanceService(
|
|||
CancellationToken cancellationToken)
|
||||
{
|
||||
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
||||
|
||||
var motion = await dbContext.Motions
|
||||
.Include(x => x.Votes)
|
||||
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
||||
|
|
@ -84,7 +83,6 @@ public sealed class MotionGovernanceService(
|
|||
}
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
actorUser.Id,
|
||||
nameof(Motion),
|
||||
|
|
|
|||
|
|
@ -114,7 +114,6 @@ public sealed class SealedBallotService(
|
|||
ballot.Commitment = commitment;
|
||||
ballot.CommittedAtUtc = now;
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
user.Id, nameof(Motion), motionId, "sealed.committed",
|
||||
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ namespace Bifrost.Web.Features.Oidc;
|
|||
|
||||
/// <summary>
|
||||
/// The decisions Bifrost owns at the OIDC provider: who the chat user is (sub = UserAccount.Id,
|
||||
/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (invited or Active, not suspended).
|
||||
/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (membership Active).
|
||||
/// OpenIddict does the protocol; these endpoints read the cookie session and the same actor facts the /App policy reads.
|
||||
/// </summary>
|
||||
public static class OidcEndpoints
|
||||
|
|
@ -26,7 +26,6 @@ public static class OidcEndpoints
|
|||
public const string NoIdentityDescription = "The account has no Bifrost identity.";
|
||||
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
|
||||
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room.";
|
||||
public const string NotInvitedDescription = "Chat is by invitation. Open an invite link, then sign in, to chat.";
|
||||
|
||||
private const string OpenIddictScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
|
||||
private const string IdentityAuthenticationType = "Bifrost.Oidc";
|
||||
|
|
@ -53,7 +52,7 @@ public static class OidcEndpoints
|
|||
}
|
||||
|
||||
var actor = await actors.GetAsync(http.RequestAborted);
|
||||
// Chat tier: an invited account or an Active member that is not suspended may sign in to chat (the invite check is below). Membership is neither required nor written;
|
||||
// Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written;
|
||||
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
|
||||
if (actor.UserAccount is null)
|
||||
{
|
||||
|
|
@ -102,13 +101,6 @@ public static class OidcEndpoints
|
|||
_ => [Destinations.AccessToken]
|
||||
});
|
||||
|
||||
// Chat is by invitation: a chat token goes only to an invited account or an Active member, and an account that is neither is not
|
||||
// sent on to agree to a notice. Read again at token and userinfo time by ChatRefusalAsync; a desk token asks no invite.
|
||||
if (!IsDeskToken(principal) && !Bifrost.Web.Features.Invites.ChatInviteService.IsInvited(account))
|
||||
{
|
||||
return Deny(Errors.AccessDenied, NotInvitedDescription);
|
||||
}
|
||||
|
||||
// The training notice is the chat's: a desk token is not a chat token and needs no receipt (Meta's ruling, 2026-11-11).
|
||||
// Last, so a refusal that no agreement can cure (suspended, no identity, reserved) is never answered with an invitation to agree.
|
||||
// Not an OIDC error: the member is sent to the consent page with this request's resume path, and the parked request
|
||||
|
|
@ -167,7 +159,7 @@ public static class OidcEndpoints
|
|||
/// <summary>
|
||||
/// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
|
||||
/// null when they may, else the description of why not. The account exists, its membership is not Suspended (absent, pending
|
||||
/// or Active all chat), and, for a chat token (not a desk token), it is invited (ChatInvitedAtUtc or Active) and holds a live receipt for the notice version in force. Re-read on every call.
|
||||
/// or Active all chat), and, for a chat token (not a desk token), it holds a live receipt for the notice version in force. Re-read on every call.
|
||||
/// </summary>
|
||||
internal static async Task<string?> ChatRefusalAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken, bool deskToken = false)
|
||||
{
|
||||
|
|
@ -184,17 +176,7 @@ public static class OidcEndpoints
|
|||
return SuspendedDescription;
|
||||
}
|
||||
|
||||
if (deskToken)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!Bifrost.Web.Features.Invites.ChatInviteService.IsInvited(account))
|
||||
{
|
||||
return NotInvitedDescription;
|
||||
}
|
||||
|
||||
return await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
|
||||
return deskToken || await ConsentEndpoints.HasLiveReceiptAsync(db, accountId, cancellationToken) ? null : ConsentRequiredDescription;
|
||||
}
|
||||
|
||||
/// <summary>The account id of the subject when it is an Active member now, else null. The door to the fork desk (cookie surfaces check IsActiveMember); a chat-tier token does not pass it. Re-read on every call.</summary>
|
||||
|
|
|
|||
|
|
@ -1,139 +0,0 @@
|
|||
using Bifrost.Web.Features.Shared;
|
||||
|
||||
namespace Bifrost.Web.Features.Passkeys;
|
||||
|
||||
public enum CeremonyKind
|
||||
{
|
||||
/// <summary>Permission to enrol one passkey, earned by a fresh Heimdall sign-in. Held by id in a cookie of the browser that signed in.</summary>
|
||||
EnrolTicket,
|
||||
/// <summary>The WebAuthn creation options in flight for an account.</summary>
|
||||
EnrolChallenge,
|
||||
/// <summary>The WebAuthn request options in flight for an account's unlink of one identity.</summary>
|
||||
UnlinkChallenge,
|
||||
/// <summary>The fact "this account's passkey assertion was verified for unlinking this identity". Carries no bearer and no credential.</summary>
|
||||
UnlinkProof
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The short-lived single-use server-side state of the passkey flows, in this process only (like the Linked accounts list):
|
||||
/// a restart empties it and every flow is simply begun again. Every entry is bound to an account and a kind, and the unlink
|
||||
/// kinds to the identity they are for; <c>Take</c> removes the entry whether or not the caller then succeeds, so a
|
||||
/// challenge, a ticket or an assertion fact can be spent once. A challenge kind has one live entry per account: a newer one
|
||||
/// replaces the older. A full table refuses new entries rather than grow.
|
||||
/// </summary>
|
||||
public sealed class PasskeyCeremonies(TimeProvider clock)
|
||||
{
|
||||
public static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(5);
|
||||
public static readonly TimeSpan ChallengeLifetime = TimeSpan.FromMinutes(2);
|
||||
public static readonly TimeSpan ProofLifetime = TimeSpan.FromMinutes(5);
|
||||
public const int MaxLive = 2048;
|
||||
|
||||
public sealed record Entry(string Id, CeremonyKind Kind, string Account, string? Subject, string? Data, DateTimeOffset ExpiresAt);
|
||||
|
||||
private readonly Dictionary<string, Entry> _held = new(StringComparer.Ordinal);
|
||||
private readonly object _gate = new();
|
||||
|
||||
/// <summary>Adds an entry and returns its id, or null when the table is full.</summary>
|
||||
public string? Issue(CeremonyKind kind, string account, string? subject, string? data, TimeSpan lifetime)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Purge();
|
||||
if (kind != CeremonyKind.UnlinkProof)
|
||||
{
|
||||
foreach (var old in _held.Values.Where(x => x.Kind == kind && x.Account == account).ToList())
|
||||
{
|
||||
_held.Remove(old.Id);
|
||||
}
|
||||
}
|
||||
|
||||
if (_held.Count >= MaxLive)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var id = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))
|
||||
.Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||
_held[id] = new Entry(id, kind, account, subject, data, clock.GetUtcNow() + lifetime);
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The live entry, without spending it. <paramref name="id"/> null finds the account's one current entry of that kind.</summary>
|
||||
public Entry? Peek(CeremonyKind kind, string account, string? subject, string? id)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Purge();
|
||||
return Find(kind, account, subject, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The live entry, removed: it can be taken once.</summary>
|
||||
public Entry? Take(CeremonyKind kind, string account, string? subject, string? id)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Purge();
|
||||
var entry = Find(kind, account, subject, id);
|
||||
if (entry is not null)
|
||||
{
|
||||
_held.Remove(entry.Id);
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
public void Discard(string? id)
|
||||
{
|
||||
if (id is not null)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_held.Remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Entry? Find(CeremonyKind kind, string account, string? subject, string? id)
|
||||
{
|
||||
var entry = id is null
|
||||
? _held.Values.FirstOrDefault(x => x.Kind == kind && x.Account == account)
|
||||
: _held.GetValueOrDefault(id);
|
||||
return entry is not null && entry.Kind == kind
|
||||
&& string.Equals(entry.Account, account, StringComparison.Ordinal)
|
||||
&& string.Equals(entry.Subject, subject, StringComparison.Ordinal)
|
||||
? entry
|
||||
: null;
|
||||
}
|
||||
|
||||
private void Purge()
|
||||
{
|
||||
var now = clock.GetUtcNow();
|
||||
foreach (var dead in _held.Values.Where(x => x.ExpiresAt <= now).ToList())
|
||||
{
|
||||
_held.Remove(dead.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The budgets on the passkey ceremonies, per Heimdall account, on the shared <see cref="FixedWindowBudget"/>. Two separate
|
||||
/// ones: asking for options or starting an enrolment sign-in (anyone holding the session can do that), and verifying a
|
||||
/// registration or an assertion, which is spent only after the caller holds what the verification needs (a live ticket, or one of
|
||||
/// the account's own strong credentials and a live challenge). Junk from a session thief that names no credential of the account, or
|
||||
/// arrives with no live challenge, spends nothing; junk naming one of the account's credentials spends one permit per challenge that
|
||||
/// was asked for, because the first such post takes the challenge. A session holder can still exhaust both budgets by asking for
|
||||
/// challenges over and over: a lockout the same session already has through revoking passkeys, not a bypass. Budgets are per process.
|
||||
/// </summary>
|
||||
public sealed class PasskeyRateLimit(TimeProvider clock)
|
||||
{
|
||||
public const int Permits = 20;
|
||||
public static readonly TimeSpan Window = TimeSpan.FromMinutes(10);
|
||||
|
||||
private readonly FixedWindowBudget _options = new(Permits, Window, 10_000, clock);
|
||||
private readonly FixedWindowBudget _verifications = new(Permits, Window, 10_000, clock);
|
||||
|
||||
public bool TryAcquire(string account, bool verification = false) => (verification ? _verifications : _options).Spend(account) is null;
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
using Bifrost.Web.Configuration;
|
||||
using Fido2NetLib;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Features.Passkeys;
|
||||
|
||||
/// <summary>
|
||||
/// The relying party every passkey ceremony runs as. RP ID and origin come from <see cref="BifrostHostOptions"/> and from
|
||||
/// nothing the browser sends: the public base URL must be https and its host must be the expected host, otherwise passkeys
|
||||
/// are unavailable (the page offers none and every ceremony endpoint refuses). A passkey is bound to the RP ID by the
|
||||
/// authenticator, so a wrong or http origin would enrol keys that cannot be used or can be phished.
|
||||
/// </summary>
|
||||
public sealed class PasskeyRelyingParty
|
||||
{
|
||||
public const string Name = "Bifrost";
|
||||
|
||||
public PasskeyRelyingParty(IOptions<BifrostHostOptions> hostOptions, ILogger<PasskeyRelyingParty> logger)
|
||||
{
|
||||
var host = hostOptions.Value;
|
||||
if (host.ExpectedHost.Contains(':') || System.Net.IPAddress.TryParse(host.ExpectedHost.Trim('[', ']'), out _))
|
||||
{
|
||||
logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare DNS host name, with no port and not an IP address (an IP address is not a valid RP ID).");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var url)
|
||||
|| url.Scheme != Uri.UriSchemeHttps
|
||||
|| string.IsNullOrWhiteSpace(host.ExpectedHost)
|
||||
|| !string.Equals(url.Host, host.ExpectedHost, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.LogWarning("Passkeys are unavailable: Host:PublicBaseUrl must be https and its host must equal Host:ExpectedHost.");
|
||||
return;
|
||||
}
|
||||
|
||||
Origin = url.GetLeftPart(UriPartial.Authority);
|
||||
RpId = url.Host.ToLowerInvariant();
|
||||
Fido2 = new Fido2(new Fido2Configuration
|
||||
{
|
||||
RPID = RpId,
|
||||
RPName = Name,
|
||||
Origins = new HashSet<string>([Origin], StringComparer.Ordinal),
|
||||
ChallengeSize = 32,
|
||||
Timeout = 120_000
|
||||
});
|
||||
}
|
||||
|
||||
public bool IsAvailable => Fido2 is not null;
|
||||
|
||||
public string? Origin { get; }
|
||||
|
||||
public string? RpId { get; }
|
||||
|
||||
public IFido2? Fido2 { get; }
|
||||
}
|
||||
|
|
@ -1,470 +0,0 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Heimdall;
|
||||
using Fido2NetLib;
|
||||
using Fido2NetLib.Objects;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Bifrost.Web.Features.Passkeys;
|
||||
|
||||
/// <summary>One passkey as the Linked accounts page shows it: a label, its cooling-off state, never a key.</summary>
|
||||
public sealed record PasskeyView(Guid Id, string Label, DateTimeOffset CreatedUtc, DateTimeOffset StrongFromUtc, DateTimeOffset? LastUsedUtc, bool IsStrong);
|
||||
|
||||
/// <summary>The base64url fields a browser posts after navigator.credentials.get (an assertion) or .create (an enrolment).</summary>
|
||||
public sealed record PasskeyFields(
|
||||
string? Id, string? RawId, string? AuthenticatorData, string? ClientDataJson, string? Signature, string? UserHandle,
|
||||
string? AttestationObject, string? Transports);
|
||||
|
||||
/// <summary>
|
||||
/// Passkeys for accounts that have a Heimdall account id (docs/passkeys.md). Enrolment needs a ticket earned by a fresh
|
||||
/// Heimdall sign-in and starts a credential in a 48 hour cooling-off; an assertion for an unlink needs a credential that is
|
||||
/// the session's own, not revoked and past its cooling-off, and records a single-use fact for that account and identity.
|
||||
/// The WebAuthn parsing and verification (CBOR, COSE, signatures, origin, RP ID, challenge, user verification, sign count)
|
||||
/// is Fido2NetLib's; this class decides who may begin, what is bound to what, and what is kept. Outcomes are the closed set
|
||||
/// of <see cref="HeimdallLinkOutcome"/> the page words itself.
|
||||
/// </summary>
|
||||
public sealed class PasskeyService(
|
||||
BifrostDbContext db,
|
||||
PasskeyRelyingParty relyingParty,
|
||||
PasskeyCeremonies ceremonies,
|
||||
PasskeyRateLimit rateLimit,
|
||||
TimeProvider clock,
|
||||
ILogger<PasskeyService> logger)
|
||||
{
|
||||
public const int MaxActive = 5;
|
||||
public const int MaxLabel = 40;
|
||||
public static readonly TimeSpan CoolingOff = TimeSpan.FromHours(48);
|
||||
|
||||
private static readonly HashSet<string> TransportNames = new(StringComparer.Ordinal)
|
||||
{
|
||||
"usb", "nfc", "ble", "internal", "hybrid", "smart-card"
|
||||
};
|
||||
|
||||
public bool IsAvailable => relyingParty.IsAvailable;
|
||||
|
||||
private Task<UserAccount?> AccountAsync(string heimdallAccountId, CancellationToken ct) =>
|
||||
string.IsNullOrEmpty(heimdallAccountId)
|
||||
? Task.FromResult<UserAccount?>(null)
|
||||
: db.UserAccounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, ct);
|
||||
|
||||
private IQueryable<PasskeyCredential> Active(Guid userId) =>
|
||||
db.PasskeyCredentials.Where(x => x.UserAccountId == userId && x.RevokedUtc == null);
|
||||
|
||||
public async Task<IReadOnlyList<PasskeyView>> ListAsync(string heimdallAccountId, CancellationToken ct)
|
||||
{
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var now = clock.GetUtcNow();
|
||||
var rows = await Active(user.Id).ToListAsync(ct);
|
||||
return rows.OrderBy(x => x.CreatedUtc)
|
||||
.Select(x => new PasskeyView(x.Id, x.Label, x.CreatedUtc, x.StrongFromUtc, x.LastUsedUtc, x.StrongFromUtc <= now))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Whether a fresh enrolment ticket is held by this browser for this account.</summary>
|
||||
public bool HasTicket(string heimdallAccountId, string? ticketId) =>
|
||||
ticketId is not null && ceremonies.Peek(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId) is not null;
|
||||
|
||||
/// <summary>Why a fresh sign-in for enrolment may not even start, or null when it may. Spends a ceremony permit.</summary>
|
||||
public async Task<HeimdallLinkOutcome?> PreflightEnrolStartAsync(string heimdallAccountId, CancellationToken ct)
|
||||
{
|
||||
if (!relyingParty.IsAvailable)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeysUnavailable;
|
||||
}
|
||||
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return HeimdallLinkOutcome.Error;
|
||||
}
|
||||
|
||||
if (await Active(user.Id).CountAsync(ct) >= MaxActive)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeyLimit;
|
||||
}
|
||||
|
||||
return rateLimit.TryAcquire(heimdallAccountId) ? null : HeimdallLinkOutcome.RateLimited;
|
||||
}
|
||||
|
||||
/// <summary>The creation options for one enrolment, bound to the account; needs the ticket the fresh sign-in earned.</summary>
|
||||
public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginEnrolAsync(string heimdallAccountId, string? ticketId, CancellationToken ct)
|
||||
{
|
||||
if (!relyingParty.IsAvailable)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||
}
|
||||
|
||||
if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return (HeimdallLinkOutcome.EnrolNeedsSignIn, null);
|
||||
}
|
||||
|
||||
if (!rateLimit.TryAcquire(heimdallAccountId))
|
||||
{
|
||||
return (HeimdallLinkOutcome.RateLimited, null);
|
||||
}
|
||||
|
||||
var existing = await Active(user.Id).Select(x => x.CredentialId).ToListAsync(ct);
|
||||
if (existing.Count >= MaxActive)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyLimit, null);
|
||||
}
|
||||
|
||||
var options = relyingParty.Fido2!.RequestNewCredential(new RequestNewCredentialParams
|
||||
{
|
||||
User = new Fido2User { Id = user.Id.ToByteArray(), Name = Label(user.DisplayName, "Bifrost member"), DisplayName = Label(user.DisplayName, "Bifrost member") },
|
||||
ExcludeCredentials = existing.Select(x => new PublicKeyCredentialDescriptor(x)).ToList(),
|
||||
AuthenticatorSelection = new AuthenticatorSelection
|
||||
{
|
||||
ResidentKey = ResidentKeyRequirement.Preferred,
|
||||
UserVerification = UserVerificationRequirement.Required
|
||||
},
|
||||
AttestationPreference = AttestationConveyancePreference.None
|
||||
});
|
||||
var json = options.ToJson();
|
||||
return ceremonies.Issue(CeremonyKind.EnrolChallenge, heimdallAccountId, null, json, PasskeyCeremonies.ChallengeLifetime) is null
|
||||
? (HeimdallLinkOutcome.Error, null)
|
||||
: (null, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a registration and stores the credential, cooling off for <see cref="CoolingOff"/>. The ticket and the
|
||||
/// challenge are both spent here, whatever the outcome: a failed attempt needs a fresh sign-in and a new challenge.
|
||||
/// </summary>
|
||||
public async Task<HeimdallLinkOutcome> EnrolAsync(
|
||||
string heimdallAccountId, string? ticketId, PasskeyFields fields, string? label, CancellationToken ct)
|
||||
{
|
||||
if (!relyingParty.IsAvailable)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeysUnavailable;
|
||||
}
|
||||
|
||||
// The caller's own preconditions first, spending nothing: someone with only the session has no ticket, so junk from them
|
||||
// can neither burn the member's ticket and challenge nor spend the verification permits.
|
||||
if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return HeimdallLinkOutcome.EnrolNeedsSignIn;
|
||||
}
|
||||
|
||||
if (await Active(user.Id).CountAsync(ct) >= MaxActive)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeyLimit;
|
||||
}
|
||||
|
||||
if (!TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AttestationObject, out var attestation)
|
||||
|| !TryDecode(fields.ClientDataJson, out var clientData) || fields.Id is null)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeyFailed;
|
||||
}
|
||||
|
||||
if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
|
||||
{
|
||||
return HeimdallLinkOutcome.RateLimited;
|
||||
}
|
||||
|
||||
// Now both are spent, whatever the outcome.
|
||||
var ticket = ceremonies.Take(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId);
|
||||
var challenge = ceremonies.Take(CeremonyKind.EnrolChallenge, heimdallAccountId, null, null);
|
||||
if (ticket is null)
|
||||
{
|
||||
return HeimdallLinkOutcome.EnrolNeedsSignIn;
|
||||
}
|
||||
|
||||
if (challenge?.Data is null)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeyExpired;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var registered = await relyingParty.Fido2!.MakeNewCredentialAsync(new MakeNewCredentialParams
|
||||
{
|
||||
AttestationResponse = new AuthenticatorAttestationRawResponse
|
||||
{
|
||||
Id = fields.Id,
|
||||
RawId = rawId,
|
||||
Type = PublicKeyCredentialType.PublicKey,
|
||||
ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
|
||||
Response = new AuthenticatorAttestationRawResponse.AttestationResponse
|
||||
{
|
||||
AttestationObject = attestation,
|
||||
ClientDataJson = clientData,
|
||||
Transports = Transports(fields.Transports)
|
||||
}
|
||||
},
|
||||
OriginalOptions = CredentialCreateOptions.FromJson(challenge.Data),
|
||||
IsCredentialIdUniqueToUserCallback = async (parameters, token) =>
|
||||
!await db.PasskeyCredentials.AnyAsync(x => x.CredentialId == parameters.CredentialId, token)
|
||||
}, ct);
|
||||
|
||||
var now = clock.GetUtcNow();
|
||||
db.PasskeyCredentials.Add(new PasskeyCredential
|
||||
{
|
||||
UserAccountId = user.Id,
|
||||
CredentialId = registered.Id,
|
||||
PublicKey = registered.PublicKey,
|
||||
SignCount = registered.SignCount,
|
||||
Transports = string.Join(',', Transports(fields.Transports).Select(x => TransportName(x))),
|
||||
AaGuid = registered.AaGuid == Guid.Empty ? null : registered.AaGuid,
|
||||
Label = Label(label, "Passkey"),
|
||||
CreatedUtc = now,
|
||||
StrongFromUtc = now + CoolingOff
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
return HeimdallLinkOutcome.PasskeyAdded;
|
||||
}
|
||||
catch (Exception error) when (error is Fido2VerificationException or DbUpdateException or FormatException or System.Text.Json.JsonException)
|
||||
{
|
||||
logger.LogWarning("Passkey enrolment refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
|
||||
return HeimdallLinkOutcome.PasskeyFailed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Revokes one of the session's own passkeys. Needs no strong proof; the page shows the revocation.</summary>
|
||||
public async Task<HeimdallLinkOutcome> RevokeAsync(string heimdallAccountId, Guid credentialId, CancellationToken ct)
|
||||
{
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return HeimdallLinkOutcome.Error;
|
||||
}
|
||||
|
||||
var credential = await Active(user.Id).SingleOrDefaultAsync(x => x.Id == credentialId, ct);
|
||||
if (credential is null)
|
||||
{
|
||||
return HeimdallLinkOutcome.PasskeyFailed;
|
||||
}
|
||||
|
||||
credential.RevokedUtc = clock.GetUtcNow();
|
||||
await db.SaveChangesAsync(ct);
|
||||
return HeimdallLinkOutcome.PasskeyRevoked;
|
||||
}
|
||||
|
||||
private IQueryable<PasskeyCredential> Strong(Guid userId)
|
||||
{
|
||||
var now = clock.GetUtcNow();
|
||||
return Active(userId).Where(x => x.StrongFromUtc <= now);
|
||||
}
|
||||
|
||||
public async Task<bool> HasStrongAsync(string heimdallAccountId, CancellationToken ct) =>
|
||||
await AccountAsync(heimdallAccountId, ct) is { } user && await Strong(user.Id).AnyAsync(ct);
|
||||
|
||||
/// <summary>When the first cooling-off credential becomes strong, or null when none is cooling.</summary>
|
||||
public async Task<DateTimeOffset?> NextStrongAtAsync(string heimdallAccountId, CancellationToken ct)
|
||||
{
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var now = clock.GetUtcNow();
|
||||
var cooling = await Active(user.Id).Where(x => x.StrongFromUtc > now).Select(x => x.StrongFromUtc).ToListAsync(ct);
|
||||
return cooling.Count == 0 ? null : cooling.Min();
|
||||
}
|
||||
|
||||
/// <summary>The request options for unlinking one identity: only the account's strong passkeys may answer, with user verification.</summary>
|
||||
public async Task<(HeimdallLinkOutcome? Refusal, string? OptionsJson)> BeginAssertionAsync(string heimdallAccountId, string identityId, CancellationToken ct)
|
||||
{
|
||||
if (!relyingParty.IsAvailable)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||
}
|
||||
|
||||
if (!rateLimit.TryAcquire(heimdallAccountId))
|
||||
{
|
||||
return (HeimdallLinkOutcome.RateLimited, null);
|
||||
}
|
||||
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user)
|
||||
{
|
||||
return (HeimdallLinkOutcome.Error, null);
|
||||
}
|
||||
|
||||
var strong = await Strong(user.Id).ToListAsync(ct);
|
||||
if (strong.Count == 0)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyRequired, null);
|
||||
}
|
||||
|
||||
var options = relyingParty.Fido2!.GetAssertionOptions(new GetAssertionOptionsParams
|
||||
{
|
||||
AllowedCredentials = strong.Select(x => new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PublicKey, x.CredentialId, Transports(x.Transports))).ToList(),
|
||||
UserVerification = UserVerificationRequirement.Required
|
||||
});
|
||||
var json = options.ToJson();
|
||||
return ceremonies.Issue(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, json, PasskeyCeremonies.ChallengeLifetime) is null
|
||||
? (HeimdallLinkOutcome.Error, null)
|
||||
: (null, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies an assertion made for unlinking <paramref name="identityId"/>. The challenge is spent first. On success the
|
||||
/// credential's sign count and last use are recorded and a single-use fact for this account and identity is issued; its id
|
||||
/// (not a credential, not a bearer) is what the fresh Heimdall sign-in's attempt carries.
|
||||
/// </summary>
|
||||
public async Task<(HeimdallLinkOutcome? Refusal, string? FactId)> VerifyAssertionAsync(
|
||||
string heimdallAccountId, string identityId, PasskeyFields fields, CancellationToken ct)
|
||||
{
|
||||
if (!relyingParty.IsAvailable)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeysUnavailable, null);
|
||||
}
|
||||
|
||||
// The caller's own preconditions first, spending nothing: a decodable assertion naming one of this account's strong,
|
||||
// un-revoked credentials. Junk from someone holding only the session fails here and burns neither the member's challenge
|
||||
// nor the verification permits.
|
||||
if (await AccountAsync(heimdallAccountId, ct) is not { } user
|
||||
|| !TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AuthenticatorData, out var authenticatorData)
|
||||
|| !TryDecode(fields.ClientDataJson, out var clientData) || !TryDecode(fields.Signature, out var signature)
|
||||
|| fields.Id is null)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||
}
|
||||
|
||||
byte[]? userHandle = null;
|
||||
if (!string.IsNullOrEmpty(fields.UserHandle) && !TryDecode(fields.UserHandle, out userHandle))
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||
}
|
||||
|
||||
// The credential must be this session's own, not revoked and past its cooling-off. Anything else is not a strong proof.
|
||||
var credential = await Strong(user.Id).SingleOrDefaultAsync(x => x.CredentialId == rawId, ct);
|
||||
if (credential is null)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||
}
|
||||
|
||||
// Without a live challenge for this account and identity nothing can verify, so no permit is spent either: junk naming the
|
||||
// account's own credential spends at most one permit per challenge that was asked for (the first junk then takes it).
|
||||
if (ceremonies.Peek(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null) is null)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyExpired, null);
|
||||
}
|
||||
|
||||
if (!rateLimit.TryAcquire(heimdallAccountId, verification: true))
|
||||
{
|
||||
return (HeimdallLinkOutcome.RateLimited, null);
|
||||
}
|
||||
|
||||
// Spent from here on, whatever the outcome.
|
||||
var challenge = ceremonies.Take(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null);
|
||||
if (challenge?.Data is null)
|
||||
{
|
||||
return (HeimdallLinkOutcome.PasskeyExpired, null);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var result = await relyingParty.Fido2!.MakeAssertionAsync(new MakeAssertionParams
|
||||
{
|
||||
AssertionResponse = new AuthenticatorAssertionRawResponse
|
||||
{
|
||||
Id = fields.Id,
|
||||
RawId = rawId,
|
||||
Type = PublicKeyCredentialType.PublicKey,
|
||||
ClientExtensionResults = new AuthenticationExtensionsClientOutputs(),
|
||||
Response = new AuthenticatorAssertionRawResponse.AssertionResponse
|
||||
{
|
||||
AuthenticatorData = authenticatorData,
|
||||
ClientDataJson = clientData,
|
||||
Signature = signature,
|
||||
UserHandle = userHandle
|
||||
}
|
||||
},
|
||||
OriginalOptions = AssertionOptions.FromJson(challenge.Data),
|
||||
StoredPublicKey = credential.PublicKey,
|
||||
StoredSignatureCounter = (uint)credential.SignCount,
|
||||
IsUserHandleOwnerOfCredentialIdCallback = (parameters, _) =>
|
||||
Task.FromResult(parameters.UserHandle.AsSpan().SequenceEqual(user.Id.ToByteArray()) && parameters.CredentialId.AsSpan().SequenceEqual(credential.CredentialId))
|
||||
}, ct);
|
||||
|
||||
credential.SignCount = result.SignCount;
|
||||
credential.LastUsedUtc = clock.GetUtcNow();
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (Exception error) when (error is Fido2VerificationException or FormatException or System.Text.Json.JsonException)
|
||||
{
|
||||
logger.LogWarning("Passkey assertion refused: {Reason}", error is Fido2VerificationException f ? f.Code.ToString() : error.GetType().Name);
|
||||
return (HeimdallLinkOutcome.PasskeyFailed, null);
|
||||
}
|
||||
|
||||
var fact = ceremonies.Issue(CeremonyKind.UnlinkProof, heimdallAccountId, identityId, credential.Id.ToString(), PasskeyCeremonies.ProofLifetime);
|
||||
return fact is null ? (HeimdallLinkOutcome.Error, null) : (null, fact);
|
||||
}
|
||||
|
||||
public void DiscardFact(string? factId) => ceremonies.Discard(factId);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the credential an assertion fact was made with is still this account's own, un-revoked and strong. Asked in the
|
||||
/// completion, before Heimdall is: a passkey revoked between the assertion and the completion no longer proves anything.
|
||||
/// </summary>
|
||||
public async Task<bool> StillStrongAsync(string heimdallAccountId, string? credentialId, CancellationToken ct) =>
|
||||
Guid.TryParse(credentialId, out var id) && await AccountAsync(heimdallAccountId, ct) is { } user
|
||||
&& await Strong(user.Id).AnyAsync(x => x.Id == id, ct);
|
||||
|
||||
/// <summary>A label from a form field: trimmed, control characters dropped, bounded; the fallback when nothing is left.</summary>
|
||||
private static string Label(string? value, string fallback)
|
||||
{
|
||||
// By rune and by text element, never by UTF-16 unit: a cut inside a surrogate pair is not valid text and Postgres refuses it.
|
||||
// Control and format characters (bidi overrides, joiners, zero-width marks) are dropped; a lone surrogate becomes U+FFFD.
|
||||
var runes = (value ?? string.Empty).EnumerateRunes()
|
||||
.Where(r => Rune.GetUnicodeCategory(r) is not (UnicodeCategory.Control or UnicodeCategory.Format))
|
||||
.Take(MaxLabel * 4);
|
||||
var cleaned = string.Concat(runes.Select(r => r.ToString())).Trim();
|
||||
var elements = new StringInfo(cleaned);
|
||||
if (elements.LengthInTextElements > MaxLabel)
|
||||
{
|
||||
cleaned = elements.SubstringByTextElements(0, MaxLabel);
|
||||
}
|
||||
|
||||
return cleaned.Length == 0 ? fallback : cleaned;
|
||||
}
|
||||
|
||||
private static bool TryDecode(string? value, out byte[] bytes)
|
||||
{
|
||||
bytes = [];
|
||||
if (string.IsNullOrEmpty(value) || value.Length > 16_384)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
bytes = WebEncoders.Base64UrlDecode(value);
|
||||
return bytes.Length > 0;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static AuthenticatorTransport[] Transports(string? csv)
|
||||
{
|
||||
var parsed = new List<AuthenticatorTransport>();
|
||||
foreach (var name in (csv ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Only names of the closed set reach the converter; one it does not know is dropped.
|
||||
if (TransportNames.Contains(name))
|
||||
{
|
||||
parsed.Add(System.Text.Json.JsonSerializer.Deserialize<AuthenticatorTransport>($"\"{name}\""));
|
||||
}
|
||||
}
|
||||
catch (System.Text.Json.JsonException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return parsed.ToArray();
|
||||
}
|
||||
|
||||
private static string TransportName(AuthenticatorTransport transport) =>
|
||||
System.Text.Json.JsonSerializer.Serialize(transport).Trim('"');
|
||||
}
|
||||
|
|
@ -10,8 +10,6 @@ public sealed class PatronageService(
|
|||
AuditTrailService auditTrailService,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron";
|
||||
|
||||
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
||||
Guid? actorUserAccountId,
|
||||
Guid userAccountId,
|
||||
|
|
@ -29,19 +27,6 @@ public sealed class PatronageService(
|
|||
CancellationToken cancellationToken,
|
||||
Guid? projectId = null)
|
||||
{
|
||||
var normalizedProviderEventId = providerEventId.Trim();
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
||||
var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
|
||||
? null
|
||||
: await dbContext.PatronSupportEvents
|
||||
.SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
|
||||
|
||||
if (existingProviderEvent is not null)
|
||||
{
|
||||
return existingProviderEvent;
|
||||
}
|
||||
|
||||
var user = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
|
@ -66,11 +51,23 @@ public sealed class PatronageService(
|
|||
throw new InvalidOperationException("Patron support adjustments must reduce support.");
|
||||
}
|
||||
|
||||
var normalizedProviderEventId = providerEventId.Trim();
|
||||
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
|
||||
{
|
||||
throw new InvalidOperationException("External patron provider events require a provider event id.");
|
||||
}
|
||||
|
||||
var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId)
|
||||
? null
|
||||
: await dbContext.PatronSupportEvents
|
||||
.SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken);
|
||||
|
||||
if (existingProviderEvent is not null)
|
||||
{
|
||||
return existingProviderEvent;
|
||||
}
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
|
||||
? "USD"
|
||||
: currencyCode.Trim().ToUpperInvariant();
|
||||
|
|
@ -89,7 +86,7 @@ public sealed class PatronageService(
|
|||
}
|
||||
}
|
||||
|
||||
var created = new PatronSupportEvent
|
||||
var supportEvent = new PatronSupportEvent
|
||||
{
|
||||
UserAccountId = userAccountId,
|
||||
ProjectId = projectId,
|
||||
|
|
@ -107,7 +104,7 @@ public sealed class PatronageService(
|
|||
Notes = notes.Trim()
|
||||
};
|
||||
|
||||
dbContext.PatronSupportEvents.Add(created);
|
||||
dbContext.PatronSupportEvents.Add(supportEvent);
|
||||
dbContext.PointTransactions.Add(new PointTransaction
|
||||
{
|
||||
UserAccountId = userAccountId,
|
||||
|
|
@ -116,22 +113,20 @@ public sealed class PatronageService(
|
|||
Amount = amount,
|
||||
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
|
||||
CreatedAtUtc = now,
|
||||
Note = $"Recorded {provider} {kind} patron support event {created.ExternalSupportId}."
|
||||
Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}."
|
||||
});
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
actorUserAccountId,
|
||||
nameof(PatronSupportEvent),
|
||||
created.Id,
|
||||
supportEvent.Id,
|
||||
"patron-support.recorded",
|
||||
$"Recorded {amount:0.##} {created.CurrencyCode} {provider} {kind} patron support for {user.DisplayName}.",
|
||||
$"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.",
|
||||
cancellationToken);
|
||||
|
||||
await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
|
||||
|
||||
return created;
|
||||
return supportEvent;
|
||||
}
|
||||
|
||||
public async Task<PatronPointSummary> RefreshPatronTierSnapshotAsync(
|
||||
|
|
@ -139,66 +134,24 @@ public sealed class PatronageService(
|
|||
Guid userAccountId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// One current Patron snapshot per membership is a database invariant (UX_TierSnapshots_MembershipId_CurrentPatron). A restage that
|
||||
// lost a race to another restage of the same membership reads the winner's snapshot and derives again from the events it now sees.
|
||||
UserAccount user;
|
||||
PatronPointSummary summary;
|
||||
PatronTierDefinition? tier;
|
||||
for (var attempt = 0; ; attempt++)
|
||||
dbContext.ChangeTracker.Clear();
|
||||
|
||||
var user = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
||||
if (user.Membership is null)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
|
||||
user = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
||||
if (user.Membership is null)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||
}
|
||||
|
||||
(summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
break;
|
||||
}
|
||||
catch (DbUpdateException error) when (attempt < 3 &&
|
||||
error.InnerException is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation, ConstraintName: CurrentPatronIndex })
|
||||
{
|
||||
}
|
||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||
}
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
actorUserAccountId,
|
||||
nameof(TierSnapshot),
|
||||
user.Membership.Id,
|
||||
"patron-tier.derived",
|
||||
tier is null
|
||||
? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
|
||||
: $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
|
||||
cancellationToken);
|
||||
|
||||
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Derives the membership's patron tier from the events once and stages it on the tracker: demotes the current Patron snapshots
|
||||
/// and adds the new one.
|
||||
/// </summary>
|
||||
private async Task<(PatronPointSummary Summary, PatronTierDefinition? Tier)> StageTierSnapshotAsync(
|
||||
Bifrost.Web.Domain.Membership membership,
|
||||
IEnumerable<PatronSupportEvent> events,
|
||||
DateTimeOffset now,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var summary = CalculatePatronPoints(events, now);
|
||||
var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
|
||||
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
||||
var currentPatronSnapshots = await dbContext.TierSnapshots
|
||||
.Where(x => x.MembershipId == membership.Id &&
|
||||
.Where(x => x.MembershipId == user.Membership.Id &&
|
||||
x.Kind == TierSnapshotKind.Patron &&
|
||||
x.IsCurrent)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
|
@ -212,7 +165,7 @@ public sealed class PatronageService(
|
|||
{
|
||||
dbContext.TierSnapshots.Add(new TierSnapshot
|
||||
{
|
||||
MembershipId = membership.Id,
|
||||
MembershipId = user.Membership.Id,
|
||||
Kind = TierSnapshotKind.Patron,
|
||||
Label = PatronTierPolicy.SnapshotLabel(tier),
|
||||
Weight = tier.VotingWeight,
|
||||
|
|
@ -223,7 +176,18 @@ public sealed class PatronageService(
|
|||
});
|
||||
}
|
||||
|
||||
return (summary, tier);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
await auditTrailService.RecordAsync(
|
||||
actorUserAccountId,
|
||||
nameof(TierSnapshot),
|
||||
user.Membership.Id,
|
||||
"patron-tier.derived",
|
||||
tier is null
|
||||
? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
|
||||
: $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
|
||||
cancellationToken);
|
||||
|
||||
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
|
||||
}
|
||||
|
||||
public static PatronPointSummary CalculatePatronPoints(
|
||||
|
|
|
|||
|
|
@ -42,8 +42,7 @@ public sealed record RegistrationOutcome(
|
|||
public sealed class NativeRegistration(
|
||||
BifrostIdentityService identities,
|
||||
RegistrationChallengeService challenges,
|
||||
RegistrationRateLimit rateLimit,
|
||||
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
|
||||
RegistrationRateLimit rateLimit)
|
||||
{
|
||||
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
|
||||
{
|
||||
|
|
@ -114,7 +113,6 @@ public sealed class NativeRegistration(
|
|||
{
|
||||
var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken);
|
||||
await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account));
|
||||
await chatInvites.RedeemCarriedAsync(http, account.Id, cancellationToken);
|
||||
return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false);
|
||||
}
|
||||
catch (BifrostIdentityException error)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ public static class BifrostCookies
|
|||
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
|
||||
public const string Voter = HostPrefix + "bifrost_voter";
|
||||
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
|
||||
public const string PasskeyTicket = HostPrefix + "bifrost_passkey_ticket";
|
||||
|
||||
public const string Path = "/";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,31 +45,18 @@ public sealed class CurrentBifrostActorAccessor(
|
|||
return Cache(httpContext, CurrentBifrostActor.Anonymous);
|
||||
}
|
||||
|
||||
// One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
|
||||
// one principal must never throw or pick by luck.
|
||||
var accounts = dbContext.UserAccounts
|
||||
var userAccount = await dbContext.UserAccounts
|
||||
.AsNoTracking()
|
||||
.Include(x => x.MemberProfile)
|
||||
.Include(x => x.Membership!)
|
||||
.ThenInclude(x => x.RoleAssignments)
|
||||
.Include(x => x.Membership!)
|
||||
.ThenInclude(x => x.TierSnapshots);
|
||||
|
||||
Bifrost.Web.Domain.UserAccount? userAccount = null;
|
||||
if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
|
||||
{
|
||||
userAccount = await accounts.SingleOrDefaultAsync(x => x.NormalizedBifrostIdentity == normalizedBifrostIdentity, cancellationToken);
|
||||
}
|
||||
|
||||
if (userAccount is null && !string.IsNullOrWhiteSpace(heimdallAccountId))
|
||||
{
|
||||
userAccount = await accounts.SingleOrDefaultAsync(x => x.HeimdallAccountId == heimdallAccountId, cancellationToken);
|
||||
}
|
||||
|
||||
if (userAccount is null && hasGitHubUserId)
|
||||
{
|
||||
userAccount = await accounts.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
|
||||
}
|
||||
.ThenInclude(x => x.TierSnapshots)
|
||||
.SingleOrDefaultAsync(
|
||||
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
|
||||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
|
||||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
|
||||
cancellationToken);
|
||||
|
||||
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,6 +102,76 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
|
|||
x.OccurredAtUtc))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var recentBridgeActions = await dbContext.BridgeActions
|
||||
.AsNoTracking()
|
||||
.OrderByDescending(x => x.UpdatedAtUtc)
|
||||
.Take(6)
|
||||
.Select(x => new DashboardBridgeAction(
|
||||
x.Id,
|
||||
x.ActorName,
|
||||
x.ActorKind.ToString(),
|
||||
x.TargetSurface.ToString(),
|
||||
x.ActionKind.ToString(),
|
||||
x.Status.ToString(),
|
||||
x.Title,
|
||||
x.TargetRepositoryFullName,
|
||||
string.IsNullOrWhiteSpace(x.ReceiptUrl) ? x.ExternalReceiptId : x.ReceiptUrl,
|
||||
x.UpdatedAtUtc))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var recentDispatchRuns = await dbContext.AgentDispatchRuns
|
||||
.AsNoTracking()
|
||||
.OrderByDescending(x => x.UpdatedAtUtc)
|
||||
.Take(6)
|
||||
.Select(x => new DashboardDispatchRun(
|
||||
x.Id,
|
||||
x.RequestId,
|
||||
x.TargetRepoName,
|
||||
x.TargetAgentIdentity,
|
||||
x.LaunchMode,
|
||||
x.Status.ToString(),
|
||||
x.ThreadId,
|
||||
x.TurnId,
|
||||
string.IsNullOrWhiteSpace(x.Note) ? x.Error : x.Note,
|
||||
x.UpdatedAtUtc))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var recentTransportReceipts = await dbContext.AgentTransportReceipts
|
||||
.AsNoTracking()
|
||||
.OrderByDescending(x => x.OccurredAtUtc)
|
||||
.Take(6)
|
||||
.Select(x => new DashboardTransportReceipt(
|
||||
x.Id,
|
||||
x.RequestId,
|
||||
x.Title,
|
||||
x.TargetRepoName,
|
||||
x.TargetAgentIdentity,
|
||||
x.ActivityKind.ToString(),
|
||||
x.Status,
|
||||
x.ActorName,
|
||||
x.Note,
|
||||
x.OccurredAtUtc))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var recentGovernanceReceipts = await dbContext.GovernanceActivityReceipts
|
||||
.AsNoTracking()
|
||||
.OrderByDescending(x => x.OccurredAtUtc)
|
||||
.Take(6)
|
||||
.Select(x => new DashboardGovernanceReceipt(
|
||||
x.Id,
|
||||
x.TopicId,
|
||||
x.CommentId,
|
||||
x.DispatchRequestId,
|
||||
x.Title,
|
||||
x.JurisdictionRepoName,
|
||||
x.JurisdictionAgentIdentity,
|
||||
x.ActivityKind.ToString(),
|
||||
x.ActorKind,
|
||||
x.ActorName,
|
||||
x.Note,
|
||||
x.OccurredAtUtc))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var payoutPreviewNominal = await dbContext.LedgerEntries
|
||||
.AsNoTracking()
|
||||
.Where(x => x.Status == LedgerEntryStatus.Approved)
|
||||
|
|
@ -116,13 +186,23 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
|
|||
OpenMotions: await dbContext.Motions.AsNoTracking().CountAsync(x => x.Status == MotionStatus.Open && x.ClosesAtUtc >= now, cancellationToken),
|
||||
PendingMembershipApprovals: outstandingApprovals,
|
||||
AssignedToCurrentMember: assignedToMe.Count,
|
||||
ActiveBridgeActions: await dbContext.BridgeActions.AsNoTracking().CountAsync(
|
||||
x => x.Status == BridgeActionStatus.Authorized || x.Status == BridgeActionStatus.InProgress,
|
||||
cancellationToken),
|
||||
ActiveDispatchRuns: await dbContext.AgentDispatchRuns.AsNoTracking().CountAsync(
|
||||
x => x.Status == AgentDispatchRunStatus.Started,
|
||||
cancellationToken),
|
||||
ApprovedNominalPayoutValue: payoutPreviewNominal,
|
||||
RecentWorkItems: recentWorkItems,
|
||||
OpenMotionHighlights: openMotions,
|
||||
MyAssignedWork: assignedToMe,
|
||||
MyVolunteeredWork: volunteeredByMe,
|
||||
MySubmittedWork: submittedByMe,
|
||||
RecentActivity: recentActivity);
|
||||
RecentActivity: recentActivity,
|
||||
RecentBridgeActions: recentBridgeActions,
|
||||
RecentDispatchRuns: recentDispatchRuns,
|
||||
RecentTransportReceipts: recentTransportReceipts,
|
||||
RecentGovernanceReceipts: recentGovernanceReceipts);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -133,13 +213,19 @@ public sealed record DashboardSnapshot(
|
|||
int OpenMotions,
|
||||
int PendingMembershipApprovals,
|
||||
int AssignedToCurrentMember,
|
||||
int ActiveBridgeActions,
|
||||
int ActiveDispatchRuns,
|
||||
decimal ApprovedNominalPayoutValue,
|
||||
IReadOnlyList<DashboardWorkItem> RecentWorkItems,
|
||||
IReadOnlyList<DashboardMotion> OpenMotionHighlights,
|
||||
IReadOnlyList<DashboardLaneItem> MyAssignedWork,
|
||||
IReadOnlyList<DashboardLaneItem> MyVolunteeredWork,
|
||||
IReadOnlyList<DashboardLaneItem> MySubmittedWork,
|
||||
IReadOnlyList<DashboardActivity> RecentActivity);
|
||||
IReadOnlyList<DashboardActivity> RecentActivity,
|
||||
IReadOnlyList<DashboardBridgeAction> RecentBridgeActions,
|
||||
IReadOnlyList<DashboardDispatchRun> RecentDispatchRuns,
|
||||
IReadOnlyList<DashboardTransportReceipt> RecentTransportReceipts,
|
||||
IReadOnlyList<DashboardGovernanceReceipt> RecentGovernanceReceipts);
|
||||
|
||||
public sealed record DashboardWorkItem(
|
||||
Guid WorkItemId,
|
||||
|
|
@ -172,3 +258,53 @@ public sealed record DashboardActivity(
|
|||
string Detail,
|
||||
string ActorName,
|
||||
DateTimeOffset OccurredAtUtc);
|
||||
|
||||
public sealed record DashboardBridgeAction(
|
||||
Guid BridgeActionId,
|
||||
string ActorName,
|
||||
string ActorKind,
|
||||
string TargetSurface,
|
||||
string ActionKind,
|
||||
string Status,
|
||||
string Title,
|
||||
string TargetRepositoryFullName,
|
||||
string ReceiptLabel,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record DashboardDispatchRun(
|
||||
Guid AgentDispatchRunId,
|
||||
string RequestId,
|
||||
string TargetRepoName,
|
||||
string TargetAgentIdentity,
|
||||
string LaunchMode,
|
||||
string Status,
|
||||
string ThreadId,
|
||||
string TurnId,
|
||||
string Note,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record DashboardTransportReceipt(
|
||||
Guid AgentTransportReceiptId,
|
||||
string RequestId,
|
||||
string Title,
|
||||
string TargetRepoName,
|
||||
string TargetAgentIdentity,
|
||||
string ActivityKind,
|
||||
string Status,
|
||||
string ActorName,
|
||||
string Note,
|
||||
DateTimeOffset OccurredAtUtc);
|
||||
|
||||
public sealed record DashboardGovernanceReceipt(
|
||||
Guid GovernanceActivityReceiptId,
|
||||
string TopicId,
|
||||
string CommentId,
|
||||
string DispatchRequestId,
|
||||
string Title,
|
||||
string JurisdictionRepoName,
|
||||
string JurisdictionAgentIdentity,
|
||||
string ActivityKind,
|
||||
string ActorKind,
|
||||
string ActorName,
|
||||
string Note,
|
||||
DateTimeOffset OccurredAtUtc);
|
||||
|
|
|
|||
|
|
@ -22,9 +22,6 @@ public sealed class StartupConfigurationValidator(
|
|||
{
|
||||
var failures = new List<string>();
|
||||
|
||||
// Building the options resolves Heimdall:AppSecretFile, and a bad file stops startup in every environment.
|
||||
_ = heimdallOptions.Value;
|
||||
|
||||
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
|
||||
var conceptVotes = conceptVoteOptions.Value;
|
||||
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
|
||||
|
|
@ -105,13 +102,6 @@ public sealed class StartupConfigurationValidator(
|
|||
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
|
||||
}
|
||||
|
||||
// The options are already resolved, so a secret from Heimdall:AppSecretFile or Heimdall:AppSecret lands in AppSecret.
|
||||
// Blank would silently switch Discord and Patreon member sign-in off.
|
||||
if (string.IsNullOrWhiteSpace(heimdallOptions.Value.AppSecret))
|
||||
{
|
||||
failures.Add("Heimdall:AppSecretFile (or Heimdall:AppSecret) must supply the Heimdall app secret outside development.");
|
||||
}
|
||||
|
||||
if (stripeOptions.Value.EnableCheckout)
|
||||
{
|
||||
if (!stripeOptions.Value.IsCheckoutConfigured)
|
||||
|
|
|
|||
|
|
@ -186,6 +186,165 @@
|
|||
}
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>Agent runs</h2>
|
||||
<p class="muted">Recent dispatched Codex runs recorded by Bifrost.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.Snapshot.RecentDispatchRuns.Count == 0)
|
||||
{
|
||||
<div class="empty-state">No dispatched agent runs have been recorded yet.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list-grid">
|
||||
@foreach (var run in Model.Snapshot.RecentDispatchRuns)
|
||||
{
|
||||
<div class="status-banner">
|
||||
<strong>@run.TargetRepoName@if (!string.IsNullOrWhiteSpace(run.TargetAgentIdentity)) {<text> / @run.TargetAgentIdentity</text>}</strong>
|
||||
<span class="muted">@run.LaunchMode dispatch</span>
|
||||
<div class="inline-actions">
|
||||
<span class="pill">@run.Status</span>
|
||||
<span class="pill">@run.RequestId</span>
|
||||
</div>
|
||||
@if (!string.IsNullOrWhiteSpace(run.ThreadId) || !string.IsNullOrWhiteSpace(run.TurnId))
|
||||
{
|
||||
<div class="muted">Thread @run.ThreadId Turn @run.TurnId</div>
|
||||
}
|
||||
@if (!string.IsNullOrWhiteSpace(run.Note))
|
||||
{
|
||||
<div class="muted">@run.Note</div>
|
||||
}
|
||||
<div class="muted">@run.UpdatedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="panel-grid" style="margin-top: 1.5rem;">
|
||||
<article class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>Transport receipts</h2>
|
||||
<p class="muted">Queue, claim, release, and closure events recorded on the request lane.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.Snapshot.RecentTransportReceipts.Count == 0)
|
||||
{
|
||||
<div class="empty-state">No request-lane receipts have been recorded yet.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list-grid">
|
||||
@foreach (var receipt in Model.Snapshot.RecentTransportReceipts)
|
||||
{
|
||||
<div class="status-banner">
|
||||
<strong>@receipt.TargetRepoName@if (!string.IsNullOrWhiteSpace(receipt.TargetAgentIdentity)) {<text> / @receipt.TargetAgentIdentity</text>}</strong>
|
||||
<span class="muted">@receipt.Title</span>
|
||||
<div class="inline-actions">
|
||||
<span class="pill">@receipt.ActivityKind</span>
|
||||
<span class="pill">@receipt.Status</span>
|
||||
<span class="pill">@receipt.ActorName</span>
|
||||
</div>
|
||||
<div class="muted">@receipt.RequestId</div>
|
||||
@if (!string.IsNullOrWhiteSpace(receipt.Note))
|
||||
{
|
||||
<div class="muted">@receipt.Note</div>
|
||||
}
|
||||
<div class="muted">@receipt.OccurredAtUtc.ToString("dd MMM yyyy HH:mm") UTC</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>Governance receipts</h2>
|
||||
<p class="muted">Hosted receipts for topic opens, comments, approvals, and promotions.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.Snapshot.RecentGovernanceReceipts.Count == 0)
|
||||
{
|
||||
<div class="empty-state">No governance receipts have been recorded yet.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list-grid">
|
||||
@foreach (var receipt in Model.Snapshot.RecentGovernanceReceipts)
|
||||
{
|
||||
<div class="status-banner">
|
||||
<strong>@receipt.JurisdictionRepoName@if (!string.IsNullOrWhiteSpace(receipt.JurisdictionAgentIdentity)) {<text> / @receipt.JurisdictionAgentIdentity</text>}</strong>
|
||||
<span class="muted">@receipt.Title</span>
|
||||
<div class="inline-actions">
|
||||
<span class="pill">@receipt.ActivityKind</span>
|
||||
<span class="pill">@receipt.ActorName</span>
|
||||
</div>
|
||||
<div class="muted">Topic @receipt.TopicId</div>
|
||||
@if (!string.IsNullOrWhiteSpace(receipt.DispatchRequestId))
|
||||
{
|
||||
<div class="muted">Dispatch @receipt.DispatchRequestId</div>
|
||||
}
|
||||
@if (!string.IsNullOrWhiteSpace(receipt.Note))
|
||||
{
|
||||
<div class="muted">@receipt.Note</div>
|
||||
}
|
||||
<div class="muted">@receipt.OccurredAtUtc.ToString("dd MMM yyyy HH:mm") UTC</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>Bridge receipts</h2>
|
||||
<p class="muted">Recent agent and service crossings recorded by Bifrost.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.Snapshot.RecentBridgeActions.Count == 0)
|
||||
{
|
||||
<div class="empty-state">No bridge actions have been recorded yet.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list-grid">
|
||||
@foreach (var action in Model.Snapshot.RecentBridgeActions)
|
||||
{
|
||||
<div class="status-banner">
|
||||
<strong>@action.ActorName</strong>
|
||||
<span class="muted">@action.ActionKind on @action.TargetSurface</span>
|
||||
<div class="inline-actions">
|
||||
<span class="pill">@action.Status</span>
|
||||
@if (!string.IsNullOrWhiteSpace(action.TargetRepositoryFullName))
|
||||
{
|
||||
<span class="pill">@action.TargetRepositoryFullName</span>
|
||||
}
|
||||
</div>
|
||||
<div class="muted">@action.Title</div>
|
||||
@if (!string.IsNullOrWhiteSpace(action.ReceiptLabel))
|
||||
{
|
||||
<div class="muted">@action.ReceiptLabel</div>
|
||||
}
|
||||
<div class="muted">@action.UpdatedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="panel-grid" style="margin-top: 1.5rem;">
|
||||
<article class="panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ public sealed class IndexModel(
|
|||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||
|
||||
public DashboardSnapshot Snapshot { get; private set; } =
|
||||
new(0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], []);
|
||||
new(0, 0, 0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], [], [], [], [], []);
|
||||
|
||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -296,3 +296,7 @@
|
|||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@
|
|||
<section class="panel-grid">
|
||||
<article class="panel">
|
||||
<span class="eyebrow">Members</span>
|
||||
<h1>Chat invites and approval gate</h1>
|
||||
<h1>Invite and approval gate</h1>
|
||||
<p class="panel-intro">
|
||||
Chat is by invitation: mint a single-use link and send it yourself. Approval remains human
|
||||
Invite-first onboarding keeps the alpha intentionally small. Approval remains human
|
||||
because trust and contributor accountability are product concerns, not just auth concerns.
|
||||
</p>
|
||||
|
||||
|
|
@ -21,24 +21,22 @@
|
|||
|
||||
@if (Model.Actor.CanManageMembership)
|
||||
{
|
||||
@if (Model.MintedLink is not null)
|
||||
{
|
||||
<div class="callout success" role="status">
|
||||
Invite link, shown once. Send it to one person; it works for 14 days and one account.
|
||||
<p><code>@Model.MintedLink</code></p>
|
||||
</div>
|
||||
}
|
||||
<form method="post" asp-page-handler="Invite">
|
||||
<div asp-validation-summary="ModelOnly" class="validation-summary-errors"></div>
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label asp-for="Input.Note"></label>
|
||||
<input asp-for="Input.Note" />
|
||||
<span asp-validation-for="Input.Note"></span>
|
||||
<label asp-for="Input.GitHubLogin"></label>
|
||||
<input asp-for="Input.GitHubLogin" />
|
||||
<span asp-validation-for="Input.GitHubLogin"></span>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label asp-for="Input.Notes"></label>
|
||||
<input asp-for="Input.Notes" />
|
||||
<span asp-validation-for="Input.Notes"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-actions">
|
||||
<button class="button" type="submit">Mint chat invite link</button>
|
||||
<button class="button" type="submit">Issue invite</button>
|
||||
</div>
|
||||
</form>
|
||||
}
|
||||
|
|
@ -249,20 +247,18 @@
|
|||
</div>
|
||||
}
|
||||
</section>
|
||||
@if (Model.Actor.CanManageMembership)
|
||||
{
|
||||
|
||||
<section class="table-panel" style="margin-top: 1.5rem;">
|
||||
<div class="panel-header" style="padding: 1.25rem 1.25rem 0;">
|
||||
<div>
|
||||
<h2>Outstanding chat invites</h2>
|
||||
<p class="table-meta">@Model.Invitations.Count unredeemed.</p>
|
||||
<h2>Outstanding invites</h2>
|
||||
<p class="table-meta">@Model.Invitations.Count active invitations tracked.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.Invitations.Count == 0)
|
||||
{
|
||||
<div class="empty-state" style="margin: 1.25rem;">No unredeemed invites.</div>
|
||||
<div class="empty-state" style="margin: 1.25rem;">No invitations yet.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -270,24 +266,24 @@
|
|||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>For</th>
|
||||
<th>GitHub login</th>
|
||||
<th>Issued</th>
|
||||
<th>Expires</th>
|
||||
<th></th>
|
||||
<th>Accepted</th>
|
||||
<th>Notes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var invite in Model.Invitations)
|
||||
@foreach (var invitation in Model.Invitations)
|
||||
{
|
||||
<tr>
|
||||
<td>@invite.Note</td>
|
||||
<td>@invite.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
||||
<td>@invite.ExpiresAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
||||
<td>@invitation.GitHubLogin</td>
|
||||
<td>@invitation.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
||||
<td>
|
||||
<form method="post" asp-page-handler="RevokeInvite" asp-route-inviteId="@invite.Id">
|
||||
<button class="button secondary" type="submit">Revoke</button>
|
||||
</form>
|
||||
@(invitation.AcceptedAtUtc is null
|
||||
? "Waiting for sign-in"
|
||||
: invitation.AcceptedAtUtc.Value.ToString("dd MMM yyyy HH:mm") + " UTC")
|
||||
</td>
|
||||
<td>@invitation.Notes</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
|
|
@ -295,4 +291,7 @@
|
|||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Invites;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
|
@ -15,11 +14,10 @@ public sealed class IndexModel(
|
|||
ICurrentBifrostActorAccessor actorAccessor,
|
||||
AuditTrailService auditTrailService,
|
||||
MembershipSuspensionService suspension,
|
||||
ChatInviteService chatInvites,
|
||||
TimeProvider timeProvider) : PageModel
|
||||
{
|
||||
[BindProperty]
|
||||
public MintInviteInput Input { get; set; } = new();
|
||||
public InviteMemberInput Input { get; set; } = new();
|
||||
|
||||
[BindProperty]
|
||||
public UpdateProfileInput Profile { get; set; } = new();
|
||||
|
|
@ -39,7 +37,6 @@ public sealed class IndexModel(
|
|||
internal const string ApproveSuspendedNotice = "Nothing changed: a suspended account can only be lifted with Unsuspend.";
|
||||
/// <summary>Admin-only text for a Suspended row whose reason predates the SuspensionReason column; the old text is never read back from the audit trail.</summary>
|
||||
internal const string LegacySuspensionText = "Suspended before reasons were recorded";
|
||||
|
||||
internal const string NoMembershipNotice = "Nothing changed: that account has no membership yet.";
|
||||
internal const string OwnAdminRoleNotice = "Nothing changed: you cannot remove or change your own platform admin role.";
|
||||
internal const string RoleOnSuspendedNotice = "Nothing changed: a suspended account's roles cannot be changed until it is unsuspended.";
|
||||
|
|
@ -48,10 +45,7 @@ public sealed class IndexModel(
|
|||
|
||||
public IReadOnlyList<MemberDirectoryItem> Users { get; private set; } = [];
|
||||
|
||||
public IReadOnlyList<ChatInvite> Invitations { get; private set; } = [];
|
||||
|
||||
/// <summary>The link just minted, present only on the response to the mint.</summary>
|
||||
public string? MintedLink { get; private set; }
|
||||
public IReadOnlyList<MembershipInvitation> Invitations { get; private set; } = [];
|
||||
|
||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
|
|
@ -66,30 +60,53 @@ public sealed class IndexModel(
|
|||
return Forbid();
|
||||
}
|
||||
|
||||
// The mint form carries only the note, so only the note is checked: ModelState also holds the profile form's required fields, which this post never sends.
|
||||
if (string.IsNullOrWhiteSpace(Input.Note) || Input.Note.Length > 500)
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
ModelState.AddModelError($"{nameof(Input)}.{nameof(Input.Note)}", "Say who this invite is for, in at most 500 characters.");
|
||||
await LoadAsync(cancellationToken);
|
||||
return Page();
|
||||
}
|
||||
|
||||
var (_, token) = await chatInvites.MintAsync(Actor.UserAccount.Id, Input.Note, cancellationToken);
|
||||
// The link is shown once, on this response: no redirect, no TempData, nothing stored that could show it again.
|
||||
MintedLink = chatInvites.LinkFor(token);
|
||||
await LoadAsync(cancellationToken);
|
||||
return Page();
|
||||
}
|
||||
var normalizedLogin = Input.GitHubLogin.Trim().ToUpperInvariant();
|
||||
var invitation = await dbContext.MembershipInvitations
|
||||
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
|
||||
|
||||
public async Task<IActionResult> OnPostRevokeInviteAsync(Guid inviteId, CancellationToken cancellationToken)
|
||||
{
|
||||
Actor = await actorAccessor.GetAsync(cancellationToken);
|
||||
if (!Actor.CanManageMembership || Actor.UserAccount is null)
|
||||
if (invitation is null)
|
||||
{
|
||||
return Forbid();
|
||||
invitation = new MembershipInvitation
|
||||
{
|
||||
GitHubLogin = Input.GitHubLogin.Trim(),
|
||||
NormalizedGitHubLogin = normalizedLogin,
|
||||
IssuedByUserAccountId = Actor.UserAccount.Id,
|
||||
IssuedAtUtc = timeProvider.GetUtcNow(),
|
||||
Notes = Input.Notes.Trim()
|
||||
};
|
||||
|
||||
dbContext.MembershipInvitations.Add(invitation);
|
||||
}
|
||||
else
|
||||
{
|
||||
invitation.RevokedAtUtc = null;
|
||||
invitation.Notes = Input.Notes.Trim();
|
||||
}
|
||||
|
||||
await chatInvites.RevokeAsync(inviteId, Actor.UserAccount.Id, cancellationToken);
|
||||
var existingUser = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
|
||||
|
||||
if (existingUser?.Membership is not null && existingUser.Membership.Status == MembershipStatus.Authenticated)
|
||||
{
|
||||
existingUser.Membership.Status = MembershipStatus.PendingApproval;
|
||||
}
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
await auditTrailService.RecordAsync(
|
||||
Actor.UserAccount.Id,
|
||||
nameof(MembershipInvitation),
|
||||
invitation.Id,
|
||||
"membership.invited",
|
||||
$"Issued invite for {invitation.GitHubLogin}.",
|
||||
cancellationToken);
|
||||
|
||||
return RedirectToPage();
|
||||
}
|
||||
|
||||
|
|
@ -390,7 +407,11 @@ public sealed class IndexModel(
|
|||
contributorTier?.Weight ?? 0m);
|
||||
}).ToList();
|
||||
|
||||
Invitations = Actor.CanManageMembership ? await chatInvites.PendingAsync(cancellationToken) : [];
|
||||
Invitations = await dbContext.MembershipInvitations
|
||||
.AsNoTracking()
|
||||
.Where(x => x.RevokedAtUtc == null)
|
||||
.OrderByDescending(x => x.IssuedAtUtc)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (Actor.UserAccount is not null)
|
||||
{
|
||||
|
|
@ -420,11 +441,14 @@ public sealed class IndexModel(
|
|||
membership.CanModerateMotions = membership.IsPlatformAdmin || roles.Contains(MemberRole.Producer) || roles.Contains(MemberRole.Maintainer);
|
||||
}
|
||||
|
||||
public sealed class MintInviteInput
|
||||
public sealed class InviteMemberInput
|
||||
{
|
||||
[Required, StringLength(120)]
|
||||
[Display(Name = "GitHub login")]
|
||||
public string GitHubLogin { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(500)]
|
||||
[Display(Name = "Who is this for")]
|
||||
public string Note { get; set; } = string.Empty;
|
||||
public string Notes { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public sealed class UpdateProfileInput
|
||||
|
|
|
|||
|
|
@ -147,3 +147,7 @@
|
|||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,3 +110,7 @@
|
|||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,3 +291,7 @@
|
|||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,14 @@
|
|||
<span>Assigned to me</span>
|
||||
<strong>@Model.AssignedToCurrentMember</strong>
|
||||
</article>
|
||||
<article class="metric-card">
|
||||
<span>Bridge actions live</span>
|
||||
<strong>@Model.ActiveBridgeActions</strong>
|
||||
</article>
|
||||
<article class="metric-card">
|
||||
<span>Dispatch runs live</span>
|
||||
<strong>@Model.ActiveDispatchRuns</strong>
|
||||
</article>
|
||||
<article class="metric-card">
|
||||
<span>Approved nominal payout</span>
|
||||
<strong>@Model.ApprovedNominalPayoutValue.ToString("0.##")</strong>
|
||||
|
|
|
|||
|
|
@ -20,12 +20,6 @@
|
|||
<code>GitHubOAuth:ClientSecret</code> before using sign-in.
|
||||
</div>
|
||||
}
|
||||
else if (Model.Auth == "identity-not-linked")
|
||||
{
|
||||
<div class="callout warning">
|
||||
No Bifrost account holds that Google login. Sign in another way, then link Google from your linked accounts, or open an invite link first.
|
||||
</div>
|
||||
}
|
||||
else if (Model.Auth == "heimdall-error")
|
||||
{
|
||||
<div class="callout warning">
|
||||
|
|
|
|||
|
|
@ -1,230 +0,0 @@
|
|||
@page
|
||||
@model Bifrost.Web.Pages.Membership.LinkedAccountsModel
|
||||
@{
|
||||
ViewData["Title"] = "Linked accounts";
|
||||
}
|
||||
|
||||
<section class="panel">
|
||||
<span class="eyebrow">Heimdall</span>
|
||||
<h1>Linked accounts</h1>
|
||||
<p class="panel-intro">
|
||||
The provider logins that sign in to this account. Heimdall holds them and decides what may change; Bifrost keeps none of
|
||||
your Heimdall sign-in, so each action sends you through Heimdall once more.
|
||||
</p>
|
||||
|
||||
@if (Model.ResultMessage is not null)
|
||||
{
|
||||
<div class="callout" role="status">@Model.ResultMessage</div>
|
||||
}
|
||||
|
||||
@if (!Model.HasHeimdallAccount)
|
||||
{
|
||||
<div class="callout warning">
|
||||
This session is not a Heimdall account, so there are no provider logins to manage here. Sign in with Discord or Patreon
|
||||
through Heimdall to see them.
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<h2>Your logins</h2>
|
||||
@if (Model.Identities is null)
|
||||
{
|
||||
<p class="muted">
|
||||
Bifrost does not hold the list: it asks Heimdall, which means signing in to Heimdall again, and keeps the answer for
|
||||
five minutes. It also cannot tell which logins this account holds right now, so it will not choose one for you.
|
||||
Pick a login you know it holds. Signing in through Discord or Patreon when the account no longer holds that login
|
||||
would create a separate Heimdall account holding it. Google cannot do that: Heimdall refuses a Google sign-in for a
|
||||
login no account holds.
|
||||
</p>
|
||||
<div class="panel-actions">
|
||||
@foreach (var provider in Model.LinkableProviders.OrderBy(x => x == "google" ? 0 : 1))
|
||||
{
|
||||
<form method="post" asp-page-handler="Refresh" class="inline-actions">
|
||||
<input type="hidden" name="via" value="@provider" />
|
||||
<button class="button secondary" type="submit">Show my logins through @LinkedAccountsModel.ProviderName(provider)@(provider == "google" ? " (cannot create an account)" : "")</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul>
|
||||
@foreach (var identity in Model.Identities)
|
||||
{
|
||||
<li>
|
||||
<strong>@LinkedAccountsModel.ProviderName(identity.Provider)</strong>
|
||||
@if (identity.DisplayName is not null)
|
||||
{
|
||||
<span>@identity.DisplayName</span>
|
||||
}
|
||||
@if (identity.LinkedAt is { } linkedAt)
|
||||
{
|
||||
<span class="muted">linked @linkedAt.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||
}
|
||||
@if (Model.HasStrongPasskey)
|
||||
{
|
||||
@if (Model.PasskeysAvailable)
|
||||
{
|
||||
<form method="post" asp-page-handler="UnlinkPasskey" class="inline-actions" data-passkey-unlink>
|
||||
<input type="hidden" name="identityId" value="@identity.Id" />
|
||||
<input type="hidden" name="id" />
|
||||
<input type="hidden" name="rawId" />
|
||||
<input type="hidden" name="authenticatorData" />
|
||||
<input type="hidden" name="clientDataJson" />
|
||||
<input type="hidden" name="signature" />
|
||||
<input type="hidden" name="userHandle" />
|
||||
<button class="button secondary" type="submit">Unlink with passkey</button>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
else if (Model.HasGoogle)
|
||||
{
|
||||
<form method="post" asp-page-handler="Unlink" class="inline-actions">
|
||||
<input type="hidden" name="identityId" value="@identity.Id" />
|
||||
<button class="button secondary" type="submit">Unlink</button>
|
||||
</form>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
@if (Model.Identities.Count == 1)
|
||||
{
|
||||
<p class="muted">This is your only login. Heimdall will not remove the last one.</p>
|
||||
}
|
||||
|
||||
@if (Model.HasStrongPasskey && !Model.PasskeysAvailable)
|
||||
{
|
||||
<p class="callout warning">
|
||||
This account has a passkey, so unlinking needs it, but passkeys are not available on this server right now (a
|
||||
configuration fault the operator must fix), so nothing can be unlinked from here at the moment. Nothing is lost:
|
||||
try again later. If you cannot wait, revoke your passkeys below; unlinking then falls back to a fresh Google sign-in,
|
||||
if a Google login is linked to this account.
|
||||
</p>
|
||||
}
|
||||
else if (Model.HasStrongPasskey)
|
||||
{
|
||||
<p class="muted">Unlinking asks for one of your passkeys, then signs you in to Heimdall once more and removes only the login you picked.</p>
|
||||
}
|
||||
else if (Model.HasGoogle)
|
||||
{
|
||||
<p class="muted">Unlinking asks you to sign in with Google again as proof, then removes only the login you picked. A passkey, once it has cooled off, is stronger proof and takes over from Google.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted">
|
||||
Unlinking needs strong proof, and none is available. Add a passkey below@(Model.NextStrongAt is { } waiting
|
||||
? $" (your newest one counts from {waiting.UtcDateTime:dd MMM yyyy HH:mm} UTC)"
|
||||
: " (it counts after a 48 hour cooling-off)"),
|
||||
or link a Google login once Heimdall has Google set up. Discord and Patreon cannot give that proof.
|
||||
</p>
|
||||
}
|
||||
|
||||
<form method="post" asp-page-handler="Refresh" class="panel-actions">
|
||||
<button class="button secondary" type="submit">Read the list again</button>
|
||||
</form>
|
||||
}
|
||||
|
||||
<h2>Passkeys</h2>
|
||||
@if (!Model.PasskeysAvailable)
|
||||
{
|
||||
<p class="muted">Passkeys are not available on this server right now, so none can be added or used. You can still revoke the ones listed.</p>
|
||||
}
|
||||
@if (Model.PasskeysAvailable)
|
||||
{
|
||||
<p class="muted">
|
||||
A passkey is the strong proof for unlinking a login: it stays on your device, and a site that is not Bifrost cannot use it.
|
||||
A new passkey is added only right after you sign in to Heimdall again, and it counts as strong proof 48 hours later, so
|
||||
someone who borrows your open browser cannot add one and use it at once. You can revoke a passkey here at any time.
|
||||
</p>
|
||||
}
|
||||
@if (Model.Passkeys.Count > 0)
|
||||
{
|
||||
<ul>
|
||||
@foreach (var key in Model.Passkeys)
|
||||
{
|
||||
<li>
|
||||
<strong>@key.Label</strong>
|
||||
@if (key.IsStrong)
|
||||
{
|
||||
<span class="muted">active</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="muted">cooling off until @key.StrongFromUtc.UtcDateTime.ToString("dd MMM yyyy HH:mm") UTC; cannot unlink yet</span>
|
||||
}
|
||||
<span class="muted">added @key.CreatedUtc.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||
@if (key.LastUsedUtc is { } used)
|
||||
{
|
||||
<span class="muted">last used @used.UtcDateTime.ToString("dd MMM yyyy") UTC</span>
|
||||
}
|
||||
<form method="post" asp-page-handler="PasskeyRevoke" class="inline-actions">
|
||||
<input type="hidden" name="credentialId" value="@key.Id" />
|
||||
<button class="button secondary" type="submit">Revoke</button>
|
||||
</form>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
|
||||
@if (Model.PasskeysAvailable)
|
||||
{
|
||||
if (Model.PasskeyLimitReached)
|
||||
{
|
||||
<p class="muted">This is the most passkeys an account can hold. Revoke one to add another.</p>
|
||||
}
|
||||
else if (Model.CanEnrol)
|
||||
{
|
||||
<form method="post" asp-page-handler="PasskeyEnrol" id="passkey-enrol" data-passkey-enrol>
|
||||
<input type="hidden" name="id" />
|
||||
<input type="hidden" name="rawId" />
|
||||
<input type="hidden" name="attestationObject" />
|
||||
<input type="hidden" name="clientDataJson" />
|
||||
<input type="hidden" name="transports" />
|
||||
<label>Name for this passkey <input type="text" name="label" maxlength="40" value="Passkey" /></label>
|
||||
<button class="button" type="submit">Add a passkey</button>
|
||||
</form>
|
||||
<noscript><p class="muted">Adding a passkey needs JavaScript.</p></noscript>
|
||||
}
|
||||
else if (Model.Identities is not null)
|
||||
{
|
||||
<form method="post" asp-page-handler="PasskeyEnrolStart" class="panel-actions">
|
||||
<button class="button secondary" type="submit">Sign in again to add a passkey</button>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted">Read your linked logins first; adding a passkey then asks you to sign in to Heimdall once more.</p>
|
||||
}
|
||||
}
|
||||
<p id="passkey-status" class="muted" role="status"></p>
|
||||
|
||||
@if (Model.Identities is not null)
|
||||
{
|
||||
<h2>Link another login</h2>
|
||||
<p class="muted">
|
||||
You will sign in to Heimdall again, then to the provider you pick. If that login already belongs to another account,
|
||||
nothing is linked and nothing is merged.
|
||||
</p>
|
||||
<div class="panel-actions">
|
||||
@foreach (var provider in Model.LinkableProviders)
|
||||
{
|
||||
<form method="post" asp-page-handler="Link" class="inline-actions">
|
||||
<input type="hidden" name="provider" value="@provider" />
|
||||
<button class="button secondary" type="submit">Link @LinkedAccountsModel.ProviderName(provider)</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
<div class="panel-actions">
|
||||
<a class="button secondary" asp-page="/Membership/Status">Back to membership status</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
@if (Model.HasHeimdallAccount && Model.PasskeysAvailable)
|
||||
{
|
||||
<script src="~/js/passkeys.js" asp-append-version="true"></script>
|
||||
}
|
||||
}
|
||||
|
|
@ -1,295 +0,0 @@
|
|||
using System.Security.Claims;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Features.Heimdall;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Passkeys;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Pages.Membership;
|
||||
|
||||
/// <summary>
|
||||
/// The member's provider logins (docs/linked-accounts.md). Bifrost keeps no Heimdall token, so every action here begins a
|
||||
/// fresh Heimdall sign-in for the account already signed in and finishes inside that sign-in's completion
|
||||
/// (<c>POST /auth/heimdall/complete</c>); this page only starts them and shows what the last read found. Every handler is a
|
||||
/// POST with antiforgery. Nothing from the query or the form is ever shown: the outcome is a code from a closed set.
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class LinkedAccountsModel(
|
||||
HeimdallAuthService heimdallAuthService,
|
||||
LinkedAccountsSnapshots snapshots,
|
||||
PasskeyService passkeys,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
ILogger<LinkedAccountsModel> logger) : PageModel
|
||||
{
|
||||
private static readonly Dictionary<string, string> ProviderNames = new(StringComparer.Ordinal)
|
||||
{
|
||||
["discord"] = "Discord",
|
||||
["patreon"] = "Patreon",
|
||||
["google"] = "Google"
|
||||
};
|
||||
|
||||
private string? AccountId => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 } id ? id : null;
|
||||
|
||||
/// <summary>The wording of the outcome the page was sent back with: a closed set, null for anything else.</summary>
|
||||
public string? ResultMessage { get; private set; }
|
||||
|
||||
/// <summary>Whether this session is a Heimdall account. A Bifrost-native GitHub session has none, so there is nothing to list.</summary>
|
||||
public bool HasHeimdallAccount => AccountId is not null;
|
||||
|
||||
/// <summary>The logins the last read found, or null when there is none or it has expired.</summary>
|
||||
public IReadOnlyList<LinkedIdentitySummary>? Identities { get; private set; }
|
||||
|
||||
/// <summary>Whether a fresh Google sign-in can be had for this account: without a strong passkey, unlinking needs one, and only Google can give it.</summary>
|
||||
public bool HasGoogle => Identities?.Any(x => x.Provider == HeimdallAuthService.StepUpProvider) == true;
|
||||
|
||||
/// <summary>The account's passkeys that are not revoked, with their cooling-off state.</summary>
|
||||
public IReadOnlyList<PasskeyView> Passkeys { get; private set; } = [];
|
||||
|
||||
/// <summary>Whether a passkey past its cooling-off exists: unlinking then needs it and no longer accepts Google as the proof.</summary>
|
||||
public bool HasStrongPasskey => Passkeys.Any(x => x.IsStrong);
|
||||
|
||||
/// <summary>When the first passkey still cooling off becomes strong.</summary>
|
||||
public DateTimeOffset? NextStrongAt => Passkeys.Where(x => !x.IsStrong).Select(x => (DateTimeOffset?)x.StrongFromUtc).Min();
|
||||
|
||||
/// <summary>Whether this browser holds a live ticket from a fresh sign-in, so a passkey can be added now.</summary>
|
||||
public bool CanEnrol { get; private set; }
|
||||
|
||||
/// <summary>Whether this server can run passkey ceremonies at all (https and the host it expects).</summary>
|
||||
public bool PasskeysAvailable => passkeys.IsAvailable;
|
||||
|
||||
public bool PasskeyLimitReached => Passkeys.Count >= PasskeyService.MaxActive;
|
||||
|
||||
public bool CanUnlink => HasStrongPasskey || HasGoogle;
|
||||
|
||||
public IReadOnlyList<string> LinkableProviders => HeimdallAuthService.LinkableProviders;
|
||||
|
||||
public static string ProviderName(string provider) => ProviderNames.GetValueOrDefault(provider, provider);
|
||||
|
||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ResultMessage = HeimdallLinkOutcomes.Wording(Request.Query[HeimdallLinkOutcomes.ResultParameter].ToString());
|
||||
Identities = AccountId is { } id ? snapshots.Get(id) : null;
|
||||
if (AccountId is { } account)
|
||||
{
|
||||
Passkeys = await passkeys.ListAsync(account, cancellationToken);
|
||||
CanEnrol = passkeys.HasTicket(account, Request.Cookies[BifrostCookies.PasskeyTicket]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the account's logins: an ordinary Heimdall sign-in, then the list inside its completion.</summary>
|
||||
public Task<IActionResult> OnPostRefreshAsync(string? via, CancellationToken cancellationToken)
|
||||
{
|
||||
// With no current list Bifrost cannot tell which provider the account still holds, so the member names one.
|
||||
if (AccountId is not { } id || (snapshots.Get(id) is null && (via is null || !HeimdallAuthService.LinkableProviders.Contains(via))))
|
||||
{
|
||||
return Task.FromResult(Done(HeimdallLinkOutcome.ProviderNeeded));
|
||||
}
|
||||
|
||||
return BeginAsync(
|
||||
(account, ct) => heimdallAuthService.StartListAsync(account, via, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||
HeimdallLinkOutcome.Error,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Links another provider. The provider is one Heimdall's bifrost profile admits; anything else starts nothing, and so does a missing list.</summary>
|
||||
public Task<IActionResult> OnPostLinkAsync(string? provider, CancellationToken cancellationToken)
|
||||
{
|
||||
if (provider is null || !HeimdallAuthService.LinkableProviders.Contains(provider))
|
||||
{
|
||||
return Task.FromResult(Done(HeimdallLinkOutcome.Error));
|
||||
}
|
||||
|
||||
if (AccountId is not { } id || snapshots.Get(id) is null)
|
||||
{
|
||||
return Task.FromResult(Done(HeimdallLinkOutcome.ListExpired));
|
||||
}
|
||||
|
||||
return BeginAsync(
|
||||
(account, ct) => heimdallAuthService.StartLinkAsync(account, provider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||
HeimdallLinkOutcome.Error,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unlinks one login with fresh proof. The identity must be on the list this account was last shown and the account must
|
||||
/// hold a Google login to prove with; otherwise Heimdall is not asked, and the page says so.
|
||||
/// </summary>
|
||||
public async Task<IActionResult> OnPostUnlinkAsync(string? identityId, CancellationToken cancellationToken)
|
||||
{
|
||||
var shown = AccountId is { } id ? snapshots.Get(id) : null;
|
||||
if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.ListExpired);
|
||||
}
|
||||
|
||||
// A strong passkey replaces Google as the proof: a member who has one is never asked for the weaker one.
|
||||
if (await passkeys.HasStrongAsync(AccountId!, cancellationToken))
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.PasskeyRequired);
|
||||
}
|
||||
|
||||
if (!shown.Any(x => x.Provider == HeimdallAuthService.StepUpProvider))
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.ProofUnavailable);
|
||||
}
|
||||
|
||||
return await BeginAsync(
|
||||
(account, ct) => heimdallAuthService.StartUnlinkAsync(account, identityId, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||
HeimdallLinkOutcome.ProofUnavailable,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Begins the fresh sign-in whose completion issues the enrolment ticket. Needs a current list: the proof provider is never guessed.</summary>
|
||||
public async Task<IActionResult> OnPostPasskeyEnrolStartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (AccountId is not { } id)
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.Error);
|
||||
}
|
||||
|
||||
if (snapshots.Get(id) is null)
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.ListExpired);
|
||||
}
|
||||
|
||||
if (await passkeys.PreflightEnrolStartAsync(id, cancellationToken) is { } refused)
|
||||
{
|
||||
return Done(refused);
|
||||
}
|
||||
|
||||
return await BeginAsync(
|
||||
(account, ct) => heimdallAuthService.StartEnrolProofAsync(account, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
|
||||
HeimdallLinkOutcome.Error,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The WebAuthn creation options for the ticket this browser holds, as JSON for the page's script.</summary>
|
||||
public async Task<IActionResult> OnPostPasskeyEnrolOptionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (AccountId is not { } id)
|
||||
{
|
||||
return Options(HeimdallLinkOutcome.Error, null);
|
||||
}
|
||||
|
||||
var (refusal, json) = await passkeys.BeginEnrolAsync(id, Request.Cookies[BifrostCookies.PasskeyTicket], cancellationToken);
|
||||
return Options(refusal, json);
|
||||
}
|
||||
|
||||
/// <summary>Verifies the registration the script posted. The ticket cookie is spent whatever the outcome.</summary>
|
||||
public async Task<IActionResult> OnPostPasskeyEnrolAsync(
|
||||
string? id, string? rawId, string? attestationObject, string? clientDataJson, string? transports, string? label, CancellationToken cancellationToken)
|
||||
{
|
||||
if (AccountId is not { } account)
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.Error);
|
||||
}
|
||||
|
||||
var outcome = await passkeys.EnrolAsync(
|
||||
account, Request.Cookies[BifrostCookies.PasskeyTicket],
|
||||
new PasskeyFields(id, rawId, null, clientDataJson, null, null, attestationObject, transports), label, cancellationToken);
|
||||
Response.Cookies.Delete(BifrostCookies.PasskeyTicket, HeimdallAttemptCookie.DeleteOptions());
|
||||
return Done(outcome);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> OnPostPasskeyRevokeAsync(Guid credentialId, CancellationToken cancellationToken) =>
|
||||
AccountId is { } id ? Done(await passkeys.RevokeAsync(id, credentialId, cancellationToken)) : Done(HeimdallLinkOutcome.Error);
|
||||
|
||||
/// <summary>The WebAuthn request options for unlinking one identity, as JSON for the page's script.</summary>
|
||||
public async Task<IActionResult> OnPostPasskeyChallengeAsync(string? identityId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (AccountId is not { } id)
|
||||
{
|
||||
return Options(HeimdallLinkOutcome.Error, null);
|
||||
}
|
||||
|
||||
if (snapshots.Get(id) is not { } shown || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||
{
|
||||
return Options(HeimdallLinkOutcome.ListExpired, null);
|
||||
}
|
||||
|
||||
var (refusal, json) = await passkeys.BeginAssertionAsync(id, identityId, cancellationToken);
|
||||
return Options(refusal, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unlinks one login on a passkey assertion. The assertion is verified here; only then does Bifrost start the fresh Heimdall sign-in
|
||||
/// whose completion asks Heimdall for the step-up and unlinks. A refused or unverifiable assertion starts no sign-in.
|
||||
/// </summary>
|
||||
public async Task<IActionResult> OnPostUnlinkPasskeyAsync(
|
||||
string? identityId, string? id, string? rawId, string? authenticatorData, string? clientDataJson, string? signature, string? userHandle,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var shown = AccountId is { } account ? snapshots.Get(account) : null;
|
||||
if (shown is null || identityId is null || !shown.Any(x => x.Id == identityId))
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.ListExpired);
|
||||
}
|
||||
|
||||
var (refusal, factId) = await passkeys.VerifyAssertionAsync(
|
||||
AccountId!, identityId, new PasskeyFields(id, rawId, authenticatorData, clientDataJson, signature, userHandle, null, null), cancellationToken);
|
||||
if (refusal is { } failed)
|
||||
{
|
||||
return Done(failed);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var started = await heimdallAuthService.StartUnlinkPasskeyAsync(
|
||||
AccountId!, identityId, factId!, hostOptions.Value.PublicBaseUrl, Request.Cookies, cancellationToken);
|
||||
Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
|
||||
return Redirect(started.AuthorizationUrl.ToString());
|
||||
}
|
||||
catch (HeimdallAuthException error)
|
||||
{
|
||||
logger.LogWarning("Linked accounts start refused: {Reason}", error.Message);
|
||||
passkeys.DiscardFact(factId);
|
||||
return Done(HeimdallLinkOutcome.ProofUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>JSON for the page's script: the options, or only a closed outcome code with the status that fits.</summary>
|
||||
private IActionResult Options(HeimdallLinkOutcome? refusal, string? json)
|
||||
{
|
||||
if (refusal is null && json is not null)
|
||||
{
|
||||
return Content(json, "application/json");
|
||||
}
|
||||
|
||||
var status = refusal == HeimdallLinkOutcome.RateLimited ? StatusCodes.Status429TooManyRequests : StatusCodes.Status400BadRequest;
|
||||
return new ContentResult
|
||||
{
|
||||
StatusCode = status,
|
||||
ContentType = "application/json",
|
||||
Content = "{\"error\":\"" + HeimdallLinkOutcomes.Code(refusal ?? HeimdallLinkOutcome.Error) + "\"}"
|
||||
};
|
||||
}
|
||||
|
||||
private IActionResult Done(HeimdallLinkOutcome outcome) =>
|
||||
RedirectToPage(null, new Dictionary<string, string?> { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });
|
||||
|
||||
private async Task<IActionResult> BeginAsync(
|
||||
Func<string, CancellationToken, Task<HeimdallAuthStartResult>> start, HeimdallLinkOutcome onRefusal, CancellationToken cancellationToken)
|
||||
{
|
||||
if (AccountId is not { } accountId)
|
||||
{
|
||||
return Done(HeimdallLinkOutcome.Error);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var started = await start(accountId, cancellationToken);
|
||||
Response.Cookies.Append(started.CookieName, started.CookieValue, HeimdallAttemptCookie.Options());
|
||||
return Redirect(started.AuthorizationUrl.ToString());
|
||||
}
|
||||
catch (HeimdallAuthException error)
|
||||
{
|
||||
logger.LogWarning("Linked accounts start refused: {Reason}", error.Message);
|
||||
return Done(onRefusal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -24,11 +24,11 @@
|
|||
<p class="muted">@Model.StatusMessage</p>
|
||||
</div>
|
||||
|
||||
@if (Model.CanManageLogins)
|
||||
@if (Model.Invitation is not null)
|
||||
{
|
||||
<div class="panel-actions">
|
||||
<a class="button secondary" asp-page="/Membership/LinkedAccounts">Linked accounts</a>
|
||||
<span class="muted">See, add and remove the provider logins that sign in to this account.</span>
|
||||
<div class="callout success">
|
||||
Invitation tracked for <code>@Model.Invitation.GitHubLogin</code>.
|
||||
Issued @Model.Invitation.IssuedAtUtc.ToString("dd MMM yyyy") UTC.
|
||||
</div>
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,20 +1,21 @@
|
|||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using System.Security.Claims;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Bifrost.Web.Pages.Membership;
|
||||
|
||||
[Authorize]
|
||||
public sealed class StatusModel(ICurrentBifrostActorAccessor actorAccessor) : PageModel
|
||||
public sealed class StatusModel(
|
||||
ICurrentBifrostActorAccessor actorAccessor,
|
||||
BifrostDbContext dbContext) : PageModel
|
||||
{
|
||||
/// <summary>Whether this session belongs to a Heimdall account whose logins the Linked accounts page can manage.</summary>
|
||||
public bool CanManageLogins => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 };
|
||||
|
||||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||
|
||||
public MembershipInvitation? Invitation { get; private set; }
|
||||
|
||||
public string StatusLabel => Actor.Membership?.Status switch
|
||||
{
|
||||
MembershipStatus.Active => "Active member",
|
||||
|
|
@ -35,14 +36,26 @@ public sealed class StatusModel(ICurrentBifrostActorAccessor actorAccessor) : Pa
|
|||
public string StatusMessage => Actor.Membership?.Status switch
|
||||
{
|
||||
MembershipStatus.Active => "You can participate in projects, claim work, vote on motions, and view the ledger console.",
|
||||
MembershipStatus.PendingApproval => "An admin still needs to approve active participation.",
|
||||
MembershipStatus.PendingApproval => "Your GitHub sign-in matched an invite, but an admin still needs to approve active participation.",
|
||||
MembershipStatus.Suspended => "Your account is currently suspended from active participation pending an admin review.",
|
||||
MembershipStatus.Authenticated => "You are signed in, but there is no approval on your account yet.",
|
||||
MembershipStatus.Authenticated => "You are signed in, but there is no active invite or approval on your account yet.",
|
||||
_ => "No membership record was found."
|
||||
};
|
||||
|
||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Actor = await actorAccessor.GetAsync(cancellationToken);
|
||||
|
||||
if (Actor.UserAccount is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Invitation = await dbContext.MembershipInvitations
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(
|
||||
x => x.NormalizedGitHubLogin == Actor.UserAccount.NormalizedGitHubLogin &&
|
||||
x.RevokedAtUtc == null,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
|
||||
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>
|
||||
|
|
@ -5,6 +5,7 @@ using System.Text.Json.Serialization;
|
|||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Bridge;
|
||||
using Bifrost.Web.Features.ConceptVotes;
|
||||
using Bifrost.Web.Features.Desk;
|
||||
using Bifrost.Web.Features.GitHub;
|
||||
|
|
@ -63,13 +64,16 @@ builder.Services
|
|||
|
||||
builder.Services
|
||||
.AddOptions<HeimdallOptions>()
|
||||
.BindConfiguration(HeimdallOptions.SectionName)
|
||||
.PostConfigure<ILogger<HeimdallOptions>>(HeimdallOptions.ResolveAppSecret);
|
||||
.BindConfiguration(HeimdallOptions.SectionName);
|
||||
|
||||
builder.Services
|
||||
.AddOptions<StripeOptions>()
|
||||
.BindConfiguration(StripeOptions.SectionName);
|
||||
|
||||
builder.Services
|
||||
.AddOptions<BridgeOptions>()
|
||||
.BindConfiguration(BridgeOptions.SectionName);
|
||||
|
||||
builder.Services
|
||||
.AddOptions<ConceptVoteOptions>()
|
||||
.BindConfiguration(ConceptVoteOptions.SectionName);
|
||||
|
|
@ -88,7 +92,6 @@ builder.Services.AddAntiforgery(options =>
|
|||
builder.Services.AddRazorPages(options =>
|
||||
{
|
||||
options.Conventions.AuthorizePage("/Membership/Status");
|
||||
options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
|
||||
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
|
||||
options.Conventions.AllowAnonymousToFolder("/Mill");
|
||||
});
|
||||
|
|
@ -117,6 +120,10 @@ builder.Services.AddScoped<ICurrentBifrostActorAccessor, CurrentBifrostActorAcce
|
|||
builder.Services.AddScoped<AuditTrailService>();
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Membership.MembershipSuspensionService>();
|
||||
builder.Services.AddScoped<DashboardSnapshotService>();
|
||||
builder.Services.AddScoped<BridgeActionService>();
|
||||
builder.Services.AddScoped<AgentDispatchRunService>();
|
||||
builder.Services.AddScoped<AgentTransportReceiptService>();
|
||||
builder.Services.AddScoped<GovernanceActivityReceiptService>();
|
||||
builder.Services.AddScoped<MembershipSynchronizationService>();
|
||||
builder.Services.AddScoped<BifrostIdentityService>();
|
||||
builder.Services.AddScoped<GitHubWebhookService>();
|
||||
|
|
@ -129,8 +136,8 @@ builder.Services.AddOptions<RegistrationOptions>().BindConfiguration(Registratio
|
|||
builder.Services.AddSingleton<RegistrationChallengeService>();
|
||||
builder.Services.AddSingleton<RegistrationRateLimit>();
|
||||
builder.Services.AddScoped<NativeRegistration>();
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Invites.ChatInviteService>();
|
||||
builder.Services.AddHostedService<SealedBallotCloser>();
|
||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
||||
builder.Services.AddScoped<PatronageService>();
|
||||
builder.Services.AddScoped<StripeWebhookService>();
|
||||
builder.Services.AddScoped<HeimdallPatronSupportIntakeService>();
|
||||
|
|
@ -142,13 +149,9 @@ builder.Services.AddScoped<ReadinessService>();
|
|||
builder.Services.AddScoped<ApplicationBootstrapper>();
|
||||
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
||||
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
||||
// The app-secret and member-bearer clients: no redirects (see HeimdallClientServices).
|
||||
builder.Services.AddHeimdallClients();
|
||||
builder.Services.AddSingleton<LinkedAccountsSnapshots>();
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyRelyingParty>();
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyCeremonies>();
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyRateLimit>();
|
||||
builder.Services.AddScoped<Bifrost.Web.Features.Passkeys.PasskeyService>();
|
||||
builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||
.RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
|
||||
builder.Services.AddSingleton<HeimdallTokenVerifier>();
|
||||
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
||||
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
||||
|
|
@ -271,8 +274,6 @@ var app = builder.Build();
|
|||
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
||||
|
||||
app.Services.GetRequiredService<StartupConfigurationValidator>().Validate();
|
||||
// Resolved now so a misconfigured RP (not https, host differs, a port in ExpectedHost) is logged once at boot, not on the first ceremony.
|
||||
_ = app.Services.GetRequiredService<Bifrost.Web.Features.Passkeys.PasskeyRelyingParty>();
|
||||
await using (var scope = app.Services.CreateAsyncScope())
|
||||
{
|
||||
await scope.ServiceProvider
|
||||
|
|
@ -358,76 +359,6 @@ app.MapPost("/github/webhooks", async (
|
|||
};
|
||||
}).AllowAnonymous();
|
||||
|
||||
// The invite link is /invite#<token>: the token sits in the fragment, which no browser sends, so it never reaches a request line,
|
||||
// an access log, an error log or a Referer. The page reads it and posts it (the body is not logged); a live invite sets a short cookie
|
||||
// and goes to the sign-in chooser, anything else gets one page with no detail. The cookie is spent by ChatInviteService.RedeemCarriedAsync after any sign-in.
|
||||
app.MapGet("/invite", (HttpContext httpContext) =>
|
||||
{
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
// same-origin, not no-referrer: a no-referrer page posts its form with Origin: null, which RequestOriginGuard refuses. The fragment is never in a Referer,
|
||||
// and same-origin sends the Referer to this site only.
|
||||
httpContext.Response.Headers["Referrer-Policy"] = "same-origin";
|
||||
return Results.Content(
|
||||
"""
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Invite - Bifrost</title></head>
|
||||
<body><main><h1>Opening your invite</h1>
|
||||
<form id="f" method="post" action="/invite"><input type="hidden" name="token" id="t" /><noscript><p>This page needs JavaScript to open your invite.</p></noscript></form>
|
||||
<script>
|
||||
var h = location.hash.slice(1);
|
||||
if (h) { history.replaceState(null, "", "/invite"); document.getElementById("t").value = h; document.getElementById("f").submit(); }
|
||||
else { document.querySelector("h1").textContent = "This link is not valid"; }
|
||||
</script></main></body></html>
|
||||
""",
|
||||
"text/html; charset=utf-8");
|
||||
}).AllowAnonymous();
|
||||
|
||||
// The post is refused cross-site by RequestOriginGuard (no antiforgery cookie exists for a visitor, so a foreign page could otherwise plant
|
||||
// its own invite in this browser), and its body is capped to what a token needs before any of it is read.
|
||||
app.MapPost("/invite", async (HttpContext httpContext, Bifrost.Web.Features.Invites.ChatInviteService invites, IOptions<BifrostHostOptions> hostOptions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
httpContext.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
if (!RequestOriginGuard.Allows(httpContext.Request, hostOptions.Value))
|
||||
{
|
||||
return Results.Text("Cross-site invite links are refused.", statusCode: StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
const int MaxInviteBodyBytes = 1024;
|
||||
if (httpContext.Request.ContentLength > MaxInviteBodyBytes)
|
||||
{
|
||||
return Results.Text("Too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
|
||||
}
|
||||
|
||||
if (httpContext.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit)
|
||||
{
|
||||
limit.MaxRequestBodySize = MaxInviteBodyBytes; // a chunked body with no declared length is cut at the same cap
|
||||
}
|
||||
|
||||
string token;
|
||||
try
|
||||
{
|
||||
token = httpContext.Request.HasFormContentType ? (await httpContext.Request.ReadFormAsync(cancellationToken))["token"].ToString() : string.Empty;
|
||||
}
|
||||
catch (Microsoft.AspNetCore.Http.BadHttpRequestException)
|
||||
{
|
||||
return Results.Text("Too large.", statusCode: StatusCodes.Status413PayloadTooLarge);
|
||||
}
|
||||
|
||||
if (token.Length is 0 or > 200 || !await invites.IsLiveAsync(token, cancellationToken))
|
||||
{
|
||||
return Results.Content(
|
||||
"""
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Invite - Bifrost</title></head>
|
||||
<body><main><h1>This link is not valid</h1></main></body></html>
|
||||
""",
|
||||
"text/html; charset=utf-8",
|
||||
statusCode: StatusCodes.Status404NotFound);
|
||||
}
|
||||
|
||||
invites.Carry(httpContext, token);
|
||||
return Results.Redirect("/auth/sign-in?returnUrl=%2F");
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuthOptions> gitHubOptions) =>
|
||||
{
|
||||
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
|
||||
|
|
@ -445,20 +376,6 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
|
|||
return;
|
||||
}
|
||||
|
||||
// GitHub sign-in spends no invite: its account is made by the per-request sync, and redeeming there would hook every request.
|
||||
// A visitor carrying an invite is told which sign-ins redeem it, instead of being signed in and refused at chat.
|
||||
if (httpContext.Request.Cookies.ContainsKey(Bifrost.Web.Features.Invites.ChatInviteService.CookieName))
|
||||
{
|
||||
httpContext.Response.StatusCode = StatusCodes.Status409Conflict;
|
||||
httpContext.Response.ContentType = "text/html; charset=utf-8";
|
||||
await httpContext.Response.WriteAsync(
|
||||
$"""
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Sign in - Bifrost</title></head>
|
||||
<body><main><h1>Use Discord, Patreon or Google to accept this invite</h1><p>GitHub sign-in cannot accept a chat invite. <a href="/auth/sign-in?returnUrl={Uri.EscapeDataString(returnPath.Value)}">Choose another sign-in</a>.</p></main></body></html>
|
||||
""");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!gitHubOptions.Value.IsConfigured)
|
||||
{
|
||||
httpContext.Response.Redirect("/?auth=github-not-configured");
|
||||
|
|
@ -779,6 +696,23 @@ app.MapPost("/patronage/stripe/webhook", async (
|
|||
};
|
||||
}).AllowAnonymous();
|
||||
|
||||
var eveGovernance = app.MapGroup("/eve/governance")
|
||||
.RequireAuthorization(ActiveMemberRequirement.PolicyName);
|
||||
|
||||
eveGovernance.MapGet("/surface", async (
|
||||
ICurrentBifrostActorAccessor actorAccessor,
|
||||
MotionGovernanceService motionGovernanceService,
|
||||
MotionEveSurfaceService motionEveSurfaceService,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var actor = await actorAccessor.GetAsync(cancellationToken);
|
||||
var state = await motionGovernanceService.GetStateAsync(actor, cancellationToken);
|
||||
var surface = motionEveSurfaceService.BuildSurface(state);
|
||||
return Results.Text(
|
||||
JsonSerializer.Serialize(surface, appJsonSerializerOptions),
|
||||
"application/json");
|
||||
});
|
||||
|
||||
// Sealed-ballot intake. Typed JSON documents posted directly by the voter; no ballot content ever rides in a room message,
|
||||
// and no response before close carries another member's ballot.
|
||||
var sealedMotions = app.MapGroup("/api/sealed-motions")
|
||||
|
|
@ -884,55 +818,15 @@ app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
|||
app.MapPost("/auth/heimdall/complete", async (
|
||||
HttpContext httpContext,
|
||||
HeimdallAuthService heimdallAuthService,
|
||||
Bifrost.Web.Features.Invites.ChatInviteService chatInvites,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
ILogger<HeimdallAuthService> logger,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
// Every answer here sets or clears an attempt cookie or signs someone in: none may be stored.
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
|
||||
var attempt = form?["attempt"].ToString();
|
||||
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
|
||||
var linking = held is not null
|
||||
&& heimdallAuthService.PurposeOf(held.Value.Value, attempt) is not (null or HeimdallAttemptPurpose.SignIn);
|
||||
try
|
||||
{
|
||||
if (linking)
|
||||
{
|
||||
// A link step never signs anyone in: the session in this browser is the one being linked.
|
||||
var step = await heimdallAuthService.ContinueLinkAsync(
|
||||
hostOptions.Value.PublicBaseUrl,
|
||||
attempt,
|
||||
held!.Value.Name,
|
||||
held.Value.Value,
|
||||
form?["code"].ToString(),
|
||||
form?["pendingLinkId"].ToString(),
|
||||
httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId),
|
||||
cancellationToken);
|
||||
if (step.Next is not null)
|
||||
{
|
||||
httpContext.Response.Cookies.Append(step.CookieName, step.CookieValue!, HeimdallAttemptCookie.Options());
|
||||
return Results.Redirect(step.Next.ToString());
|
||||
}
|
||||
|
||||
if (step.EnrolTicket is not null)
|
||||
{
|
||||
// The ticket id goes only to the browser that completed the fresh sign-in; the server holds what it is bound to.
|
||||
httpContext.Response.Cookies.Append(BifrostCookies.PasskeyTicket, step.EnrolTicket, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Lax,
|
||||
Path = BifrostCookies.Path,
|
||||
MaxAge = Bifrost.Web.Features.Passkeys.PasskeyCeremonies.TicketLifetime
|
||||
});
|
||||
}
|
||||
|
||||
httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
|
||||
return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value));
|
||||
}
|
||||
|
||||
var signIn = await heimdallAuthService.CompleteAsync(
|
||||
hostOptions.Value.PublicBaseUrl,
|
||||
attempt,
|
||||
|
|
@ -940,11 +834,6 @@ app.MapPost("/auth/heimdall/complete", async (
|
|||
form?["code"].ToString(),
|
||||
cancellationToken);
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, signIn.Principal);
|
||||
if (Guid.TryParse(signIn.Principal.FindFirstValue(ClaimTypes.NameIdentifier), out var signedInAccountId))
|
||||
{
|
||||
await chatInvites.RedeemCarriedAsync(httpContext, signedInAccountId, cancellationToken);
|
||||
}
|
||||
|
||||
httpContext.Response.Cookies.Delete(held!.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
||||
return Results.LocalRedirect(signIn.ReturnPath.Value);
|
||||
}
|
||||
|
|
@ -956,9 +845,7 @@ app.MapPost("/auth/heimdall/complete", async (
|
|||
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
||||
}
|
||||
|
||||
return linking
|
||||
? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error))
|
||||
: Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||
return Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||
}
|
||||
}).AllowAnonymous();
|
||||
|
||||
|
|
@ -1030,10 +917,6 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
|
|||
httpContext.Response.ContentType = "text/html; charset=utf-8";
|
||||
var encodedReturnUrl = Uri.EscapeDataString(returnUrl);
|
||||
var escapedReturnUrl = System.Net.WebUtility.HtmlEncode(returnUrl);
|
||||
// GitHub sign-in spends no invite (only Heimdall completion and native registration call RedeemCarriedAsync), so a visitor carrying one is not offered it.
|
||||
var gitHubChoice = httpContext.Request.Cookies.ContainsKey(Bifrost.Web.Features.Invites.ChatInviteService.CookieName)
|
||||
? string.Empty
|
||||
: $"""<a href="/auth/sign-in?provider=github&returnUrl={encodedReturnUrl}">GitHub <span>OAuth</span></a>""";
|
||||
await httpContext.Response.WriteAsync($$"""
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
|
@ -1058,10 +941,10 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
|
|||
<h1>Create or use a Bifrost patron account</h1>
|
||||
<p>Choose a provider to attach this checkout to a Bifrost account. Patron accounts do not automatically grant active member access.</p>
|
||||
<div class="providers">
|
||||
{{gitHubChoice}}
|
||||
<a href="/auth/sign-in?provider=github&returnUrl={{encodedReturnUrl}}">GitHub <span>OAuth</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/discord?returnUrl={{encodedReturnUrl}}">Discord <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/patreon?returnUrl={{encodedReturnUrl}}">Patreon <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/google?returnUrl={{encodedReturnUrl}}">Google <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/twitch?returnUrl={{encodedReturnUrl}}">Twitch <span>Heimdall</span></a>
|
||||
</div>
|
||||
<p><small>After sign-in, Bifrost returns you to {{escapedReturnUrl}}.</small></p>
|
||||
</main>
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@
|
|||
"BaseUrl": "https://heimdall.gamecult.org",
|
||||
"AppSlug": "bifrost",
|
||||
"AppSecret": "",
|
||||
"AppSecretFile": "",
|
||||
"DiscordGuildId": "",
|
||||
"DiscordAllowedRoleIds": [],
|
||||
"PatreonTierTitle": "Inner Sanctum",
|
||||
|
|
|
|||
|
|
@ -8,19 +8,6 @@
|
|||
"resolved": "2.4.0",
|
||||
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
|
||||
},
|
||||
"Fido2": {
|
||||
"type": "Direct",
|
||||
"requested": "[4.3.3, )",
|
||||
"resolved": "4.3.3",
|
||||
"contentHash": "++G8ohXlhp9AH49FXIvYqziXUAEpuCtT+z5HBevX6+Pl6sYz9zfDHGTgvne6t3UEhM0hudesgMudyNG7RlpaEA==",
|
||||
"dependencies": {
|
||||
"Fido2.Models": "4.3.3",
|
||||
"Microsoft.Extensions.Http": "9.0.0",
|
||||
"Microsoft.IdentityModel.JsonWebTokens": "8.2.0",
|
||||
"NSec.Cryptography": "25.4.0",
|
||||
"System.Formats.Cbor": "9.0.24"
|
||||
}
|
||||
},
|
||||
"MessagePack": {
|
||||
"type": "Direct",
|
||||
"requested": "[3.1.12, )",
|
||||
|
|
@ -124,24 +111,11 @@
|
|||
"resolved": "8.0.5",
|
||||
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
|
||||
},
|
||||
"Fido2.Models": {
|
||||
"type": "Transitive",
|
||||
"resolved": "4.3.3",
|
||||
"contentHash": "G/Q8MYgptOwMrbWgDoGsy90u3J5GTdNAHub8aZRg/mQrUETzB5CqFzstGdTXE9UhL0qD6sRynOoPUnqCwKRnMw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Bcl.Memory": "9.0.14"
|
||||
}
|
||||
},
|
||||
"Humanizer.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.14.1",
|
||||
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
|
||||
},
|
||||
"libsodium": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.20.1",
|
||||
"contentHash": "pkiceEqJDQFHjbga3k/oPfTVX9g+GKJZ1VrkuiLhaymt9YNw1Dr7cX9hNuZuNaWcr9WD0moW55k4pMwzQ7JaZQ=="
|
||||
},
|
||||
"MessagePack.Annotations": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.1.12",
|
||||
|
|
@ -165,11 +139,6 @@
|
|||
"System.Formats.Asn1": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Bcl.Memory": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.14",
|
||||
"contentHash": "laQCcjTM2FnbyznkAu9hwBuQh3z2/OtJKwjGkJOUevylFpFXZIUVq/+MU2jM0HQm1n5wsjjwtLIDOiWJ6Nai3A=="
|
||||
},
|
||||
"Microsoft.CodeAnalysis.Analyzers": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.3.3",
|
||||
|
|
@ -257,43 +226,26 @@
|
|||
"Microsoft.Extensions.Primitives": "8.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "YIMO9T3JL8MeEXgVozKt2v79hquo/EFtnY0vgxmLnUvk1Rei/halI7kOWZL2RBeV9FMGzgM9LZA8CVaNwFMaNA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "lqvd7W3FGKUO1+ZoUEMaZ5XDJeWvjpy2/M/ptCGz3tXLD4HWVaSzjufsAsjemasBEg+2SxXVtYVvGt5r2nKDlg==",
|
||||
"resolved": "8.0.0",
|
||||
"contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Binder": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "RiScL99DcyngY9zJA2ROrri7Br8tn5N4hP4YNvGdTN/bvg1A3dwvDOxHnNZ3Im7x2SJ5i4LkX1uPiR/MfSFBLQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0"
|
||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "MCPrg7v3QgNMr0vX4vzRXvkNGgLg8vKWX0nKCWUxu2uPyMsaRgiRc1tHBnbTcfJMhMKj2slE/j2M9oGkd25DNw==",
|
||||
"resolved": "8.0.1",
|
||||
"contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0"
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "+6f2qv2a3dLwd5w6JanPIPs47CxRbnk+ZocMJUhv9NxP88VlOcJYZs9jY+MYSjxvady08bUZn6qgiNh7DadGgg=="
|
||||
"resolved": "8.0.2",
|
||||
"contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
|
||||
},
|
||||
"Microsoft.Extensions.DependencyModel": {
|
||||
"type": "Transitive",
|
||||
|
|
@ -304,83 +256,37 @@
|
|||
"System.Text.Json": "8.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "0CF9ZrNw5RAlRfbZuVIvzzhP8QeWqHiUmMBU/2H7Nmit8/vwP3/SbHeEctth7D4Gz2fBnEbokPc1NU8/j/1ZLw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "9.0.0",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "1K8P7XzuzX8W8pmXcZjcrqS6x5eSSdvhQohmcpgiQNY/HlDAlnrhR9dvlURfFz428A+RTCJpUyB+aKTA6AgVcQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Options": "9.0.0",
|
||||
"System.Diagnostics.DiagnosticSource": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Http": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "DqI4q54U4hH7bIAq9M5a/hl5Odr/KBAoaZ0dcT4OgutD8dook34CbkvAfAIzkMVjYXiL+E5ul9etwwqiX4PHGw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Diagnostics": "9.0.0",
|
||||
"Microsoft.Extensions.Logging": "9.0.0",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Options": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "crjWyORoug0kK7RSNJBTeSE6VX8IQgLf3nUpTB9m62bPXp/tzbnOsnbe8TXEG0AASNaKZddnpHKw7fET8E++Pg==",
|
||||
"resolved": "8.0.1",
|
||||
"contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection": "9.0.0",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Options": "9.0.0"
|
||||
"Microsoft.Extensions.DependencyInjection": "8.0.1",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.2",
|
||||
"Microsoft.Extensions.Options": "8.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "g0UfujELzlLbHoVG8kPKVBaW470Ewi+jnptGS9KUi6jcb+k2StujtK3m26DFSGGwQ/+bVgZfsWqNzlP6YOejvw==",
|
||||
"resolved": "8.0.2",
|
||||
"contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||
"System.Diagnostics.DiagnosticSource": "9.0.0"
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "y2146b3jrPI3Q0lokKXdKLpmXqakYbDIPDV6r3M8SqvSf45WwOTzkyfDpxnZXJsJQEpAsAqjUq5Pu8RCJMjubg==",
|
||||
"resolved": "8.0.2",
|
||||
"contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "Ob3FXsXkcSMQmGZi7qP07EQ39kZpSBlTcAZLbJLdI4FIf0Jug8biv2HTavWmnTirchctPlq9bl/26CXtQRguzA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Configuration.Binder": "9.0.0",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||
"Microsoft.Extensions.Options": "9.0.0",
|
||||
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
|
||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Primitives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "N3qEBzmLMYiASUlKxxFIISP4AiwuPTHF5uCh+2CWSwwzAJiIYx0kBJsS30cp1nvhSySFAVi30jecD307jV+8Kg=="
|
||||
"resolved": "8.0.0",
|
||||
"contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g=="
|
||||
},
|
||||
"Microsoft.IdentityModel.Abstractions": {
|
||||
"type": "Transitive",
|
||||
|
|
@ -434,14 +340,6 @@
|
|||
"System.CodeDom": "4.4.0"
|
||||
}
|
||||
},
|
||||
"NSec.Cryptography": {
|
||||
"type": "Transitive",
|
||||
"resolved": "25.4.0",
|
||||
"contentHash": "Z3wPpG0xefMLmhn9T+Ka/EzAmMQPT0THL/5E4lf9cXI/N9rbGH0G23ZFpRcPnD0ast2k7ieG6QSVNIjmfPCXBQ==",
|
||||
"dependencies": {
|
||||
"libsodium": "[1.0.20.1, 1.0.21)"
|
||||
}
|
||||
},
|
||||
"OpenIddict.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "7.7.1",
|
||||
|
|
@ -550,21 +448,11 @@
|
|||
"System.Composition.Runtime": "6.0.0"
|
||||
}
|
||||
},
|
||||
"System.Diagnostics.DiagnosticSource": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "ddppcFpnbohLWdYKr/ZeLZHmmI+DXFgZ3Snq+/E7SwcdW4UnvxmaugkwGywvGVWkHPGCSZjCP+MLzu23AL5SDw=="
|
||||
},
|
||||
"System.Formats.Asn1": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
|
||||
},
|
||||
"System.Formats.Cbor": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.24",
|
||||
"contentHash": "SEfEvHu6qXcXoDsDKagddLDf8A9iHIhHUD0hGemdmwlP206KLLCI5ksskOpeXMgNpQCs2diB0fOBKcnjySHFUQ=="
|
||||
},
|
||||
"System.IO.Pipelines": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.3",
|
||||
|
|
|
|||
|
|
@ -1,125 +0,0 @@
|
|||
// The Linked accounts page's passkey ceremonies (docs/passkeys.md). First-party, no dependency. It asks the server for
|
||||
// WebAuthn options, calls navigator.credentials, and posts back only base64url strings in a same-origin form. Nothing it
|
||||
// reads from the options is shown or evaluated; the server checks the origin, the challenge and the signature.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var status = document.getElementById("passkey-status");
|
||||
|
||||
function say(text) {
|
||||
if (status) {
|
||||
status.textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
function toBytes(value) {
|
||||
var padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
||||
while (padded.length % 4) {
|
||||
padded += "=";
|
||||
}
|
||||
var raw = atob(padded);
|
||||
var bytes = new Uint8Array(raw.length);
|
||||
for (var i = 0; i < raw.length; i++) {
|
||||
bytes[i] = raw.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
function toText(buffer) {
|
||||
var bytes = new Uint8Array(buffer);
|
||||
var raw = "";
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
raw += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function token(form) {
|
||||
var field = form.querySelector("input[name=__RequestVerificationToken]");
|
||||
return field ? field.value : "";
|
||||
}
|
||||
|
||||
// Posts to a handler of this page with the form's antiforgery token and returns the parsed JSON, or throws.
|
||||
function options(handler, form, fields) {
|
||||
return fetch(location.pathname + "?handler=" + handler, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "RequestVerificationToken": token(form), "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(fields)
|
||||
}).then(function (response) {
|
||||
return response.json().then(function (body) {
|
||||
if (!response.ok) {
|
||||
throw new Error(body && body.error ? body.error : "error");
|
||||
}
|
||||
return body;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function descriptors(list) {
|
||||
return (list || []).map(function (item) {
|
||||
var copy = { type: item.type, id: toBytes(item.id) };
|
||||
if (item.transports) {
|
||||
copy.transports = item.transports;
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
function set(form, name, value) {
|
||||
form.elements[name].value = value;
|
||||
}
|
||||
|
||||
function failed(error) {
|
||||
var code = error && error.message ? error.message : "error";
|
||||
location.assign(location.pathname + "?result=" + (/^[a-z_]+$/.test(code) && code !== "error" ? encodeURIComponent(code) : "passkey_failed"));
|
||||
}
|
||||
|
||||
document.querySelectorAll("form[data-passkey-enrol]").forEach(function (form) {
|
||||
form.addEventListener("submit", function (event) {
|
||||
if (form.dataset.ready === "1") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
say("Waiting for your device...");
|
||||
options("PasskeyEnrolOptions", form, {}).then(function (created) {
|
||||
created.challenge = toBytes(created.challenge);
|
||||
created.user.id = toBytes(created.user.id);
|
||||
created.excludeCredentials = descriptors(created.excludeCredentials);
|
||||
return navigator.credentials.create({ publicKey: created });
|
||||
}).then(function (credential) {
|
||||
set(form, "id", credential.id);
|
||||
set(form, "rawId", toText(credential.rawId));
|
||||
set(form, "attestationObject", toText(credential.response.attestationObject));
|
||||
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||
set(form, "transports", credential.response.getTransports ? credential.response.getTransports().join(",") : "");
|
||||
form.dataset.ready = "1";
|
||||
form.submit();
|
||||
}).catch(failed);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("form[data-passkey-unlink]").forEach(function (form) {
|
||||
form.addEventListener("submit", function (event) {
|
||||
if (form.dataset.ready === "1") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
say("Waiting for your device...");
|
||||
options("PasskeyChallenge", form, { identityId: form.elements.identityId.value }).then(function (requested) {
|
||||
requested.challenge = toBytes(requested.challenge);
|
||||
requested.allowCredentials = descriptors(requested.allowCredentials);
|
||||
return navigator.credentials.get({ publicKey: requested });
|
||||
}).then(function (credential) {
|
||||
set(form, "id", credential.id);
|
||||
set(form, "rawId", toText(credential.rawId));
|
||||
set(form, "authenticatorData", toText(credential.response.authenticatorData));
|
||||
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||
set(form, "signature", toText(credential.response.signature));
|
||||
set(form, "userHandle", credential.response.userHandle ? toText(credential.response.userHandle) : "");
|
||||
form.dataset.ready = "1";
|
||||
form.submit();
|
||||
}).catch(failed);
|
||||
});
|
||||
});
|
||||
})();
|
||||
22
src/Bifrost.Web/wwwroot/lib/bootstrap/LICENSE
Normal file
22
src/Bifrost.Web/wwwroot/lib/bootstrap/LICENSE
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011-2021 Twitter, Inc.
|
||||
Copyright (c) 2011-2021 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
4085
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css
vendored
Normal file
4085
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
4084
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.css
vendored
Normal file
4084
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-grid.rtl.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
597
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css
vendored
Normal file
597
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css
vendored
Normal file
|
|
@ -0,0 +1,597 @@
|
|||
/*!
|
||||
* Bootstrap Reboot v5.3.3 (https://getbootstrap.com/)
|
||||
* Copyright 2011-2024 The Bootstrap Authors
|
||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
|
||||
*/
|
||||
:root,
|
||||
[data-bs-theme=light] {
|
||||
--bs-blue: #0d6efd;
|
||||
--bs-indigo: #6610f2;
|
||||
--bs-purple: #6f42c1;
|
||||
--bs-pink: #d63384;
|
||||
--bs-red: #dc3545;
|
||||
--bs-orange: #fd7e14;
|
||||
--bs-yellow: #ffc107;
|
||||
--bs-green: #198754;
|
||||
--bs-teal: #20c997;
|
||||
--bs-cyan: #0dcaf0;
|
||||
--bs-black: #000;
|
||||
--bs-white: #fff;
|
||||
--bs-gray: #6c757d;
|
||||
--bs-gray-dark: #343a40;
|
||||
--bs-gray-100: #f8f9fa;
|
||||
--bs-gray-200: #e9ecef;
|
||||
--bs-gray-300: #dee2e6;
|
||||
--bs-gray-400: #ced4da;
|
||||
--bs-gray-500: #adb5bd;
|
||||
--bs-gray-600: #6c757d;
|
||||
--bs-gray-700: #495057;
|
||||
--bs-gray-800: #343a40;
|
||||
--bs-gray-900: #212529;
|
||||
--bs-primary: #0d6efd;
|
||||
--bs-secondary: #6c757d;
|
||||
--bs-success: #198754;
|
||||
--bs-info: #0dcaf0;
|
||||
--bs-warning: #ffc107;
|
||||
--bs-danger: #dc3545;
|
||||
--bs-light: #f8f9fa;
|
||||
--bs-dark: #212529;
|
||||
--bs-primary-rgb: 13, 110, 253;
|
||||
--bs-secondary-rgb: 108, 117, 125;
|
||||
--bs-success-rgb: 25, 135, 84;
|
||||
--bs-info-rgb: 13, 202, 240;
|
||||
--bs-warning-rgb: 255, 193, 7;
|
||||
--bs-danger-rgb: 220, 53, 69;
|
||||
--bs-light-rgb: 248, 249, 250;
|
||||
--bs-dark-rgb: 33, 37, 41;
|
||||
--bs-primary-text-emphasis: #052c65;
|
||||
--bs-secondary-text-emphasis: #2b2f32;
|
||||
--bs-success-text-emphasis: #0a3622;
|
||||
--bs-info-text-emphasis: #055160;
|
||||
--bs-warning-text-emphasis: #664d03;
|
||||
--bs-danger-text-emphasis: #58151c;
|
||||
--bs-light-text-emphasis: #495057;
|
||||
--bs-dark-text-emphasis: #495057;
|
||||
--bs-primary-bg-subtle: #cfe2ff;
|
||||
--bs-secondary-bg-subtle: #e2e3e5;
|
||||
--bs-success-bg-subtle: #d1e7dd;
|
||||
--bs-info-bg-subtle: #cff4fc;
|
||||
--bs-warning-bg-subtle: #fff3cd;
|
||||
--bs-danger-bg-subtle: #f8d7da;
|
||||
--bs-light-bg-subtle: #fcfcfd;
|
||||
--bs-dark-bg-subtle: #ced4da;
|
||||
--bs-primary-border-subtle: #9ec5fe;
|
||||
--bs-secondary-border-subtle: #c4c8cb;
|
||||
--bs-success-border-subtle: #a3cfbb;
|
||||
--bs-info-border-subtle: #9eeaf9;
|
||||
--bs-warning-border-subtle: #ffe69c;
|
||||
--bs-danger-border-subtle: #f1aeb5;
|
||||
--bs-light-border-subtle: #e9ecef;
|
||||
--bs-dark-border-subtle: #adb5bd;
|
||||
--bs-white-rgb: 255, 255, 255;
|
||||
--bs-black-rgb: 0, 0, 0;
|
||||
--bs-font-sans-serif: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
--bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
--bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));
|
||||
--bs-body-font-family: var(--bs-font-sans-serif);
|
||||
--bs-body-font-size: 1rem;
|
||||
--bs-body-font-weight: 400;
|
||||
--bs-body-line-height: 1.5;
|
||||
--bs-body-color: #212529;
|
||||
--bs-body-color-rgb: 33, 37, 41;
|
||||
--bs-body-bg: #fff;
|
||||
--bs-body-bg-rgb: 255, 255, 255;
|
||||
--bs-emphasis-color: #000;
|
||||
--bs-emphasis-color-rgb: 0, 0, 0;
|
||||
--bs-secondary-color: rgba(33, 37, 41, 0.75);
|
||||
--bs-secondary-color-rgb: 33, 37, 41;
|
||||
--bs-secondary-bg: #e9ecef;
|
||||
--bs-secondary-bg-rgb: 233, 236, 239;
|
||||
--bs-tertiary-color: rgba(33, 37, 41, 0.5);
|
||||
--bs-tertiary-color-rgb: 33, 37, 41;
|
||||
--bs-tertiary-bg: #f8f9fa;
|
||||
--bs-tertiary-bg-rgb: 248, 249, 250;
|
||||
--bs-heading-color: inherit;
|
||||
--bs-link-color: #0d6efd;
|
||||
--bs-link-color-rgb: 13, 110, 253;
|
||||
--bs-link-decoration: underline;
|
||||
--bs-link-hover-color: #0a58ca;
|
||||
--bs-link-hover-color-rgb: 10, 88, 202;
|
||||
--bs-code-color: #d63384;
|
||||
--bs-highlight-color: #212529;
|
||||
--bs-highlight-bg: #fff3cd;
|
||||
--bs-border-width: 1px;
|
||||
--bs-border-style: solid;
|
||||
--bs-border-color: #dee2e6;
|
||||
--bs-border-color-translucent: rgba(0, 0, 0, 0.175);
|
||||
--bs-border-radius: 0.375rem;
|
||||
--bs-border-radius-sm: 0.25rem;
|
||||
--bs-border-radius-lg: 0.5rem;
|
||||
--bs-border-radius-xl: 1rem;
|
||||
--bs-border-radius-xxl: 2rem;
|
||||
--bs-border-radius-2xl: var(--bs-border-radius-xxl);
|
||||
--bs-border-radius-pill: 50rem;
|
||||
--bs-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
|
||||
--bs-box-shadow-sm: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
|
||||
--bs-box-shadow-lg: 0 1rem 3rem rgba(0, 0, 0, 0.175);
|
||||
--bs-box-shadow-inset: inset 0 1px 2px rgba(0, 0, 0, 0.075);
|
||||
--bs-focus-ring-width: 0.25rem;
|
||||
--bs-focus-ring-opacity: 0.25;
|
||||
--bs-focus-ring-color: rgba(13, 110, 253, 0.25);
|
||||
--bs-form-valid-color: #198754;
|
||||
--bs-form-valid-border-color: #198754;
|
||||
--bs-form-invalid-color: #dc3545;
|
||||
--bs-form-invalid-border-color: #dc3545;
|
||||
}
|
||||
|
||||
[data-bs-theme=dark] {
|
||||
color-scheme: dark;
|
||||
--bs-body-color: #dee2e6;
|
||||
--bs-body-color-rgb: 222, 226, 230;
|
||||
--bs-body-bg: #212529;
|
||||
--bs-body-bg-rgb: 33, 37, 41;
|
||||
--bs-emphasis-color: #fff;
|
||||
--bs-emphasis-color-rgb: 255, 255, 255;
|
||||
--bs-secondary-color: rgba(222, 226, 230, 0.75);
|
||||
--bs-secondary-color-rgb: 222, 226, 230;
|
||||
--bs-secondary-bg: #343a40;
|
||||
--bs-secondary-bg-rgb: 52, 58, 64;
|
||||
--bs-tertiary-color: rgba(222, 226, 230, 0.5);
|
||||
--bs-tertiary-color-rgb: 222, 226, 230;
|
||||
--bs-tertiary-bg: #2b3035;
|
||||
--bs-tertiary-bg-rgb: 43, 48, 53;
|
||||
--bs-primary-text-emphasis: #6ea8fe;
|
||||
--bs-secondary-text-emphasis: #a7acb1;
|
||||
--bs-success-text-emphasis: #75b798;
|
||||
--bs-info-text-emphasis: #6edff6;
|
||||
--bs-warning-text-emphasis: #ffda6a;
|
||||
--bs-danger-text-emphasis: #ea868f;
|
||||
--bs-light-text-emphasis: #f8f9fa;
|
||||
--bs-dark-text-emphasis: #dee2e6;
|
||||
--bs-primary-bg-subtle: #031633;
|
||||
--bs-secondary-bg-subtle: #161719;
|
||||
--bs-success-bg-subtle: #051b11;
|
||||
--bs-info-bg-subtle: #032830;
|
||||
--bs-warning-bg-subtle: #332701;
|
||||
--bs-danger-bg-subtle: #2c0b0e;
|
||||
--bs-light-bg-subtle: #343a40;
|
||||
--bs-dark-bg-subtle: #1a1d20;
|
||||
--bs-primary-border-subtle: #084298;
|
||||
--bs-secondary-border-subtle: #41464b;
|
||||
--bs-success-border-subtle: #0f5132;
|
||||
--bs-info-border-subtle: #087990;
|
||||
--bs-warning-border-subtle: #997404;
|
||||
--bs-danger-border-subtle: #842029;
|
||||
--bs-light-border-subtle: #495057;
|
||||
--bs-dark-border-subtle: #343a40;
|
||||
--bs-heading-color: inherit;
|
||||
--bs-link-color: #6ea8fe;
|
||||
--bs-link-hover-color: #8bb9fe;
|
||||
--bs-link-color-rgb: 110, 168, 254;
|
||||
--bs-link-hover-color-rgb: 139, 185, 254;
|
||||
--bs-code-color: #e685b5;
|
||||
--bs-highlight-color: #dee2e6;
|
||||
--bs-highlight-bg: #664d03;
|
||||
--bs-border-color: #495057;
|
||||
--bs-border-color-translucent: rgba(255, 255, 255, 0.15);
|
||||
--bs-form-valid-color: #75b798;
|
||||
--bs-form-valid-border-color: #75b798;
|
||||
--bs-form-invalid-color: #ea868f;
|
||||
--bs-form-invalid-border-color: #ea868f;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
:root {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--bs-body-font-family);
|
||||
font-size: var(--bs-body-font-size);
|
||||
font-weight: var(--bs-body-font-weight);
|
||||
line-height: var(--bs-body-line-height);
|
||||
color: var(--bs-body-color);
|
||||
text-align: var(--bs-body-text-align);
|
||||
background-color: var(--bs-body-bg);
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 1rem 0;
|
||||
color: inherit;
|
||||
border: 0;
|
||||
border-top: var(--bs-border-width) solid;
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
h6, h5, h4, h3, h2, h1 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
color: var(--bs-heading-color);
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: calc(1.375rem + 1.5vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h1 {
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: calc(1.325rem + 0.9vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h2 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: calc(1.3rem + 0.6vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h3 {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: calc(1.275rem + 0.3vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h4 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
h5 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
h6 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
abbr[title] {
|
||||
-webkit-text-decoration: underline dotted;
|
||||
text-decoration: underline dotted;
|
||||
cursor: help;
|
||||
-webkit-text-decoration-skip-ink: none;
|
||||
text-decoration-skip-ink: none;
|
||||
}
|
||||
|
||||
address {
|
||||
margin-bottom: 1rem;
|
||||
font-style: normal;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul {
|
||||
padding-left: 2rem;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul,
|
||||
dl {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
ol ol,
|
||||
ul ul,
|
||||
ol ul,
|
||||
ul ol {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
dt {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin-bottom: 0.5rem;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
b,
|
||||
strong {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
mark {
|
||||
padding: 0.1875em;
|
||||
color: var(--bs-highlight-color);
|
||||
background-color: var(--bs-highlight-bg);
|
||||
}
|
||||
|
||||
sub,
|
||||
sup {
|
||||
position: relative;
|
||||
font-size: 0.75em;
|
||||
line-height: 0;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
sub {
|
||||
bottom: -0.25em;
|
||||
}
|
||||
|
||||
sup {
|
||||
top: -0.5em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: rgba(var(--bs-link-color-rgb), var(--bs-link-opacity, 1));
|
||||
text-decoration: underline;
|
||||
}
|
||||
a:hover {
|
||||
--bs-link-color-rgb: var(--bs-link-hover-color-rgb);
|
||||
}
|
||||
|
||||
a:not([href]):not([class]), a:not([href]):not([class]):hover {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
kbd,
|
||||
samp {
|
||||
font-family: var(--bs-font-monospace);
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
pre {
|
||||
display: block;
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
overflow: auto;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
pre code {
|
||||
font-size: inherit;
|
||||
color: inherit;
|
||||
word-break: normal;
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: 0.875em;
|
||||
color: var(--bs-code-color);
|
||||
word-wrap: break-word;
|
||||
}
|
||||
a > code {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
kbd {
|
||||
padding: 0.1875rem 0.375rem;
|
||||
font-size: 0.875em;
|
||||
color: var(--bs-body-bg);
|
||||
background-color: var(--bs-body-color);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
kbd kbd {
|
||||
padding: 0;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
img,
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
table {
|
||||
caption-side: bottom;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
caption {
|
||||
padding-top: 0.5rem;
|
||||
padding-bottom: 0.5rem;
|
||||
color: var(--bs-secondary-color);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: inherit;
|
||||
text-align: -webkit-match-parent;
|
||||
}
|
||||
|
||||
thead,
|
||||
tbody,
|
||||
tfoot,
|
||||
tr,
|
||||
td,
|
||||
th {
|
||||
border-color: inherit;
|
||||
border-style: solid;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
label {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
button:focus:not(:focus-visible) {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
input,
|
||||
button,
|
||||
select,
|
||||
optgroup,
|
||||
textarea {
|
||||
margin: 0;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
select {
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
[role=button] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
select {
|
||||
word-wrap: normal;
|
||||
}
|
||||
select:disabled {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
[list]:not([type=date]):not([type=datetime-local]):not([type=month]):not([type=week]):not([type=time])::-webkit-calendar-picker-indicator {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
button,
|
||||
[type=button],
|
||||
[type=reset],
|
||||
[type=submit] {
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
button:not(:disabled),
|
||||
[type=button]:not(:disabled),
|
||||
[type=reset]:not(:disabled),
|
||||
[type=submit]:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
::-moz-focus-inner {
|
||||
padding: 0;
|
||||
border-style: none;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
legend {
|
||||
float: left;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: calc(1.275rem + 0.3vw);
|
||||
line-height: inherit;
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
legend {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
legend + * {
|
||||
clear: left;
|
||||
}
|
||||
|
||||
::-webkit-datetime-edit-fields-wrapper,
|
||||
::-webkit-datetime-edit-text,
|
||||
::-webkit-datetime-edit-minute,
|
||||
::-webkit-datetime-edit-hour-field,
|
||||
::-webkit-datetime-edit-day-field,
|
||||
::-webkit-datetime-edit-month-field,
|
||||
::-webkit-datetime-edit-year-field {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
::-webkit-inner-spin-button {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
[type=search] {
|
||||
-webkit-appearance: textfield;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
/* rtl:raw:
|
||||
[type="tel"],
|
||||
[type="url"],
|
||||
[type="email"],
|
||||
[type="number"] {
|
||||
direction: ltr;
|
||||
}
|
||||
*/
|
||||
::-webkit-search-decoration {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
::-webkit-color-swatch-wrapper {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
::-webkit-file-upload-button {
|
||||
font: inherit;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
::file-selector-button {
|
||||
font: inherit;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
output {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
iframe {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
summary {
|
||||
display: list-item;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
progress {
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/*# sourceMappingURL=bootstrap-reboot.css.map */
|
||||
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
594
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.css
vendored
Normal file
594
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.css
vendored
Normal file
|
|
@ -0,0 +1,594 @@
|
|||
/*!
|
||||
* Bootstrap Reboot v5.3.3 (https://getbootstrap.com/)
|
||||
* Copyright 2011-2024 The Bootstrap Authors
|
||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
|
||||
*/
|
||||
:root,
|
||||
[data-bs-theme=light] {
|
||||
--bs-blue: #0d6efd;
|
||||
--bs-indigo: #6610f2;
|
||||
--bs-purple: #6f42c1;
|
||||
--bs-pink: #d63384;
|
||||
--bs-red: #dc3545;
|
||||
--bs-orange: #fd7e14;
|
||||
--bs-yellow: #ffc107;
|
||||
--bs-green: #198754;
|
||||
--bs-teal: #20c997;
|
||||
--bs-cyan: #0dcaf0;
|
||||
--bs-black: #000;
|
||||
--bs-white: #fff;
|
||||
--bs-gray: #6c757d;
|
||||
--bs-gray-dark: #343a40;
|
||||
--bs-gray-100: #f8f9fa;
|
||||
--bs-gray-200: #e9ecef;
|
||||
--bs-gray-300: #dee2e6;
|
||||
--bs-gray-400: #ced4da;
|
||||
--bs-gray-500: #adb5bd;
|
||||
--bs-gray-600: #6c757d;
|
||||
--bs-gray-700: #495057;
|
||||
--bs-gray-800: #343a40;
|
||||
--bs-gray-900: #212529;
|
||||
--bs-primary: #0d6efd;
|
||||
--bs-secondary: #6c757d;
|
||||
--bs-success: #198754;
|
||||
--bs-info: #0dcaf0;
|
||||
--bs-warning: #ffc107;
|
||||
--bs-danger: #dc3545;
|
||||
--bs-light: #f8f9fa;
|
||||
--bs-dark: #212529;
|
||||
--bs-primary-rgb: 13, 110, 253;
|
||||
--bs-secondary-rgb: 108, 117, 125;
|
||||
--bs-success-rgb: 25, 135, 84;
|
||||
--bs-info-rgb: 13, 202, 240;
|
||||
--bs-warning-rgb: 255, 193, 7;
|
||||
--bs-danger-rgb: 220, 53, 69;
|
||||
--bs-light-rgb: 248, 249, 250;
|
||||
--bs-dark-rgb: 33, 37, 41;
|
||||
--bs-primary-text-emphasis: #052c65;
|
||||
--bs-secondary-text-emphasis: #2b2f32;
|
||||
--bs-success-text-emphasis: #0a3622;
|
||||
--bs-info-text-emphasis: #055160;
|
||||
--bs-warning-text-emphasis: #664d03;
|
||||
--bs-danger-text-emphasis: #58151c;
|
||||
--bs-light-text-emphasis: #495057;
|
||||
--bs-dark-text-emphasis: #495057;
|
||||
--bs-primary-bg-subtle: #cfe2ff;
|
||||
--bs-secondary-bg-subtle: #e2e3e5;
|
||||
--bs-success-bg-subtle: #d1e7dd;
|
||||
--bs-info-bg-subtle: #cff4fc;
|
||||
--bs-warning-bg-subtle: #fff3cd;
|
||||
--bs-danger-bg-subtle: #f8d7da;
|
||||
--bs-light-bg-subtle: #fcfcfd;
|
||||
--bs-dark-bg-subtle: #ced4da;
|
||||
--bs-primary-border-subtle: #9ec5fe;
|
||||
--bs-secondary-border-subtle: #c4c8cb;
|
||||
--bs-success-border-subtle: #a3cfbb;
|
||||
--bs-info-border-subtle: #9eeaf9;
|
||||
--bs-warning-border-subtle: #ffe69c;
|
||||
--bs-danger-border-subtle: #f1aeb5;
|
||||
--bs-light-border-subtle: #e9ecef;
|
||||
--bs-dark-border-subtle: #adb5bd;
|
||||
--bs-white-rgb: 255, 255, 255;
|
||||
--bs-black-rgb: 0, 0, 0;
|
||||
--bs-font-sans-serif: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
--bs-font-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
--bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));
|
||||
--bs-body-font-family: var(--bs-font-sans-serif);
|
||||
--bs-body-font-size: 1rem;
|
||||
--bs-body-font-weight: 400;
|
||||
--bs-body-line-height: 1.5;
|
||||
--bs-body-color: #212529;
|
||||
--bs-body-color-rgb: 33, 37, 41;
|
||||
--bs-body-bg: #fff;
|
||||
--bs-body-bg-rgb: 255, 255, 255;
|
||||
--bs-emphasis-color: #000;
|
||||
--bs-emphasis-color-rgb: 0, 0, 0;
|
||||
--bs-secondary-color: rgba(33, 37, 41, 0.75);
|
||||
--bs-secondary-color-rgb: 33, 37, 41;
|
||||
--bs-secondary-bg: #e9ecef;
|
||||
--bs-secondary-bg-rgb: 233, 236, 239;
|
||||
--bs-tertiary-color: rgba(33, 37, 41, 0.5);
|
||||
--bs-tertiary-color-rgb: 33, 37, 41;
|
||||
--bs-tertiary-bg: #f8f9fa;
|
||||
--bs-tertiary-bg-rgb: 248, 249, 250;
|
||||
--bs-heading-color: inherit;
|
||||
--bs-link-color: #0d6efd;
|
||||
--bs-link-color-rgb: 13, 110, 253;
|
||||
--bs-link-decoration: underline;
|
||||
--bs-link-hover-color: #0a58ca;
|
||||
--bs-link-hover-color-rgb: 10, 88, 202;
|
||||
--bs-code-color: #d63384;
|
||||
--bs-highlight-color: #212529;
|
||||
--bs-highlight-bg: #fff3cd;
|
||||
--bs-border-width: 1px;
|
||||
--bs-border-style: solid;
|
||||
--bs-border-color: #dee2e6;
|
||||
--bs-border-color-translucent: rgba(0, 0, 0, 0.175);
|
||||
--bs-border-radius: 0.375rem;
|
||||
--bs-border-radius-sm: 0.25rem;
|
||||
--bs-border-radius-lg: 0.5rem;
|
||||
--bs-border-radius-xl: 1rem;
|
||||
--bs-border-radius-xxl: 2rem;
|
||||
--bs-border-radius-2xl: var(--bs-border-radius-xxl);
|
||||
--bs-border-radius-pill: 50rem;
|
||||
--bs-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
|
||||
--bs-box-shadow-sm: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
|
||||
--bs-box-shadow-lg: 0 1rem 3rem rgba(0, 0, 0, 0.175);
|
||||
--bs-box-shadow-inset: inset 0 1px 2px rgba(0, 0, 0, 0.075);
|
||||
--bs-focus-ring-width: 0.25rem;
|
||||
--bs-focus-ring-opacity: 0.25;
|
||||
--bs-focus-ring-color: rgba(13, 110, 253, 0.25);
|
||||
--bs-form-valid-color: #198754;
|
||||
--bs-form-valid-border-color: #198754;
|
||||
--bs-form-invalid-color: #dc3545;
|
||||
--bs-form-invalid-border-color: #dc3545;
|
||||
}
|
||||
|
||||
[data-bs-theme=dark] {
|
||||
color-scheme: dark;
|
||||
--bs-body-color: #dee2e6;
|
||||
--bs-body-color-rgb: 222, 226, 230;
|
||||
--bs-body-bg: #212529;
|
||||
--bs-body-bg-rgb: 33, 37, 41;
|
||||
--bs-emphasis-color: #fff;
|
||||
--bs-emphasis-color-rgb: 255, 255, 255;
|
||||
--bs-secondary-color: rgba(222, 226, 230, 0.75);
|
||||
--bs-secondary-color-rgb: 222, 226, 230;
|
||||
--bs-secondary-bg: #343a40;
|
||||
--bs-secondary-bg-rgb: 52, 58, 64;
|
||||
--bs-tertiary-color: rgba(222, 226, 230, 0.5);
|
||||
--bs-tertiary-color-rgb: 222, 226, 230;
|
||||
--bs-tertiary-bg: #2b3035;
|
||||
--bs-tertiary-bg-rgb: 43, 48, 53;
|
||||
--bs-primary-text-emphasis: #6ea8fe;
|
||||
--bs-secondary-text-emphasis: #a7acb1;
|
||||
--bs-success-text-emphasis: #75b798;
|
||||
--bs-info-text-emphasis: #6edff6;
|
||||
--bs-warning-text-emphasis: #ffda6a;
|
||||
--bs-danger-text-emphasis: #ea868f;
|
||||
--bs-light-text-emphasis: #f8f9fa;
|
||||
--bs-dark-text-emphasis: #dee2e6;
|
||||
--bs-primary-bg-subtle: #031633;
|
||||
--bs-secondary-bg-subtle: #161719;
|
||||
--bs-success-bg-subtle: #051b11;
|
||||
--bs-info-bg-subtle: #032830;
|
||||
--bs-warning-bg-subtle: #332701;
|
||||
--bs-danger-bg-subtle: #2c0b0e;
|
||||
--bs-light-bg-subtle: #343a40;
|
||||
--bs-dark-bg-subtle: #1a1d20;
|
||||
--bs-primary-border-subtle: #084298;
|
||||
--bs-secondary-border-subtle: #41464b;
|
||||
--bs-success-border-subtle: #0f5132;
|
||||
--bs-info-border-subtle: #087990;
|
||||
--bs-warning-border-subtle: #997404;
|
||||
--bs-danger-border-subtle: #842029;
|
||||
--bs-light-border-subtle: #495057;
|
||||
--bs-dark-border-subtle: #343a40;
|
||||
--bs-heading-color: inherit;
|
||||
--bs-link-color: #6ea8fe;
|
||||
--bs-link-hover-color: #8bb9fe;
|
||||
--bs-link-color-rgb: 110, 168, 254;
|
||||
--bs-link-hover-color-rgb: 139, 185, 254;
|
||||
--bs-code-color: #e685b5;
|
||||
--bs-highlight-color: #dee2e6;
|
||||
--bs-highlight-bg: #664d03;
|
||||
--bs-border-color: #495057;
|
||||
--bs-border-color-translucent: rgba(255, 255, 255, 0.15);
|
||||
--bs-form-valid-color: #75b798;
|
||||
--bs-form-valid-border-color: #75b798;
|
||||
--bs-form-invalid-color: #ea868f;
|
||||
--bs-form-invalid-border-color: #ea868f;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
:root {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--bs-body-font-family);
|
||||
font-size: var(--bs-body-font-size);
|
||||
font-weight: var(--bs-body-font-weight);
|
||||
line-height: var(--bs-body-line-height);
|
||||
color: var(--bs-body-color);
|
||||
text-align: var(--bs-body-text-align);
|
||||
background-color: var(--bs-body-bg);
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 1rem 0;
|
||||
color: inherit;
|
||||
border: 0;
|
||||
border-top: var(--bs-border-width) solid;
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
h6, h5, h4, h3, h2, h1 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
color: var(--bs-heading-color);
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: calc(1.375rem + 1.5vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h1 {
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: calc(1.325rem + 0.9vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h2 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: calc(1.3rem + 0.6vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h3 {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: calc(1.275rem + 0.3vw);
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
h4 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
h5 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
h6 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
abbr[title] {
|
||||
-webkit-text-decoration: underline dotted;
|
||||
text-decoration: underline dotted;
|
||||
cursor: help;
|
||||
-webkit-text-decoration-skip-ink: none;
|
||||
text-decoration-skip-ink: none;
|
||||
}
|
||||
|
||||
address {
|
||||
margin-bottom: 1rem;
|
||||
font-style: normal;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul {
|
||||
padding-right: 2rem;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul,
|
||||
dl {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
ol ol,
|
||||
ul ul,
|
||||
ol ul,
|
||||
ul ol {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
dt {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin-bottom: 0.5rem;
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
b,
|
||||
strong {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
mark {
|
||||
padding: 0.1875em;
|
||||
color: var(--bs-highlight-color);
|
||||
background-color: var(--bs-highlight-bg);
|
||||
}
|
||||
|
||||
sub,
|
||||
sup {
|
||||
position: relative;
|
||||
font-size: 0.75em;
|
||||
line-height: 0;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
sub {
|
||||
bottom: -0.25em;
|
||||
}
|
||||
|
||||
sup {
|
||||
top: -0.5em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: rgba(var(--bs-link-color-rgb), var(--bs-link-opacity, 1));
|
||||
text-decoration: underline;
|
||||
}
|
||||
a:hover {
|
||||
--bs-link-color-rgb: var(--bs-link-hover-color-rgb);
|
||||
}
|
||||
|
||||
a:not([href]):not([class]), a:not([href]):not([class]):hover {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
kbd,
|
||||
samp {
|
||||
font-family: var(--bs-font-monospace);
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
pre {
|
||||
display: block;
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
overflow: auto;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
pre code {
|
||||
font-size: inherit;
|
||||
color: inherit;
|
||||
word-break: normal;
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: 0.875em;
|
||||
color: var(--bs-code-color);
|
||||
word-wrap: break-word;
|
||||
}
|
||||
a > code {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
kbd {
|
||||
padding: 0.1875rem 0.375rem;
|
||||
font-size: 0.875em;
|
||||
color: var(--bs-body-bg);
|
||||
background-color: var(--bs-body-color);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
kbd kbd {
|
||||
padding: 0;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
img,
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
table {
|
||||
caption-side: bottom;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
caption {
|
||||
padding-top: 0.5rem;
|
||||
padding-bottom: 0.5rem;
|
||||
color: var(--bs-secondary-color);
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: inherit;
|
||||
text-align: -webkit-match-parent;
|
||||
}
|
||||
|
||||
thead,
|
||||
tbody,
|
||||
tfoot,
|
||||
tr,
|
||||
td,
|
||||
th {
|
||||
border-color: inherit;
|
||||
border-style: solid;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
label {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
button:focus:not(:focus-visible) {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
input,
|
||||
button,
|
||||
select,
|
||||
optgroup,
|
||||
textarea {
|
||||
margin: 0;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
select {
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
[role=button] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
select {
|
||||
word-wrap: normal;
|
||||
}
|
||||
select:disabled {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
[list]:not([type=date]):not([type=datetime-local]):not([type=month]):not([type=week]):not([type=time])::-webkit-calendar-picker-indicator {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
button,
|
||||
[type=button],
|
||||
[type=reset],
|
||||
[type=submit] {
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
button:not(:disabled),
|
||||
[type=button]:not(:disabled),
|
||||
[type=reset]:not(:disabled),
|
||||
[type=submit]:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
::-moz-focus-inner {
|
||||
padding: 0;
|
||||
border-style: none;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
legend {
|
||||
float: right;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: calc(1.275rem + 0.3vw);
|
||||
line-height: inherit;
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
legend {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
legend + * {
|
||||
clear: right;
|
||||
}
|
||||
|
||||
::-webkit-datetime-edit-fields-wrapper,
|
||||
::-webkit-datetime-edit-text,
|
||||
::-webkit-datetime-edit-minute,
|
||||
::-webkit-datetime-edit-hour-field,
|
||||
::-webkit-datetime-edit-day-field,
|
||||
::-webkit-datetime-edit-month-field,
|
||||
::-webkit-datetime-edit-year-field {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
::-webkit-inner-spin-button {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
[type=search] {
|
||||
-webkit-appearance: textfield;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
[type="tel"],
|
||||
[type="url"],
|
||||
[type="email"],
|
||||
[type="number"] {
|
||||
direction: ltr;
|
||||
}
|
||||
::-webkit-search-decoration {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
::-webkit-color-swatch-wrapper {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
::-webkit-file-upload-button {
|
||||
font: inherit;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
::file-selector-button {
|
||||
font: inherit;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
|
||||
output {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
iframe {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
summary {
|
||||
display: list-item;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
progress {
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
/*# sourceMappingURL=bootstrap-reboot.rtl.css.map */
|
||||
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-reboot.rtl.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
5402
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.css
vendored
Normal file
5402
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
5393
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.css
vendored
Normal file
5393
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap-utilities.rtl.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
12057
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.css
vendored
Normal file
12057
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css
vendored
Normal file
6
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css.map
vendored
Normal file
1
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.min.css.map
vendored
Normal file
File diff suppressed because one or more lines are too long
12030
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.rtl.css
vendored
Normal file
12030
src/Bifrost.Web/wwwroot/lib/bootstrap/dist/css/bootstrap.rtl.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue