Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d200b52dff | ||
|
|
7dd2ff8720 | ||
|
|
f6ca1188a9 | ||
|
|
1ad80b6849 | ||
|
|
425ceb75b9 | ||
|
|
21b7741b21 | ||
|
|
7f226f7fb9 | ||
|
|
51d23f0ba4 | ||
|
|
10413141af | ||
|
|
d770223322 | ||
|
|
10988f3459 | ||
|
|
67e088da98 | ||
|
|
506ee990d0 | ||
| 6cc829237c | |||
| 0b11e0e72b | |||
| 343d09f985 | |||
| 5d9fc14598 | |||
| 3414143125 | |||
|
|
6e705852fb | ||
|
|
870b475795 | ||
|
|
11fc87c8e4 | ||
|
|
8bcd6d67e9 | ||
|
|
1480883a3b | ||
| b688fec8e0 | |||
|
|
63b9596ff1 | ||
|
|
e60953e469 | ||
|
|
a92638511c | ||
|
|
6606f8e6e6 | ||
|
|
ca726c057a | ||
|
|
6bd3ce4371 | ||
|
|
a8c489b0d0 | ||
|
|
c0b7b6a857 | ||
|
|
817363e366 | ||
|
|
a1ee88cdbb | ||
|
|
ed3645e048 | ||
|
|
5ddfca9b55 | ||
|
|
ec28dffba1 | ||
|
|
8175e5ed99 | ||
|
|
24a880ad4c | ||
|
|
e9a2e29c61 | ||
|
|
1924433af2 | ||
|
|
7bf284876a | ||
|
|
3907259cb3 | ||
|
|
5fbb673c55 | ||
|
|
8175f6f61e | ||
|
|
0599aedf08 | ||
| 2d9eb868bf | |||
|
|
757ca2eeab | ||
|
|
a2172349ba | ||
|
|
b47a6557cb | ||
|
|
41f4cc3853 | ||
|
|
cdf64b2a10 | ||
|
|
c62166c6ce | ||
|
|
f726101207 | ||
|
|
5df08bd94a | ||
|
|
41189e14d3 | ||
|
|
10fc9803d7 | ||
|
|
537a477dc3 | ||
|
|
b7b33bc5db | ||
|
|
aa348d3b43 | ||
|
|
1ffb8886c0 | ||
|
|
f402eb13cc | ||
|
|
baa70bcef0 | ||
|
|
13ab2e3be7 | ||
|
|
84ff2c4578 | ||
|
|
fbb5853b1d | ||
|
|
b54cf27101 | ||
|
|
ee700d4931 | ||
| 425af74500 | |||
| c20947af1c | |||
|
|
18f1ec6aca | ||
|
|
8e65f56b0c | ||
|
|
b65bec65ce | ||
|
|
59ecaa606b | ||
| 9a716cfd7e | |||
| ae0037c159 | |||
|
|
96665a778b | ||
|
|
3b0a614ee9 | ||
|
|
d29f8014f9 | ||
|
|
25ce117f16 | ||
|
|
f04b20feed | ||
| e58e9531df | |||
|
|
1771f15789 | ||
|
|
1739d5552a | ||
| 920ecb1fbe | |||
|
|
1298e7db1e | ||
|
|
f9d0c24f66 | ||
| dc151e6cac | |||
|
|
1fbe16eb73 | ||
|
|
4c9937f881 | ||
|
|
95416653ba | ||
| d1d13992aa | |||
|
|
1998f0e6ae | ||
|
|
31ced94f2a | ||
| b687da954b | |||
|
|
87a1bb6b3b | ||
|
|
c085cead9d | ||
| fe0ff40864 | |||
|
|
280d843aeb | ||
|
|
25b9cc1683 | ||
|
|
95d2e8d262 | ||
| b80b27da0f | |||
| 420a4dbf85 | |||
| a1b173079d | |||
| afafff18bd | |||
| c2de290628 | |||
|
|
e639e13a8b | ||
|
|
46cf7d4492 | ||
|
|
a3bab9b8e5 | ||
|
|
beafbe18e2 | ||
|
|
8a3262b3e8 | ||
|
|
ee88bc709d | ||
|
|
abeb8a1d5f | ||
|
|
6c4c9c00f9 | ||
| b1725a106f | |||
| d26aa50041 | |||
| 4cb83971f9 | |||
| d4365a8364 | |||
| 0d820fdc00 | |||
| 7231cdb977 | |||
| f6a826b6e7 | |||
| 6acb4980b8 | |||
| e8e8fcc178 | |||
| 1da912d5e9 | |||
| e12b8e2298 | |||
| dc35c4a254 | |||
| ab89556101 | |||
| e8df60630e | |||
| 7813426e6d | |||
| 70a2038435 | |||
|
|
2aabaabc53 | ||
|
|
99128e9f90 | ||
|
|
8abd912917 |
362 changed files with 23056 additions and 87527 deletions
|
|
@ -4,5 +4,3 @@
|
||||||
COMPOSE_PROJECT_NAME=bifrost-local
|
COMPOSE_PROJECT_NAME=bifrost-local
|
||||||
BIFROST_ROOT_VERSE=asgard
|
BIFROST_ROOT_VERSE=asgard
|
||||||
BIFROST_MACHINE_ID=yggdrasil
|
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
|
- UI: Razor Pages
|
||||||
- database: PostgreSQL
|
- database: PostgreSQL
|
||||||
- hosting target: `bifrost.gamecult.org` on Yggdrasil
|
- hosting target: `bifrost.gamecult.org` on Yggdrasil
|
||||||
- deployment pattern: nginx + systemd + localhost-only Postgres, matching `E:\Projects\gamecult-ops`
|
- deployment pattern: nginx + systemd + localhost-only Postgres, matching `F:\Projects\gamecult-ops`
|
||||||
|
|
||||||
## Naming Defaults
|
## Naming Defaults
|
||||||
|
|
||||||
|
|
@ -43,7 +43,7 @@
|
||||||
|
|
||||||
## Ops Assumptions
|
## Ops Assumptions
|
||||||
|
|
||||||
- follow the GameCult ops pattern already documented in `E:\Projects\gamecult-ops`
|
- follow the GameCult ops pattern already documented in `F:\Projects\gamecult-ops`
|
||||||
- prefer one web app process for v1
|
- prefer one web app process for v1
|
||||||
- keep Postgres bound to localhost on the host
|
- keep Postgres bound to localhost on the host
|
||||||
- add deployment runbooks to `gamecult-ops` when app work begins
|
- add deployment runbooks to `gamecult-ops` when app work begins
|
||||||
|
|
@ -57,26 +57,3 @@
|
||||||
- If a question is about trust, accountability, or payout fairness, prefer auditability over automation.
|
- If a question is about 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.
|
- 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.
|
- 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,6 +11,7 @@ This repository now includes a viable alpha foundation slice of the ASP.NET Core
|
||||||
- Razor Pages app under `src/Bifrost.Web`
|
- Razor Pages app under `src/Bifrost.Web`
|
||||||
- PostgreSQL-backed EF Core model with an initial migration under `src/Bifrost.Web/Data/Migrations`
|
- 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
|
- 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
|
- 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
|
- 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
|
- shared work board with estimates, actual time logs, review flow, and GitHub issue or PR links
|
||||||
|
|
@ -89,13 +90,12 @@ For the full staged roadmap, including contribution points, revenue share, patro
|
||||||
- set `Heimdall:PatronSupportIntakeSecret` before enabling Heimdall patron support intake in production
|
- set `Heimdall:PatronSupportIntakeSecret` before enabling Heimdall patron support intake in production
|
||||||
- default connection string points at local PostgreSQL
|
- default connection string points at local PostgreSQL
|
||||||
- build with `dotnet build Bifrost.slnx`
|
- build with `dotnet build Bifrost.slnx`
|
||||||
- test with `DOTNET_ROLL_FORWARD=Major dotnet test Bifrost.slnx` if the machine only has the .NET 10 runtime installed
|
- test with `dotnet test Bifrost.slnx`; the suite needs a real .NET 8 runtime (`DOTNET_ROOT`, with a runsettings `DotNetHostPath` if the SDK is newer; .NET 10 roll-forward makes Mvc.Testing 8.0.0 return 500 on every JSON response) and a built CultLib TypeScript runtime (`dist/` and `node_modules`) at `$VOIDBOT_CULTLIB_ROOT`
|
||||||
- dry-run a Reddit organizing thread with `node tools/bifrost-bridge.mjs reddit-post --title "Thread title" --persona-name Bifrost --content "Thread body" --dry-run true`
|
- 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`
|
- 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`
|
- 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
|
- provider advertisement commands require explicit `BIFROST_ROOT_VERSE` and
|
||||||
`BIFROST_MACHINE_ID` deployment identity
|
`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 test with `docker compose -f compose.local.yaml up --build`
|
||||||
- container smoke tests may hit `/healthz` and `/readyz` as product probes.
|
- container smoke tests may hit `/healthz` and `/readyz` as product probes.
|
||||||
Provider advertisements, Docker health, and deploy gates must come from
|
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:
|
Before implementation work starts in a new session, read these files in order:
|
||||||
|
|
||||||
1. [AGENTS.md](E:\Projects\Bifrost\AGENTS.md)
|
1. [AGENTS.md](AGENTS.md)
|
||||||
2. [docs/bifrost-mvp-plan.md](E:\Projects\Bifrost\docs\bifrost-mvp-plan.md)
|
2. [docs/bifrost-mvp-plan.md](docs/bifrost-mvp-plan.md)
|
||||||
3. [docs/jurisdiction-map.md](E:\Projects\Bifrost\docs\jurisdiction-map.md)
|
3. [docs/jurisdiction-map.md](docs/jurisdiction-map.md)
|
||||||
4. [docs/bridge.md](E:\Projects\Bifrost\docs\bridge.md)
|
4. [docs/bridge.md](docs/bridge.md)
|
||||||
5. [docs/verse-service-contract.md](E:\Projects\Bifrost\docs\verse-service-contract.md)
|
5. [docs/verse-service-contract.md](docs/verse-service-contract.md)
|
||||||
6. [docs/agent-transport.md](E:\Projects\Bifrost\docs\agent-transport.md)
|
6. [docs/agent-transport.md](docs/agent-transport.md)
|
||||||
7. [docs/reddit.md](E:\Projects\Bifrost\docs\reddit.md)
|
7. [docs/reddit.md](docs/reddit.md)
|
||||||
8. [docs/paypal-patronage.md](E:\Projects\Bifrost\docs\paypal-patronage.md)
|
8. [docs/paypal-patronage.md](docs/paypal-patronage.md)
|
||||||
9. [docs/full-implementation-strategy.md](E:\Projects\Bifrost\docs\full-implementation-strategy.md)
|
9. [docs/full-implementation-strategy.md](docs/full-implementation-strategy.md)
|
||||||
10. [docs/context.md](E:\Projects\Bifrost\docs\context.md)
|
10. [docs/context.md](docs/context.md)
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -41,7 +41,7 @@ Bifrost head `bf83a93` (2026-10-10; `20d5efa` plus the prior-art note, docs only
|
||||||
|
|
||||||
### Data Protection on the live host
|
### Data Protection on the live host
|
||||||
|
|
||||||
18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*`, `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
|
18. The live env file sets no `DataProtection__KeysPath` (key names only: `AllowedHosts`, `Bootstrap__*`, `ConnectionStrings__Bifrost`, `GitHubApp__EnableWebhookSync`, `GitHubOAuth__*`, `Heimdall__*` (the app secret as `Heimdall__AppSecret`; `Heimdall__AppSecretFile` is the replacement), `Host__*`, `Stripe__*`). So `Program.cs:113-119` never calls `PersistKeysToFileSystem`, and ASP.NET Core's default applies: the service runs as `bifrost` with `HOME=/srv/bifrost`, and the key ring is `/srv/bifrost/.aspnet/DataProtection-Keys` with two keys (created 2026-04-22 and 2026-07-22, the 90-day roll; prior-art note `docs/research/anonymous-vote-stuffing-prior-art.md:65-69`). A third, unused directory `/srv/bifrost/data-protection-keys` holds one key from 2026-07-15. Keys therefore persist across restarts today by accident of `HOME`, not by configuration.
|
||||||
19. The service's working directory resolves to the release directory: `readlink /proc/<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).
|
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
|
### Proxy and client address
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,16 @@ permits, windows and `MaxTrackedKeys`.
|
||||||
|
|
||||||
New since the live release, and not read by the validator:
|
New since the live release, and not read by the validator:
|
||||||
|
|
||||||
- **`Heimdall__AppSecret`**: required for Discord and Patreon sign-in. Without it `HeimdallOptions.IsDiscordConfigured` and
|
- **`Heimdall__AppSecretFile`**: the preferred way to give Bifrost the app secret below. A path to a file holding it (one
|
||||||
`IsPatreonConfigured` are false and those sign-ins stop working (GitHub sign-in is unaffected); startup does not fail,
|
trailing newlines are trimmed), for example `%d/heimdall-app-secret` under systemd `LoadCredential=`, so the secret never
|
||||||
so a missing key shows only at the live check. The value is Heimdall's app secret for slug `bifrost`
|
rides in the process environment. When set, the file wins over `Heimdall__AppSecret`; a missing, unreadable or empty file
|
||||||
|
stops startup in every environment, with a message that names the option and path and never the value. Ops steps:
|
||||||
|
`docs/heimdall-app-secret-file.md`.
|
||||||
|
- **`Heimdall__AppSecret`** (deprecated; use `Heimdall__AppSecretFile`; startup logs a warning when it is set): required for
|
||||||
|
Discord and Patreon sign-in. Outside Development and Testing startup fails when neither this nor
|
||||||
|
`Heimdall__AppSecretFile` supplies a non-blank secret (the message names both options, never a value), because
|
||||||
|
`HeimdallOptions.IsDiscordConfigured` and `IsPatreonConfigured` would otherwise be false and those sign-ins silently
|
||||||
|
stop working (GitHub sign-in is unaffected). The value is Heimdall's app secret for slug `bifrost`
|
||||||
(`GC_ACCESS_APP_BIFROST_SHARED_SECRET` on the Heimdall side). Bifrost sends it as `x-heimdall-app-secret`, redacted
|
(`GC_ACCESS_APP_BIFROST_SHARED_SECRET` on the Heimdall side). Bifrost sends it as `x-heimdall-app-secret`, redacted
|
||||||
from logs.
|
from logs.
|
||||||
- **`Bifrost__Oidc__*`**: optional. Absent, the OIDC issuer is not mapped and discovery answers 404. Present, it must be
|
- **`Bifrost__Oidc__*`**: optional. Absent, the OIDC issuer is not mapped and discovery answers 404. Present, it must be
|
||||||
|
|
@ -129,7 +136,7 @@ All must hold before step 1. A missing one means the window is not used.
|
||||||
not a workstation.
|
not a workstation.
|
||||||
6. **Env diff done.** Every row of the Configuration table is marked present by the reader, `ConceptVotes__NetworkTagSecret`
|
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`
|
included and at least 32 characters (a count, not the value), and the `Heimdall__AppSecret` line is in `bifrost.env`
|
||||||
(mode 600, owner `bifrost`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
|
(mode 600, owner `bifrost`; a build with the empty-secret refusal does not start without it or `Heimdall__AppSecretFile`) with Heimdall holding the same value. Nothing in "Configuration" is left unresolved.
|
||||||
7. **Quiet.** No motion closing and no known vote in flight inside the window. Check the motions page. Members told that
|
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").
|
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
|
8. **Watchdog.** `bifrost-watchdog-notice.timer` fires one minute after boot and one minute after each run
|
||||||
|
|
@ -232,6 +239,44 @@ Rollback signs members out again (the old release reads the old cookie names); s
|
||||||
`pg_restore` from it, then `shred -u` the copy and `rmdir $S`; readback `test ! -e $S`. The dump itself stays root-only.
|
`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.
|
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
|
## 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
|
It does not deploy, does not add an Idunn recipe, and does not touch `bifrost-watchdog-notice.timer`. The
|
||||||
|
|
|
||||||
117
docs/desk-feed-design.md
Normal file
117
docs/desk-feed-design.md
Normal file
|
|
@ -0,0 +1,117 @@
|
||||||
|
# Desk feed: per-Mind open forks for a signed-in member (design, no code)
|
||||||
|
|
||||||
|
Status: proposal, 2026-11-11, Heimdall (Imagination pass) against `origin/main` e8e8fcc. Docs only; nothing here is built, ruled or deployed.
|
||||||
|
Labels: **FACT** = read at the cited place. **INFERENCE** = my reading. **UNREACHED** = I could not read it.
|
||||||
|
Reads: `src/Bifrost.Web/Features/Desk/*` (main), `docs/ratatoskr-voting-auth.md` (PR #37, e172869), `/opt/commons/handoff/fork-desk-answer-binding-20261110.md`, Ratatoskr `fbec032` (`src/app/features/desk/*`), `tools/persona-matrix-mouth.mjs`, `docs/bridge.md`. UNREACHED: CultLib `fork-card.md` (no checkout here; I rely on the Desk code that pins it at de8a062a), Huginn's `desk_wire.rs` (PR #31 is merged; the list/read half of the door wire is not defined in anything I read).
|
||||||
|
|
||||||
|
## 1. What is asked, and the finding that shapes it
|
||||||
|
|
||||||
|
Ratatoskr's Desk row per Mind is empty "until Bifrost feeds it" (FACT `src/app/features/desk/source.ts`: `deskFor(mind): ForkList | undefined`, slice 2 "replaces this with Bifrost's list reader"). The page already decodes `gamecult.fork.list.v0` (`forkContract.ts`).
|
||||||
|
|
||||||
|
**Finding: the feed route is already built.** `GET /api/desk/{mind}/forks?status=open&limit=N` is on main (PR #40, hardened #42-#45): list, per-Mind socket door, `open_count`, `stamp`, notes stripped for non-deciders. It serves nothing today because its two ports have no production implementation (`DeskPorts.cs`: `IDeskCredential`, `IDeskDoor`; `MapDesk` fails startup if either is missing). So the smallest honest feed is **not a new endpoint. It is the existing list route, read-only, with its two ports filled and a token that carries only `desk.read`.** A second route would need a second contract, vectors and owner for no gain.
|
||||||
|
|
||||||
|
## 2. The endpoint
|
||||||
|
|
||||||
|
- `GET https://<bifrost>/api/desk/{mind}/forks?status=open&limit=50[&cursor=c<N>]`, one call per Mind (the client already asks per Mind). `limit=0` returns counts and stamp only (FACT binding file, route table), usable for a badge.
|
||||||
|
- Response: `gamecult.fork.list.v0` (`ForkList`: `mind`, `stamp`, `open_count`, `recorded_count`, `forks[]` of `ForkEntry`, `next_cursor`). **JSON, and why:** Ratatoskr is a browser client, the xenos boundary; the contract (CultLib `fork-card.md`, Transport) fixes JSON at the HTTP edge with every key written, and the documents are typed C# records (`DeskDocuments.cs`) mirroring CultLib's. Bifrost to Huginn is the typed door, not JSON.
|
||||||
|
- The row the UI needs is derived by the client from each entry: `card.fork_id`, `card.title`, age (section 5), and the count is `open_count`. The page "derives nothing" (FACT `forkContract.ts` header), so it takes `open_count` as the one count.
|
||||||
|
- Not offered: any POST (`/api/desk/{mind}/answers` stays unreachable to this client because its token has no `desk.answer`, so it is refused 403 `insufficient_scope` at step 4 of the pipeline, before the body), any vote, any write.
|
||||||
|
|
||||||
|
## 3. Auth: what a signed-in member can call today, and what the feed reuses
|
||||||
|
|
||||||
|
FACT today: a signed-in member holds only the cookie `__Host-bifrost_session`; the default scheme is Cookie (`Program.cs:189-200`); no `AddValidation` exists, so no access token authenticates any `/api/*` route; the desk handler is `.AllowAnonymous()` and judges its own bearer (`DeskEndpoints.cs`, `MapDesk`), and the cookie scheme cannot authenticate `/api/desk/*`. **A signed-in member can call nothing on the desk today.** Chat.gamecult.org never holds the `__Host-` cookie, so "the Heimdall session" cannot be sent by the browser to Bifrost from chat.
|
||||||
|
|
||||||
|
So the session is used as PR #37 uses it: the **sign-in leg of an OIDC code+PKCE flow** (`/connect/authorize` resumes on the Heimdall-backed session, FACT `OidcEndpoints.cs:44-70`, which admits any account that is not Suspended and has an identity: membership is neither required nor written, so the sign-in leg does not prove Active. It works for `desk.read` only because the desk re-checks Active on every request) mints a short access token. Reuse, exactly:
|
||||||
|
1. Token: PR #37's second public PKCE client (Ratatoskr) and OpenIddict validation as a non-default scheme (built as `OidcDeskCredential` on OpenIddict's fixed scheme name `OpenIddict.Validation.AspNetCore`; the label `BifrostBearer` in PR #37 section 5 names the role, not the scheme string; handler `IDeskCredential` production impl, the credential port; H4 in the desk cut map, a label used only there). Request scope `desk.read` only, audience `bifrost-desk`. No `desk.answer`, no `votes.*`.
|
||||||
|
2. Judgment: unchanged `DeskEndpoints.HandleAsync`: audience, scope, then `OidcEndpoints.ActiveMemberIdAsync(db, sub)` re-read every request (non-Active gets 403 `forbidden`).
|
||||||
|
3. CORS: existing `DeskCors` (exactly `Desk:AllowedOrigin`, GET and POST, no credentials).
|
||||||
|
Rejected: a cookie-authenticated same-origin JSON route (works for a Bifrost page, not for the chat origin; a second auth path on the same data), and letting chat present its Matrix/MAS token (Bifrost does not validate it; INFERENCE per PR #37 section 1).
|
||||||
|
|
||||||
|
## 4. Where the data comes from (compare, recommend one)
|
||||||
|
|
||||||
|
Huginn is the truth. A fork is a question record with options, a derived status, deciders and a server-computed `options_hash` (FACT binding file, "Cards are a read-only projection"). Bifrost holds no fork store, no cache, no hash (FACT cut map authority map). Everything else is a cache or an unrelated plane. Options:
|
||||||
|
|
||||||
|
- **(a) A small Huginn endpoint Bifrost calls.** This is already the plan of record, not a new thing: `IDeskDoor.ListAsync(socket, context, request)` over the per-Mind peer-checked unix socket, `context` = {Mind, authority, subject, deciders} built by Bifrost alone (`DeskPorts.cs`). Huginn returns the list "as it projects it for this viewer".
|
||||||
|
- **(b) A file the persona mouth tails or writes.** FACT the mouth holds one `cursor.cc` per Persona and it stores only the Matrix `/sync` position `next_batch` (`persona-matrix-mouth.mjs` ~:491, :906-912). `chat_pending` is Matrix deliveries to a Persona over loopback RUDP (credential-derived connection id), served *to* Huginn, which is the client; the mouth reads Matrix, not Huginn. It holds no fork, no question and no Huginn client. A file route means a new writer inside the Matrix actuator that copies private records out of the mind into the chat plane, a second owner of "what a member may see", a Node process rewriting Rust's projection, and staleness equal to its write period. The mouth would gain a job it was split away from.
|
||||||
|
- **(c) Bifrost reads Huginn directly with a CultNet selection** (what `huginn open <campaign>` / `huginn blocked <spec>` do). Rejected: those return every in-force question and follow-up of a campaign (`epiphany.pipeline.question.v2`, `follow_up.v2`), most of which are not forks. Bifrost would need a general read of the mind and would decide fork-hood and visibility itself. Also Bifrost has no Huginn client at all (FACT: no CultNet/RUDP/unix-socket client in C#; `UnixDomainSocketEndPoint` appears nowhere).
|
||||||
|
|
||||||
|
**Recommend (a), as the existing desk door, list request only.** Reasons:
|
||||||
|
- **Auth:** the door is peer-credential checked (the receiver's uid); Bifrost passes the verified subject; the member's token never reaches Huginn.
|
||||||
|
- **Staleness:** none added. A live read, `Cache-Control: no-store` (FACT), with Huginn's `stamp` (`s<N>`, same stamp same state) as the change signal; a client polls, or `limit=0` for the cheap probe. Bifrost may cache by stamp later; it need not.
|
||||||
|
- **Failure:** per Mind and per call. A dead socket, timeout or unknown outcome is 503 `unavailable` with `Retry-After` (FACT `WriteUnavailableAsync`); the other Minds' rows are unaffected because the client asks per Mind. The mouth being down is irrelevant. Nothing is served from a stale copy that could mislead.
|
||||||
|
- **Mouth overlap:** none, which is the point. Chat plane (mouth) and fork plane (door) stay two owners.
|
||||||
|
- **Not yet existing:** `UnixSocketDeskDoor` (the door port's production impl; H5 in the desk cut map) and the Huginn side of the list wire. Eureka owns that wire (binding file section 5, "The door wire is Eureka's"). I found no definition of the list/read request bytes; this note does not invent one.
|
||||||
|
|
||||||
|
## 5. Meaning of "open" and "age"
|
||||||
|
|
||||||
|
- **open** = the card's `status` is `open` as Huginn derives it (`ForkCard.status`; `?status=open` filter). Bifrost does not decide it. The count is `open_count` of the same response, so the number and the rows come from one stamp. `recorded_count` (closed with a ruling) is not part of the feed.
|
||||||
|
- **age** = now minus when the question was raised. **The contract cannot give this today.** FACT `ForkCard` has `order` (a position), `raised_in` (a reference) and no timestamp; answers carry `answered_at`/`received_at` but an unanswered fork has none. Ruled 2026-11-11 by Libby (CultLib steward): the card gains `raised_at`, a REQUIRED key whose value is an RFC3339 string or nil (the card goes from 16 to 17 keys; its hex changes). Huginn emits the question's admission time, or nil when it has none. Bifrost's record gains one field that must accept string or nil. Age derives from `raised_at` and is computed by the client; Bifrost computes nothing; nil means age unknown and the row shows no age. Until the contract lands the feed ships without age (the fallback loses nothing else).
|
||||||
|
|
||||||
|
## 6. D1 (options_hash) and the feed
|
||||||
|
|
||||||
|
Two different "D1"s exist: the ruling cited for this feed is the fork-desk answer-binding D1 (2026-11-10: `options_hash` covers title, context, options with ids, recommendation and depends; `fork_id` is bound beside it). PR #37 also has a D1 (consent). This section is the first; section 7 the second.
|
||||||
|
- Feed rows carry the card as Huginn returns it, `options_hash` included. Bifrost never computes or corrects a hash (FACT binding file). A row's identity is `(fork_id, options_hash)`: an edit to a shown title changes the hash, so the row changes with it.
|
||||||
|
- The feed shows title, which the hash covers, so feed and detail cannot disagree about it.
|
||||||
|
- **Age is not decision content.** Ruled by Libby (X2, my earlier "inside the hash" option is withdrawn): `raised_at` stays OUT of `options_hash`, which keeps exactly five members (title, context, options, recommendation, depends), so the hash digests and Void's `optionsHash.ts` vectors do not change. Only the card's own bytes change, by the added key.
|
||||||
|
|
||||||
|
## 7. PR #37 decisions, what this feed needs
|
||||||
|
|
||||||
|
| id | decision (brief) | for the feed |
|
||||||
|
|---|---|---|
|
||||||
|
| D1 | explicit consent for `votes.cast`, or first-party implicit | **not needed**: a `desk.read` grant casts and changes nothing; implicit read consent (PR #37 section 7) |
|
||||||
|
| D2 | re-authentication at cast for high-stakes motions | **not needed**: no cast |
|
||||||
|
| D3 | token lifetime | **decided** (PR #37 section 14 D3): no refresh token; `desk.read`-only requests get a 60-minute access token, so a polling feed needs no redirect per 10 minutes. Per-audience lifetime is not built; probe 7 is owed |
|
||||||
|
| D4 | where a member lists and revokes grants | **not needed** while the grant is read-only; revisit with `desk.answer` |
|
||||||
|
| D5 | runtime brake | **decided** (section 14 D5): the existing marker-file brake, held by the steward. It is NOT per-client and does not cover `/api/desk` until the guard's matching is extended; that and the desk-only deployment are the code PR's to settle |
|
||||||
|
| D6 | rate limits | **decided** (section 14 D6): 120 requests/min per account for `desk.read`, in configuration. A 429 has no refusal code in the contract (Q3 of the desk cut map): not decided there |
|
||||||
|
| D7 | order against the MAS rollout | **decided** (section 14 D7): independent; the Ratatoskr client is seeded only when configured. The feed still needs Bifrost OIDC live, which it is not (PR #37 section 1) |
|
||||||
|
|
||||||
|
Already ruled: the answer-binding D1 above, visibility ruling c (any `desk.read` holder sees cards and outcomes; notes only for deciders), read with Bifrost's requirement that the door returns only cards this member may see, D2/answer-binding (decider list authored in Bifrost admin, Mind read-only).
|
||||||
|
|
||||||
|
## 8. Privacy: what a member may see per Mind
|
||||||
|
|
||||||
|
- **Filter owner: Huginn.** The list and read calls carry the viewer's `subject` and that Mind's `deciders` (no `authority`; an answer carries it); Huginn projects "for this viewer". The policy is in Huginn's `docs/desk-feed-door.md` ("Listing", Huginn main 79d954c or later) and is not copied here: not listed unless a listing record is in force, deciders see every showable fork, a hidden fork reads as `fork_unknown`. That gate is not live on Huginn main yet (`cut-desk-feed-listing`), so no Mind that holds private questions goes behind a live receiver before it lands. Bifrost holds NO audience rule: no filter on which forks appear, no per-card visibility rule, no copy of the policy (two copies would drift). Bifrost's two new acts are the per-request Active check and the `desk.read` bearer (below), beside two already built: it nils every `note` for a non-decider (`DeskNotes.Strip`), and it resolves `{mind}` only against the configured list (unknown Mind and unknown fork return the same 404 bytes, so Minds are not probeable).
|
||||||
|
- **Fields safe for a member:** `fork_id`, `title`, `options`, `recommendation`, `depends`, `status`, `order`, `options_hash`, counts, `stamp`, and `raised_at` (string or nil). **Not safe, and not in the feed:** `note` (stripped), the decider list beyond ids already on the card, anything from the mind that is not a fork card (follow-ups, findings, research, persona state, room text).
|
||||||
|
- **Answerer ids (X3, closed by the steward in PR #37 section 14):** `ForkEntry.record.answers[]` carries each answerer's account id (a Bifrost `UserAccount.Id`) to any `desk.read` holder; ruling c permits cards and outcomes, but a member list of who answered what is more than a feed needs. The feed does not need `record` at all. SUPERSEDED by Eureka's ruling `eureka-substrate:ruling:desk-read-visibility-withheld-ids` (Huginn #56, 79d954c): the door, not Bifrost, withholds decider ids and answerer ids from a non-decider and returns counts. Bifrost masks nothing it cannot read (the card is opaque to it) and keeps no answerer mask; it still nils `note` for a non-decider. Until Huginn's cut and the CultLib change land, the door sends ids whole, so no receiver goes live on a Mind before then.
|
||||||
|
- **Content privacy:** a fork's `context` and `title` are Mind-authored prose and may name people or private matter. The door is the only gate: Bifrost requires the list wire to carry only cards the member may see, passes them through; the door withholds answerer and decider ids. The audience policy is Huginn's door spec's, not here. The feed ships no free text Bifrost wrote.
|
||||||
|
- **Consent and receipts:** reading creates no member record, so no receipt and no consent object; the member's act is the token grant (read-only, implicit). Answer receipts and the append-only record belong to the answer path and stay out. Audit: log client id and `sub`, not the response. The training-notice receipt gates the chat token only (Meta's ruling, 2026-11-11): a desk token issues for a member with no receipt.
|
||||||
|
|
||||||
|
## 9. Failure modes
|
||||||
|
|
||||||
|
Bearer unjudgeable: 503 `unavailable` (not a refusal of the caller). Not Active: 403. Unknown Mind: 404 `fork_unknown`. Oversize fork: 422 `fork_too_large` with a cursor to continue (FACT #42/#44; the client must handle it, not render nothing). Token expired: 401; the client restarts the redirect (D3). Door down: 503; the Desk row shows "unavailable, retry", never an empty list (an empty list must mean zero open forks). Huginn emits a decider list outside 1..64 for a configured Mind: 503 (config fault, FACT). Ratatoskr's source is synchronous; it needs a fetch-and-hold layer that keeps the last good `stamp` and marks it stale, which is Void's.
|
||||||
|
|
||||||
|
## 10. Tests that would prove it (consumer side)
|
||||||
|
|
||||||
|
1. Ratatoskr, against a stubbed list: a `ForkList` fixture from the vendored vectors renders the right rows and count; a 503 renders "unavailable", not an empty desk; `open_count` 0 with an empty page renders "none open".
|
||||||
|
2. Bifrost, `DeskWebApplicationFactory` + `FakeDeskDoor`: a token with `desk.read` lists (200); no token 401; wrong audience 401; a `desk.read`-only token POSTing an answer is 403 `insufficient_scope` with the door never called; a non-Active subject is 403 with the door never called; a cookie alone gets 401.
|
||||||
|
3. Privacy: a non-decider's response has every `note` nil (key present); Bifrost masks no `answerer` (Huginn's door withholds ids); a decider keeps notes; an unknown Mind and an unknown fork return identical bytes; Bifrost relays exactly the cards the door returns (a door double returning N cards yields N rows, none dropped or added) and applies no audience filter of its own.
|
||||||
|
4. Hash: a row's `options_hash` equals the vector value, and Ratatoskr's `optionsHash.ts` recomputed over the rendered title/context/options matches it (pins D1 end to end).
|
||||||
|
5. Probes owed by PR #37 section 11 (items 1, 3, 5): public client exchange, audience+scope enforced, bearer on `/App` still refused.
|
||||||
|
6. Door contract: a `UnixSocketDeskDoor` against a Huginn double returns `Listed`, `NotListed`, `ForkTooLarge`, and an exception maps to 503.
|
||||||
|
|
||||||
|
## 11. Size estimate (lines, include tests)
|
||||||
|
|
||||||
|
| file | lines |
|
||||||
|
|---|---|
|
||||||
|
| Bifrost `Features/Desk/UnixSocketDeskDoor.cs` (list only; read/answer added by the answer cut) | ~180 |
|
||||||
|
| Bifrost `Features/Oidc/*` bearer validation, `desk.read` scope, audience, second client seed (shared with PR #37) | ~150 |
|
||||||
|
| Bifrost `IDeskCredential` production impl (validates the bearer, returns `DeskToken`) + wiring in `Program.cs`; no audience or visibility logic | ~60 |
|
||||||
|
| Bifrost sweep revoking the Ratatoskr/desk client's authorizations for subjects failing the chat-tier test (PR #37 section 8; derived from membership, no outbound POST) | ~80 |
|
||||||
|
| Bifrost `OidcGuard` match extended to `/api/desk` (D5 brake) and the desk-only deployment settlement | ~30 |
|
||||||
|
| Bifrost per-audience token lifetime at authorize (D3: 60 minutes for `desk.read`-only; probe 7 first) | ~30 |
|
||||||
|
| Bifrost `DeskNotes` extension: mask `answerer` for non-deciders (dropped: the door withholds ids) | 0 |
|
||||||
|
| Bifrost re-vendor `tests/Bifrost.Web.Tests/Fixtures/fork-card-vectors.json` (17-key card, new CultLib commit) + `DeskVectors.cs:9,11` pin + `ForkCard` 17th member `RaisedAt`, string or nil (`DeskDocuments.cs:64-80`) + `DeskDocumentTests`/`DeskScenarioTests` updates | ~60 |
|
||||||
|
| CultLib `fork-card.md` + schema + card vectors for `raised_at` (17-key card; `options_hash` vectors unchanged) | ~40 |
|
||||||
|
| Huginn: list wire handler and `raised_at` (Eureka's) | not estimated |
|
||||||
|
| Ratatoskr list reader + token redirect + stale holder (Void's) | ~250 |
|
||||||
|
| Bifrost tests (items 2, 3, 6) | ~250 |
|
||||||
|
| This doc and `docs/oidc-issuer.md` note | ~40 |
|
||||||
|
|
||||||
|
Subtraction: no new route, no store, no migration, no DTO type beyond one field. The two shared ports (door, bearer) are the cost, and the answer path needs them anyway.
|
||||||
|
|
||||||
|
## 12. Open decisions
|
||||||
|
|
||||||
|
- **X1** (CultLib, ruled 2026-11-11, Libby): `raised_at` is a required card key, RFC3339 string or nil; 16 to 17 keys. Huginn's emission of it is Eureka's, still to build.
|
||||||
|
- **X2** (withdrawn): `raised_at` is out of `options_hash`, digests unchanged (Libby).
|
||||||
|
- **Nothing in this note is open for Bifrost's own design.** Decided and recorded elsewhere: `raised_at` (Libby, CultLib ruling 2026-11-11, X1/X2 closed); answerer ids (X3: withheld by Huginn's door, ruling `desk-read-visibility-withheld-ids`, supersedes the Bifrost mask); PR #37 D1-D7 (section 14); card visibility (the Huginn door's policy, `docs/desk-feed-door.md` in Huginn; Bifrost holds no audience rule).
|
||||||
|
- Owed by others: Eureka owns Huginn's emission of `raised_at`, the listing gate (`cut-desk-feed-listing`) and the ops root-run that binds the sockets; the door wire is on Huginn main and its golden fixtures are the contract for `UnixSocketDeskDoor`.
|
||||||
370
docs/feedback-receiver.md
Normal file
370
docs/feedback-receiver.md
Normal file
|
|
@ -0,0 +1,370 @@
|
||||||
|
# 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.
|
||||||
294
docs/guest-accounts.md
Normal file
294
docs/guest-accounts.md
Normal file
|
|
@ -0,0 +1,294 @@
|
||||||
|
# Guest accounts
|
||||||
|
|
||||||
|
Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifrost-guest-accounts` under
|
||||||
|
`eureka-body:ruling:guest-arrival-bifrost` (Meta: guests need no Matrix account of their own; they get a GameCult
|
||||||
|
account through Bifrost with a guest role, and move to member, user or patron on the same account seamlessly),
|
||||||
|
building on `eureka-body:ruling:bifrost-owns-accounts-invite-only`. I could not `view` either ruling from the
|
||||||
|
Heimdall mind, so their text here is the follow-up brief's wording. Eureka's review (PR comment, 2026-11-07) checked
|
||||||
|
it against the rulings and found guest-arrival matches; the conflicts it found are folded in below. First guest:
|
||||||
|
sletz (Faust developer). Aqua decides on `#aquasynth` access, so the first grant list is hers to name.
|
||||||
|
|
||||||
|
Read at Bifrost `bf8ff62` (`src/Bifrost.Web/Domain/BifrostModels.cs`, `Features/Membership`, `Features/Heimdall`,
|
||||||
|
`Features/Oidc`, `Features/Motions`, `Features/ConceptVotes`, `Pages/App/Members`) and Heimdall `575be9c`
|
||||||
|
(`src/app-profiles.ts`, `docs/app-profiles/bifrost.md`). File and line references re-read at Bifrost main `e58e953` and Heimdall main
|
||||||
|
`afa1b74` on 2026-11-12; where main moved the subject, the text says so. Nothing in this design has landed on main.
|
||||||
|
|
||||||
|
## Rulings of the steward (Heimdall, 2026-11-12)
|
||||||
|
|
||||||
|
These four are the Bifrost steward's; they replace the recommendations further down. Eureka's, Aqua's and Meta's items are not ruled here.
|
||||||
|
|
||||||
|
1. **Name and shape: a stored `Membership.Role` (enum `AccountRole`), not a boolean.** One stored field is one reading, and an account with no role is denied by default (least privilege). `MemberRole` keeps its name and meaning; renaming it is not needed, and nothing existing is removed.
|
||||||
|
2. **Invite: a single-use code redeemed from a form, never a token in a URL.** The issuer is shown the code once; the guest pastes it into `POST /invite/guest` (a body, not a path or query), so it reaches no log, referrer or browser history. Hashed at rest, seven days, one use, receipted on issue, accept and revoke. The issuer may bind `ExpectedProvider` (optional, narrows the invite). The sign-in return path carries only the Heimdall attempt, never the code.
|
||||||
|
3. **Provider lists: Bifrost narrows to the intersection with Heimdall's `bifrost` profile, `discord, patreon, google`; no widening.** Twitch cannot start in Heimdall and has been removed from Bifrost's `AllowedProviders`. Google is a sign-in provider too: a Google start carrying a live invite asks Heimdall for an invite grant, and Heimdall mints an account only under it (Bifrost PR #93). Which provider sletz uses is still the issuer's to learn.
|
||||||
|
4. **Collector: a guest has no `member_id` and none of their messages are collected.** A sender with no linked member is already dropped (`docs/answer-collector-consent.md` l.197 in Heimdall). A `member_id`, and a consent record under it, exists only on promotion to `member`.
|
||||||
|
|
||||||
|
## The shape in one paragraph
|
||||||
|
|
||||||
|
A guest is a `UserAccount` like any other: same `Id` (the OIDC `sub`), same `NormalizedBifrostIdentity` (the Matrix
|
||||||
|
localpart, minted once). What is new is one field, `Membership.Role`, with four values: `guest`, `user`, `patron`,
|
||||||
|
`member`. Role is the single place that says what an account may do. A role change rewrites that field and writes a
|
||||||
|
receipt; it never creates a second account, never re-mints the identity, so chat history, grants and the Matrix
|
||||||
|
user stay attached.
|
||||||
|
|
||||||
|
## What exists today
|
||||||
|
|
||||||
|
- `UserAccount.Id` is the OIDC subject; `NormalizedBifrostIdentity` is `preferred_username` and, through MAS, the
|
||||||
|
Matrix localpart (`docs/oidc-issuer.md`). `HeimdallAccountId` is only an authenticator handle.
|
||||||
|
- `Membership.Status` is `Authenticated | PendingApproval | Active | Suspended`. `CurrentBifrostActor.IsActiveMember`
|
||||||
|
(`CurrentBifrostActor.cs:17`, `Status == Active`) is the one test behind `/App`, motion votes
|
||||||
|
(`Membership.EffectiveVotingWeight`, `BifrostModels.cs:361`, read at `MotionGovernanceService.cs:72`), concept votes (`VoterIdentity.For`,
|
||||||
|
`VoterIdentity.cs:20`, member versus account class), Mind moderation (`MindIntakeService.cs:241`) and the fork desk's subject check
|
||||||
|
(`OidcEndpoints.ActiveMemberIdAsync`, `OidcEndpoints.cs:183-194`). The OIDC chat tier is not behind it: main lets any account that is
|
||||||
|
not `Suspended` and holds a live training-notice receipt sign in to chat (`OidcEndpoints.cs:55-65` and `ChatRefusalAsync`, `:164-180`,
|
||||||
|
called at `:127` and `:144`; `docs/oidc-issuer.md` l.72-77), and the back-channel logout reconciler (`OidcLogoutReconciler.cs`, 30 s
|
||||||
|
interval, l.34) ends sessions of suspended or deleted subjects, never of a chat-tier account for lacking membership.
|
||||||
|
- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability
|
||||||
|
roles a member holds in addition. They are not the new field.
|
||||||
|
- Chat invites are `ChatInvite` (see `oidc-issuer.md`, Chat invites), not keyed to any login;
|
||||||
|
a guest may have no GitHub login at all.
|
||||||
|
- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an
|
||||||
|
identity-only account at `Authenticated`; with member access it creates `Active`.
|
||||||
|
- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research
|
||||||
|
only, `docs/charter-amendment-proposal.md`).
|
||||||
|
|
||||||
|
## Decision: one role field, status stays lifecycle
|
||||||
|
|
||||||
|
Two authorities cannot both say "may this account vote". Today `Status == Active` says it. The cut:
|
||||||
|
|
||||||
|
- `Membership.Status` keeps its meaning as lifecycle of the account: may it hold a session. Add `Left` and
|
||||||
|
`Erased` (see Leave and erase). `Active` means admitted and in good standing, for any role.
|
||||||
|
- `Membership.Role` (new, non-null, enum `AccountRole`) decides rights. `IsActiveMember` becomes
|
||||||
|
`Status == Active && Role == Member`, and is the only place that expression exists. Every current
|
||||||
|
`IsActiveMember` caller keeps working unchanged and a guest fails all of them without a per-site edit.
|
||||||
|
- OIDC needs no change for guests: main already admits any non-`Suspended` account with a live training-notice receipt to chat (see
|
||||||
|
What exists today), so a guest, user or patron holds a chat session, and a member demoted to `Suspended` loses it. The change this
|
||||||
|
design owes is the two new statuses: `Left` and `Erased` must be refused at the same three places (`OidcEndpoints.cs:62`,
|
||||||
|
`ChatRefusalAsync` `:174`) and ended by the reconciler, which today looks for `Suspended` only. That is the line to review.
|
||||||
|
- Backfill: `Active` becomes `member`; `Authenticated` and `PendingApproval` become `user`; an account with a
|
||||||
|
current `Patron` tier snapshot and not `Active` becomes `patron`. Nobody starts as `guest`.
|
||||||
|
|
||||||
|
Naming risk: `MemberRole` already exists for capability roles. If the collision bites, call the new field
|
||||||
|
`Class`; the published field below follows whichever name is chosen. I use `Role` because that is the ruling's word.
|
||||||
|
|
||||||
|
Alternative considered and not recommended: a boolean `IsGuest` on `Membership` with guests kept at `Active`.
|
||||||
|
Smaller to land, but `user` and `patron` stay implicit in status and tier snapshots, so "the role field Personas
|
||||||
|
read" would have to be derived in three places. One stored field is one reading.
|
||||||
|
|
||||||
|
## Invite shape
|
||||||
|
|
||||||
|
New table `GuestInvitation`, separate from `ChatInvite` (which leads to chat, and
|
||||||
|
not to a guest). Fields:
|
||||||
|
|
||||||
|
| field | rule |
|
||||||
|
|---|---|
|
||||||
|
| `Id` | Guid. |
|
||||||
|
| `CodeHash` | SHA-256 of a 256-bit random code. The code itself is shown to the issuer once and never stored. |
|
||||||
|
| `IntendedIdentity` | the localpart the issuer picks (for example `sletz`), validated by `BifrostIdentityService.NormalizeIdentity`, reserved while the invite is open. Minted once on accept; a collision gets the usual `-2` suffix. |
|
||||||
|
| `Label` | free note for the issuer ("sletz, Faust developer"). |
|
||||||
|
| `RoomGrants` | the rooms to grant on accept (below), as a list of grant requests. |
|
||||||
|
| `IssuedByUserAccountId`, `IssuedAtUtc` | issuer must be a platform admin (`CanManageMembership`), as for member invites. |
|
||||||
|
| `ExpiresAtUtc` | default seven days. |
|
||||||
|
| `AcceptedByUserAccountId`, `AcceptedAtUtc`, `RevokedAtUtc` | one use; revoke before accept ends it. |
|
||||||
|
|
||||||
|
The code is a bearer: whoever redeems it first is the guest. That is the cost of not needing sletz's
|
||||||
|
provider handle in advance, and it is why the code is single-use and short-lived and why the accept is shown
|
||||||
|
to the issuer. Ruled over binding the invite to a provider handle (which needs a Discord or Google id the
|
||||||
|
issuer may not have); the issuer may still set `ExpectedProvider` (see Rulings). It is carried in a form body, never in a URL.
|
||||||
|
|
||||||
|
## Sign-in via Heimdall
|
||||||
|
|
||||||
|
1. Guest opens `/invite/guest`, pastes the code, and posts it. Bifrost checks hash, expiry, unused, unrevoked, and stores the invite id in
|
||||||
|
the existing Heimdall attempt (`HeimdallAuthService` protects attempt state with the data protector).
|
||||||
|
2. Bifrost starts Heimdall sign-in with `requireMemberAccess = false` (identity only, no entitlement policy).
|
||||||
|
Heimdall authenticates; it does not issue the identity (`docs/jurisdiction-map.md`).
|
||||||
|
3. On the callback, in one transaction: resolve `HeimdallAccountId`.
|
||||||
|
- No account: create `UserAccount` with `IntendedIdentity`, `Membership { Status = Active, Role = Guest }`, write
|
||||||
|
the room grants, mark the invite accepted, write the receipt.
|
||||||
|
- Account exists: the invite never lowers an account. A `member`, `patron` or `user` keeps their role; the grants
|
||||||
|
are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse.
|
||||||
|
4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client.
|
||||||
|
|
||||||
|
Bifrost's `AllowedProviders` is `discord, patreon, google` (`HeimdallAuthService.cs`), matching Heimdall's `bifrost` app profile (`app-profiles.ts`, `bifrostProfile`). A Google start carrying a live invite asks Heimdall for an invite grant (Bifrost PR #93); Google also stays the explicit link by a signed-in member (`HeimdallAttemptPurpose.LinkAwaitGoogle`, PRs #81 and #82). Which provider sletz uses is unknown; the issuer learns it before the first invite.
|
||||||
|
|
||||||
|
## Guest rights
|
||||||
|
|
||||||
|
A guest may: sign in, hold a Bifrost cookie, hold a chat session through OIDC (after accepting the training notice, as any chat account does on main, `ConsentEndpoints.HasLiveReceiptAsync`, `ConsentEndpoints.cs:146`), see and edit their own profile
|
||||||
|
(`MemberProfile`), be in the rooms granted to them, and leave or erase (below). A guest may not:
|
||||||
|
|
||||||
|
- vote on motions: `EffectiveVotingWeight` is `0` for any role but `member` (today it is `Max(1, ...)` for
|
||||||
|
`Active` (`BifrostModels.cs:361-363`), which would give every guest weight 1; that line must read the role);
|
||||||
|
- cast concept-mill appraisals: `VoterIdentity.For` returns no voter for a guest (not even `VoterClass.Account`);
|
||||||
|
- appear on any estate roll or in any tally. The charter proposal snapshots each estate's roll at notice (A6);
|
||||||
|
`guest` is on no roll, so a guest cannot be counted, cannot make a quorum, and reclassifying a guest after a
|
||||||
|
snapshot changes nothing for that snapshot;
|
||||||
|
- use bridge transport, claim or log work, earn points or ledger credit, or hold tier snapshots (those make them
|
||||||
|
a patron or member by changing role, not by decorating a guest);
|
||||||
|
- hold a `MemberRole` or any of the `CanManage*` flags;
|
||||||
|
- invite anyone.
|
||||||
|
|
||||||
|
This list is enforced by role in one place (`CurrentBifrostActor`), not by a check at each use.
|
||||||
|
|
||||||
|
## Per-room grants
|
||||||
|
|
||||||
|
Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, so a grant is Bifrost state:
|
||||||
|
|
||||||
|
`GuestRoomGrant { Id, UserAccountId, RoomRef, GrantedByUserAccountId, GrantedAtUtc, ExpiresAtUtc?, RevokedAtUtc? }`
|
||||||
|
|
||||||
|
`RoomRef` is a room id or alias as chat names it. Aqua's `#aquasynth` is the first one if she says yes.
|
||||||
|
|
||||||
|
**Scope (per `guest-room-moderation-ruled`, `guest-room-authority-ruled`).** Project rooms are public-join and
|
||||||
|
hand-moderated by the steward, with Eureka as backstop, so a guest who can reach a public room needs no grant. A
|
||||||
|
grant exists only for a room its steward chooses to keep closed, and its grantor is that room's steward, not a
|
||||||
|
platform admin (the invite itself is still issued by a platform admin; `GrantedByUserAccountId` records the
|
||||||
|
steward). Room entry for public rooms is not Bifrost's decision.
|
||||||
|
|
||||||
|
The grant has to reach Matrix to mean anything. Today Bifrost's only Matrix writer is the Persona mouth, with
|
||||||
|
per-Persona access tokens (`docs/bridge.md`), and it holds no admin or invite right.
|
||||||
|
|
||||||
|
Gap (largest in this doc): something must perform "invite this Matrix user to that room" on a grant and "remove
|
||||||
|
them" on revoke or expiry. Candidates: a Bifrost-owned bot user that is a member with invite power in the granted
|
||||||
|
rooms (reuses the Matrix client API, no Synapse admin credential), or the Synapse admin API. I recommend the bot
|
||||||
|
user: narrower credential, and the room's power levels remain the real gate. Until it exists, the grant is a
|
||||||
|
record, a human invites the guest by hand, and the receipt says `delivered_by: manual`. Whether the closed rooms a
|
||||||
|
steward keeps are invite-only in Synapse is a chat configuration fact I have not verified.
|
||||||
|
|
||||||
|
What Matrix takes from the Bifrost account is exactly this effector: invite or remove on a grant, and the power
|
||||||
|
level the effector sets on invite. Role never enters OIDC, so Matrix reads no role from the issuer
|
||||||
|
(`bifrost-owns-accounts-invite-only`: grants flow from the account through the effector, not through claims).
|
||||||
|
|
||||||
|
**Guest DMs (`guest-dms-ruled`) conflict, open.** The mouth declines invites from other servers and accepts
|
||||||
|
same-server DM invites (`tools/persona-matrix-mouth.mjs` `answerInvites`). The ruling's decline-for-now assumed
|
||||||
|
federated guests; a Bifrost guest is a local `@sletz:<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.
|
||||||
18
docs/heimdall-app-secret-file.md
Normal file
18
docs/heimdall-app-secret-file.md
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
# Heimdall app secret from a file
|
||||||
|
|
||||||
|
`Heimdall:AppSecret` (`Heimdall__AppSecret`) is Bifrost's app secret for Heimdall slug `bifrost`; it is sent as the
|
||||||
|
`x-heimdall-app-secret` header. Set through the environment it rides in the process environment. `Heimdall:AppSecretFile`
|
||||||
|
(`Heimdall__AppSecretFile`) names a file holding it instead.
|
||||||
|
|
||||||
|
- File set: Bifrost reads it once at startup and trailing newlines are trimmed. The file wins over `Heimdall__AppSecret`.
|
||||||
|
- File set but missing, unreadable, a directory, or empty: startup fails in every environment. The message names
|
||||||
|
`Heimdall:AppSecretFile` and the path, never the secret.
|
||||||
|
- Only `Heimdall__AppSecret` set: still works; startup logs a deprecation warning (without the value).
|
||||||
|
- Neither set: startup fails outside Development and Testing, naming `Heimdall:AppSecretFile` and `Heimdall:AppSecret`
|
||||||
|
(`StartupConfigurationValidator`). Development and Testing still start, with Discord and Patreon sign-in off.
|
||||||
|
|
||||||
|
Under systemd, pass the file with `LoadCredential=heimdall-app-secret:<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,6 +105,8 @@ This keeps Reddit useful without making subreddit mechanics the secret constitut
|
||||||
|
|
||||||
Heimdall authenticates; it does not issue GameCult identity. Bifrost owns the identity (`UserAccount.Id`, `NormalizedBifrostIdentity`) and issues it to chat as an OIDC provider (`docs/oidc-issuer.md`). `HeimdallAccountId` is an authenticator handle that links a Heimdall account to a Bifrost identity.
|
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.
|
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
|
### Patron Collection Crossing
|
||||||
|
|
|
||||||
68
docs/linked-accounts.md
Normal file
68
docs/linked-accounts.md
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
# Linked accounts
|
||||||
|
|
||||||
|
`/Membership/LinkedAccounts` (`src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml[.cs]`) is where a signed-in member sees the provider logins attached to their Heimdall account, links another one, and unlinks one. Heimdall owns the logins and every rule about them; this page starts the flows and shows what Heimdall answered. A member reaches it from the membership status page. A session with no Heimdall account (a Bifrost-native GitHub sign-in) gets a note instead of controls.
|
||||||
|
|
||||||
|
## What it does
|
||||||
|
|
||||||
|
| Action | What Bifrost does | Heimdall call |
|
||||||
|
|---|---|---|
|
||||||
|
| Show my logins | A fresh ordinary Heimdall sign-in as the session's account, through the proof provider (below); inside its completion, the list | `GET /v1/me/identities` with that sign-in's bearer |
|
||||||
|
| Link Discord, Patreon or Google | The same fresh sign-in as proof, then the link start for the chosen provider with its bearer. Needs a current list. Discord and Patreon attach in Heimdall's callback and return a link completion; Google writes a pending link, and a second fresh sign-in confirms it | `POST /v1/oauth/{provider}/start` `mode: "link"`, then for Google `POST /v1/apps/bifrost/links/confirm` |
|
||||||
|
| Unlink | A sign-in through Google with `stepUp: true` (app secret); inside its completion, the unlink | `POST /v1/me/identities/{id}/unlink` with that sign-in's bearer |
|
||||||
|
| Unlink with a passkey (an account with a strong passkey) | A WebAuthn assertion verified at Bifrost, then a fresh ordinary sign-in as the account; inside its completion, Heimdall's app-asserted step-up, then the unlink with the token it returns | `POST /v1/apps/bifrost/step-up` `{method: "bifrost-passkey", nonce}`, then `POST /v1/me/identities/{id}/unlink` |
|
||||||
|
| Add or revoke a passkey | Enrolment needs a fresh Heimdall sign-in first and cools off 48 hours; revoking needs no proof | none |
|
||||||
|
|
||||||
|
The linkable providers are the ones Heimdall's `bifrost` profile admits (`identityProviders` in Heimdall `src/app-profiles.ts`): Discord, Patreon, Google.
|
||||||
|
|
||||||
|
## How the bearer is kept: it is not
|
||||||
|
|
||||||
|
Bifrost keeps no Heimdall token. Each action is an attempt: a Data Protection cookie (`__Host-bifrost_heimdall_<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.
|
||||||
|
|
@ -5,7 +5,8 @@ Authentication Service (MAS) can sign chat users in with their Bifrost account.
|
||||||
Bifrost; it does not issue the identity chat sees.
|
Bifrost; it does not issue the identity chat sees.
|
||||||
|
|
||||||
The provider is OpenIddict (`OpenIddict.AspNetCore` and `OpenIddict.EntityFrameworkCore`, 7.7.1). Bifrost owns two
|
The provider is OpenIddict (`OpenIddict.AspNetCore` and `OpenIddict.EntityFrameworkCore`, 7.7.1). Bifrost owns two
|
||||||
decisions at the authorize endpoint: who the chat user is, and whether they may get a session.
|
decisions at the authorize endpoint: who the chat user is, and whether they may get a session (not suspended, and agreed to
|
||||||
|
the training notice in force; see "Chat needs a receipt").
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
|
|
@ -70,7 +71,11 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
|
||||||
the return path carries only a short `request_uri`, so `LocalReturnPath.MaxLength` stays 256.
|
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
|
- Signed in, membership `Suspended`: redirect to the client's `redirect_uri` with `error=access_denied` and
|
||||||
`error_description=The account is suspended.`
|
`error_description=The account is suspended.`
|
||||||
- Signed in with no membership, `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
|
- Signed in, not suspended, with no `ChatInvitedAtUtc` and a membership that is not `Active` (the chat tier before an invite):
|
||||||
|
`error=access_denied` with `error_description=Chat is by invitation. Open an invite link, then sign in, to chat.`
|
||||||
|
(`OidcEndpoints.NotInvitedDescription`). This follows the suspension and identity refusals and comes before the consent redirect,
|
||||||
|
so an uninvited account is never invited to agree. A desk token (every scope a desk scope) asks no invite.
|
||||||
|
- Signed in, invited or `Active`, with no membership or `Authenticated` or `PendingApproval` (the chat tier): treated like an active member for
|
||||||
sign-in to chat and nothing else. The token carries the same `openid profile` claims; the issuer writes no membership,
|
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)
|
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.
|
still asks for `Active` itself, so neither the session nor the token opens them.
|
||||||
|
|
@ -80,17 +85,96 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
|
||||||
accounts and the system names, the same 28 as MAS `banned_usernames`): `error=access_denied` with
|
accounts and the system names, the same 28 as MAS `banned_usernames`): `error=access_denied` with
|
||||||
`error_description=The account's Bifrost identity is reserved.` Creation refuses these names, but a row minted before
|
`error_description=The account's Bifrost identity is reserved.` Creation refuses these names, but a row minted before
|
||||||
that refusal may hold one and there is no rename path, so the issuer never vouches for a Mind's or a system's localpart. The refusal is at authorize only: a code or access token issued for such a row before this check deployed stays redeemable until it expires (minutes), and token and userinfo re-read membership, not the name. Whether any such row exists is not known from the code; one query of `UserAccounts` against the 28 names would say.
|
that refusal may hold one and there is no rename path, so the issuer never vouches for a Mind's or a system's localpart. The refusal is at authorize only: a code or access token issued for such a row before this check deployed stays redeemable until it expires (minutes), and token and userinfo re-read membership, not the name. Whether any such row exists is not known from the code; one query of `UserAccounts` against the 28 names would say.
|
||||||
|
- Signed in, not refused above, but no live consent receipt for the training notice version in force
|
||||||
|
(`TrainingNotice.Version`; none ever, withdrawn, or for another version): **not an OIDC error.** A 302 to
|
||||||
|
`/auth/bifrost/consent?returnUrl=<this request's own /connect/authorize?request_uri=... path>`. No code is issued and the
|
||||||
|
client's `redirect_uri` is not called. The consent page shows the notice and an Agree button; agreeing is a 303 back to
|
||||||
|
the `returnUrl`, which resumes the same parked request and issues the code. The parked request is single use and lives ten
|
||||||
|
minutes (it is spent only by an OpenIddict response, which the redirect is not), so a member who agrees after it has expired
|
||||||
|
gets MAS's error and starts the sign-in again, now with a receipt. This check comes last, so a suspended, identity-less or
|
||||||
|
reserved account is refused as before and never invited to agree.
|
||||||
- Otherwise: a code is issued.
|
- Otherwise: a code is issued.
|
||||||
- Token endpoint and userinfo: suspension is read again; an account suspended or deleted since gets `invalid_grant` (token) or 403 (userinfo). The logout reconciler ends the sessions of those same accounts; a chat-tier account is never logged out for lacking membership.
|
- Token endpoint and userinfo: suspension and the receipt are read again, on every call. An account suspended or deleted
|
||||||
|
since, or without a live current receipt since (withdrawn, or the notice version bumped), gets `invalid_grant` (token) or
|
||||||
|
403 `insufficient_access` (userinfo), with the description of the reason, and no claim. So an access token already in a
|
||||||
|
chat client's hands stops answering userinfo the moment the receipt goes, and answers again if the member agrees again
|
||||||
|
(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
|
||||||
|
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.
|
||||||
|
|
||||||
|
Where they learn it: the refused authorize lands them on the consent page, which states what agreement is for ("to speak in a
|
||||||
|
recorded room"), shows the notice, and returns them to chat sign-in when they agree. Nothing else prompts them: the
|
||||||
|
members page and the sign-in form do not nag, and an existing member who never opens chat is never asked.
|
||||||
|
|
||||||
|
What a Persona or Eureka sees:
|
||||||
|
|
||||||
|
| Step | Receipt live and current | No receipt, withdrawn, or another version |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Authorize | 302 to the client with `code` | 302 to `/auth/bifrost/consent?returnUrl=...`; no `code`, no `error` |
|
||||||
|
| Token | 200 with tokens | 400 `invalid_grant`, description "Agreement to the training notice in force is needed to speak in a recorded room." |
|
||||||
|
| Userinfo | 200 with `sub`, `preferred_username`, `name` | 403 `insufficient_access`; no claim in the body |
|
||||||
|
| Back-channel logout | none | Only when `BackchannelLogoutUri` is set (the reconciler runs): MAS is sent a logout for the subject and its authorizations are revoked, within one reconciler tick. Otherwise an already-open session is not ended; only new logins and userinfo calls are refused |
|
||||||
|
|
||||||
|
Deploy note: on the first reconciler tick, every subject holding a MAS authorization and no receipt (all existing chat users, admins included) is sent a back-channel logout and loses its authorizations. That is the ruling working as designed, not a fault; they return through the consent page.
|
||||||
|
|
||||||
|
The gate is on the token, so as built it covers every room the MAS login reaches. Which rooms are "recorded", and whether any
|
||||||
|
room is not, is the chat side's to say; the issuer does not know.
|
||||||
|
|
||||||
|
### Userinfo smoke notes for Eureka
|
||||||
|
|
||||||
|
Run against a deployed instance with two throwaway accounts that hold a membership of any kind: A has agreed on its consent
|
||||||
|
page, B has not (register without ticking the box, or click Withdraw). `$ISS` is the issuer, `$MAS` the registered client with
|
||||||
|
its secret, sessions are the cookie jars of a browser signed in as A or as B. Use the MAS client's own redirect URI.
|
||||||
|
|
||||||
|
1. Sign in as A through chat (MAS), or by hand (the first authorize answer is a 302 to `?request_uri=...`; follow that hop, the next answer is the code redirect): `GET $ISS/connect/authorize?response_type=code&client_id=...&redirect_uri=...&scope=openid%20profile&state=s&nonce=n&code_challenge=...&code_challenge_method=S256` with A's cookie.
|
||||||
|
Expect 302 to the redirect URI with `code` and `state`. Exchange it: `POST $ISS/connect/token` with `client_secret_basic`
|
||||||
|
and `grant_type=authorization_code`, `code`, `redirect_uri`, `code_verifier`. Expect 200 with `access_token` and `id_token`.
|
||||||
|
2. `GET $ISS/connect/userinfo` with `Authorization: Bearer <A's access_token>`. Expect 200 and exactly `sub`, `preferred_username`, `name`.
|
||||||
|
3. Same authorize request with B's cookie. Expect 302 whose `Location` starts `/auth/bifrost/consent?returnUrl=%2Fconnect%2Fauthorize%3Frequest_uri`,
|
||||||
|
and no `code` anywhere. (OpenIddict first parks the request and redirects to the same URL with a `request_uri`; follow
|
||||||
|
that one hop, the consent redirect is the next answer. A missing receipt ignores `prompt=none`: still a 302 to the consent page, never `consent_required`.) `GET` that Location with B's cookie: expect 200 and a page that contains
|
||||||
|
"to speak in a recorded room" and a form posting to `/auth/bifrost/consent/accept`.
|
||||||
|
4. Withdraw A: on A's consent page click Withdraw (a form `POST /auth/bifrost/consent/withdraw`, 303 back). Repeat step 2 with
|
||||||
|
A's old access token: expect 403, `WWW-Authenticate` with `error="insufficient_access"`, and no `sub` or `preferred_username`
|
||||||
|
in the body. Repeat step 1's authorize for A: expect the consent redirect of step 3, not a code.
|
||||||
|
5. A clicks Agree. Repeat step 1's authorize and token, then step 2: expect 302 with `code`, 200 tokens, 200 userinfo.
|
||||||
|
6. A code obtained before step 4 and exchanged after it: expect 400 `invalid_grant` and no `access_token`.
|
||||||
|
7. Control: with the receipt gone, B can still sign in to Bifrost, open `/App/Members` and vote; only chat is refused.
|
||||||
|
|
||||||
## Back-channel logout
|
## Back-channel logout
|
||||||
|
|
||||||
When `BackchannelLogoutUri` is set, a hosted reconciler (`OidcLogoutReconciler`) runs every 30 seconds. It lists the
|
When `BackchannelLogoutUri` is set, a hosted reconciler (`OidcLogoutReconciler`) runs every 30 seconds. It lists the
|
||||||
subjects holding valid authorizations of the MAS client; for each subject who may no longer chat (the same
|
subjects holding valid authorizations of the MAS client; for each subject who may no longer chat (the same
|
||||||
reading the token and userinfo endpoints use: membership `Suspended`, a deleted account, or a subject that is not an account id; an
|
reading the token and userinfo endpoints use: membership `Suspended`, a deleted account, a subject that is not an account id, or
|
||||||
account with no membership or a pending one may chat and is left alone) it POSTs one OIDC back-channel logout token to MAS, and only after a 2xx revokes that subject's authorizations,
|
no live receipt for the notice version in force; an account with no membership or a pending one that has agreed may chat and is left alone) it POSTs one OIDC back-channel logout token to MAS, and only after a 2xx revokes that subject's authorizations,
|
||||||
which also invalidates their tokens. Membership is never written by this path: any way of being suspended or deleted (admin
|
which also invalidates their tokens. Membership and receipts are never written by this path: any way of being suspended, deleted or withdrawn (admin
|
||||||
action, sync, a database edit) is covered because the work is derived from membership state.
|
action, sync, a database edit, the consent page) is covered because the work is derived from stored state.
|
||||||
|
|
||||||
The token is an ES256 JWT signed with the issuer key, header `typ` `logout+jwt`, with `iss` as the id_token carries it,
|
The token is an ES256 JWT signed with the issuer key, header `typ` `logout+jwt`, with `iss` as the id_token carries it,
|
||||||
`aud` the MAS client id, `sub` the account id, `iat`, `exp` two minutes later, a fresh `jti` and the
|
`aud` the MAS client id, `sub` the account id, `iat`, `exp` two minutes later, a fresh `jti` and the
|
||||||
|
|
@ -103,6 +187,10 @@ to 15 minutes; a 400 (token refused) or 404 (unknown provider ULID) is a configu
|
||||||
and retried at the 15 minute cap. Nothing is revoked until MAS answers 2xx. A restart loses the backoff and nothing
|
and retried at the 15 minute cap. Nothing is revoked until MAS answers 2xx. A restart loses the backoff and nothing
|
||||||
else: the authorizations table is the queue, so a later-set URI also catches up on earlier demotions.
|
else: the authorizations table is the queue, so a later-set URI also catches up on earlier demotions.
|
||||||
|
|
||||||
|
Without `BackchannelLogoutUri` none of this runs: suspension stops new chat tokens (the authorize, token and userinfo
|
||||||
|
endpoints refuse a suspended account; there is no refresh token, and MAS does not call userinfo) but does not end a chat session that is already live, which runs to its natural expiry, and the issuer logs one warning at
|
||||||
|
startup saying so. The other lever is MAS admin deactivation of the user (ops, not built here).
|
||||||
|
|
||||||
Tradeoff: delivery latency is up to one tick, and a member demoted and re-promoted inside one tick keeps their sessions.
|
Tradeoff: delivery latency is up to one tick, and a member demoted and re-promoted inside one tick keeps their sessions.
|
||||||
|
|
||||||
MAS verified at v1.28.0 (`crates/handlers/src/upstream_oauth2/backchannel_logout.rs`): the token is checked like an
|
MAS verified at v1.28.0 (`crates/handlers/src/upstream_oauth2/backchannel_logout.rs`): the token is checked like an
|
||||||
|
|
|
||||||
133
docs/passkeys.md
Normal file
133
docs/passkeys.md
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
# Passkeys: strong proof for unlinking a login
|
||||||
|
|
||||||
|
A Heimdall-backed member can enrol WebAuthn passkeys on `/Membership/LinkedAccounts` and use one as the strong proof that unlinking a provider login needs. Bifrost verifies the passkey; Heimdall accepts Bifrost's word through its app-asserted step-up route (`POST /v1/apps/bifrost/step-up`, Heimdall `docs/service-contract.md`, `docs/app-profiles/bifrost.md`). Scoping and the option comparison are in the handoff `strong-proof-scoping-20261113.md` (option 1a with the S1 sink).
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- Accounts that have a `HeimdallAccountId`: the accounts that can unlink at all. A Bifrost-native-only account (a native `BifrostIdentity` or GitHub sign-in) has no logins to unlink and gets no passkeys from this cut; the page shows it nothing.
|
||||||
|
- Unlink only. A passkey is not a sign-in method here.
|
||||||
|
|
||||||
|
## The library: Fido2NetLib (`Fido2` 4.3.3)
|
||||||
|
|
||||||
|
Decision: use `Fido2` 4.3.3 (NuGet id `Fido2`, repository `passwordless-lib/fido2-net-lib`) for every byte of WebAuthn parsing and verification. Bifrost hand-rolls no CBOR, COSE or signature code.
|
||||||
|
|
||||||
|
What was checked on 2026-11-13, against the package and the repository, not from memory:
|
||||||
|
|
||||||
|
| Question | Finding |
|
||||||
|
|---|---|
|
||||||
|
| Licence | MIT, in the nuspec (`<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`.
|
||||||
190
docs/ratatoskr-voting-auth.md
Normal file
190
docs/ratatoskr-voting-auth.md
Normal file
|
|
@ -0,0 +1,190 @@
|
||||||
|
# How a Ratatoskr voting module authenticates to Bifrost (design, no code)
|
||||||
|
|
||||||
|
Status: proposal, 2026-11-10, written by Heimdall (Self) against `origin/main` 276f611 (sections 1-13, citations as first read); section 14 and the corrections marked "e8e8fcc" in sections 1-13 are re-read against `origin/main` e8e8fcc. Decided 2026-11-11 by the steward of Bifrost for the read-only Desk feed (section 14); the cast scopes (`votes.cast`, `desk.answer`) stay gated by D1, D2 and D4. Docs only; nothing here is built or deployed.
|
||||||
|
Labels: **FACT** = read at the cited `file:line` at the base named for that section or citation, 276f611 unless it says e8e8fcc (paths under `src/Bifrost.Web/` unless written otherwise). **INFERENCE** = my reading, not stated by code. **EXTERNAL** = OpenIddict/ASP.NET behaviour I know from its documentation and did not run here; each one needs a probe before the cut (section 11).
|
||||||
|
Companion reads: `/opt/commons/handoff/bifrost-browser-voting-facts.md` (Eyes, at 416f11a; its Program.cs/OIDC lines still hold at 276f611, only `Features/Motions/MotionGovernanceService.cs` changed in between, in the close path), `heimdall-ratatoskr-sso-plan*.md`.
|
||||||
|
|
||||||
|
## 1. The problem in four facts
|
||||||
|
|
||||||
|
- FACT: a member's only Bifrost credential is the cookie `__Host-bifrost_session` (`Program.cs:189-200`; `Features/Shared/BifrostCookies.cs:10`). `__Host-` makes it host-only: chat.gamecult.org never holds it.
|
||||||
|
- FACT: the member API carries no CORS: the single CORS policy is the anonymous tally GET (`Features/ConceptVotes/ConceptTallyExport.cs:8-27`), so a JSON POST from the chat origin is blocked at preflight.
|
||||||
|
- FACT: Bifrost is an OIDC issuer with exactly one client, MAS, confidential, secret basic auth only, scopes `openid profile` (`Features/Oidc/OidcServiceCollectionExtensions.cs:39-46`; `Features/Oidc/OidcClientSeeder.cs:35-51` is the one MAS descriptor; startup deletes every other client, loop `:63-75`, all at e8e8fcc). No OpenIddict validation handler is registered (grep for `AddValidation` under `src` returns nothing), so no access token authenticates any `/api/*` route.
|
||||||
|
- FACT: there is no JSON read or cast API for Standard motions (Razor form POST with 302 and no receipt: `Features/Motions/MotionGovernanceService.cs:47-86`, `Pages/App/Motions/Index.cshtml.cs`); sealed-ballot motions have JSON endpoints but no list (`Program.cs:718-763`).
|
||||||
|
- INFERENCE: the access token chat holds today is Matrix's, minted by MAS after MAS authenticates the person at Bifrost (SSO plan section D). Bifrost's own access token goes to MAS, never to the browser. PR #24's "the OIDC access token Bifrost already issues to chat" is therefore not true as written: this design makes Bifrost issue a token to chat directly.
|
||||||
|
- FACT (deployment): Bifrost has no `Bifrost__Oidc__*` variable live, MAS is disabled, Synapse is its own password authority (`heimdall-ratatoskr-sso-plan-live-read-20261110.md` section 1). Everything below is for after OIDC is enabled; `Bifrost:Oidc` absent means the provider surface is not mapped (`docs/oidc-issuer.md:37`).
|
||||||
|
|
||||||
|
## 2. Proposal in one paragraph
|
||||||
|
|
||||||
|
Ratatoskr's voting module is a second OIDC client of Bifrost: **public, PKCE (S256), no secret**, redirect URI exactly one URL on https://chat.gamecult.org. It runs authorization-code + PKCE in a top-level redirect to Bifrost (so the person's existing `__Host-` session cookie is used first-party; chat never sees it), receives an **access token for audience `bifrost-votes` and scopes `votes.read` / `votes.cast` (10 minutes for cast scopes; `desk.read`: see section 14)**, keeps it in memory only, and sends it as `Authorization: Bearer` to a **new `/api/votes` surface that accepts bearer tokens and refuses cookies**. CORS on exactly two route groups (`/connect/token`, `/api/votes`) allows exactly `https://chat.gamecult.org`, no credentials. Everything else in Bifrost keeps its current cookie-only behaviour. The Persona/Mind signed path is untouched.
|
||||||
|
|
||||||
|
## 3. Client registration
|
||||||
|
|
||||||
|
- A second client entry beside MAS, from configuration (`Bifrost:Oidc:Clients:Ratatoskr:{ClientId,RedirectUri}`), seeded by the same startup seeder. FACT the seeder today builds one descriptor and deletes all others (`OidcClientSeeder.cs:33-75` at e8e8fcc); it needs to build two and delete the rest.
|
||||||
|
- `ClientType = Public`, no `ClientSecret`; permissions: authorization endpoint, token endpoint, authorization_code grant, response type `code`, scopes `profile`, `openid`, `votes.read`, `votes.cast`. PKCE is already required server-wide (`OidcServiceCollectionExtensions.cs:39`).
|
||||||
|
- `RedirectUri` is one absolute URL, compared exactly (OpenIddict does exact match; EXTERNAL). No wildcard, no localhost entry in production configuration; a dev client is a separate config file never deployed.
|
||||||
|
- FACT the token endpoint accepts only `client_secret_basic` (`OidcServiceCollectionExtensions.cs:45-46` clears and sets the list). EXTERNAL/needs probe: a public client authenticates by `client_id` alone and OpenIddict still accepts it with that list; if it does not, add `none` to the list for public clients only.
|
||||||
|
- Not in scope: dynamic registration, implicit/hybrid flows, a client secret in the browser. The MAS client and its flow do not change.
|
||||||
|
|
||||||
|
## 4. Scopes, audience, what a token carries
|
||||||
|
|
||||||
|
| Scope | Grants | Never grants |
|
||||||
|
|---|---|---|
|
||||||
|
| `openid`, `profile` | `sub` = `UserAccount.Id`, `preferred_username`, `name` (FACT `OidcEndpoints.cs:79-84`, `docs/oidc-issuer.md:55-61`) | email, Heimdall id, membership detail |
|
||||||
|
| `votes.read` | read motions the member may see, their own ballot status, results after close | other members' sealed ballots; weights of other members |
|
||||||
|
| `votes.cast` | cast/change a Standard vote; sealed commit and reveal for the token's own `sub` | anything in the next list |
|
||||||
|
|
||||||
|
Audience: access tokens for these scopes carry audience `bifrost-votes` (INFERENCE: OpenIddict `SetResources`/audience per request; EXTERNAL detail). `/api/votes` requires the audience **and** a vote scope. This stops the MAS client's access token (same issuer, same signing key, scopes `openid profile`) from being accepted on `/api/votes`, and a Ratatoskr token from being accepted by anything else.
|
||||||
|
|
||||||
|
**A token may never:** grant or change a role (`RoleAssignments`); set, read-modify or choose a weight (weight is `Membership.EffectiveVotingWeight` computed server-side at cast, `Domain/BifrostModels.cs:360-364`; the API request has no weight field and the receipt does not echo it); open, close or edit a motion; register or revoke Mind keys (`Program.cs:754-763`, moderator, cookie only); reach `/App/*`, `/eve/*`, `/connect/userinfo` beyond the three profile claims; mint another token (no refresh token, `docs/oidc-issuer.md:26`; no token-exchange); act for a different account (the voter is always `sub`, never a body field). These are enforced by structure, not by a deny list: the vote endpoints take the account from the principal and expose no parameter for the rest.
|
||||||
|
|
||||||
|
## 5. The bearer surface
|
||||||
|
|
||||||
|
- Register OpenIddict validation (local server) as a **named, non-default** authentication scheme `BifrostBearer` (the desk's credential is built on OpenIddict's fixed scheme name `OpenIddict.Validation.AspNetCore`; keep that name, and read `BifrostBearer` as the role). FACT the default scheme is Cookie (`Program.cs:189-200`), so every existing endpoint stays cookie-only and a bearer token cannot reach `/App`, `/api/sealed-motions` or `/eve` (a test pins it).
|
||||||
|
- New group `app.MapGroup("/api/votes")` with a policy `ActiveMember + scope + audience` whose `AuthenticationSchemes` is `BifrostBearer` only. A request that also carries the Bifrost session cookie is judged on the bearer alone, so the surface has no ambient credential: this is what removes CSRF from it (section 9).
|
||||||
|
- **Actor resolution is a new job.** FACT `CurrentBifrostActorAccessor` builds the actor from cookie claims (`BifrostIdentity`, `HeimdallAccountId`, GitHub `NameIdentifier`) and returns Anonymous when none are present (`Features/Shared/CurrentBifrostActorAccessor.cs:33-46`). A bearer principal has only `sub`, so existing services would see an anonymous actor. FACT `OidcEndpoints.ActiveMemberIdAsync` already resolves by `sub` and re-reads membership (`OidcEndpoints.cs:170`, used by `Features/Desk/DeskEndpoints.cs:105`; e8e8fcc). Proposal: one accessor path "principal with `sub` and `BifrostBearer` → load `UserAccount` + `Membership` by id", reusing that reading, and the `/api/votes` handlers call the existing services (`MotionGovernanceService.CastVoteAsync`, `SealedBallotService.CommitAsync/RevealAsync`) with that actor. No second vote implementation.
|
||||||
|
- Endpoints (names are a proposal, shapes belong to the cut spec): `GET /api/votes/motions`, `GET /api/votes/motions/{id}`, `PUT /api/votes/motions/{id}/ballot` `{choice, comment?}` (Standard), `POST …/commit` and `…/reveal` for sealed, `GET …/result`. FACT today's Standard cast returns silently when the motion is not open and throws on an unknown id (`MotionGovernanceService.cs:57-61`); the API wraps it with typed errors (404, 409 not open) rather than copying that.
|
||||||
|
- Errors are JSON 401/403/404/409/429, never a 302 to a sign-in page (FACT the cookie challenge redirects, `Program.cs:197`; a `fetch` client must get a status it can act on, e.g. 401 with `WWW-Authenticate: Bearer error="invalid_token"`).
|
||||||
|
- Persona/Mind path: FACT `POST /api/sealed-motions/{id}/mind` is anonymous, Ed25519-signed, rate-limited at 30/min/source and 4096 bytes (`Program.cs:767-809`). Unchanged. Minds never use this bearer flow; `/api/votes` has no Mind route, and a Persona's account is not a Ratatoskr login.
|
||||||
|
|
||||||
|
## 6. The flow (browser)
|
||||||
|
|
||||||
|
1. Ratatoskr voting module starts login: generates `state`, `nonce`, PKCE verifier/challenge (S256), stores them in `sessionStorage` for the one tab, navigates to `GET /connect/authorize` with `client_id`, exact `redirect_uri`, `scope=openid profile votes.read votes.cast`, `response_type=code`.
|
||||||
|
2. FACT authorize without a session challenges to `/auth/sign-in` and resumes via a short `request_uri` (`OidcEndpoints.cs:44-51`); with a session it admits any account that is not Suspended and has an identity (chat tier; membership is neither required nor written), otherwise `access_denied` (`OidcEndpoints.cs:53-70`). So the sign-in leg does not prove Active: the `/api/votes` and `/api/desk` surfaces re-check Active on every request, which is what makes this safe. Heimdall sign-in and the Bifrost session happen on the Bifrost host exactly as for MAS.
|
||||||
|
3. For a chat token without a live notice receipt (a desk or vote token needs none: the receipt gates the chat token only, Meta's ruling 2026-11-11), Bifrost first redirects to its training-notice consent page and resumes the parked request (`OidcEndpoints.cs:99-102`, e8e8fcc; not a grant to the client). Then, for cast scopes only, the per-client grant screen (section 7, D1); `desk.read` alone has none. Then 302 to `https://chat.gamecult.org/<redirect path>?code=…&state=…`.
|
||||||
|
4. The module checks `state`, immediately removes `code` and `state` from the address bar (`history.replaceState`), POSTs `/connect/token` (form: `grant_type=authorization_code`, `code`, `code_verifier`, `client_id`, `redirect_uri`) cross-origin. FACT the token endpoint re-reads the account and refuses with `invalid_grant` when `ChatRefusalAsync` says so: account missing, Suspended, or no live notice receipt (`OidcEndpoints.cs:107-120`, `ChatRefusalAsync` `:151`). It does not test Active; the per-request Active check is the new surfaces' own (section 14 D3).
|
||||||
|
5. The access token lives in a JS variable. Not `localStorage`, not `sessionStorage`, not IndexedDB. A page reload logs the module out of Bifrost votes (not out of chat) and the next vote action restarts step 1; with an existing Bifrost session it is two redirects and no typing.
|
||||||
|
|
||||||
|
INFERENCE on re-auth without refresh tokens: FACT none exist (`docs/oidc-issuer.md:26`). EXTERNAL: `prompt=none` in a hidden iframe is dead (third-party cookie rules), so renewal is a top-level redirect. That is the cost of a no-refresh-token design; see D3.
|
||||||
|
|
||||||
|
## 7. Consent screen: needed, because one hop is cheap and a vote is not
|
||||||
|
|
||||||
|
- FACT (e8e8fcc) there is no per-client grant consent: authorize redirects to `ConsentEndpoints` when the member has no live receipt (`OidcEndpoints.cs:99-102`, `Features/Registration/ConsentPage.cs`), but that is the training-notice receipt, a once-per-notice-version agreement independent of any client, not a grant to Ratatoskr. "Consent" below means the per-client grant unless it says notice. MAS needs no grant screen (it is the chat's own login service).
|
||||||
|
- Reasoning (INFERENCE): `votes.cast` lets whoever holds the token change the member's recorded vote. The member is already redirected to Bifrost, so a consent step costs one click and makes the grant visible and revocable in Bifrost, which is the only place it can be. Recommend **explicit consent for `votes.cast`, implicit for `votes.read`** (OpenIddict `ConsentType` per client or per authorization; EXTERNAL).
|
||||||
|
- Page content: client name ("Ratatoskr, chat.gamecult.org"), the account being used, the two powers in plain words ("see motions and your own ballots", "cast and change your votes"), Allow / Deny, a note that the grant lasts until revoked and tokens last 10 minutes (cast scopes). Served with `frame-ancestors 'none'` and `X-Frame-Options: DENY` (clickjacking). The consent wording for the chat side is `ratatoskr-consent-wording-draft-20261109.md` and is separate from this one.
|
||||||
|
- A stored authorization (OpenIddict permanent authorization) lets the next login skip the consent page; it is the object revoked in section 8.
|
||||||
|
|
||||||
|
## 8. Token lifetime, revocation, receipts, rate limits
|
||||||
|
|
||||||
|
**Lifetime.** FACT the code sets no access-token lifetime (only `RequestTokenLifetime` 10 min, `OidcServiceCollectionExtensions.cs:47`); INFERENCE/EXTERNAL OpenIddict's defaults apply (about 1 hour for access tokens, 5 min for codes). Set explicitly: **access token 10 minutes for cast scopes (`desk.read`: 60 minutes, section 14 D3)**, authorization code 60 seconds, id_token short. No refresh token. Because every `/api/votes` call re-reads the account and membership (section 5), the lifetime bounds token theft, not demotion.
|
||||||
|
|
||||||
|
**Revocation.**
|
||||||
|
- Demotion is immediate: each request re-checks Active (`ActiveMemberIdAsync`, `OidcEndpoints.cs:170`, e8e8fcc). A token held by a suspended member returns 403.
|
||||||
|
- Authorization cleanup: FACT `OidcLogoutReconciler` finds subjects who fail the chat-tier test (Suspended, account gone, or no live notice receipt) and hold authorizations of the MAS client and tells MAS (`docs/oidc-issuer.md:146-164`); it is MAS-specific (it needs `Clients:Mas:BackchannelLogoutUri`, `OidcLogoutReconciler.cs:180` at e8e8fcc) and nothing in it serves another client today. To be built: a derived-from-membership sweep that revokes the Ratatoskr/desk client's authorizations for non-Active subjects (no outbound POST needed; the client is ours). Membership is never written by it.
|
||||||
|
- Member-initiated revoke: needs a place to list and revoke grants. Not built; D4.
|
||||||
|
- Operator kill: with the seeder extended to more than one client, removing a client from configuration deletes it and its tokens at next start (the delete-others loop, `OidcClientSeeder.cs:63-75` at e8e8fcc, today spares only the MAS client); a runtime brake is D5.
|
||||||
|
|
||||||
|
**Receipts.** Every cast returns a JSON receipt, since Standard votes return none today (facts file section 5): `{motionId, choice, revision, castAtUtc, receiptId}`; sealed commit/reveal keep their existing receipt (`SealedBallotReceipt`, `SealedBallotService.cs`). Receipt contains no weight. The audit trail already records casts (`MotionGovernanceService.cs:86`); the audit row gains the client id and `jti` so a vote can be traced to the grant that cast it (INFERENCE: this is what "receipts" is for after an XSS: the member can see which client cast it).
|
||||||
|
|
||||||
|
**Rate limits.** FACT none on the member API (facts file section 5); the primitives exist: `FixedWindowBudget` keyed by account (`Features/ConceptVotes/ConceptVoteRateLimits.cs:14-24`) and a 429 + Retry-After pattern (`Program.cs:~773-774`, e8e8fcc). Proposal: per-account budgets — casts 30 per 10 min (the Mill's number), reads 120 per minute; token endpoint per source address; 429 with `Retry-After`. Numbers are D6.
|
||||||
|
|
||||||
|
## 9. Threat list
|
||||||
|
|
||||||
|
| Threat | Why it matters here | Answer |
|
||||||
|
|---|---|---|
|
||||||
|
| **Token theft by XSS in chat** | Ratatoskr renders other people's Matrix messages; a script in the chat origin can read an in-memory token or call the module's own functions | Token memory-only, 10 min (cast scopes), scopes limited to votes, audience-bound, no refresh. Honest limit: an XSS can **cast during the page's life** whatever the token allows; shortening and scoping bound it, they do not stop it. Mitigations to require: strict CSP on chat.gamecult.org, message sanitisation, and an in-module confirmation step for `votes.cast` that is rendered by the module itself (Ratatoskr's cut). D2 asks whether casting should demand a fresh re-authentication (`prompt=login`, `max_age`) for high-stakes motions. Sealed motions are better off: the salt is generated and held client-side, but a compromised page holds it too. |
|
||||||
|
| **CSRF** | A third-party page makes the member's browser vote | `/api/votes` accepts no cookie (section 5), so a forged cross-site request carries no credential. CORS has no `AllowCredentials`, so a credentialed cross-origin read is unreadable. The cookie surfaces keep their current protection (FACT: Razor antiforgery, `Index.cshtml:127,139`; the sealed API relies on SameSite and JSON binding, `Program.cs:718-763`) and are untouched. |
|
||||||
|
| **Authorization-code interception / injection** | Code arrives in a URL on the chat origin | PKCE S256 required (FACT `:39`), exact redirect match, codes single-use and 60 s, `state` checked, URL cleaned at once, `Referrer-Policy: no-referrer` on the callback page. |
|
||||||
|
| **Login CSRF / mix-up** | Attacker finishes a flow with their own code | `state` bound to the tab, `nonce` checked in the id_token, one issuer only. |
|
||||||
|
| **Replay** | A captured request resent | Token expiry; codes single-use; Standard cast is `PUT` and idempotent by `(motion, sub)` (FACT one row per member per motion, `MotionGovernanceService.cs:64-85`); sealed commit/reveal already carry `revision` and phase checks; the commitment binds the voter id (`docs/sealed-ballot-motion.md:22-26`). Replaying the same cast cannot double a vote. |
|
||||||
|
| **Token substitution** | MAS-bound token used at `/api/votes`, or a Ratatoskr token elsewhere | Audience + scope + named scheme (sections 4-5). |
|
||||||
|
| **Open redirect / redirect abuse** | | One exact redirect URI; Bifrost local return paths unchanged (FACT `Features/Shared/LocalReturnPath.cs:13-31`). |
|
||||||
|
| **Overreach by a demoted or compromised account** | Membership changes after issue | Per-request Active check; sweep revokes authorizations. |
|
||||||
|
| **CORS misread as security** | CORS stops browsers only | Not relied on for authorisation; it is an availability measure. Tokens authenticate; non-browser callers need a token. |
|
||||||
|
| **Consent phishing** | Look-alike client asks for `votes.cast` | One registered client; consent page names it and shows the redirect host. |
|
||||||
|
| **Scraping / vote spam** | | Rate limits (section 8); no list of other members' ballots exists. |
|
||||||
|
| **Clickjacking of consent/sign-in** | | `frame-ancestors 'none'` on Bifrost auth pages. |
|
||||||
|
| **Logout gap** | The Bifrost session ends but a token lives on: 10 min for cast scopes; up to 60 min for `desk.read` (section 14 D3) | Accepted; bounded by lifetime and the per-request Active check. For `desk.read` the Bifrost session can end while the token keeps feeding `/api/desk` for up to 60 minutes; accepted because the feed is read-only and every request re-checks Active. |
|
||||||
|
|
||||||
|
## 10. CORS, exactly
|
||||||
|
|
||||||
|
- A **second named policy**, separate from `ConceptTallies` (FACT that policy reads `ConceptVotes:AllowedOrigins`, `ConceptTallyExport.cs:13-27`, so reusing it would couple two features' origin lists): `WithOrigins("https://chat.gamecult.org")`, methods `GET, POST, PUT, OPTIONS`, headers `Authorization, Content-Type`, **no `AllowCredentials`**, no exposed headers except `Retry-After`, preflight cache bounded. Origin comes from configuration as one exact value; no wildcard, no subdomain pattern, no `null`.
|
||||||
|
- Applied by route metadata to `/connect/token` and `/api/votes/*` only. `/connect/authorize` is a top-level navigation and needs none; `/.well-known/*` is not fetched by the module (the client config is static). Every response under those routes carries `Vary: Origin` (the pattern the tally export already follows).
|
||||||
|
- Bifrost still sends no CORS headers for `/api/sealed-motions/*`, `/App`, `/eve`, `/connect/userinfo` (the facts file's blocker 1 stays closed there on purpose).
|
||||||
|
|
||||||
|
## 11. Probes owed before the cut spec (each is an EXTERNAL claim above)
|
||||||
|
|
||||||
|
1. A public client with no secret completes code exchange when `ClientAuthenticationMethods` holds only `client_secret_basic`.
|
||||||
|
2. Per-client explicit grant consent (D1) works with the request-caching path (`request_uri`) used at `OidcEndpoints.cs:44-51`, alongside the existing notice-receipt redirect (`:99-102`, e8e8fcc), which parks and resumes the same request.
|
||||||
|
3. Audience and scope reach the access token and the validation handler enforces them; the MAS client's token is refused at `/api/votes`.
|
||||||
|
4. Default token lifetimes before the explicit settings.
|
||||||
|
5. OpenIddict validation as a non-default scheme leaves cookie-default endpoints unchanged (test: bearer on `/App` and `/api/sealed-motions` is 302/401, as now).
|
||||||
|
6. CORS preflight on `/connect/token` through OpenIddict's passthrough (the endpoint is mapped as a minimal API at `OidcEndpoints.cs:35`).
|
||||||
|
7. (owed by D3) Per-audience lifetimes: `principal.SetAccessTokenLifetime` / `SetAuthorizationCodeLifetime` set at authorize give a `desk.read`-only request a 60-minute access token and a cast-scope request 10 minutes, and the token's `exp` shows it.
|
||||||
|
|
||||||
|
## 12. Questions as raised (decided in section 14)
|
||||||
|
|
||||||
|
Decided 2026-11-11 by the steward of Bifrost: D1-D7 below are answered in section 14; the questions are kept as asked and are not open.
|
||||||
|
|
||||||
|
For **Meta**:
|
||||||
|
- D1 Is explicit consent for `votes.cast` wanted (recommended) or is a first-party client implicit?
|
||||||
|
- D2 Should a vote on a high-stakes motion demand re-authentication (`prompt=login`) at cast time? Recommend yes for sealed commit and for any motion whose result moves money or roles; no for ordinary reads.
|
||||||
|
- D3 Accept that a 10-minute cast token with no refresh means a redirect round-trip to keep voting, or allow a refresh token (it widens theft impact; I recommend against).
|
||||||
|
|
||||||
|
For **Eureka** (platform/ops, MAS and deploy order):
|
||||||
|
- D4 Where does a member list and revoke grants (a Bifrost `/App` page)? Needed before `votes.cast` ships if consent is explicit.
|
||||||
|
- D5 Is a runtime brake wanted on the Ratatoskr client (disable without redeploy), and who holds it?
|
||||||
|
- D6 Rate-limit numbers, and whether they belong in configuration (recommended) or code.
|
||||||
|
- D7 Order against the MAS rollout: this design needs Bifrost OIDC live (it is not, section 1), and the two clients can ship separately; do voting tokens wait for MAS, or does voting go first as the first OIDC consumer? Recommend independent; the collision-and-import hazards in the SSO live read concern MAS only.
|
||||||
|
|
||||||
|
For **Ratatoskr (Void)**: the module owns the CSP, the in-module confirmation step, the callback page behaviour (section 6) and memory-only storage; this doc cannot enforce them from Bifrost's side.
|
||||||
|
|
||||||
|
## 13. What this deliberately does not do
|
||||||
|
|
||||||
|
No new identity: `sub` stays `UserAccount.Id`. No change to Heimdall, MAS, or the Mind key path. No weights or roles in tokens. No second vote implementation: the bearer surface is a thin projection of the existing services. No cookie sharing between chat and Bifrost, and no proxy on the chat origin pretending to hold one.
|
||||||
|
|
||||||
|
## 14. Decision record (steward, 2026-11-11)
|
||||||
|
|
||||||
|
Decided by the steward of Bifrost (the Persona), recorded by Heimdall (Self). Scope: the first consumer is the read-only Desk feed (scope `desk.read`, audience `bifrost-desk`, `docs/desk-feed-design.md`, draft PR #67), not votes. Each decision is the least-power, most-inspectable option that keeps exit (the member or operator can end it) and receipts (the act can be traced afterwards). Numbering: D1-D7 here are this document's (D1 consent, D2 re-auth, D3 token lifetime, D4 grant page, D5 brake, D6 rate limits, D7 ordering vs MAS); the "D1: `options_hash` covers everything shown" of the fork-desk answer-binding handoff is a different ruling and is not decided here.
|
||||||
|
|
||||||
|
**D1 consent (per-client grant).**
|
||||||
|
- Decision: explicit per-client grant consent stays REQUIRED for any scope that can cast or answer (`votes.cast`, `desk.answer`), as recommended in section 7. `desk.read` (read-only, the member's own account) needs no per-client grant screen: implicit. Two senses of "consent" exist and are kept apart: the training-notice receipt (every authorize already redirects to `ConsentEndpoints` without a live receipt, `OidcEndpoints.cs:99-102`, `Features/Registration/ConsentPage.cs`, e8e8fcc), which applies to all clients and is unchanged; and the per-client grant, which does not exist yet.
|
||||||
|
- Reasons: FACT (e8e8fcc) there is no per-client grant consent today: the only consent step is the notice receipt; a `desk.read` grant changes nothing, so a click would buy no protection; a cast changes a recorded vote or answer, so the member must see the grant.
|
||||||
|
- Keeps: exit is the revocable stored authorization (D4); receipts are the audit row carrying client id and `jti` (section 8).
|
||||||
|
- Probe owed: 2 (section 11), the grant screen beside the notice redirect on the parked-request path.
|
||||||
|
- Holder: the steward of Bifrost.
|
||||||
|
|
||||||
|
**D2 re-authentication.**
|
||||||
|
- Decision: yes (`prompt=login` at cast time) for sealed commit, and for answering or casting on any motion or fork whose result moves money or roles. Not needed for `desk.read`.
|
||||||
|
- Reasons: a stolen 10-minute token must not be enough to move money or roles; a read-only feed has nothing to protect that a fresh login would add.
|
||||||
|
- Keeps: exit, because the member re-proves the account each time; receipts, because the cast receipt follows a fresh authentication.
|
||||||
|
- Holder: the steward of Bifrost.
|
||||||
|
|
||||||
|
**D3 token lifetime and refresh.**
|
||||||
|
- Decision: NO refresh token, anywhere. Access token 10 minutes for the cast and answer scopes; 60 minutes for the read-only audience `bifrost-desk`. Authorization code 60 seconds. One client may request both audiences; the lifetime follows the requested scope set: a request containing any cast or answer scope gets 10 minutes, a `desk.read`-only request gets 60.
|
||||||
|
- Reasons: FACT the code sets no access-token lifetime (only `RequestTokenLifetime` 10 minutes, `OidcServiceCollectionExtensions.cs:47`, e8e8fcc), so the explicit values replace OpenIddict defaults. Every `/api/desk` request re-checks Active membership (`ActiveMemberIdAsync`, `OidcEndpoints.cs:170`, used by `Features/Desk/DeskEndpoints.cs:105`), so lifetime bounds only theft of a read-only credential, not demotion; a 10-minute token would force a redirect round trip into a polling feed. Not to be confused with `ChatRefusalAsync` (`OidcEndpoints.cs:151`), which the token and userinfo endpoints use for chat subjects and which refuses a Suspended account or one without a live notice receipt, not a non-Active one. A refresh token would outlive the redirect and widen theft impact.
|
||||||
|
- Per-audience lifetime is not built or proven: it would be set with `principal.SetAccessTokenLifetime` / `SetAuthorizationCodeLifetime` at authorize. Probe 7 (section 11) is owed before the cut.
|
||||||
|
- Keeps: exit, because demotion is immediate and the sweep (to be built, section 8) revokes grants of non-Active subjects; no long-lived secret exists to leak. Accepted gap: the Bifrost session can end while a `desk.read` token feeds `/api/desk` for up to 60 minutes; acceptable for a read-only feed because every request re-checks Active.
|
||||||
|
- Holder: the steward of Bifrost.
|
||||||
|
|
||||||
|
**D4 grant list and revoke page.**
|
||||||
|
- Decision: a member-facing page in `/App` that lists and revokes grants is a BLOCKING condition for shipping any cast or answer scope. It is not needed for `desk.read`, which is ended by the derived-from-membership sweep and by the operator brake (D5). Nothing further is decided here.
|
||||||
|
- Reasons: explicit consent (D1) without a place to withdraw it is half a control; a read-only grant ends with the sweep and the brake. Neither exists for a second client today: the sweep is to be built (`OidcLogoutReconciler` is MAS-specific, section 8), and the brake covers only the three `/connect` endpoints (D5).
|
||||||
|
- Keeps: exit (the page itself) before any scope that can act.
|
||||||
|
- Holder: the steward of Bifrost (the page is Bifrost code).
|
||||||
|
|
||||||
|
**D5 runtime brake.**
|
||||||
|
- Decision: yes. Reuse the existing marker-file brake of PR #50 (commit 5201508; `OidcGuardMiddleware`, `OidcGuard.cs:32`, `BrakeEngaged` at `OidcGuard.cs:71`, option `Bifrost:Oidc:BrakePath`, `Configuration/OidcIssuerOptions.cs:26`, `docs/oidc-issuer.md` "Limits, prune, brake") rather than a new mechanism. It is held by the Bifrost steward (the Persona).
|
||||||
|
- The brake is NOT per-client. FACT (e8e8fcc) the guard matches `/connect/authorize`, `/token`, `/userinfo` for all clients (`EndpointOf`, `OidcGuard.cs:64-68`), so engaging it also 503s MAS sign-in; it is registered only when `Bifrost:Oidc` is configured (`Program.cs:294-297`) and `BrakePath` lives under `Bifrost:Oidc`. The code PR must extend the guard's matching to `/api/desk` and must settle a desk-only deployment (a host running the desk without `Bifrost:Oidc` configured has no guard and no brake path; either the desk requires `Bifrost:Oidc`, which it does for its tokens, or the brake option moves). Not decided here: that settlement is the code PR's to bring back.
|
||||||
|
- Reasons: FACT the guard is checked per request (no restart) and treats an unreadable marker as engaged; no second brake, no second owner.
|
||||||
|
- Keeps: exit for the operator (delete the file to release; discovery and keys stay up, as the issuer test asserts); receipts in the 503 `temporarily_unavailable` answers and the guard's log line.
|
||||||
|
- Holder: the Bifrost steward holds the brake. FLAG, not decided: where the marker file lives on the host is Eureka's (ops) to name.
|
||||||
|
|
||||||
|
**D6 rate limits.**
|
||||||
|
- Decision: the numbers live in configuration, defaults: `desk.read` 120 requests per minute per account; casts 30 per 10 minutes per account (the Mill's number) when they exist. The token endpoint keeps the existing per-address budget (`OidcRateLimit`, `OidcGuard.cs:102`): that is ONE budget shared by authorize, token and userinfo together (`docs/oidc-issuer.md:187-188`), not a token-endpoint budget of its own.
|
||||||
|
- Reasons: FACT the member API has none today; the primitive `FixedWindowBudget` keyed by account exists (`ConceptVoteRateLimits.cs:14-24`) and the 429 plus `Retry-After` pattern too (`Program.cs:~773-774`, e8e8fcc; `RefuseAsync` in the guard). Config keeps the numbers inspectable and changeable without a build. Per-client budgets stay out, as in `docs/oidc-issuer.md` (the client id is public).
|
||||||
|
- Keeps: exit via the brake (D5); receipts via the 429 answers. The desk cut map's open point (a 429 has no refusal code in the contract, Q3 there) is not decided here.
|
||||||
|
- Holder: the steward of Bifrost.
|
||||||
|
|
||||||
|
**D7 ordering against MAS.**
|
||||||
|
- Decision: independent. A second client is seeded only when `Bifrost:Oidc:Clients:Ratatoskr` is configured. This is a code change, not existing behaviour: FACT (e8e8fcc) the seeder builds one MAS descriptor and its delete-others loop (`OidcClientSeeder.cs:63-75`) removes everything else. Constraint on the code PR: under the MAS-less or default configuration it adds nothing observable (no new client, route, scope or discovery change), so window B (cut stays ab89556) is not widened. `desk.read` is the first consumer. It needs Bifrost OIDC live, as MAS does.
|
||||||
|
- Reasons: nothing in this client touches the MAS client, the Heimdall path or the Mind key path; "seeded only when configured, removed when no longer configured" is the behaviour to build, and the loop must be changed to spare configured clients rather than only MAS.
|
||||||
|
- Keeps: exit, because removing the configuration section deletes the client and its tokens at next start (once built); no receipts needed beyond the audit rows above.
|
||||||
|
- Holder: the steward of Bifrost.
|
||||||
|
|
||||||
|
**Decided with the feed.** The Desk feed never carries answerer account ids (the door withholds them from a non-decider, `eureka-substrate:ruling:desk-read-visibility-withheld-ids`; Bifrost masks nothing it cannot read, and this supersedes the Bifrost mask that closed X3 of `docs/desk-feed-design.md`).
|
||||||
|
|
||||||
|
**Flags to other stewards.**
|
||||||
|
- Eureka: the Huginn door list and read wire and its audience policy are written in Huginn's `docs/desk-feed-door.md` (Huginn main 79d954c or later, with golden fixtures); the host path of the D5 marker is still open. The listing gate that implements the audience policy is NOT live on Huginn main (cut `cut-desk-feed-listing`): until it lands, the door returns every showable question to every reader, so no Mind that holds private questions goes behind a live receiver.
|
||||||
|
- Libby (CultLib steward), ruled 2026-11-11: ForkCard gains `raised_at`, which stays OUT of `options_hash` (that hash keeps its five members: title, context, options, recommendation, depends, so digests are unchanged) and is a REQUIRED card key, an RFC3339 string or nil; the card goes from 16 to 17 keys and its hex changes. This closes X1 and X2 of `docs/desk-feed-design.md` (X2 withdrawn).
|
||||||
|
|
||||||
|
**Who sees which card: Huginn's door (Eureka), not Bifrost.** The policy is written in Huginn's `docs/desk-feed-door.md` ("Listing"), and this note holds no copy of it: a fork is shown to a reader who is not on the call's `deciders` only while a listing record for it is in force; a decider sees every showable fork; a hidden fork reads as `fork_unknown`, with the same bytes as a fork that does not exist. Bifrost applies no audience rule of its own: it relays exactly what the door returns. Reads carry `subject` and `deciders` (no `authority`; that is only on an answer), so anyone who must see unlisted forks is put on the Mind's decider list in Bifrost's admin. Bifrost adds three acts on the desk path: the per-request Active membership check, the `desk.read` bearer (audience `bifrost-desk`), and nilling notes for a non-decider; they sit beside the two already built (the note strip for non-deciders and the configured-Mind 404). Bifrost does NOT filter by audience, hold any per-card visibility rule, or keep a second copy of the policy (two copies would drift). The card is opaque to Bifrost (its `raised_at` key and order are being re-pinned in CultLib), so it is relayed as the door sent it.
|
||||||
|
|
@ -11,7 +11,7 @@ This page scopes the three that did not exist, says where each lives, and record
|
||||||
| Rate limits and brake | `OidcGuardMiddleware` (`docs/oidc-issuer.md`) | Merged. Covers `/connect/*` only, not the register endpoint. |
|
| Rate limits and brake | `OidcGuardMiddleware` (`docs/oidc-issuer.md`) | Merged. Covers `/connect/*` only, not the register endpoint. |
|
||||||
| Reserved names | `BifrostIdentityService.IsReserved`, 28 names | Merged, at creation and at authorize. |
|
| Reserved names | `BifrostIdentityService.IsReserved`, 28 names | Merged, at creation and at authorize. |
|
||||||
| Chat tier, no vote | `Authenticated` / `PendingApproval` accounts chat and open no member or governance surface | Merged. |
|
| Chat tier, no vote | `Authenticated` / `PendingApproval` accounts chat and open no member or governance surface | Merged. |
|
||||||
| Suspension | `MembershipSuspensionService` | Merged. |
|
| Suspension | `MembershipSuspensionService` | Merged. The reason is `Membership.SuspensionReason`, written with the status change and its receipt, cleared on unsuspend, projected only to admins on the members page; the receipt (`AuditEvent.Detail`) holds no reason text. Receipts written before the column existed still hold their reasons as history; the member dashboard keeps filtering suspension receipts out. A Suspended row with no stored reason (suspended before the column existed) shows admins the fixed text "Suspended before reasons were recorded"; the old text is never read out of the receipt. An unsuspend still requires a reason, but nothing stores it. |
|
||||||
| CAPTCHA | `Features/Registration/RegistrationChallengeService` | Built here. |
|
| CAPTCHA | `Features/Registration/RegistrationChallengeService` | Built here. |
|
||||||
| Consent receipt | `ConsentReceipt`, `TrainingNotice` | Built here. |
|
| Consent receipt | `ConsentReceipt`, `TrainingNotice` | Built here. |
|
||||||
| Email verification | nowhere | Scoped below, not built. |
|
| Email verification | nowhere | Scoped below, not built. |
|
||||||
|
|
@ -80,10 +80,11 @@ raise the wait or lower the budget; do not add a visual or audio puzzle, which e
|
||||||
Lives in Bifrost: the account, the receipt and the registration are one transaction, and chat admission is Bifrost's
|
Lives in Bifrost: the account, the receipt and the registration are one transaction, and chat admission is Bifrost's
|
||||||
decision (`admission-is-bifrost-membership`).
|
decision (`admission-is-bifrost-membership`).
|
||||||
|
|
||||||
- Consent is optional. Registration succeeds with or without it; a receipt exists only if the person agreed. See
|
- Consent is optional at registration. Registration succeeds with or without it; a receipt exists only if the person
|
||||||
`training-notice.md` for why and for what the notice says.
|
agreed. It is not optional for chat: the OIDC chat sign-in needs a live receipt for the version in force
|
||||||
|
(`oidc-issuer.md`, Who may sign in). See `training-notice.md` for why and for what the notice says.
|
||||||
- Notice: `TrainingNotice.Version` (positive integer, no leading zeros, per the version rule in Heimdall's
|
- Notice: `TrainingNotice.Version` (positive integer, no leading zeros, per the version rule in Heimdall's
|
||||||
`answer-collector-consent.md`) and `TrainingNotice.Text`, served at `GET /auth/bifrost/notice`. Version 2 is in force.
|
`answer-collector-consent.md`) and `TrainingNotice.Text`, served at `GET /auth/bifrost/notice`. Version 1 is in force, and its text is frozen (a test pins its hash).
|
||||||
Changing the text is a version bump, never an edit in place. The text states that nothing from Discord is used.
|
Changing the text is a version bump, never an edit in place. The text states that nothing from Discord is used.
|
||||||
- Receipt: `ConsentReceipt` (account, notice version, `AcceptedAtUtc`, `WithdrawnAtUtc`). One live (not withdrawn)
|
- Receipt: `ConsentReceipt` (account, notice version, `AcceptedAtUtc`, `WithdrawnAtUtc`). One live (not withdrawn)
|
||||||
receipt per account and version; withdrawn rows stay as history. At registration an `acceptedNoticeVersion` equal to
|
receipt per account and version; withdrawn rows stay as history. At registration an `acceptedNoticeVersion` equal to
|
||||||
|
|
@ -91,7 +92,8 @@ decision (`admission-is-bifrost-membership`).
|
||||||
nothing; absent means no receipt.
|
nothing; absent means no receipt.
|
||||||
- Consent page: `GET /auth/bifrost/consent`, for any signed-in account (native, provider, existing). It shows the notice,
|
- Consent page: `GET /auth/bifrost/consent`, for any signed-in account (native, provider, existing). It shows the notice,
|
||||||
the account's state (no agreement, agreed to the current version, agreed to an older one, withdrawn) and the buttons
|
the account's state (no agreement, agreed to the current version, agreed to an older one, withdrawn) and the buttons
|
||||||
that apply: Withdraw whenever any receipt is live, Agree whenever none is live for the version in force (so an account
|
that apply (with a `returnUrl` query a refused chat sign-in sends, a local path only, Agree returns the member there):
|
||||||
|
Withdraw whenever any receipt is live, Agree whenever none is live for the version in force (so an account
|
||||||
on an older version sees both). `POST /auth/bifrost/consent/accept` and `POST /auth/bifrost/consent/withdraw` are form posts refused
|
on an older version sees both). `POST /auth/bifrost/consent/accept` and `POST /auth/bifrost/consent/withdraw` are form posts refused
|
||||||
with 403 unless they came from the site itself (the strict `RequestOriginGuard`), before anything is read or written.
|
with 403 unless they came from the site itself (the strict `RequestOriginGuard`), before anything is read or written.
|
||||||
Agree is idempotent; withdraw stamps `WithdrawnAtUtc` once and deletes nothing; agreeing again after a withdrawal writes
|
Agree is idempotent; withdraw stamps `WithdrawnAtUtc` once and deletes nothing; agreeing again after a withdrawal writes
|
||||||
|
|
|
||||||
|
|
@ -137,9 +137,10 @@ to one member account and the account to that one persona (`MindPersonas`, uniqu
|
||||||
cannot share the account and overwrite the first's ballot, and a registration race loses on the index). The trust is the moderator's: Bifrost cannot tell whether a registered public
|
cannot share the account and overwrite the first's ballot, and a registration race loses on the index). The trust is the moderator's: Bifrost cannot tell whether a registered public
|
||||||
key really belongs to the Mind.
|
key really belongs to the Mind.
|
||||||
|
|
||||||
**What a Mind holds.** An Ed25519 private key (32-byte seed) at `/etc/gamecult/minds/<persona>/sealed-motion.key`, mode 0400,
|
**What a Mind holds.** An Ed25519 private key (32-byte seed) at `/var/lib/mind-<persona>/sealed-motion.key`. The generator script writes it mode 0400 and the signer accepts 0400 or 0600.
|
||||||
owned by that Mind's own user, never in the mind store or a room. Eureka generates it on the host and prints only the public
|
It is owned by `mind-<persona>`, the Persona user, which is also the signer; never in the mind store or a room. Eureka generates it on the host and prints only the public
|
||||||
half; a moderator registers it. **Whoever can read that file can vote as that Mind.** Root on the host can; Bifrost cannot.
|
half. By rule, a moderator registers that public half only after the Persona shell, running as `mind-<persona>`, has signed a real `commit` envelope
|
||||||
|
(production domain `gamecult.sealed_intake.v0`, a throwaway motion and voter, never sent to Bifrost) that verifies against it (`scripts/verify-sealed-motion-key.sh` in gamecult-ops, which must print `PASS`). **Whoever can read that file can vote as that Mind.** Root on the host can; Bifrost cannot.
|
||||||
|
|
||||||
**Signing.** `tools/sealed-motion-sign.mjs` (`pubkey`, `commit`, `reveal`) reads the key file, checks its type, mode and owner,
|
**Signing.** `tools/sealed-motion-sign.mjs` (`pubkey`, `commit`, `reveal`) reads the key file, checks its type, mode and owner,
|
||||||
and prints the envelope; it posts nothing. `commit` also prints the ballot (candidate, reason, salt), which the Mind keeps in
|
and prints the envelope; it posts nothing. `commit` also prints the ballot (candidate, reason, salt), which the Mind keeps in
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,32 @@
|
||||||
# Training notice, version 2
|
# Training notice, version 1
|
||||||
|
|
||||||
Eureka proposed a tighter notice and listed five gaps in the receipt flow (PR #55). The steward (Heimdall) ruled on
|
The served text is `TrainingNotice.Text` and nothing else: this page records why it says what it says and what each gap in
|
||||||
2026-11-11. The served text is `TrainingNotice.Text` and nothing else: this page records why it says what it says and
|
the receipt flow became, and does not repeat the wording. Contract for the receipt and the export is in
|
||||||
what each gap became, and does not repeat the wording. Contract for the receipt and the export is in
|
`registration-gates.md`. What the receipt gates in chat is in `oidc-issuer.md`.
|
||||||
`registration-gates.md`.
|
|
||||||
|
|
||||||
## What version 2 changed from version 1
|
Version 1 is the first notice that will be live under that number, but the number has been used before: main carried a
|
||||||
|
version 1 with different words from #54 onward, and #58 labelled its drafts version 2. Receipts therefore do not migrate.
|
||||||
|
**The text is frozen as version 1**: a test pins its hash, so editing the words without bumping `TrainingNotice.Version`
|
||||||
|
fails a test. A reworded notice is version 2, with its own pinned hash.
|
||||||
|
|
||||||
| Version 1 | Version 2 |
|
## Before deploy
|
||||||
|
|
||||||
|
Migration `20261111120000_ClearLegacyConsentReceipts` deletes every row from `ConsentReceipts` when it runs, because
|
||||||
|
version 1 receipts were given to different words and must not count as agreement to these. Manual emptying is therefore only
|
||||||
|
a belt-and-braces check: confirm the table is empty after the migrate on any database that ever ran main at or after
|
||||||
|
`33be966`. Meta/ops must still confirm whether anything was deployed with receipts in it; if so, the people who agreed are
|
||||||
|
asked again on their next chat sign-in.
|
||||||
|
|
||||||
|
## What the notice says and why
|
||||||
|
|
||||||
|
| The notice says | Why |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| "Chat messages and activity" | Names what counts: the text of messages with time and room, tied to the account name. Not the email address, sign-in details or anything not posted. |
|
| What counts: the text of messages with time and room, tied to the account name. Not the email address, sign-in details or anything not posted. | Names the data instead of "messages and activity". |
|
||||||
| "train and evaluate AI models" | "that GameCult builds and runs". Whether a dataset or model may leave GameCult is Meta's call, still open (below); the notice makes no claim either way beyond what it says. |
|
| "that GameCult builds and runs" | Whether a dataset or model may leave GameCult is Meta's call, still open (below); the notice claims nothing either way. |
|
||||||
| "No Discord material is used" | "Nothing that came from Discord is used, in any form." Kept: `gamecult-chat:ruling:discord-taints-training`. Whether any path carries Discord content into a chat room is for the chat steward to confirm (not established here), and any that exists must be excluded from every set for the sentence to stay true. |
|
| "Nothing that came from Discord is used, in any form." | `gamecult-chat:ruling:discord-taints-training`. Whether any path carries Discord content into a chat room is for the chat steward to confirm (not established here), and any that exists must be excluded from every set for the sentence to stay true. |
|
||||||
| Consent required to register | Optional. See below. |
|
| "Agreement is needed to speak in a recorded room. You can have a GameCult account, see the members page and vote without agreeing." | Meta's ruling, 2026-11-11: the chat token needs a live receipt for the version in force; nothing else does. "to speak in a recorded room" is settled wording. |
|
||||||
| "withdraw at any time" with no door | Names the door: the consent page, while signed in. |
|
| "Lines you have already spoken stay: withdrawing deletes nothing." | Withdrawing ends future speaking and future training use; it recalls nothing. The sentence is on the page where the Agree button is (the consent page and the registration form both render the notice beside it), so nobody agrees believing they can unsay a line. |
|
||||||
| Silent on deletion | Says plainly that withdrawing deletes nothing and what it does and does not undo. |
|
| Names the door: the consent page, while signed in. | "Withdraw at any time" with no door is no promise. |
|
||||||
|
|
||||||
## Rulings on the five gaps
|
## Rulings on the five gaps
|
||||||
|
|
||||||
|
|
@ -29,24 +41,27 @@ what each gap became, and does not repeat the wording. Contract for the receipt
|
||||||
(not withdrawn) receipt for the version in force exists. After a bump, everyone is out until they agree again. The
|
(not withdrawn) receipt for the version in force exists. After a bump, everyone is out until they agree again. The
|
||||||
notice says so ("if the notice changes, its version changes and we ask again; until you agree to the new version, your
|
notice says so ("if the notice changes, its version changes and we ask again; until you agree to the new version, your
|
||||||
messages are not used"), and the consent page shows the person that their agreement is to an older version and
|
messages are not used"), and the consent page shows the person that their agreement is to an older version and
|
||||||
offers the new one. Nobody is emailed or prompted elsewhere; asking is the page's job, and silence means no.
|
offers the new one. Since the chat gate, a bump also stops new chat tokens for everyone until they agree (their next chat sign-in lands on that page; a session already open runs to its natural expiry unless `BackchannelLogoutUri` is set, when the 30 s reconciler ends it). Nobody is emailed or prompted elsewhere; asking is the page's job, and silence means no.
|
||||||
3. **Withdrawal had no CSRF check.** True. The session cookie's SameSite default is Lax, which already keeps a cross-site
|
3. **Withdrawal had no CSRF check.** True. The session cookie's SameSite default is Lax, which already keeps a cross-site
|
||||||
POST from carrying it, but nothing in the handler relied on that. Both state changes (agree, withdraw) are now
|
POST from carrying it, but nothing in the handler relied on that. Both state changes (agree, withdraw) are now
|
||||||
form POSTs refused with 403 unless they came from the site itself (`RequestOriginGuard`, the strict form), before
|
form POSTs refused with 403 unless they came from the site itself (`RequestOriginGuard`, the strict form), before
|
||||||
anything is read or written.
|
anything is read or written.
|
||||||
4. **Provider-created and existing accounts have no receipt.** Correct, and now stated as the rule: no receipt, no use.
|
4. **Provider-created and existing accounts have no receipt.** Correct, and now stated as the rule: no receipt, no use.
|
||||||
They can opt in on the consent page like anyone else, which is also the only way an existing member is asked.
|
Since the 2026-11-11 ruling it is also: no receipt, no chat token. They keep their account, the members page and their
|
||||||
|
votes, and learn it where it bites: the refused chat sign-in lands them on the consent page (`oidc-issuer.md`, Chat needs a
|
||||||
|
receipt). Nobody is emailed or prompted elsewhere.
|
||||||
5. **No export exists.** True. Every promise about use is a promise about code not written. The notice must not be
|
5. **No export exists.** True. Every promise about use is a promise about code not written. The notice must not be
|
||||||
treated as operative for real people until the export enforces the contract with a test that a withdrawn or
|
treated as operative for real people until the export enforces the contract with a test that a withdrawn or
|
||||||
never-agreed account's rows are absent (`registration-gates.md`, Consent receipt, Consumer). No deploy has put
|
never-agreed account's rows are absent (`registration-gates.md`, Consent receipt, Consumer). Confirm (Before deploy) that no
|
||||||
version 2 in front of anyone.
|
deploy has put an earlier version 1 in front of anyone.
|
||||||
|
|
||||||
## Consent is optional
|
## Consent is optional
|
||||||
|
|
||||||
Registration succeeds with or without agreement. A receipt exists only if the person agreed. The contract already
|
Registration succeeds with or without agreement. A receipt exists only if the person agreed. The account is not
|
||||||
excluded accounts without a receipt, so optional costs nothing in correctness; it costs training data, and it removes
|
conditioned on agreement, which removes the objection that agreement obtained as a condition of an account is not a free
|
||||||
the objection that agreement obtained as a condition of an account is not a free choice. This is the steward's ruling
|
choice; what agreement buys is speaking in a recorded room, and the form says so beside the checkbox. This is the
|
||||||
on Eureka's recommendation; Meta can overrule it. One consequence: the registration form no longer enforces the notice.
|
steward's ruling on Eureka's recommendation, and Meta's ruling of 2026-11-11 added the chat gate. One consequence: the
|
||||||
|
registration form does not enforce the notice.
|
||||||
|
|
||||||
## Still open for Meta
|
## Still open for Meta
|
||||||
|
|
||||||
|
|
@ -54,11 +69,10 @@ on Eureka's recommendation; Meta can overrule it. One consequence: the registrat
|
||||||
messages to answer them is covered. The notice is silent on both.
|
messages to answer them is covered. The notice is silent on both.
|
||||||
- Deletion of messages on request, who does it, and the contact words. The notice offers none.
|
- Deletion of messages on request, who does it, and the contact words. The notice offers none.
|
||||||
- Controller and contact, and minimum age. Nothing here addresses either.
|
- Controller and contact, and minimum age. Nothing here addresses either.
|
||||||
- Whether existing members should be asked to opt in beyond the consent page existing.
|
|
||||||
- Counsel's reading of consent under the law that applies to the people registering. Not researched here.
|
- Counsel's reading of consent under the law that applies to the people registering. Not researched here.
|
||||||
|
|
||||||
## What remains
|
## What remains
|
||||||
|
|
||||||
- A signed-out native account cannot withdraw until sign-in recovery exists.
|
- A signed-out native account cannot withdraw until sign-in recovery exists.
|
||||||
- No training export, so no operative use.
|
- No training export, so no operative use.
|
||||||
- Wording changes are a version bump with a new text; never edit version 2's text in place after it has been served.
|
- Wording changes are a version bump with a new text and a new pinned hash in `TrainingNoticeFrozenTests`; never edit a version's text in place; the frozen-hash test fails if you do.
|
||||||
|
|
|
||||||
|
|
@ -7,17 +7,22 @@
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="Bifrost.Web.Tests" />
|
||||||
|
<PackageReference Include="MessagePack" Version="3.1.12" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
|
||||||
|
<PackageReference Include="Fido2" Version="4.3.3" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
||||||
<!-- Direct pins lift transitive packages past their advisories; the lockfile holds the result. -->
|
<!-- Direct pins lift transitive packages past their advisories; the lockfile holds the result. -->
|
||||||
<PackageReference Include="Npgsql" Version="8.0.3" />
|
<PackageReference Include="Npgsql" Version="8.0.3" />
|
||||||
<PackageReference Include="System.Text.Json" Version="8.0.5" />
|
<PackageReference Include="System.Text.Json" Version="8.0.5" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
|
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
|
||||||
<PackageReference Include="OpenIddict.Server.AspNetCore" Version="7.7.1" />
|
<PackageReference Include="OpenIddict.Server.AspNetCore" Version="7.7.1" />
|
||||||
|
<PackageReference Include="OpenIddict.Validation.AspNetCore" Version="7.7.1" />
|
||||||
|
<PackageReference Include="OpenIddict.Validation.ServerIntegration" Version="7.7.1" />
|
||||||
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="7.7.1" />
|
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="7.7.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
namespace Bifrost.Web.Configuration;
|
|
||||||
|
|
||||||
public sealed class BridgeOptions
|
|
||||||
{
|
|
||||||
public const string SectionName = "Bridge";
|
|
||||||
|
|
||||||
public string LocalBridgeToken { get; init; } = string.Empty;
|
|
||||||
|
|
||||||
public bool HasLocalBridgeToken => !string.IsNullOrWhiteSpace(LocalBridgeToken);
|
|
||||||
}
|
|
||||||
|
|
@ -14,7 +14,11 @@ public sealed class HeimdallOptions
|
||||||
|
|
||||||
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
|
public string PatreonTierTitle { get; init; } = "Inner Sanctum";
|
||||||
|
|
||||||
public string AppSecret { get; init; } = string.Empty;
|
/// <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 PatronSupportIntakeSecret { get; init; } = string.Empty;
|
public string PatronSupportIntakeSecret { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
|
@ -39,4 +43,37 @@ public sealed class HeimdallOptions
|
||||||
IsConfigured &&
|
IsConfigured &&
|
||||||
EnablePatronSupportIntake &&
|
EnablePatronSupportIntake &&
|
||||||
!string.IsNullOrWhiteSpace(PatronSupportIntakeSecret);
|
!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<TierSnapshot> TierSnapshots => Set<TierSnapshot>();
|
||||||
|
|
||||||
public DbSet<MembershipInvitation> MembershipInvitations => Set<MembershipInvitation>();
|
public DbSet<ChatInvite> ChatInvites => Set<ChatInvite>();
|
||||||
|
|
||||||
public DbSet<Project> Projects => Set<Project>();
|
public DbSet<Project> Projects => Set<Project>();
|
||||||
|
|
||||||
|
|
@ -45,6 +45,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
|
|
||||||
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
public DbSet<ConsentReceipt> ConsentReceipts => Set<ConsentReceipt>();
|
||||||
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
public DbSet<MindKey> MindKeys => Set<MindKey>();
|
||||||
|
public DbSet<PasskeyCredential> PasskeyCredentials => Set<PasskeyCredential>();
|
||||||
|
|
||||||
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
public DbSet<MindNonce> MindNonces => Set<MindNonce>();
|
||||||
|
|
||||||
|
|
@ -136,23 +137,30 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
entity.Property(x => x.Label).HasMaxLength(120);
|
entity.Property(x => x.Label).HasMaxLength(120);
|
||||||
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
||||||
entity.HasIndex(x => new { x.MembershipId, x.Kind, x.IsCurrent });
|
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)
|
entity.HasOne(x => x.Membership)
|
||||||
.WithMany(x => x.TierSnapshots)
|
.WithMany(x => x.TierSnapshots)
|
||||||
.HasForeignKey(x => x.MembershipId);
|
.HasForeignKey(x => x.MembershipId);
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<MembershipInvitation>(entity =>
|
modelBuilder.Entity<ChatInvite>(entity =>
|
||||||
{
|
{
|
||||||
entity.HasIndex(x => x.NormalizedGitHubLogin).IsUnique();
|
entity.HasIndex(x => x.TokenHash).IsUnique();
|
||||||
entity.Property(x => x.GitHubLogin).HasMaxLength(120);
|
entity.Property(x => x.TokenHash).HasMaxLength(64);
|
||||||
entity.Property(x => x.NormalizedGitHubLogin).HasMaxLength(120);
|
entity.Property(x => x.Note).HasMaxLength(500);
|
||||||
entity.HasOne(x => x.IssuedByUserAccount)
|
// 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>()
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey(x => x.IssuedByUserAccountId)
|
.HasForeignKey(x => x.IssuedByUserAccountId)
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
entity.HasOne(x => x.AcceptedByUserAccount)
|
entity.HasOne<UserAccount>()
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey(x => x.AcceptedByUserAccountId)
|
.HasForeignKey(x => x.RedeemedByUserAccountId)
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -333,6 +341,16 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.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 =>
|
modelBuilder.Entity<MindKey>(entity =>
|
||||||
{
|
{
|
||||||
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
entity.HasIndex(x => new { x.PersonaId, x.PublicKey }).IsUnique();
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like ConsentReceiptsOneLivePerVersion: no dotnet-ef on the authoring host; the snapshot was edited to match.
|
||||||
|
// Reasons already written to AuditEvent.Detail stay there as history; new ones live only in this admin-read column.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261111110000_AddMembershipSuspensionReason")]
|
||||||
|
public partial class AddMembershipSuspensionReason : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(name: "SuspensionReason", table: "Memberships", type: "text", nullable: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(name: "SuspensionReason", table: "Memberships");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddMembershipSuspensionReason: data only, so no schema change and the snapshot is untouched.
|
||||||
|
// Notice v1 was reused for new words, so any receipt written against the earlier v1 text must not count as agreement
|
||||||
|
// to these. Every row goes; people who agreed are asked again on their next chat sign-in.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261111120000_ClearLegacyConsentReceipts")]
|
||||||
|
public partial class ClearLegacyConsentReceipts : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.Sql("DELETE FROM \"ConsentReceipts\";");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
// Deleted agreements cannot be restored, and must not be.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,48 @@
|
||||||
|
using System;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddConsentReceipts: no dotnet-ef on the authoring host; the snapshot was edited to match. Additive only.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261113120000_AddPasskeyCredentials")]
|
||||||
|
public partial class AddPasskeyCredentials : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "PasskeyCredentials",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,216 @@
|
||||||
|
using System;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Scaffolded by IMigrationsScaffolder against the previous snapshot (no dotnet-ef on the authoring host), the designer file dropped and
|
||||||
|
// the snapshot edited by hand to match, like AddPasskeyCredentials. Additive only; Down drops what Up adds.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114120000_AddAccountMerges")]
|
||||||
|
public partial class AddAccountMerges : Migration
|
||||||
|
{
|
||||||
|
/// <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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddAccountMerges, the snapshot edited to match. Additive: the saga's columns on AccountMerges. Down is
|
||||||
|
// roll-forward only, like AddAccountMerges: it drops the Heimdall idempotency keys and the consent record, so it refuses while
|
||||||
|
// any merge row exists (heimdall-body:ruling:merge-roll-forward-only).
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114130000_AddAccountMergeSaga")]
|
||||||
|
public partial class AddAccountMergeSaga : Migration
|
||||||
|
{
|
||||||
|
private static readonly string[] Columns =
|
||||||
|
[
|
||||||
|
"HeimdallMoveId", "HeimdallReverseMoveId", "SealedProofs", "PreviewDigest", "ConfirmedByUserAccountId", "ConfirmedUtc",
|
||||||
|
"SurvivorProofProvider", "FoldedProofProviders", "ProofFromTier", "ProofToTier", "MovedIdentityIds", "Attempts",
|
||||||
|
"NextAttemptUtc", "LastOutcome", "UndoRequestedUtc", "ReversedUtc"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddAccountMergeSaga (no dotnet-ef on the authoring host), the snapshot edited to match. Additive: one table of
|
||||||
|
// acks, the only fact a notice reader adds; the notices themselves are derived from AccountMerges. Down may drop it: it holds only acks.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261114140000_AddAccountMergeNoticeAcks")]
|
||||||
|
public partial class AddAccountMergeNoticeAcks : Migration
|
||||||
|
{
|
||||||
|
/// <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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
105
src/Bifrost.Web/Data/Migrations/20261127120000_AddChatInvites.cs
Normal file
105
src/Bifrost.Web/Data/Migrations/20261127120000_AddChatInvites.cs
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
// Hand-written like AddAccountMergeNoticeAcks (no dotnet-ef on the authoring host), the snapshot edited to match.
|
||||||
|
// MembershipInvitations (keyed to a GitHub login, matched only on a GitHub sign-in) is dropped: the live table held zero rows
|
||||||
|
// when this was written (read 2026-11-27 on the production database), so nothing is carried over. Down recreates the empty table.
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261127120000_AddChatInvites")]
|
||||||
|
public partial class AddChatInvites : Migration
|
||||||
|
{
|
||||||
|
/// <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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Data.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(BifrostDbContext))]
|
||||||
|
[Migration("20261203120000_DropAccountMergeTables")]
|
||||||
|
public partial class DropAccountMergeTables : Migration
|
||||||
|
{
|
||||||
|
/// <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).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -821,6 +821,9 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("SuspensionReason")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
b.Property<Guid>("UserAccountId")
|
b.Property<Guid>("UserAccountId")
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
|
@ -832,51 +835,52 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.ToTable("Memberships");
|
b.ToTable("Memberships");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<DateTimeOffset?>("AcceptedAtUtc")
|
b.Property<DateTimeOffset>("ExpiresAtUtc")
|
||||||
.HasColumnType("timestamp with time zone");
|
.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")
|
b.Property<DateTimeOffset>("IssuedAtUtc")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<Guid?>("IssuedByUserAccountId")
|
b.Property<Guid?>("IssuedByUserAccountId")
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<string>("NormalizedGitHubLogin")
|
b.Property<string>("Note")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasMaxLength(120)
|
.HasMaxLength(500)
|
||||||
.HasColumnType("character varying(120)");
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
b.Property<string>("Notes")
|
b.Property<DateTimeOffset?>("RedeemedAtUtc")
|
||||||
.IsRequired()
|
.IsConcurrencyToken()
|
||||||
.HasColumnType("text");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid?>("RedeemedByUserAccountId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<DateTimeOffset?>("RevokedAtUtc")
|
b.Property<DateTimeOffset?>("RevokedAtUtc")
|
||||||
|
.IsConcurrencyToken()
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("TokenHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
b.HasIndex("AcceptedByUserAccountId");
|
|
||||||
|
|
||||||
b.HasIndex("IssuedByUserAccountId");
|
b.HasIndex("IssuedByUserAccountId");
|
||||||
|
|
||||||
b.HasIndex("NormalizedGitHubLogin")
|
b.HasIndex("RedeemedByUserAccountId");
|
||||||
|
|
||||||
|
b.HasIndex("TokenHash")
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
|
|
||||||
b.ToTable("MembershipInvitations");
|
b.ToTable("ChatInvites");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
||||||
|
|
@ -1333,6 +1337,11 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
|
|
||||||
b.HasIndex("MembershipId", "Kind", "IsCurrent");
|
b.HasIndex("MembershipId", "Kind", "IsCurrent");
|
||||||
|
|
||||||
|
b.HasIndex("MembershipId")
|
||||||
|
.IsUnique()
|
||||||
|
.HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
|
||||||
|
.HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||||
|
|
||||||
b.ToTable("TierSnapshots");
|
b.ToTable("TierSnapshots");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -1352,6 +1361,9 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
.HasMaxLength(120)
|
.HasMaxLength(120)
|
||||||
.HasColumnType("character varying(120)");
|
.HasColumnType("character varying(120)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("ChatInvitedAtUtc")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<DateTimeOffset>("CreatedAtUtc")
|
b.Property<DateTimeOffset>("CreatedAtUtc")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
|
@ -1467,6 +1479,59 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.ToTable("ConsentReceipts");
|
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 =>
|
modelBuilder.Entity("Bifrost.Web.Domain.MindKey", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
|
|
@ -2180,6 +2245,17 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Navigation("UserAccount");
|
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 =>
|
modelBuilder.Entity("Bifrost.Web.Domain.MemberProfile", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
b.HasOne("Bifrost.Web.Domain.UserAccount", "UserAccount")
|
||||||
|
|
@ -2202,21 +2278,17 @@ namespace Bifrost.Web.Data.Migrations
|
||||||
b.Navigation("UserAccount");
|
b.Navigation("UserAccount");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.MembershipInvitation", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.ChatInvite", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "AcceptedByUserAccount")
|
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||||
.WithMany()
|
|
||||||
.HasForeignKey("AcceptedByUserAccountId")
|
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
|
||||||
|
|
||||||
b.HasOne("Bifrost.Web.Domain.UserAccount", "IssuedByUserAccount")
|
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey("IssuedByUserAccountId")
|
.HasForeignKey("IssuedByUserAccountId")
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
|
|
||||||
b.Navigation("AcceptedByUserAccount");
|
b.HasOne("Bifrost.Web.Domain.UserAccount", null)
|
||||||
|
.WithMany()
|
||||||
b.Navigation("IssuedByUserAccount");
|
.HasForeignKey("RedeemedByUserAccountId")
|
||||||
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
modelBuilder.Entity("Bifrost.Web.Domain.Motion", b =>
|
||||||
|
|
|
||||||
|
|
@ -264,6 +264,9 @@ public sealed class UserAccount
|
||||||
|
|
||||||
public DateTimeOffset LastSeenAtUtc { get; set; }
|
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 MemberProfile? MemberProfile { get; set; }
|
||||||
|
|
||||||
public Membership? Membership { get; set; }
|
public Membership? Membership { get; set; }
|
||||||
|
|
@ -334,6 +337,9 @@ public sealed class Membership
|
||||||
|
|
||||||
public MembershipStatus Status { get; set; } = MembershipStatus.Authenticated;
|
public MembershipStatus Status { get; set; } = MembershipStatus.Authenticated;
|
||||||
|
|
||||||
|
/// <summary>Why an admin suspended the account; set and cleared only by <c>MembershipSuspensionService</c> and projected only to admins.</summary>
|
||||||
|
public string? SuspensionReason { get; set; }
|
||||||
|
|
||||||
public bool IsPlatformAdmin { get; set; }
|
public bool IsPlatformAdmin { get; set; }
|
||||||
|
|
||||||
public bool CanManageProjects { get; set; }
|
public bool CanManageProjects { get; set; }
|
||||||
|
|
@ -404,29 +410,30 @@ public sealed class TierSnapshot
|
||||||
public Membership Membership { get; set; } = null!;
|
public Membership Membership { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class MembershipInvitation
|
/// <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 Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
public string GitHubLogin { get; set; } = string.Empty;
|
/// <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 NormalizedGitHubLogin { get; set; } = string.Empty;
|
public string Note { get; set; } = string.Empty;
|
||||||
|
|
||||||
public Guid? IssuedByUserAccountId { get; set; }
|
public Guid? IssuedByUserAccountId { get; set; }
|
||||||
|
|
||||||
public Guid? AcceptedByUserAccountId { get; set; }
|
|
||||||
|
|
||||||
public DateTimeOffset IssuedAtUtc { get; set; }
|
public DateTimeOffset IssuedAtUtc { get; set; }
|
||||||
|
|
||||||
public DateTimeOffset? AcceptedAtUtc { get; set; }
|
public DateTimeOffset ExpiresAtUtc { get; set; }
|
||||||
|
|
||||||
|
public Guid? RedeemedByUserAccountId { get; set; }
|
||||||
|
|
||||||
|
public DateTimeOffset? RedeemedAtUtc { get; set; }
|
||||||
|
|
||||||
public DateTimeOffset? RevokedAtUtc { get; set; }
|
public 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
|
public sealed class Project
|
||||||
|
|
@ -1174,6 +1181,41 @@ public sealed class ConsentReceipt
|
||||||
public UserAccount? UserAccount { get; set; }
|
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>
|
/// <summary>A Mind's registered Ed25519 public key. Bifrost never holds a private key.</summary>
|
||||||
public sealed class MindKey
|
public sealed class MindKey
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -1,271 +0,0 @@
|
||||||
using Bifrost.Web.Data;
|
|
||||||
using Bifrost.Web.Domain;
|
|
||||||
using Bifrost.Web.Features.Shared;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Bridge;
|
|
||||||
|
|
||||||
public sealed class AgentDispatchRunService(
|
|
||||||
BifrostDbContext dbContext,
|
|
||||||
AuditTrailService auditTrailService,
|
|
||||||
TimeProvider timeProvider)
|
|
||||||
{
|
|
||||||
public async Task<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);
|
|
||||||
|
|
@ -1,194 +0,0 @@
|
||||||
using Bifrost.Web.Data;
|
|
||||||
using Bifrost.Web.Domain;
|
|
||||||
using Bifrost.Web.Features.Shared;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Bridge;
|
|
||||||
|
|
||||||
public sealed class AgentTransportReceiptService(
|
|
||||||
BifrostDbContext dbContext,
|
|
||||||
AuditTrailService auditTrailService,
|
|
||||||
TimeProvider timeProvider)
|
|
||||||
{
|
|
||||||
public async Task<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);
|
|
||||||
|
|
@ -1,629 +0,0 @@
|
||||||
using Bifrost.Web.Data;
|
|
||||||
using Bifrost.Web.Domain;
|
|
||||||
using Bifrost.Web.Features.Membership;
|
|
||||||
using Bifrost.Web.Features.Shared;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Bridge;
|
|
||||||
|
|
||||||
public sealed class BridgeActionService(
|
|
||||||
BifrostDbContext dbContext,
|
|
||||||
AuditTrailService auditTrailService,
|
|
||||||
TimeProvider timeProvider)
|
|
||||||
{
|
|
||||||
private const string AgentTransportRequestSourceKind = "bifrost_agent_transport_request";
|
|
||||||
private const string GovernanceTopicSourceKind = "bifrost_governance_topic";
|
|
||||||
private const string LegacyGovernanceTopicSourceKind = "governance_topic";
|
|
||||||
|
|
||||||
public async Task<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);
|
|
||||||
|
|
@ -1,190 +0,0 @@
|
||||||
using Bifrost.Web.Data;
|
|
||||||
using Bifrost.Web.Domain;
|
|
||||||
using Bifrost.Web.Features.Shared;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Bridge;
|
|
||||||
|
|
||||||
public sealed class GovernanceActivityReceiptService(
|
|
||||||
BifrostDbContext dbContext,
|
|
||||||
AuditTrailService auditTrailService,
|
|
||||||
TimeProvider timeProvider)
|
|
||||||
{
|
|
||||||
public async Task<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,13 +80,31 @@ public sealed class ConceptAppraisalService(
|
||||||
? string.Empty
|
? string.Empty
|
||||||
: NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret);
|
: 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);
|
var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken);
|
||||||
if (existing is not null)
|
if (existing is not null)
|
||||||
{
|
{
|
||||||
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
|
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
var row = new ConceptAppraisal
|
dbContext.ConceptAppraisals.Add(new ConceptAppraisal
|
||||||
{
|
{
|
||||||
SubjectId = subject.Id,
|
SubjectId = subject.Id,
|
||||||
VoterKey = voter.Key,
|
VoterKey = voter.Key,
|
||||||
|
|
@ -95,26 +113,9 @@ public sealed class ConceptAppraisalService(
|
||||||
UserAccountId = voter.UserAccountId,
|
UserAccountId = voter.UserAccountId,
|
||||||
NetworkTag = tag,
|
NetworkTag = tag,
|
||||||
CastAtUtc = timeProvider.GetUtcNow()
|
CastAtUtc = timeProvider.GetUtcNow()
|
||||||
};
|
});
|
||||||
dbContext.ConceptAppraisals.Add(row);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
return CastResult.Recorded;
|
||||||
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(
|
public async Task<bool> RetractAsync(
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,13 @@ using System.Text.Json.Serialization;
|
||||||
namespace Bifrost.Web.Features.Desk;
|
namespace Bifrost.Web.Features.Desk;
|
||||||
|
|
||||||
// The fork-desk documents Bifrost reads or writes, spelled as CultLib's contracts/cultnet/governance/fork-card.md
|
// The fork-desk documents Bifrost reads or writes, spelled as CultLib's contracts/cultnet/governance/fork-card.md
|
||||||
// (commit de8a062a) spells them: snake_case keys, every key written (nil where absent), declared in the
|
// (commit d3025d3c) spells them: snake_case keys, every key written (nil where absent), declared in the
|
||||||
// contract's key order. Bifrost authors only DeskRefusal and DeskUnavailable. AnswerRequest is the client's body;
|
// contract's key order. Bifrost authors only DeskRefusal and DeskUnavailable. AnswerRequest is the client's body;
|
||||||
// ForkCard, DeskAnswerDocument and AnswerResult are Huginn's documents, typed here so they pass through unchanged.
|
// DeskAnswerDocument, ForkList and AnswerResult are Huginn's documents, typed here so they pass through unchanged.
|
||||||
|
// The card (gamecult.fork.card.v0) is deliberately NOT typed: the Huginn door owns what a reader's card holds (the
|
||||||
|
// decider view carries ids, the non-decider view withholds them and keeps decider_count), and Bifrost neither reads
|
||||||
|
// nor edits it, so it is an opaque JsonElement that keeps every key, key order and integer. The door refuses a float,
|
||||||
|
// a binary or an extension value anywhere in a reply (the contract has none), so no number is ever rewritten.
|
||||||
|
|
||||||
public static class DeskSchemas
|
public static class DeskSchemas
|
||||||
{
|
{
|
||||||
|
|
@ -53,32 +57,6 @@ public sealed record DeskUnavailable(
|
||||||
[property: JsonPropertyName("error")] string Error,
|
[property: JsonPropertyName("error")] string Error,
|
||||||
[property: JsonPropertyName("retryAfterSeconds")] int? RetryAfterSeconds);
|
[property: JsonPropertyName("retryAfterSeconds")] int? RetryAfterSeconds);
|
||||||
|
|
||||||
public sealed record ForkOption(
|
|
||||||
[property: JsonPropertyName("id")] string Id,
|
|
||||||
[property: JsonPropertyName("text")] string Text);
|
|
||||||
|
|
||||||
public sealed record ForkRef(
|
|
||||||
[property: JsonPropertyName("kind")] string Kind,
|
|
||||||
[property: JsonPropertyName("id")] string Id);
|
|
||||||
|
|
||||||
public sealed record ForkCard(
|
|
||||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
|
||||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
|
||||||
[property: JsonPropertyName("title")] string Title,
|
|
||||||
[property: JsonPropertyName("context")] string Context,
|
|
||||||
[property: JsonPropertyName("options")] ForkOption[] Options,
|
|
||||||
[property: JsonPropertyName("recommendation")] string Recommendation,
|
|
||||||
[property: JsonPropertyName("depends")] string[] Depends,
|
|
||||||
[property: JsonPropertyName("leans")] string? Leans,
|
|
||||||
[property: JsonPropertyName("flag")] string? Flag,
|
|
||||||
[property: JsonPropertyName("raised_in")] ForkRef? RaisedIn,
|
|
||||||
[property: JsonPropertyName("deciders")] string[] Deciders,
|
|
||||||
[property: JsonPropertyName("status")] string Status,
|
|
||||||
[property: JsonPropertyName("ruling")] string? Ruling,
|
|
||||||
[property: JsonPropertyName("ruled_from")] string[] RuledFrom,
|
|
||||||
[property: JsonPropertyName("order")] long Order,
|
|
||||||
[property: JsonPropertyName("options_hash")] string OptionsHash);
|
|
||||||
|
|
||||||
// One stored answer: Counted, Revision, Retraction or Refused, told apart by Outcome and Code.
|
// One stored answer: Counted, Revision, Retraction or Refused, told apart by Outcome and Code.
|
||||||
public sealed record DeskAnswerDocument(
|
public sealed record DeskAnswerDocument(
|
||||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||||
|
|
@ -94,7 +72,9 @@ public sealed record DeskAnswerDocument(
|
||||||
[property: JsonPropertyName("answered_at")] string AnsweredAt,
|
[property: JsonPropertyName("answered_at")] string AnsweredAt,
|
||||||
[property: JsonPropertyName("received_at")] string ReceivedAt,
|
[property: JsonPropertyName("received_at")] string ReceivedAt,
|
||||||
[property: JsonPropertyName("claim_in_future")] bool ClaimInFuture,
|
[property: JsonPropertyName("claim_in_future")] bool ClaimInFuture,
|
||||||
[property: JsonPropertyName("answerer")] string Answerer,
|
// Nil in a non-decider's view (Huginn withholds the ids). The key is required, and the door's wire walker (Closed in
|
||||||
|
// UnixSocketDeskDoor) is the one owner of that: a missing key is a door fault, never a nil Bifrost invented.
|
||||||
|
[property: JsonPropertyName("answerer")] string? Answerer,
|
||||||
[property: JsonPropertyName("authority")] string Authority,
|
[property: JsonPropertyName("authority")] string Authority,
|
||||||
[property: JsonPropertyName("request_id")] string RequestId);
|
[property: JsonPropertyName("request_id")] string RequestId);
|
||||||
|
|
||||||
|
|
@ -103,11 +83,12 @@ public sealed record ForkRecord(
|
||||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
[property: JsonPropertyName("fork_id")] string ForkId,
|
||||||
[property: JsonPropertyName("options_hash")] string OptionsHash,
|
[property: JsonPropertyName("options_hash")] string OptionsHash,
|
||||||
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId,
|
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId,
|
||||||
|
[property: JsonPropertyName("answerer_count")] int AnswererCount,
|
||||||
[property: JsonPropertyName("answers")] DeskAnswerDocument[] Answers);
|
[property: JsonPropertyName("answers")] DeskAnswerDocument[] Answers);
|
||||||
|
|
||||||
public sealed record ForkEntry(
|
public sealed record ForkEntry(
|
||||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||||
[property: JsonPropertyName("card")] ForkCard Card,
|
[property: JsonPropertyName("card")] JsonElement Card,
|
||||||
[property: JsonPropertyName("record")] ForkRecord Record);
|
[property: JsonPropertyName("record")] ForkRecord Record);
|
||||||
|
|
||||||
public sealed record ForkList(
|
public sealed record ForkList(
|
||||||
|
|
@ -122,7 +103,7 @@ public sealed record ForkList(
|
||||||
public sealed record AnswerResult(
|
public sealed record AnswerResult(
|
||||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||||
[property: JsonPropertyName("answer")] DeskAnswerDocument Answer,
|
[property: JsonPropertyName("answer")] DeskAnswerDocument Answer,
|
||||||
[property: JsonPropertyName("card")] ForkCard? Card,
|
[property: JsonPropertyName("card")] JsonElement? Card,
|
||||||
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId);
|
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId);
|
||||||
|
|
||||||
// The refusal codes Bifrost itself writes, each with its one status and message (vectors doorRefusals).
|
// The refusal codes Bifrost itself writes, each with its one status and message (vectors doorRefusals).
|
||||||
|
|
@ -183,14 +164,3 @@ public static class DeskUnavailables
|
||||||
"unavailable: the outcome is not confirmed, try again with the same request_id",
|
"unavailable: the outcome is not confirmed, try again with the same request_id",
|
||||||
retryAfterSeconds);
|
retryAfterSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notes are returned only to deciders. For everyone else Bifrost nils every note at the door: the key stays written
|
|
||||||
// (every key written, nil where absent), so the stripped body is still the contract's shape. Cards, outcomes, codes
|
|
||||||
// and counts are untouched; Huginn returns the full record.
|
|
||||||
public static class DeskNotes
|
|
||||||
{
|
|
||||||
public static ForkEntry Strip(ForkEntry entry) =>
|
|
||||||
entry with { Record = entry.Record with { Answers = [.. entry.Record.Answers.Select(a => a with { Note = null })] } };
|
|
||||||
|
|
||||||
public static ForkList Strip(ForkList list) => list with { Forks = [.. list.Forks.Select(Strip)] };
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Features.Oidc;
|
using Bifrost.Web.Features.Oidc;
|
||||||
using Microsoft.AspNetCore.Cors.Infrastructure;
|
using Microsoft.AspNetCore.Cors.Infrastructure;
|
||||||
using Microsoft.AspNetCore.Routing;
|
using Microsoft.AspNetCore.Routing;
|
||||||
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.Net.Http.Headers;
|
using Microsoft.Net.Http.Headers;
|
||||||
|
|
||||||
|
|
@ -22,8 +23,30 @@ public static class DeskEndpoints
|
||||||
public const string AnswerScope = "desk.answer";
|
public const string AnswerScope = "desk.answer";
|
||||||
public const string CorsPolicy = "DeskCors";
|
public const string CorsPolicy = "DeskCors";
|
||||||
|
|
||||||
public static IServiceCollection AddBifrostDesk(this IServiceCollection services)
|
public static bool IsDeskScope(string scope) => scope is ReadScope or AnswerScope;
|
||||||
|
|
||||||
|
// The desk's credential is OpenIddict validation against the local server, so it exists only where Bifrost:Oidc is
|
||||||
|
// configured. Without it nothing is registered here and startup fails in the validator, with its own message.
|
||||||
|
public static IServiceCollection AddBifrostDesk(this IServiceCollection services, bool oidcConfigured)
|
||||||
{
|
{
|
||||||
|
if (oidcConfigured)
|
||||||
|
{
|
||||||
|
services.AddOpenIddict()
|
||||||
|
.AddServer(server => server.RegisterScopes(ReadScope, AnswerScope))
|
||||||
|
.AddValidation(validation =>
|
||||||
|
{
|
||||||
|
validation.UseLocalServer();
|
||||||
|
// The bearer travels in the Authorization header only: a token in a URL lands in access logs.
|
||||||
|
validation.UseAspNetCore().Configure(options =>
|
||||||
|
{
|
||||||
|
options.DisableAccessTokenExtractionFromQueryString = true;
|
||||||
|
options.DisableAccessTokenExtractionFromBodyForm = true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
services.TryAddSingleton<IDeskCredential, OidcDeskCredential>();
|
||||||
|
}
|
||||||
|
|
||||||
|
services.TryAddSingleton<IDeskDoor>(_ => new UnixSocketDeskDoor());
|
||||||
services.AddSingleton(provider => new DeskMindRoutes(provider.GetRequiredService<IOptions<DeskOptions>>().Value.Minds));
|
services.AddSingleton(provider => new DeskMindRoutes(provider.GetRequiredService<IOptions<DeskOptions>>().Value.Minds));
|
||||||
services.AddCors();
|
services.AddCors();
|
||||||
// Exactly the configured origin, no credentials, and only on the routes that require this policy.
|
// Exactly the configured origin, no credentials, and only on the routes that require this policy.
|
||||||
|
|
@ -167,7 +190,7 @@ public static class DeskEndpoints
|
||||||
var listed = await door.ListAsync(mind.Socket, context, listRequest! with { Mind = mind.Id }, cancellationToken);
|
var listed = await door.ListAsync(mind.Socket, context, listRequest! with { Mind = mind.Id }, cancellationToken);
|
||||||
if (listed is DeskListOutcome.Listed(var list))
|
if (listed is DeskListOutcome.Listed(var list))
|
||||||
{
|
{
|
||||||
await WriteJsonAsync(http, 200, IsDecider(context) ? list : DeskNotes.Strip(list));
|
await WriteJsonAsync(http, 200, IsDecider(context) ? list : DeskRedaction.ForNonDecider(list));
|
||||||
}
|
}
|
||||||
else if (listed is DeskListOutcome.ForkTooLarge(var largeId, var largeOrder))
|
else if (listed is DeskListOutcome.ForkTooLarge(var largeId, var largeOrder))
|
||||||
{
|
{
|
||||||
|
|
@ -187,7 +210,7 @@ public static class DeskEndpoints
|
||||||
var found = await door.ReadAsync(mind.Socket, context, forkId, cancellationToken);
|
var found = await door.ReadAsync(mind.Socket, context, forkId, cancellationToken);
|
||||||
if (found is DeskReadOutcome.Found(var entry))
|
if (found is DeskReadOutcome.Found(var entry))
|
||||||
{
|
{
|
||||||
await WriteJsonAsync(http, 200, IsDecider(context) ? entry : DeskNotes.Strip(entry));
|
await WriteJsonAsync(http, 200, IsDecider(context) ? entry : DeskRedaction.ForNonDecider(entry));
|
||||||
}
|
}
|
||||||
else if (found is DeskReadOutcome.ForkTooLarge(var largeFork))
|
else if (found is DeskReadOutcome.ForkTooLarge(var largeFork))
|
||||||
{
|
{
|
||||||
|
|
@ -253,7 +276,8 @@ public static class DeskEndpoints
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A note is a decider's own words: only a caller on the admin-set list reads them (visibility ruling c).
|
// A note is a decider's own words: only a caller on the admin-set list reads one. Bifrost strips notes itself; answerer
|
||||||
|
// and decider ids are withheld by Huginn's door (desk-read-visibility-withheld-ids), not here.
|
||||||
private static bool IsDecider(DeskDoorContext context) =>
|
private static bool IsDecider(DeskDoorContext context) =>
|
||||||
context.Deciders.Contains(context.Subject, StringComparer.Ordinal);
|
context.Deciders.Contains(context.Subject, StringComparer.Ordinal);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,9 @@ namespace Bifrost.Web.Features.Desk;
|
||||||
|
|
||||||
// The two ports the desk stands on. Bifrost owns the edge's order and judgments; these two own what is not
|
// The two ports the desk stands on. Bifrost owns the edge's order and judgments; these two own what is not
|
||||||
// Bifrost's yet: validating a bearer token (the OIDC validation scheme) and speaking to a Mind's Huginn on the
|
// Bifrost's yet: validating a bearer token (the OIDC validation scheme) and speaking to a Mind's Huginn on the
|
||||||
// peer-checked door. No production implementation is registered here: with the Desk section configured and a port
|
// peer-checked door. The door's production implementation is UnixSocketDeskDoor (registered by AddBifrostDesk unless
|
||||||
// missing, startup fails (DeskEndpoints.MapDesk) instead of serving.
|
// a test or host registered its own); the credential has none registered here, so with the Desk section configured
|
||||||
|
// and a port missing, startup fails (DeskEndpoints.MapDesk) instead of serving.
|
||||||
|
|
||||||
// What a validated bearer token claims. The credential port verifies the token; the desk judges audience, scope and
|
// What a validated bearer token claims. The credential port verifies the token; the desk judges audience, scope and
|
||||||
// membership. A null Subject or Audience means the token did not carry one.
|
// membership. A null Subject or Audience means the token did not carry one.
|
||||||
|
|
|
||||||
14
src/Bifrost.Web/Features/Desk/DeskRedaction.cs
Normal file
14
src/Bifrost.Web/Features/Desk/DeskRedaction.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
namespace Bifrost.Web.Features.Desk;
|
||||||
|
|
||||||
|
// What a caller who is not a decider of the Mind does not read, taken out at the door and nowhere else: every note is
|
||||||
|
// nil, with every key still written, so the body is still the contract's shape. Account ids are not Bifrost's to hide:
|
||||||
|
// Huginn's door withholds the decider ids and answerer ids from a non-decider and returns counts
|
||||||
|
// (eureka-substrate:ruling:desk-read-visibility-withheld-ids), and Bifrost cannot mask what it cannot read (the card is
|
||||||
|
// opaque to it). Cards, outcomes, codes, counts and the number of answers are untouched.
|
||||||
|
public static class DeskRedaction
|
||||||
|
{
|
||||||
|
public static ForkEntry ForNonDecider(ForkEntry entry) =>
|
||||||
|
entry with { Record = entry.Record with { Answers = [.. entry.Record.Answers.Select(a => a with { Note = null })] } };
|
||||||
|
|
||||||
|
public static ForkList ForNonDecider(ForkList list) => list with { Forks = [.. list.Forks.Select(ForNonDecider)] };
|
||||||
|
}
|
||||||
28
src/Bifrost.Web/Features/Desk/OidcDeskCredential.cs
Normal file
28
src/Bifrost.Web/Features/Desk/OidcDeskCredential.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using OpenIddict.Abstractions;
|
||||||
|
using OpenIddict.Validation.AspNetCore;
|
||||||
|
using static OpenIddict.Abstractions.OpenIddictConstants;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Desk;
|
||||||
|
|
||||||
|
// The production IDeskCredential: OpenIddict's validation handler against the local server, asked for by its own
|
||||||
|
// scheme name and no other. It authenticates only. The default scheme stays the cookie, so a bearer token reaches no
|
||||||
|
// cookie surface, and this credential never reads the cookie, so the session cookie authenticates nothing on the
|
||||||
|
// desk. Audience, scope and Active membership are the desk's judgments (DeskEndpoints), not this port's.
|
||||||
|
public sealed class OidcDeskCredential : IDeskCredential
|
||||||
|
{
|
||||||
|
public async ValueTask<DeskToken?> AuthenticateAsync(HttpContext context, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = await context.AuthenticateAsync(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
|
||||||
|
if (!result.Succeeded || result.Principal is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A token may name several audiences; the desk's own is reported when present so the desk judges it, else the
|
||||||
|
// first (or none).
|
||||||
|
var audiences = result.Principal.GetAudiences();
|
||||||
|
var audience = audiences.Contains(DeskEndpoints.Audience) ? DeskEndpoints.Audience : audiences.FirstOrDefault();
|
||||||
|
return new DeskToken(result.Principal.GetClaim(Claims.Subject), audience, [.. result.Principal.GetScopes()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
624
src/Bifrost.Web/Features/Desk/UnixSocketDeskDoor.cs
Normal file
624
src/Bifrost.Web/Features/Desk/UnixSocketDeskDoor.cs
Normal file
|
|
@ -0,0 +1,624 @@
|
||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using MessagePack;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Desk;
|
||||||
|
|
||||||
|
// The door could not confirm an outcome: no connection, no whole reply in time, or a reply that is not the contract's
|
||||||
|
// (an error, a failure, a Mind refusal, an unknown variant). The desk edge maps any exception from the door to 503
|
||||||
|
// `unavailable`; this is the one type the client throws for every one of those, so a failure is never an empty page.
|
||||||
|
public sealed class DeskDoorException(string message, Exception? inner = null) : Exception(message, inner);
|
||||||
|
|
||||||
|
// The production IDeskDoor: a client of Huginn's desk door (Huginn docs/desk-feed-door.md at 232764bf). One new
|
||||||
|
// connection per call, one request frame, one reply frame, closed after, all inside one deadline. The client holds no
|
||||||
|
// connection state, so a dead socket fails only the calls addressed to that Mind.
|
||||||
|
//
|
||||||
|
// frame = u32 big-endian length || CultNet message (MessagePack map), at most 65536 bytes each way
|
||||||
|
// payload = standard base64 of the named MessagePack of Huginn's externally tagged DeskRequest / DeskResponse
|
||||||
|
//
|
||||||
|
// The reply is decoded by key, never by position, and strictly: every contract document is a closed map whose keys are
|
||||||
|
// all present with the right type (the variants' own maps too: as_of is an unsigned integer, as Huginn's DeskResponse
|
||||||
|
// declares), a key written twice anywhere is a failure, and so is a float, a binary or an extension value (the
|
||||||
|
// contract has none; integers keep every digit). The card inside an entry is not read beyond
|
||||||
|
// being a map: it stays an opaque JsonElement, so whatever keys and integers Huginn wrote leave unchanged.
|
||||||
|
public sealed partial class UnixSocketDeskDoor : IDeskDoor
|
||||||
|
{
|
||||||
|
public const int MaxFrameBytes = 65536;
|
||||||
|
public static readonly TimeSpan Deadline = TimeSpan.FromSeconds(1);
|
||||||
|
|
||||||
|
private const string ServiceId = "huginn.desk";
|
||||||
|
private const string RequestSchema = "huginn.desk_request.v1";
|
||||||
|
private const string ResponseSchema = "huginn.desk_response.v1";
|
||||||
|
private const string Encoding64 = "messagepack-base64";
|
||||||
|
private const int MaxMessageIdBytes = 256;
|
||||||
|
|
||||||
|
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||||
|
|
||||||
|
private readonly Func<string> messageIds;
|
||||||
|
|
||||||
|
public UnixSocketDeskDoor()
|
||||||
|
: this(() => Guid.NewGuid().ToString("N"))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public UnixSocketDeskDoor(Func<string> messageIds) => this.messageIds = messageIds;
|
||||||
|
|
||||||
|
public async Task<DeskAnswerOutcome> AnswerAsync(
|
||||||
|
string socket, DeskDoorContext context, ReadOnlyMemory<byte> body, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
byte[] request;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Every key, null and key order of the client's body, as MessagePack.
|
||||||
|
request = MessagePackSerializer.ConvertFromJson(StrictUtf8.GetString(body.Span));
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the answer body does not convert to the request map", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = Payload("Answer", 5, (ref MessagePackWriter w) =>
|
||||||
|
{
|
||||||
|
w.Write("mind");
|
||||||
|
w.Write(context.Mind);
|
||||||
|
w.Write("subject");
|
||||||
|
w.Write(context.Subject);
|
||||||
|
w.Write("authority");
|
||||||
|
w.Write(context.Authority);
|
||||||
|
w.Write("deciders");
|
||||||
|
Strings(ref w, context.Deciders);
|
||||||
|
w.Write("request");
|
||||||
|
w.WriteRaw(request);
|
||||||
|
});
|
||||||
|
|
||||||
|
var (variant, value) = await ExchangeAsync(socket, "answer", payload, cancellationToken);
|
||||||
|
switch (variant)
|
||||||
|
{
|
||||||
|
case "Answered":
|
||||||
|
Closed(value, "Answered", string.Empty, ("answer", Kind.Map), ("counted_answer_id", Kind.TextOrNull), ("as_of", Kind.Unsigned));
|
||||||
|
var answer = AnswerDocument(value, "answer");
|
||||||
|
|
||||||
|
// Huginn's reply carries no card: a stale_fork answer gets the current card from the edge's read.
|
||||||
|
return new DeskAnswerOutcome.Answered(new AnswerResult(
|
||||||
|
DeskSchemas.AnswerResult, answer, null, OptionalString(value, "counted_answer_id")));
|
||||||
|
case "NotStored":
|
||||||
|
var code = RefusalCode(value);
|
||||||
|
return code is DeskRefusals.ForkTooLarge
|
||||||
|
? throw new DeskDoorException("fork_too_large is not an answer refusal")
|
||||||
|
: new DeskAnswerOutcome.NotStored(code);
|
||||||
|
default:
|
||||||
|
throw Unexpected(variant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<DeskReadOutcome> ReadAsync(
|
||||||
|
string socket, DeskDoorContext context, string forkId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var payload = Payload("Fork", 4, (ref MessagePackWriter w) =>
|
||||||
|
{
|
||||||
|
w.Write("mind");
|
||||||
|
w.Write(context.Mind);
|
||||||
|
w.Write("subject");
|
||||||
|
w.Write(context.Subject);
|
||||||
|
w.Write("deciders");
|
||||||
|
Strings(ref w, context.Deciders);
|
||||||
|
w.Write("fork_id");
|
||||||
|
w.Write(forkId);
|
||||||
|
});
|
||||||
|
|
||||||
|
var (variant, value) = await ExchangeAsync(socket, "fork", payload, cancellationToken);
|
||||||
|
switch (variant)
|
||||||
|
{
|
||||||
|
case "Fork":
|
||||||
|
Closed(value, "Fork", string.Empty, ("entry", Kind.Map), ("as_of", Kind.Unsigned));
|
||||||
|
var entry = Entry(Required(value, "entry"), "entry");
|
||||||
|
// The route asked for one fork. An entry whose card names another is not the answer to it. (That the record
|
||||||
|
// agrees with the card is a rule of the entry, CultLib's validators' and Huginn's, not the door's.)
|
||||||
|
if (!entry.Card.TryGetProperty("fork_id", out var cardFork) || cardFork.ValueKind != JsonValueKind.String
|
||||||
|
|| cardFork.GetString() != forkId)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the entry is not for the fork asked");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new DeskReadOutcome.Found(entry);
|
||||||
|
case "NotStored":
|
||||||
|
var code = RefusalCode(value);
|
||||||
|
// The route's fork id, never the refusal's informational text.
|
||||||
|
return code == DeskRefusals.ForkTooLarge
|
||||||
|
? new DeskReadOutcome.ForkTooLarge(forkId)
|
||||||
|
: new DeskReadOutcome.NotFound(code);
|
||||||
|
default:
|
||||||
|
throw Unexpected(variant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<DeskListOutcome> ListAsync(
|
||||||
|
string socket, DeskDoorContext context, DeskListRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var payload = Payload("Forks", 6, (ref MessagePackWriter w) =>
|
||||||
|
{
|
||||||
|
w.Write("mind");
|
||||||
|
w.Write(context.Mind);
|
||||||
|
w.Write("subject");
|
||||||
|
w.Write(context.Subject);
|
||||||
|
w.Write("deciders");
|
||||||
|
Strings(ref w, context.Deciders);
|
||||||
|
w.Write("status");
|
||||||
|
w.Write(request.Status);
|
||||||
|
w.Write("cursor");
|
||||||
|
w.Write(request.Cursor);
|
||||||
|
w.Write("limit");
|
||||||
|
w.Write(request.Limit);
|
||||||
|
});
|
||||||
|
|
||||||
|
var (variant, value) = await ExchangeAsync(socket, "forks", payload, cancellationToken);
|
||||||
|
switch (variant)
|
||||||
|
{
|
||||||
|
case "Forks":
|
||||||
|
Closed(value, "Forks", string.Empty, ("list", Kind.Map), ("as_of", Kind.Unsigned));
|
||||||
|
var list = List(Required(value, "list"));
|
||||||
|
return list.Mind == context.Mind
|
||||||
|
? new DeskListOutcome.Listed(list)
|
||||||
|
: throw new DeskDoorException("the list is for another Mind");
|
||||||
|
case "NotStored":
|
||||||
|
var code = RefusalCode(value);
|
||||||
|
if (code != DeskRefusals.ForkTooLarge)
|
||||||
|
{
|
||||||
|
return new DeskListOutcome.NotListed(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fork and its order exist only in the informational text; anything but the exact form is a fault.
|
||||||
|
var text = RequiredString(value, "error");
|
||||||
|
var match = ListTooLarge().Match(text);
|
||||||
|
if (!match.Success || !int.TryParse(match.Groups["order"].ValueSpan, NumberStyles.None, CultureInfo.InvariantCulture, out var order))
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("fork_too_large does not name its fork and order in the list form");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new DeskListOutcome.ForkTooLarge(match.Groups["id"].Value, order);
|
||||||
|
default:
|
||||||
|
throw Unexpected(variant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fork_too_large: fork <id> at order <N> is past the page budget by itself; ...
|
||||||
|
[GeneratedRegex(@"\Afork_too_large: fork (?<id>\S+) at order (?<order>0|[1-9][0-9]*) is past the page budget(?:[ ;][^\r\n]*)?\z", RegexOptions.CultureInvariant)]
|
||||||
|
private static partial Regex ListTooLarge();
|
||||||
|
|
||||||
|
// ---- strict documents: a closed map, every key present with its type, then bound to the typed record ----
|
||||||
|
|
||||||
|
private enum Kind
|
||||||
|
{
|
||||||
|
Text,
|
||||||
|
TextOrNull,
|
||||||
|
Flag,
|
||||||
|
Count,
|
||||||
|
Unsigned,
|
||||||
|
Map,
|
||||||
|
Items,
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly (string, Kind)[] AnswerKeys =
|
||||||
|
[
|
||||||
|
("schemaVersion", Kind.Text), ("answer_id", Kind.Text), ("fork_id", Kind.Text), ("outcome", Kind.Text),
|
||||||
|
("of", Kind.TextOrNull), ("retracts", Kind.TextOrNull), ("code", Kind.TextOrNull), ("options_hash", Kind.Text),
|
||||||
|
("choice", Kind.TextOrNull), ("note", Kind.TextOrNull), ("answered_at", Kind.Text), ("received_at", Kind.Text),
|
||||||
|
("claim_in_future", Kind.Flag), ("answerer", Kind.TextOrNull), ("authority", Kind.Text), ("request_id", Kind.Text),
|
||||||
|
];
|
||||||
|
|
||||||
|
private static void Closed(JsonElement map, string what, string schema, params (string Key, Kind Kind)[] keys)
|
||||||
|
{
|
||||||
|
if (map.ValueKind != JsonValueKind.Object || map.EnumerateObject().Count() != keys.Length)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException($"{what} is not a closed map of {keys.Length} keys");
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (key, kind) in keys)
|
||||||
|
{
|
||||||
|
var ok = Property(map, key) is { } v && kind switch
|
||||||
|
{
|
||||||
|
Kind.Text => v.ValueKind == JsonValueKind.String,
|
||||||
|
Kind.TextOrNull => v.ValueKind is JsonValueKind.String or JsonValueKind.Null,
|
||||||
|
Kind.Flag => v.ValueKind is JsonValueKind.True or JsonValueKind.False,
|
||||||
|
Kind.Count => v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n) && n >= 0,
|
||||||
|
Kind.Unsigned => v.ValueKind == JsonValueKind.Number && v.TryGetUInt64(out _),
|
||||||
|
Kind.Map => v.ValueKind == JsonValueKind.Object,
|
||||||
|
_ => v.ValueKind == JsonValueKind.Array,
|
||||||
|
};
|
||||||
|
if (!ok)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException($"{what}.{key} is missing or not the contract's type");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (schema.Length > 0 && Property(map, "schemaVersion")!.Value.GetString() != schema)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException($"{what} is not {schema}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DeskAnswerDocument AnswerDocument(JsonElement value, string what)
|
||||||
|
{
|
||||||
|
var map = Required(value, what);
|
||||||
|
Closed(map, what, DeskSchemas.DeskAnswer, AnswerKeys);
|
||||||
|
return Bind<DeskAnswerDocument>(map, what);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ForkEntry Entry(JsonElement map, string what)
|
||||||
|
{
|
||||||
|
Closed(map, what, "gamecult.fork.entry.v0", ("schemaVersion", Kind.Text), ("card", Kind.Map), ("record", Kind.Map));
|
||||||
|
var record = Property(map, "record")!.Value;
|
||||||
|
Closed(record, what + ".record", "gamecult.fork.record.v0",
|
||||||
|
("schemaVersion", Kind.Text), ("fork_id", Kind.Text), ("options_hash", Kind.Text), ("counted_answer_id", Kind.TextOrNull),
|
||||||
|
("answerer_count", Kind.Count), ("answers", Kind.Items));
|
||||||
|
foreach (var answer in Property(record, "answers")!.Value.EnumerateArray())
|
||||||
|
{
|
||||||
|
Closed(answer, what + ".record.answers[]", DeskSchemas.DeskAnswer, AnswerKeys);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Bind<ForkEntry>(map, what);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ForkList List(JsonElement map)
|
||||||
|
{
|
||||||
|
Closed(map, "list", "gamecult.fork.list.v0",
|
||||||
|
("schemaVersion", Kind.Text), ("mind", Kind.Text), ("stamp", Kind.Text), ("open_count", Kind.Count),
|
||||||
|
("recorded_count", Kind.Count), ("forks", Kind.Items), ("next_cursor", Kind.TextOrNull));
|
||||||
|
foreach (var entry in Property(map, "forks")!.Value.EnumerateArray())
|
||||||
|
{
|
||||||
|
Entry(entry, "list.forks[]");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Bind<ForkList>(map, "list");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static T Bind<T>(JsonElement map, string what)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return map.Deserialize<T>(DeskJson.Options) ?? throw new DeskDoorException($"{what} does not decode");
|
||||||
|
}
|
||||||
|
catch (JsonException e)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException($"{what} does not decode", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonElement Required(JsonElement map, string name) =>
|
||||||
|
Property(map, name) ?? throw new DeskDoorException($"{name} is missing");
|
||||||
|
|
||||||
|
private static DeskDoorException Unexpected(string variant) =>
|
||||||
|
new($"the door answered with {(variant == "Refused" ? "a Mind refusal" : "a variant this call does not take")}");
|
||||||
|
|
||||||
|
private static string RefusalCode(JsonElement refusal)
|
||||||
|
{
|
||||||
|
Closed(refusal, "the refusal", DeskSchemas.Refusal, ("schemaVersion", Kind.Text), ("code", Kind.Text), ("error", Kind.Text));
|
||||||
|
var code = RequiredString(refusal, "code");
|
||||||
|
return code is DeskRefusals.ForkUnknown or DeskRefusals.BodyInvalid or DeskRefusals.RequestIdConflict or DeskRefusals.ForkTooLarge
|
||||||
|
? code
|
||||||
|
: throw new DeskDoorException("the refusal code is not one the contract names");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- request ----
|
||||||
|
|
||||||
|
private delegate void FieldWriter(ref MessagePackWriter writer);
|
||||||
|
|
||||||
|
private static byte[] Payload(string variant, int fields, FieldWriter write)
|
||||||
|
{
|
||||||
|
var buffer = new ArrayBufferWriter<byte>();
|
||||||
|
var w = new MessagePackWriter(buffer);
|
||||||
|
w.WriteMapHeader(1);
|
||||||
|
w.Write(variant);
|
||||||
|
w.WriteMapHeader(fields);
|
||||||
|
write(ref w);
|
||||||
|
w.Flush();
|
||||||
|
return buffer.WrittenSpan.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Strings(ref MessagePackWriter w, IReadOnlyList<string> values)
|
||||||
|
{
|
||||||
|
w.WriteArrayHeader(values.Count);
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
w.Write(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Operation messages write their keys sorted, absent optionals omitted.
|
||||||
|
private static byte[] RequestMessage(string messageId, string operation, byte[] payload)
|
||||||
|
{
|
||||||
|
var buffer = new ArrayBufferWriter<byte>();
|
||||||
|
var w = new MessagePackWriter(buffer);
|
||||||
|
w.WriteMapHeader(7);
|
||||||
|
w.Write("messageId");
|
||||||
|
w.Write(messageId);
|
||||||
|
w.Write("operation");
|
||||||
|
w.Write(operation);
|
||||||
|
w.Write("payload");
|
||||||
|
w.Write(Convert.ToBase64String(payload));
|
||||||
|
w.Write("payloadEncoding");
|
||||||
|
w.Write(Encoding64);
|
||||||
|
w.Write("payloadSchema");
|
||||||
|
w.Write(RequestSchema);
|
||||||
|
w.Write("schemaVersion");
|
||||||
|
w.Write("cultnet.operation_request.v0");
|
||||||
|
w.Write("serviceId");
|
||||||
|
w.Write(ServiceId);
|
||||||
|
w.Flush();
|
||||||
|
return buffer.WrittenSpan.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- exchange ----
|
||||||
|
|
||||||
|
private async Task<(string Variant, JsonElement Value)> ExchangeAsync(
|
||||||
|
string socketPath, string operation, byte[] payload, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var messageId = messageIds();
|
||||||
|
if (messageId.Length == 0 || StrictUtf8.GetByteCount(messageId) > MaxMessageIdBytes)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the message id is empty or over 256 bytes");
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = RequestMessage(messageId, operation, payload);
|
||||||
|
if (message.Length > MaxFrameBytes)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the request is past the frame bound");
|
||||||
|
}
|
||||||
|
|
||||||
|
var frame = new byte[4 + message.Length];
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(frame, (uint)message.Length);
|
||||||
|
message.CopyTo(frame, 4);
|
||||||
|
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
deadline.CancelAfter(Deadline);
|
||||||
|
byte[] reply;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||||
|
await socket.ConnectAsync(new UnixDomainSocketEndPoint(socketPath), deadline.Token);
|
||||||
|
for (var sent = 0; sent < frame.Length;)
|
||||||
|
{
|
||||||
|
sent += await socket.SendAsync(frame.AsMemory(sent), SocketFlags.None, deadline.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = new byte[4];
|
||||||
|
await ReadWholeAsync(socket, header, deadline.Token);
|
||||||
|
var length = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||||
|
if (length == 0 || length > MaxFrameBytes)
|
||||||
|
{
|
||||||
|
// Refused on the prefix alone: the body is never read.
|
||||||
|
throw new DeskDoorException("the reply's length prefix is outside the frame bound");
|
||||||
|
}
|
||||||
|
|
||||||
|
reply = new byte[length];
|
||||||
|
await ReadWholeAsync(socket, reply, deadline.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("no whole reply within the deadline");
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is SocketException or IOException or ObjectDisposedException or ArgumentException)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the desk socket failed", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Decode(reply, messageId, operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loops until the buffer is whole: a stream socket may hand it over in pieces. A peer closing early is a failure.
|
||||||
|
private static async Task ReadWholeAsync(Socket socket, byte[] buffer, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
for (var read = 0; read < buffer.Length;)
|
||||||
|
{
|
||||||
|
var count = await socket.ReceiveAsync(buffer.AsMemory(read), SocketFlags.None, cancellationToken);
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the peer closed before a whole reply frame");
|
||||||
|
}
|
||||||
|
|
||||||
|
read += count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- reply ----
|
||||||
|
|
||||||
|
// The envelope judged by key; the payload's one variant returned with its value. Everything else throws.
|
||||||
|
private static (string Variant, JsonElement Value) Decode(byte[] frame, string messageId, string operation)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var envelope = ToJson(frame);
|
||||||
|
var root = envelope.RootElement;
|
||||||
|
if (root.ValueKind != JsonValueKind.Object)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the reply is not a map");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A CultNet Error message is not an operation reply (and its keys are not in operation order).
|
||||||
|
if (RequiredString(root, "schemaVersion") != "cultnet.operation_response.v0")
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the reply is not an operation response");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (RequiredString(root, "serviceId") != ServiceId
|
||||||
|
|| RequiredString(root, "operation") != operation
|
||||||
|
|| RequiredString(root, "messageId") != messageId)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the reply is not for this request");
|
||||||
|
}
|
||||||
|
|
||||||
|
var status = RequiredString(root, "status");
|
||||||
|
if (RequiredString(root, "payloadSchema") != ResponseSchema || RequiredString(root, "payloadEncoding") != Encoding64)
|
||||||
|
{
|
||||||
|
// Including gamecult.cultnet.operation_failure.v1: the envelope or payload did not decode.
|
||||||
|
throw new DeskDoorException("the reply carries no desk response");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict standard base64: Convert would skip whitespace, so the text must be the canonical encoding of what it decodes to.
|
||||||
|
var text = RequiredString(root, "payload");
|
||||||
|
byte[] payload;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
payload = Convert.FromBase64String(text);
|
||||||
|
}
|
||||||
|
catch (FormatException e)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the payload is not base64", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Convert.ToBase64String(payload) != text)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the payload is not strict standard base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
using var body = ToJson(payload);
|
||||||
|
if (body.RootElement.ValueKind != JsonValueKind.Object)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the payload is not a tagged variant");
|
||||||
|
}
|
||||||
|
|
||||||
|
var variants = body.RootElement.EnumerateObject().ToList();
|
||||||
|
if (variants.Count != 1)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the payload is not a one-key variant");
|
||||||
|
}
|
||||||
|
|
||||||
|
var (variant, expectedStatus) = (variants[0].Name, variants[0].Name switch
|
||||||
|
{
|
||||||
|
"Answered" or "Forks" or "Fork" => "accepted",
|
||||||
|
"NotStored" or "Refused" => "rejected",
|
||||||
|
_ => null,
|
||||||
|
});
|
||||||
|
var takesVariant = operation switch
|
||||||
|
{
|
||||||
|
"answer" => variant == "Answered",
|
||||||
|
"forks" => variant == "Forks",
|
||||||
|
"fork" => variant == "Fork",
|
||||||
|
_ => false,
|
||||||
|
} || variant is "NotStored" or "Refused";
|
||||||
|
if (expectedStatus is null || !takesVariant || status != expectedStatus)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the reply's variant or status does not fit the operation");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (variant, variants[0].Value.Clone());
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is not (DeskDoorException or OperationCanceledException))
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the reply does not decode", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MessagePack to JSON text by walking the reader: the JSON writer escapes every control character, keys keep their
|
||||||
|
// order, integers keep every digit. A map key that is not text, a key written twice, a float, a binary, an
|
||||||
|
// extension, invalid UTF-8 or nesting past 64 is a failure; none is in the contract.
|
||||||
|
private static JsonDocument ToJson(ReadOnlyMemory<byte> messagePack)
|
||||||
|
{
|
||||||
|
var reader = new MessagePackReader(messagePack);
|
||||||
|
var json = new ArrayBufferWriter<byte>();
|
||||||
|
using (var writer = new Utf8JsonWriter(json, new JsonWriterOptions { MaxDepth = 64 }))
|
||||||
|
{
|
||||||
|
Walk(ref reader, writer, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!reader.End)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("bytes follow the message");
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonDocument.Parse(json.WrittenMemory, new JsonDocumentOptions { MaxDepth = 64 });
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Walk(ref MessagePackReader reader, Utf8JsonWriter writer, int depth)
|
||||||
|
{
|
||||||
|
if (depth > 64)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("the message nests past 64");
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (reader.NextMessagePackType)
|
||||||
|
{
|
||||||
|
case MessagePackType.Nil:
|
||||||
|
reader.ReadNil();
|
||||||
|
writer.WriteNullValue();
|
||||||
|
break;
|
||||||
|
case MessagePackType.Boolean:
|
||||||
|
writer.WriteBooleanValue(reader.ReadBoolean());
|
||||||
|
break;
|
||||||
|
case MessagePackType.Integer:
|
||||||
|
if (reader.NextCode == MessagePackCode.UInt64)
|
||||||
|
{
|
||||||
|
writer.WriteNumberValue(reader.ReadUInt64());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
writer.WriteNumberValue(reader.ReadInt64());
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case MessagePackType.String:
|
||||||
|
writer.WriteStringValue(Text(ref reader));
|
||||||
|
break;
|
||||||
|
case MessagePackType.Array:
|
||||||
|
var items = reader.ReadArrayHeader();
|
||||||
|
writer.WriteStartArray();
|
||||||
|
for (var i = 0; i < items; i++)
|
||||||
|
{
|
||||||
|
Walk(ref reader, writer, depth + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteEndArray();
|
||||||
|
break;
|
||||||
|
case MessagePackType.Map:
|
||||||
|
var pairs = reader.ReadMapHeader();
|
||||||
|
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
writer.WriteStartObject();
|
||||||
|
for (var i = 0; i < pairs; i++)
|
||||||
|
{
|
||||||
|
if (reader.NextMessagePackType != MessagePackType.String)
|
||||||
|
{
|
||||||
|
throw new DeskDoorException("a map key is not text");
|
||||||
|
}
|
||||||
|
|
||||||
|
var key = Text(ref reader);
|
||||||
|
if (!seen.Add(key))
|
||||||
|
{
|
||||||
|
throw new DeskDoorException($"{key} is written twice");
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WritePropertyName(key);
|
||||||
|
Walk(ref reader, writer, depth + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteEndObject();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new DeskDoorException("the message holds a float, binary or extension value, which the contract does not use");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Text(ref MessagePackReader reader) =>
|
||||||
|
StrictUtf8.GetString(reader.ReadStringSequence() ?? throw new DeskDoorException("text is nil"));
|
||||||
|
|
||||||
|
// A key's value by name; a key written twice never gets here (the walk refuses it).
|
||||||
|
private static JsonElement? Property(JsonElement map, string name) =>
|
||||||
|
map.ValueKind == JsonValueKind.Object && map.TryGetProperty(name, out var value) ? value : null;
|
||||||
|
|
||||||
|
private static string RequiredString(JsonElement map, string name) =>
|
||||||
|
Property(map, name) is { ValueKind: JsonValueKind.String } value
|
||||||
|
? value.GetString()!
|
||||||
|
: throw new DeskDoorException($"{name} is missing or not text");
|
||||||
|
|
||||||
|
private static string? OptionalString(JsonElement map, string name) =>
|
||||||
|
Property(map, name) switch
|
||||||
|
{
|
||||||
|
{ ValueKind: JsonValueKind.String } value => value.GetString(),
|
||||||
|
{ ValueKind: JsonValueKind.Null } => null,
|
||||||
|
_ => throw new DeskDoorException($"{name} is missing or not text"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -8,6 +8,7 @@ using Bifrost.Web.Configuration;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
using Bifrost.Web.Features.Membership;
|
using Bifrost.Web.Features.Membership;
|
||||||
|
using Bifrost.Web.Features.Passkeys;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.AspNetCore.DataProtection;
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
using Microsoft.AspNetCore.WebUtilities;
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
|
@ -20,7 +21,9 @@ namespace Bifrost.Web.Features.Heimdall;
|
||||||
/// Heimdall sign-in. Start issues an attempt that lives only in a Data Protection-protected cookie in the
|
/// 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
|
/// 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
|
/// URL fragment; Bifrost redeems it at Heimdall itself and signs in only when that browser holds the
|
||||||
/// attempt's cookie and the redeemed return target names the same attempt.
|
/// attempt's cookie and the redeemed return target names the same attempt. The Linked accounts page's steps (list,
|
||||||
|
/// link, unlink) are the same machine with other attempt purposes: each is a fresh Heimdall sign-in whose bearer is
|
||||||
|
/// used inside that one request and dropped.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class HeimdallAuthService(
|
public sealed class HeimdallAuthService(
|
||||||
HttpClient httpClient,
|
HttpClient httpClient,
|
||||||
|
|
@ -29,7 +32,12 @@ public sealed class HeimdallAuthService(
|
||||||
BifrostIdentityService bifrostIdentityService,
|
BifrostIdentityService bifrostIdentityService,
|
||||||
IOptions<HeimdallOptions> heimdallOptions,
|
IOptions<HeimdallOptions> heimdallOptions,
|
||||||
IDataProtectionProvider dataProtectionProvider,
|
IDataProtectionProvider dataProtectionProvider,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider,
|
||||||
|
HeimdallMemberClient memberClient,
|
||||||
|
LinkedAccountsSnapshots snapshots,
|
||||||
|
PasskeyCeremonies ceremonies,
|
||||||
|
PasskeyService passkeys,
|
||||||
|
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
|
||||||
{
|
{
|
||||||
public const string ErrorRedirect = "/?auth=heimdall-error";
|
public const string ErrorRedirect = "/?auth=heimdall-error";
|
||||||
public const string AppSecretHeader = "x-heimdall-app-secret";
|
public const string AppSecretHeader = "x-heimdall-app-secret";
|
||||||
|
|
@ -38,9 +46,20 @@ public sealed class HeimdallAuthService(
|
||||||
{
|
{
|
||||||
"discord",
|
"discord",
|
||||||
"patreon",
|
"patreon",
|
||||||
"twitch"
|
"google"
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <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");
|
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>
|
/// <summary>Points the client at Heimdall and, when the app has a secret, identifies Bifrost as the app.</summary>
|
||||||
|
|
@ -53,15 +72,39 @@ 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(
|
public async Task<HeimdallAuthStartResult> StartAsync(
|
||||||
string provider,
|
string provider,
|
||||||
string callbackBaseUrl,
|
string callbackBaseUrl,
|
||||||
LocalReturnPath returnPath,
|
LocalReturnPath returnPath,
|
||||||
bool requireMemberAccess,
|
bool requireMemberAccess,
|
||||||
IEnumerable<KeyValuePair<string, string>> requestCookies,
|
IEnumerable<KeyValuePair<string, string>> requestCookies,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken,
|
||||||
|
HeimdallAttemptPurpose purpose = HeimdallAttemptPurpose.SignIn,
|
||||||
|
string? expectedAccountId = null,
|
||||||
|
string? pendingLinkId = null,
|
||||||
|
string? replaceSlot = null,
|
||||||
|
bool stepUp = false,
|
||||||
|
string? target = null,
|
||||||
|
string? proof = null)
|
||||||
{
|
{
|
||||||
if (!AllowedProviders.Contains(provider))
|
// The public sign-in routes offer AllowedProviders; the proofs of the Linked accounts page may also use Google
|
||||||
|
// (a step-up proof only Google can give a bifrost sign-in, an ordinary one for an account that holds Google).
|
||||||
|
if (!(purpose == HeimdallAttemptPurpose.SignIn ? AllowedProviders : ProofProviders).Contains(provider))
|
||||||
{
|
{
|
||||||
throw new HeimdallAuthException("Unsupported Heimdall provider.");
|
throw new HeimdallAuthException("Unsupported Heimdall provider.");
|
||||||
}
|
}
|
||||||
|
|
@ -77,21 +120,30 @@ public sealed class HeimdallAuthService(
|
||||||
: null;
|
: null;
|
||||||
var nonce = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
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(
|
var request = new HeimdallStartRequest(
|
||||||
options.AppSlug,
|
options.AppSlug,
|
||||||
"sign_in",
|
"sign_in",
|
||||||
ToAttemptReturnUrl(callbackBaseUrl, nonce),
|
ToAttemptReturnUrl(callbackBaseUrl, nonce),
|
||||||
new HeimdallHandoff("browser_completion"),
|
new HeimdallHandoff("browser_completion"),
|
||||||
entitlementPolicy);
|
entitlementPolicy,
|
||||||
|
stepUp ? true : null,
|
||||||
|
grant);
|
||||||
|
|
||||||
var response = await httpClient.PostAsJsonAsync(
|
// Headers only: a refusal body is read through RefusedStartMessageAsync's own 4 KiB bound, not buffered whole.
|
||||||
$"/v1/oauth/{provider}/start",
|
using var startMessage = new HttpRequestMessage(HttpMethod.Post, $"/v1/oauth/{provider}/start")
|
||||||
request,
|
{
|
||||||
cancellationToken);
|
Content = JsonContent.Create(request)
|
||||||
|
};
|
||||||
|
using var response = await SendStartAsync(startMessage, cancellationToken);
|
||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
throw new HeimdallAuthException("Heimdall rejected the auth start.");
|
throw new HeimdallAuthException(await RefusedStartMessageAsync(response, cancellationToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
var payload = await response.Content.ReadFromJsonAsync<HeimdallStartResponse>(cancellationToken);
|
var payload = await response.Content.ReadFromJsonAsync<HeimdallStartResponse>(cancellationToken);
|
||||||
|
|
@ -105,11 +157,171 @@ public sealed class HeimdallAuthService(
|
||||||
provider,
|
provider,
|
||||||
requireMemberAccess,
|
requireMemberAccess,
|
||||||
returnPath,
|
returnPath,
|
||||||
timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime);
|
timeProvider.GetUtcNow() + HeimdallAttemptCookie.Lifetime,
|
||||||
|
purpose,
|
||||||
|
expectedAccountId,
|
||||||
|
pendingLinkId,
|
||||||
|
target,
|
||||||
|
proof);
|
||||||
return new HeimdallAuthStartResult(
|
return new HeimdallAuthStartResult(
|
||||||
new Uri(payload.AuthorizationUrl, UriKind.Absolute), ChooseSlot(requestCookies), Protect(attempt));
|
new Uri(payload.AuthorizationUrl, UriKind.Absolute), replaceSlot ?? 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>
|
/// <summary>
|
||||||
/// The slot the new attempt's cookie takes: the first slot that holds no live attempt, else the one whose
|
/// 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
|
/// attempt expires first. Parallel starts carry the same request cookies, so they choose the same slot and
|
||||||
|
|
@ -156,15 +368,13 @@ public sealed class HeimdallAuthService(
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<HeimdallCompletedSignIn> CompleteAsync(
|
/// <summary>What the attempt this browser holds for the nonce is for, or null when it holds none.</summary>
|
||||||
string callbackBaseUrl,
|
public HeimdallAttemptPurpose? PurposeOf(string? cookieValue, string? nonce) => Unprotect(cookieValue, nonce)?.Purpose;
|
||||||
string? nonce,
|
|
||||||
string? cookieValue,
|
/// <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>
|
||||||
string? code,
|
private async Task<(HeimdallVerifiedIdentity Identity, string AccessToken, HeimdallRedeemResponse Redeemed)> RedeemVerifiedAsync(
|
||||||
CancellationToken cancellationToken)
|
string callbackBaseUrl, HeimdallAttempt attempt, string? code, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var attempt = Unprotect(cookieValue, nonce)
|
|
||||||
?? throw new HeimdallAuthException("Heimdall completion has no attempt for this browser.");
|
|
||||||
if (string.IsNullOrWhiteSpace(code))
|
if (string.IsNullOrWhiteSpace(code))
|
||||||
{
|
{
|
||||||
throw new HeimdallAuthException("Heimdall completion carried no code.");
|
throw new HeimdallAuthException("Heimdall completion carried no code.");
|
||||||
|
|
@ -182,6 +392,24 @@ public sealed class HeimdallAuthService(
|
||||||
}
|
}
|
||||||
|
|
||||||
var identity = await tokenVerifier.VerifyAsync(redeemed.AccessToken, redeemed.Account?.Id, cancellationToken);
|
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)
|
if (attempt.RequiresMemberAccess && !identity.HasMemberAccess)
|
||||||
{
|
{
|
||||||
throw new HeimdallAuthException("Heimdall did not grant Bifrost member access.");
|
throw new HeimdallAuthException("Heimdall did not grant Bifrost member access.");
|
||||||
|
|
@ -197,6 +425,323 @@ public sealed class HeimdallAuthService(
|
||||||
attempt.ReturnPath);
|
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)
|
private async Task<HeimdallRedeemResponse> RedeemAsync(string code, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|
@ -221,7 +766,8 @@ public sealed class HeimdallAuthService(
|
||||||
|
|
||||||
private string Protect(HeimdallAttempt attempt) =>
|
private string Protect(HeimdallAttempt attempt) =>
|
||||||
_protector.Protect(JsonSerializer.Serialize(new AttemptWire(
|
_protector.Protect(JsonSerializer.Serialize(new AttemptWire(
|
||||||
attempt.Nonce, attempt.Provider, attempt.RequiresMemberAccess, attempt.ReturnPath.Value, attempt.ExpiresAt)));
|
attempt.Nonce, attempt.Provider, attempt.RequiresMemberAccess, attempt.ReturnPath.Value, attempt.ExpiresAt,
|
||||||
|
attempt.Purpose, attempt.ExpectedAccountId, attempt.PendingLinkId, attempt.Target, attempt.Proof)));
|
||||||
|
|
||||||
/// <summary>The live attempt a cookie value protects when it belongs to this nonce, else null.</summary>
|
/// <summary>The live attempt a cookie value protects when it belongs to this nonce, else null.</summary>
|
||||||
private HeimdallAttempt? Unprotect(string? cookieValue, string? nonce) =>
|
private HeimdallAttempt? Unprotect(string? cookieValue, string? nonce) =>
|
||||||
|
|
@ -238,13 +784,14 @@ public sealed class HeimdallAuthService(
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var wire = JsonSerializer.Deserialize<AttemptWire>(_protector.Unprotect(cookieValue));
|
var wire = JsonSerializer.Deserialize<AttemptWire>(_protector.Unprotect(cookieValue));
|
||||||
if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow())
|
if (wire is null || wire.ExpiresAt <= timeProvider.GetUtcNow() || !Enum.IsDefined(wire.Purpose))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new HeimdallAttempt(
|
return new HeimdallAttempt(
|
||||||
wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt);
|
wire.Nonce, wire.Provider, wire.RequiresMemberAccess, LocalReturnPath.Parse(wire.ReturnPath), wire.ExpiresAt,
|
||||||
|
wire.Purpose, wire.ExpectedAccountId, wire.PendingLinkId, wire.Target, wire.Proof);
|
||||||
}
|
}
|
||||||
catch (Exception error) when (error is CryptographicException or JsonException or FormatException)
|
catch (Exception error) when (error is CryptographicException or JsonException or FormatException)
|
||||||
{
|
{
|
||||||
|
|
@ -257,7 +804,12 @@ public sealed class HeimdallAuthService(
|
||||||
string Provider,
|
string Provider,
|
||||||
bool RequiresMemberAccess,
|
bool RequiresMemberAccess,
|
||||||
string ReturnPath,
|
string ReturnPath,
|
||||||
DateTimeOffset ExpiresAt);
|
DateTimeOffset ExpiresAt,
|
||||||
|
HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
|
||||||
|
string? ExpectedAccountId = null,
|
||||||
|
string? PendingLinkId = null,
|
||||||
|
string? Target = null,
|
||||||
|
string? Proof = null);
|
||||||
|
|
||||||
private async Task<UserAccount> UpsertUserAccountAsync(
|
private async Task<UserAccount> UpsertUserAccountAsync(
|
||||||
HeimdallVerifiedIdentity identity,
|
HeimdallVerifiedIdentity identity,
|
||||||
|
|
@ -314,11 +866,13 @@ public sealed class HeimdallAuthService(
|
||||||
Headline = $"Verified through Heimdall {provider}",
|
Headline = $"Verified through Heimdall {provider}",
|
||||||
UpdatedAtUtc = now
|
UpdatedAtUtc = now
|
||||||
};
|
};
|
||||||
userAccount.Membership ??= new Bifrost.Web.Domain.Membership
|
if (userAccount.Membership is null)
|
||||||
{
|
{
|
||||||
UserAccountId = userAccount.Id,
|
// Added explicitly: a row with a preset key assigned to a tracked account is taken for an existing one and the save fails.
|
||||||
CreatedAtUtc = now
|
userAccount.Membership = new Bifrost.Web.Domain.Membership { UserAccountId = userAccount.Id, CreatedAtUtc = now };
|
||||||
};
|
dbContext.Memberships.Add(userAccount.Membership);
|
||||||
|
}
|
||||||
|
|
||||||
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it.
|
// A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it.
|
||||||
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended)
|
if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended)
|
||||||
{
|
{
|
||||||
|
|
@ -333,10 +887,10 @@ public sealed class HeimdallAuthService(
|
||||||
userAccount,
|
userAccount,
|
||||||
displayName,
|
displayName,
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
if (grantMemberAccess && userAccount.Membership!.Status == MembershipStatus.Active)
|
if (grantMemberAccess && userAccount.Membership is { Status: MembershipStatus.Active })
|
||||||
{
|
{
|
||||||
ApplicationBootstrapper.EnsureRole(
|
ApplicationBootstrapper.EnsureRole(
|
||||||
userAccount.Membership!,
|
userAccount.Membership,
|
||||||
MemberRole.StandardMember,
|
MemberRole.StandardMember,
|
||||||
null,
|
null,
|
||||||
now,
|
now,
|
||||||
|
|
@ -344,6 +898,7 @@ public sealed class HeimdallAuthService(
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
return userAccount;
|
return userAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -409,7 +964,151 @@ public sealed record HeimdallAttempt(
|
||||||
string Provider,
|
string Provider,
|
||||||
bool RequiresMemberAccess,
|
bool RequiresMemberAccess,
|
||||||
LocalReturnPath ReturnPath,
|
LocalReturnPath ReturnPath,
|
||||||
DateTimeOffset ExpiresAt);
|
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);
|
||||||
|
|
||||||
public sealed record HeimdallStartRequest(
|
public sealed record HeimdallStartRequest(
|
||||||
[property: JsonPropertyName("appSlug")] string AppSlug,
|
[property: JsonPropertyName("appSlug")] string AppSlug,
|
||||||
|
|
@ -417,7 +1116,11 @@ public sealed record HeimdallStartRequest(
|
||||||
[property: JsonPropertyName("returnTo")] string ReturnTo,
|
[property: JsonPropertyName("returnTo")] string ReturnTo,
|
||||||
[property: JsonPropertyName("handoff")] HeimdallHandoff Handoff,
|
[property: JsonPropertyName("handoff")] HeimdallHandoff Handoff,
|
||||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy);
|
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy,
|
||||||
|
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
[property: JsonPropertyName("stepUp")] bool? StepUp = null,
|
||||||
|
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
[property: JsonPropertyName("firstLoginGrant")] string? FirstLoginGrant = null);
|
||||||
|
|
||||||
public sealed record HeimdallHandoff(
|
public sealed record HeimdallHandoff(
|
||||||
[property: JsonPropertyName("kind")] string Kind);
|
[property: JsonPropertyName("kind")] string Kind);
|
||||||
|
|
@ -440,7 +1143,10 @@ public sealed record HeimdallRedeemRequest(
|
||||||
public sealed record HeimdallRedeemResponse(
|
public sealed record HeimdallRedeemResponse(
|
||||||
[property: JsonPropertyName("returnTo")] string? ReturnTo,
|
[property: JsonPropertyName("returnTo")] string? ReturnTo,
|
||||||
[property: JsonPropertyName("accessToken")] string? AccessToken,
|
[property: JsonPropertyName("accessToken")] string? AccessToken,
|
||||||
[property: JsonPropertyName("account")] HeimdallAccount? Account);
|
[property: JsonPropertyName("account")] HeimdallAccount? Account,
|
||||||
|
[property: JsonPropertyName("mode")] string? Mode = null,
|
||||||
|
[property: JsonPropertyName("provider")] string? Provider = null,
|
||||||
|
[property: JsonPropertyName("stepUpRequested")] bool? StepUpRequested = null);
|
||||||
|
|
||||||
public sealed record HeimdallAccount(
|
public sealed record HeimdallAccount(
|
||||||
[property: JsonPropertyName("id")] string Id);
|
[property: JsonPropertyName("id")] string Id);
|
||||||
|
|
@ -477,3 +1183,26 @@ public static class HeimdallAttemptCookie
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path, Secure = true };
|
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,7 +3,8 @@ namespace Bifrost.Web.Features.Heimdall;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The page Heimdall's "Return to the app" lands on. The completion code arrives in the URL fragment, which
|
/// 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 server never sees, so the page's script reads it, drops it from the address bar, and posts it with
|
||||||
/// the attempt to the same path. The page is static: it never contains a code.
|
/// the attempt to the same path. A Google link returns a pending link id the same way instead of a code. The page
|
||||||
|
/// is static: it never contains a code or an id.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class HeimdallCompletePage
|
public static class HeimdallCompletePage
|
||||||
{
|
{
|
||||||
|
|
@ -22,21 +23,35 @@ public static class HeimdallCompletePage
|
||||||
<form id="complete" method="post" action="/auth/heimdall/complete">
|
<form id="complete" method="post" action="/auth/heimdall/complete">
|
||||||
<input type="hidden" name="attempt" />
|
<input type="hidden" name="attempt" />
|
||||||
<input type="hidden" name="code" />
|
<input type="hidden" name="code" />
|
||||||
|
<input type="hidden" name="pendingLinkId" />
|
||||||
</form>
|
</form>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var fragment = new URLSearchParams(location.hash.slice(1));
|
var fragment = new URLSearchParams(location.hash.slice(1));
|
||||||
var attempt = new URLSearchParams(location.search).get("attempt");
|
var attempt = new URLSearchParams(location.search).get("attempt");
|
||||||
var code = fragment.get("heimdall_completion_code");
|
var code = fragment.get("heimdall_completion_code");
|
||||||
|
var pendingLinkId = fragment.get("heimdall_pending_link_id");
|
||||||
var failed = fragment.get("heimdall_status") === "error";
|
var failed = fragment.get("heimdall_status") === "error";
|
||||||
history.replaceState(null, "", location.pathname + location.search);
|
history.replaceState(null, "", location.pathname + location.search);
|
||||||
if (failed || !code || !attempt) {
|
// 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) {
|
||||||
location.replace("/?auth=heimdall-error");
|
location.replace("/?auth=heimdall-error");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var form = document.getElementById("complete");
|
var form = document.getElementById("complete");
|
||||||
form.elements.attempt.value = attempt;
|
form.elements.attempt.value = attempt;
|
||||||
form.elements.code.value = code;
|
form.elements.code.value = code || "";
|
||||||
|
form.elements.pendingLinkId.value = pendingLinkId || "";
|
||||||
form.submit();
|
form.submit();
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
112
src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
Normal file
112
src/Bifrost.Web/Features/Heimdall/HeimdallMemberClient.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Heimdall;
|
||||||
|
|
||||||
|
/// <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,21 +64,18 @@ public sealed class HeimdallPatronSupportIntakeService(
|
||||||
x.ProviderEventId == request.ProviderEventId.Trim(),
|
x.ProviderEventId == request.ProviderEventId.Trim(),
|
||||||
cancellationToken);
|
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
|
var user = await dbContext.UserAccounts
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
||||||
|
|
||||||
if (user is null)
|
if (user is null)
|
||||||
{
|
{
|
||||||
return HeimdallPatronSupportIntakeResult.BadRequest(
|
return existingEvent is not null
|
||||||
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
|
? HeimdallPatronSupportIntakeResult.Processed(
|
||||||
|
$"Already processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||||
|
existingEvent.Id)
|
||||||
|
: HeimdallPatronSupportIntakeResult.BadRequest(
|
||||||
|
$"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||||
|
|
@ -98,7 +95,9 @@ public sealed class HeimdallPatronSupportIntakeService(
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
return HeimdallPatronSupportIntakeResult.Processed(
|
return HeimdallPatronSupportIntakeResult.Processed(
|
||||||
$"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
existingEvent is not null
|
||||||
|
? $"Already processed {request.Provider} patron support event {request.ProviderEventId}."
|
||||||
|
: $"Processed {request.Provider} patron support event {request.ProviderEventId}.",
|
||||||
supportEvent.Id);
|
supportEvent.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
47
src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
Normal file
47
src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
35
src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
Normal file
35
src/Bifrost.Web/Features/Heimdall/LinkedAccountsSnapshots.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
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 _);
|
||||||
|
}
|
||||||
143
src/Bifrost.Web/Features/Invites/ChatInviteService.cs
Normal file
143
src/Bifrost.Web/Features/Invites/ChatInviteService.cs
Normal file
|
|
@ -0,0 +1,143 @@
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using Bifrost.Web.Configuration;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Shared;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Invites;
|
||||||
|
|
||||||
|
/// <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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -17,7 +17,7 @@ public enum SuspensionOutcome
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit
|
/// The one place a membership becomes Suspended or stops being. Only a platform admin may call it, every use leaves an audit
|
||||||
/// receipt naming the admin, the account and the reason, and no sign-in path writes or lifts a suspension (Heimdall and GitHub
|
/// receipt naming the admin and the account (the reason is kept on the membership row, readable by admins only), and no sign-in path writes or lifts a suspension (Heimdall and GitHub
|
||||||
/// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved,
|
/// sign-in leave a Suspended membership as it is). Unsuspending restores Active for an account that was once approved,
|
||||||
/// Authenticated for one that never was; a pending request is not remembered.
|
/// Authenticated for one that never was; a pending request is not remembered.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -65,14 +65,16 @@ public sealed class MembershipSuspensionService(BifrostDbContext dbContext, Audi
|
||||||
membership.Status = suspend
|
membership.Status = suspend
|
||||||
? MembershipStatus.Suspended
|
? MembershipStatus.Suspended
|
||||||
: membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active;
|
: membership.ApprovedAtUtc is null ? MembershipStatus.Authenticated : MembershipStatus.Active;
|
||||||
|
// The reason is a column on the membership, for admins; the receipt names who and what changed, never why.
|
||||||
var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim();
|
var clipped = reason.Trim().Length > MaxReasonLength ? reason.Trim()[..MaxReasonLength] : reason.Trim();
|
||||||
// One save: the status change and its receipt stand or fall together (RecordAsync saves the shared context).
|
membership.SuspensionReason = suspend ? clipped : null;
|
||||||
|
// One save: the status change, the reason and the receipt stand or fall together (RecordAsync saves the shared context).
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
actor.UserAccount.Id,
|
actor.UserAccount.Id,
|
||||||
nameof(Membership),
|
nameof(Membership),
|
||||||
membership.Id,
|
membership.Id,
|
||||||
suspend ? "membership.suspended" : "membership.unsuspended",
|
suspend ? "membership.suspended" : "membership.unsuspended",
|
||||||
$"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}): {clipped}",
|
$"{(suspend ? "Suspended" : "Unsuspended")} {user.DisplayName} ({before} -> {membership.Status}).",
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
return SuspensionOutcome.Done;
|
return SuspensionOutcome.Done;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,9 @@ public sealed class MembershipSynchronizationService(
|
||||||
BifrostDbContext dbContext,
|
BifrostDbContext dbContext,
|
||||||
BifrostIdentityService bifrostIdentityService,
|
BifrostIdentityService bifrostIdentityService,
|
||||||
IOptions<BootstrapOptions> bootstrapOptions,
|
IOptions<BootstrapOptions> bootstrapOptions,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider,
|
||||||
|
AuditTrailService auditTrailService,
|
||||||
|
ILogger<MembershipSynchronizationService> logger)
|
||||||
{
|
{
|
||||||
public async Task SynchronizeAsync(ClaimsPrincipal principal, CancellationToken cancellationToken)
|
public async Task SynchronizeAsync(ClaimsPrincipal principal, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|
@ -34,11 +36,6 @@ public sealed class MembershipSynchronizationService(
|
||||||
.ThenInclude(x => x.TierSnapshots)
|
.ThenInclude(x => x.TierSnapshots)
|
||||||
.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.GitHubUserId == gitHubUserId, cancellationToken);
|
||||||
|
|
||||||
var invitation = await dbContext.MembershipInvitations
|
|
||||||
.SingleOrDefaultAsync(
|
|
||||||
x => x.NormalizedGitHubLogin == normalizedLogin && x.RevokedAtUtc == null,
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
if (userAccount is null)
|
if (userAccount is null)
|
||||||
{
|
{
|
||||||
userAccount = new UserAccount
|
userAccount = new UserAccount
|
||||||
|
|
@ -58,7 +55,7 @@ public sealed class MembershipSynchronizationService(
|
||||||
},
|
},
|
||||||
Membership = new Bifrost.Web.Domain.Membership
|
Membership = new Bifrost.Web.Domain.Membership
|
||||||
{
|
{
|
||||||
Status = invitation is null ? MembershipStatus.Authenticated : MembershipStatus.PendingApproval,
|
Status = MembershipStatus.Authenticated,
|
||||||
CreatedAtUtc = now
|
CreatedAtUtc = now
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -86,11 +83,6 @@ public sealed class MembershipSynchronizationService(
|
||||||
UserAccountId = userAccount.Id,
|
UserAccountId = userAccount.Id,
|
||||||
CreatedAtUtc = now
|
CreatedAtUtc = now
|
||||||
};
|
};
|
||||||
|
|
||||||
if (invitation is not null && userAccount.Membership.Status == MembershipStatus.Authenticated)
|
|
||||||
{
|
|
||||||
userAccount.Membership.Status = MembershipStatus.PendingApproval;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(userAccount.MemberProfile!.Nickname))
|
if (string.IsNullOrWhiteSpace(userAccount.MemberProfile!.Nickname))
|
||||||
|
|
@ -103,15 +95,14 @@ public sealed class MembershipSynchronizationService(
|
||||||
userAccount.GitHubLogin,
|
userAccount.GitHubLogin,
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
if (invitation is not null && invitation.AcceptedByUserAccountId is null)
|
MembershipStatus? promotedFrom = null;
|
||||||
{
|
|
||||||
invitation.AcceptedByUserAccountId = userAccount.Id;
|
|
||||||
invitation.AcceptedAtUtc = now;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
|
if (IsBootstrapAdmin(gitHubLogin, bootstrapOptions.Value))
|
||||||
{
|
{
|
||||||
PromoteToBootstrapAdmin(userAccount.Membership!, now);
|
promotedFrom = userAccount.Membership!.Status;
|
||||||
|
if (!ApplicationBootstrapper.TryPromoteBootstrapAdmin(userAccount, now, logger))
|
||||||
|
{
|
||||||
|
promotedFrom = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if (userAccount.Membership!.Status == MembershipStatus.Active)
|
else if (userAccount.Membership!.Status == MembershipStatus.Active)
|
||||||
{
|
{
|
||||||
|
|
@ -125,22 +116,16 @@ public sealed class MembershipSynchronizationService(
|
||||||
|
|
||||||
userAccount.MemberProfile!.UpdatedAtUtc = now;
|
userAccount.MemberProfile!.UpdatedAtUtc = now;
|
||||||
|
|
||||||
|
if (promotedFrom is { } before && before != userAccount.Membership!.Status)
|
||||||
|
{
|
||||||
|
// One save: the promotion and its receipt stand or fall together.
|
||||||
|
await ApplicationBootstrapper.RecordPromotionAsync(auditTrailService, userAccount, before, cancellationToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void PromoteToBootstrapAdmin(Bifrost.Web.Domain.Membership membership, DateTimeOffset now)
|
|
||||||
{
|
|
||||||
membership.Status = MembershipStatus.Active;
|
|
||||||
membership.IsPlatformAdmin = true;
|
|
||||||
membership.CanManageProjects = true;
|
|
||||||
membership.CanManageLedger = true;
|
|
||||||
membership.CanModerateMotions = true;
|
|
||||||
membership.ApprovedAtUtc ??= now;
|
|
||||||
|
|
||||||
ApplicationBootstrapper.EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
|
|
||||||
ApplicationBootstrapper.EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool TryReadGitHubIdentity(
|
private static bool TryReadGitHubIdentity(
|
||||||
ClaimsPrincipal principal,
|
ClaimsPrincipal principal,
|
||||||
out long gitHubUserId,
|
out long gitHubUserId,
|
||||||
|
|
|
||||||
|
|
@ -1,203 +0,0 @@
|
||||||
using Bifrost.Web.Domain;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Features.Motions;
|
|
||||||
|
|
||||||
public sealed class MotionEveSurfaceService
|
|
||||||
{
|
|
||||||
private const string MotionCommandTarget = "cultmesh://asgard.starfire.bifrost/commands/motion";
|
|
||||||
|
|
||||||
public EveSurfaceDocument BuildSurface(MotionGovernanceState state)
|
|
||||||
{
|
|
||||||
var motionNodes = state.Motions.Count > 0
|
|
||||||
? state.Motions.Select(BuildMotionCard).ToArray()
|
|
||||||
: [TextNode("motion-empty", "No motions yet.")];
|
|
||||||
|
|
||||||
return new EveSurfaceDocument(
|
|
||||||
"gamecult.eve.surface.v1",
|
|
||||||
"bifrost-motion-verse",
|
|
||||||
"Bifrost Motion Verse",
|
|
||||||
new EveNode(
|
|
||||||
"bifrost-motion-root",
|
|
||||||
"workspace",
|
|
||||||
new Dictionary<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,6 +52,7 @@ public sealed class MotionGovernanceService(
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
||||||
|
|
||||||
var motion = await dbContext.Motions
|
var motion = await dbContext.Motions
|
||||||
.Include(x => x.Votes)
|
.Include(x => x.Votes)
|
||||||
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
||||||
|
|
@ -83,6 +84,7 @@ public sealed class MotionGovernanceService(
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
actorUser.Id,
|
actorUser.Id,
|
||||||
nameof(Motion),
|
nameof(Motion),
|
||||||
|
|
|
||||||
|
|
@ -114,6 +114,7 @@ public sealed class SealedBallotService(
|
||||||
ballot.Commitment = commitment;
|
ballot.Commitment = commitment;
|
||||||
ballot.CommittedAtUtc = now;
|
ballot.CommittedAtUtc = now;
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
user.Id, nameof(Motion), motionId, "sealed.committed",
|
user.Id, nameof(Motion), motionId, "sealed.committed",
|
||||||
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
|
$"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.",
|
||||||
|
|
|
||||||
|
|
@ -14,10 +14,17 @@ public sealed class OidcClientSeeder(
|
||||||
IServiceScopeFactory scopeFactory,
|
IServiceScopeFactory scopeFactory,
|
||||||
OidcIssuerOptions options,
|
OidcIssuerOptions options,
|
||||||
OidcKeyMaterial material,
|
OidcKeyMaterial material,
|
||||||
IOptions<OpenIddictServerOptions> serverOptions) : IHostedService
|
IOptions<OpenIddictServerOptions> serverOptions,
|
||||||
|
ILogger<OidcClientSeeder> logger) : IHostedService
|
||||||
{
|
{
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri))
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"Bifrost:Oidc:Clients:Mas:BackchannelLogoutUri is not set: suspending an account stops new sign-ins and token refresh but does not end its existing chat sessions.");
|
||||||
|
}
|
||||||
|
|
||||||
// Reading the server options now runs their configuration, so a bad issuer stops startup rather than the first request.
|
// Reading the server options now runs their configuration, so a bad issuer stops startup rather than the first request.
|
||||||
_ = serverOptions.Value;
|
_ = serverOptions.Value;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,9 @@ using System.Security.Claims;
|
||||||
using Microsoft.AspNetCore;
|
using Microsoft.AspNetCore;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Desk;
|
||||||
using Bifrost.Web.Features.Membership;
|
using Bifrost.Web.Features.Membership;
|
||||||
|
using Bifrost.Web.Features.Registration;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
|
@ -15,7 +17,7 @@ namespace Bifrost.Web.Features.Oidc;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The decisions Bifrost owns at the OIDC provider: who the chat user is (sub = UserAccount.Id,
|
/// 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 (membership Active).
|
/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (invited or Active, not suspended).
|
||||||
/// OpenIddict does the protocol; these endpoints read the cookie session and the same actor facts the /App policy reads.
|
/// OpenIddict does the protocol; these endpoints read the cookie session and the same actor facts the /App policy reads.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class OidcEndpoints
|
public static class OidcEndpoints
|
||||||
|
|
@ -23,6 +25,8 @@ public static class OidcEndpoints
|
||||||
public const string SuspendedDescription = "The account is suspended.";
|
public const string SuspendedDescription = "The account is suspended.";
|
||||||
public const string NoIdentityDescription = "The account has no Bifrost identity.";
|
public const string NoIdentityDescription = "The account has no Bifrost identity.";
|
||||||
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved.";
|
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 OpenIddictScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
|
||||||
private const string IdentityAuthenticationType = "Bifrost.Oidc";
|
private const string IdentityAuthenticationType = "Bifrost.Oidc";
|
||||||
|
|
@ -34,7 +38,7 @@ public static class OidcEndpoints
|
||||||
app.MapMethods(OidcServiceCollectionExtensions.UserInfoPath, ["GET", "POST"], (Delegate)UserInfoAsync).AllowAnonymous();
|
app.MapMethods(OidcServiceCollectionExtensions.UserInfoPath, ["GET", "POST"], (Delegate)UserInfoAsync).AllowAnonymous();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IResult> AuthorizeAsync(HttpContext http, ICurrentBifrostActorAccessor actors)
|
private static async Task<IResult> AuthorizeAsync(HttpContext http, ICurrentBifrostActorAccessor actors, BifrostDbContext db)
|
||||||
{
|
{
|
||||||
var request = http.GetOpenIddictServerRequest()
|
var request = http.GetOpenIddictServerRequest()
|
||||||
?? throw new InvalidOperationException("The OpenIddict request could not be retrieved.");
|
?? throw new InvalidOperationException("The OpenIddict request could not be retrieved.");
|
||||||
|
|
@ -49,7 +53,7 @@ public static class OidcEndpoints
|
||||||
}
|
}
|
||||||
|
|
||||||
var actor = await actors.GetAsync(http.RequestAborted);
|
var actor = await actors.GetAsync(http.RequestAborted);
|
||||||
// Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written;
|
// 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;
|
||||||
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
|
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
|
||||||
if (actor.UserAccount is null)
|
if (actor.UserAccount is null)
|
||||||
{
|
{
|
||||||
|
|
@ -83,6 +87,13 @@ public static class OidcEndpoints
|
||||||
|
|
||||||
var principal = new ClaimsPrincipal(identity);
|
var principal = new ClaimsPrincipal(identity);
|
||||||
principal.SetScopes(request.GetScopes());
|
principal.SetScopes(request.GetScopes());
|
||||||
|
// A desk scope is what makes a token a desk token: its audience is the desk's. The client's permissions already
|
||||||
|
// decided whether it may ask for the scope (the MAS client may not), so this branch is reached only by one that may.
|
||||||
|
if (request.GetScopes().Any(DeskEndpoints.IsDeskScope))
|
||||||
|
{
|
||||||
|
principal.SetResources(DeskEndpoints.Audience);
|
||||||
|
}
|
||||||
|
|
||||||
principal.SetDestinations(claim => claim.Type switch
|
principal.SetDestinations(claim => claim.Type switch
|
||||||
{
|
{
|
||||||
Claims.Subject => [Destinations.AccessToken, Destinations.IdentityToken],
|
Claims.Subject => [Destinations.AccessToken, Destinations.IdentityToken],
|
||||||
|
|
@ -91,19 +102,39 @@ public static class OidcEndpoints
|
||||||
_ => [Destinations.AccessToken]
|
_ => [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
|
||||||
|
// (single use, ten minutes) is still there when they come back, because only an OpenIddict response spends it.
|
||||||
|
if (!IsDeskToken(principal) && !await ConsentEndpoints.HasLiveReceiptAsync(db, account.Id, http.RequestAborted))
|
||||||
|
{
|
||||||
|
return Results.Redirect(ConsentEndpoints.PathFor(http.Request.PathBase + http.Request.Path + http.Request.QueryString));
|
||||||
|
}
|
||||||
|
|
||||||
return Results.SignIn(principal, properties: null, OpenIddictScheme);
|
return Results.SignIn(principal, properties: null, OpenIddictScheme);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>A token whose scopes include a desk scope is a desk token. Only the chat token requires the training-notice receipt.</summary>
|
||||||
|
// Only a token whose every scope is a desk scope skips the consent gate: a client that may hold chat scopes too cannot ride a desk scope past the receipt.
|
||||||
|
private static bool IsDeskToken(ClaimsPrincipal? principal) => principal is not null && principal.GetScopes() is { Length: > 0 } scopes && scopes.All(DeskEndpoints.IsDeskScope);
|
||||||
|
|
||||||
private static async Task<IResult> ExchangeAsync(HttpContext http, BifrostDbContext db)
|
private static async Task<IResult> ExchangeAsync(HttpContext http, BifrostDbContext db)
|
||||||
{
|
{
|
||||||
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
|
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
|
||||||
// The code's own principal carries the claims chosen at authorize time; suspension is read again here,
|
// The code's own principal carries the claims chosen at authorize time; suspension and agreement are read again here,
|
||||||
// because the code outlives the authorize decision (an account suspended since gets no tokens).
|
// because the code outlives the authorize decision (an account suspended or withdrawn since gets no tokens).
|
||||||
var result = await http.AuthenticateAsync(OpenIddictScheme);
|
var result = await http.AuthenticateAsync(OpenIddictScheme);
|
||||||
var subject = result.Principal?.GetClaim(Claims.Subject);
|
var subject = result.Principal?.GetClaim(Claims.Subject);
|
||||||
if (!await IsStillChatEligibleAsync(db, subject, http.RequestAborted))
|
if (await ChatRefusalAsync(db, subject, http.RequestAborted, IsDeskToken(result.Principal)) is { } refusal)
|
||||||
{
|
{
|
||||||
return Deny(Errors.InvalidGrant, SuspendedDescription);
|
return Deny(Errors.InvalidGrant, refusal);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme);
|
return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme);
|
||||||
|
|
@ -117,10 +148,10 @@ public static class OidcEndpoints
|
||||||
return Results.Challenge(authenticationSchemes: [OpenIddictScheme]);
|
return Results.Challenge(authenticationSchemes: [OpenIddictScheme]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// An access token outlives the authorize decision too: an account suspended since is no longer answered.
|
// An access token outlives the authorize decision too: an account suspended since, or one whose agreement has gone, is no longer answered.
|
||||||
if (!await IsStillChatEligibleAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted))
|
if (await ChatRefusalAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted, IsDeskToken(result.Principal)) is { } refusal)
|
||||||
{
|
{
|
||||||
return Deny(Errors.InsufficientAccess, SuspendedDescription);
|
return Deny(Errors.InsufficientAccess, refusal);
|
||||||
}
|
}
|
||||||
|
|
||||||
var claims = new Dictionary<string, object?> { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) };
|
var claims = new Dictionary<string, object?> { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) };
|
||||||
|
|
@ -135,19 +166,35 @@ public static class OidcEndpoints
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
|
/// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
|
||||||
/// the account exists and its membership is not Suspended. Membership may be absent, pending or Active. Re-read on every call.
|
/// 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.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static async Task<bool> IsStillChatEligibleAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken)
|
internal static async Task<string?> ChatRefusalAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken, bool deskToken = false)
|
||||||
{
|
{
|
||||||
if (!Guid.TryParse(subject, out var accountId))
|
if (!Guid.TryParse(subject, out var accountId))
|
||||||
{
|
{
|
||||||
return false;
|
return SuspendedDescription;
|
||||||
}
|
}
|
||||||
|
|
||||||
var account = await db.UserAccounts.AsNoTracking()
|
var account = await db.UserAccounts.AsNoTracking()
|
||||||
.Include(x => x.Membership)
|
.Include(x => x.Membership)
|
||||||
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
||||||
return account is not null && account.Membership?.Status != MembershipStatus.Suspended;
|
if (account is null || account.Membership?.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <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>
|
/// <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>
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ using static OpenIddict.Abstractions.OpenIddictConstants;
|
||||||
namespace Bifrost.Web.Features.Oidc;
|
namespace Bifrost.Web.Features.Oidc;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ends the chat sessions of a subject who is no longer allowed to chat (suspended, or the account gone). Each tick it lists the subjects holding valid
|
/// Ends the chat sessions of a subject who is no longer allowed to chat (suspended, the account gone, or no live receipt for the training notice in force). Each tick it lists the subjects holding valid
|
||||||
/// authorizations of the configured client; for each one the shared chat-eligibility reading refuses, it POSTs one signed
|
/// authorizations of the configured client; for each one the shared chat-eligibility reading refuses, it POSTs one signed
|
||||||
/// OIDC back-channel logout token to MAS and, only after a 2xx, revokes that subject's authorizations. The
|
/// OIDC back-channel logout token to MAS and, only after a 2xx, revokes that subject's authorizations. The
|
||||||
/// authorizations table is the queue: nothing is stored, so a restart, a MAS outage or a later-set URI resumes from it.
|
/// authorizations table is the queue: nothing is stored, so a restart, a MAS outage or a later-set URI resumes from it.
|
||||||
|
|
@ -127,7 +127,7 @@ public sealed class OidcLogoutReconciler(
|
||||||
{
|
{
|
||||||
await using var scope = scopeFactory.CreateAsyncScope();
|
await using var scope = scopeFactory.CreateAsyncScope();
|
||||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||||
if (await OidcEndpoints.IsStillChatEligibleAsync(db, subject, cancellationToken))
|
if (await OidcEndpoints.ChatRefusalAsync(db, subject, cancellationToken) is null)
|
||||||
{
|
{
|
||||||
_backoff.Remove(subject);
|
_backoff.Remove(subject);
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
139
src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
Normal file
139
src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
54
src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
Normal file
54
src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
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; }
|
||||||
|
}
|
||||||
470
src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
Normal file
470
src/Bifrost.Web/Features/Passkeys/PasskeyService.cs
Normal file
|
|
@ -0,0 +1,470 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Bifrost.Web.Data;
|
||||||
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Heimdall;
|
||||||
|
using Fido2NetLib;
|
||||||
|
using Fido2NetLib.Objects;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Bifrost.Web.Features.Passkeys;
|
||||||
|
|
||||||
|
/// <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,6 +10,8 @@ public sealed class PatronageService(
|
||||||
AuditTrailService auditTrailService,
|
AuditTrailService auditTrailService,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
|
private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron";
|
||||||
|
|
||||||
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
||||||
Guid? actorUserAccountId,
|
Guid? actorUserAccountId,
|
||||||
Guid userAccountId,
|
Guid userAccountId,
|
||||||
|
|
@ -27,6 +29,19 @@ public sealed class PatronageService(
|
||||||
CancellationToken cancellationToken,
|
CancellationToken cancellationToken,
|
||||||
Guid? projectId = null)
|
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
|
var user = await dbContext.UserAccounts
|
||||||
.Include(x => x.Membership)
|
.Include(x => x.Membership)
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
@ -51,23 +66,11 @@ public sealed class PatronageService(
|
||||||
throw new InvalidOperationException("Patron support adjustments must reduce support.");
|
throw new InvalidOperationException("Patron support adjustments must reduce support.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var normalizedProviderEventId = providerEventId.Trim();
|
|
||||||
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
|
if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("External patron provider events require a provider event id.");
|
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)
|
var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode)
|
||||||
? "USD"
|
? "USD"
|
||||||
: currencyCode.Trim().ToUpperInvariant();
|
: currencyCode.Trim().ToUpperInvariant();
|
||||||
|
|
@ -86,7 +89,7 @@ public sealed class PatronageService(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var supportEvent = new PatronSupportEvent
|
var created = new PatronSupportEvent
|
||||||
{
|
{
|
||||||
UserAccountId = userAccountId,
|
UserAccountId = userAccountId,
|
||||||
ProjectId = projectId,
|
ProjectId = projectId,
|
||||||
|
|
@ -104,7 +107,7 @@ public sealed class PatronageService(
|
||||||
Notes = notes.Trim()
|
Notes = notes.Trim()
|
||||||
};
|
};
|
||||||
|
|
||||||
dbContext.PatronSupportEvents.Add(supportEvent);
|
dbContext.PatronSupportEvents.Add(created);
|
||||||
dbContext.PointTransactions.Add(new PointTransaction
|
dbContext.PointTransactions.Add(new PointTransaction
|
||||||
{
|
{
|
||||||
UserAccountId = userAccountId,
|
UserAccountId = userAccountId,
|
||||||
|
|
@ -113,20 +116,22 @@ public sealed class PatronageService(
|
||||||
Amount = amount,
|
Amount = amount,
|
||||||
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
|
IsDecaying = kind == PatronSupportEventKind.OneTimeDonation,
|
||||||
CreatedAtUtc = now,
|
CreatedAtUtc = now,
|
||||||
Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}."
|
Note = $"Recorded {provider} {kind} patron support event {created.ExternalSupportId}."
|
||||||
});
|
});
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
await auditTrailService.RecordAsync(
|
await auditTrailService.RecordAsync(
|
||||||
actorUserAccountId,
|
actorUserAccountId,
|
||||||
nameof(PatronSupportEvent),
|
nameof(PatronSupportEvent),
|
||||||
supportEvent.Id,
|
created.Id,
|
||||||
"patron-support.recorded",
|
"patron-support.recorded",
|
||||||
$"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.",
|
$"Recorded {amount:0.##} {created.CurrencyCode} {provider} {kind} patron support for {user.DisplayName}.",
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
|
await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken);
|
||||||
return supportEvent;
|
|
||||||
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PatronPointSummary> RefreshPatronTierSnapshotAsync(
|
public async Task<PatronPointSummary> RefreshPatronTierSnapshotAsync(
|
||||||
|
|
@ -134,24 +139,66 @@ public sealed class PatronageService(
|
||||||
Guid userAccountId,
|
Guid userAccountId,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
dbContext.ChangeTracker.Clear();
|
// 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.
|
||||||
var user = await dbContext.UserAccounts
|
UserAccount user;
|
||||||
.Include(x => x.Membership)
|
PatronPointSummary summary;
|
||||||
.Include(x => x.PatronSupportEvents)
|
PatronTierDefinition? tier;
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
for (var attempt = 0; ; attempt++)
|
||||||
|
|
||||||
if (user.Membership is null)
|
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
dbContext.ChangeTracker.Clear();
|
||||||
|
|
||||||
|
user = await dbContext.UserAccounts
|
||||||
|
.Include(x => x.Membership)
|
||||||
|
.Include(x => x.PatronSupportEvents)
|
||||||
|
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
||||||
|
if (user.Membership is null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||||
|
}
|
||||||
|
|
||||||
|
(summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await dbContext.SaveChangesAsync(cancellationToken);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (DbUpdateException error) when (attempt < 3 &&
|
||||||
|
error.InnerException is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation, ConstraintName: CurrentPatronIndex })
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var summary = CalculatePatronPoints(user.PatronSupportEvents, timeProvider.GetUtcNow());
|
await auditTrailService.RecordAsync(
|
||||||
|
actorUserAccountId,
|
||||||
|
nameof(TierSnapshot),
|
||||||
|
user.Membership.Id,
|
||||||
|
"patron-tier.derived",
|
||||||
|
tier is null
|
||||||
|
? $"Cleared patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points."
|
||||||
|
: $"Derived {tier.Label} patron tier for {user.DisplayName}; {summary.EffectivePoints:0.##} effective patron points.",
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return summary with { TierLabel = tier?.Label ?? string.Empty, VotingWeight = tier?.VotingWeight ?? 0m };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <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 tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
|
var tier = PatronTierPolicy.ResolveTier(summary.EffectivePoints);
|
||||||
var now = timeProvider.GetUtcNow();
|
|
||||||
|
|
||||||
var currentPatronSnapshots = await dbContext.TierSnapshots
|
var currentPatronSnapshots = await dbContext.TierSnapshots
|
||||||
.Where(x => x.MembershipId == user.Membership.Id &&
|
.Where(x => x.MembershipId == membership.Id &&
|
||||||
x.Kind == TierSnapshotKind.Patron &&
|
x.Kind == TierSnapshotKind.Patron &&
|
||||||
x.IsCurrent)
|
x.IsCurrent)
|
||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
|
|
@ -165,7 +212,7 @@ public sealed class PatronageService(
|
||||||
{
|
{
|
||||||
dbContext.TierSnapshots.Add(new TierSnapshot
|
dbContext.TierSnapshots.Add(new TierSnapshot
|
||||||
{
|
{
|
||||||
MembershipId = user.Membership.Id,
|
MembershipId = membership.Id,
|
||||||
Kind = TierSnapshotKind.Patron,
|
Kind = TierSnapshotKind.Patron,
|
||||||
Label = PatronTierPolicy.SnapshotLabel(tier),
|
Label = PatronTierPolicy.SnapshotLabel(tier),
|
||||||
Weight = tier.VotingWeight,
|
Weight = tier.VotingWeight,
|
||||||
|
|
@ -176,18 +223,7 @@ public sealed class PatronageService(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbContext.SaveChangesAsync(cancellationToken);
|
return (summary, tier);
|
||||||
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(
|
public static PatronPointSummary CalculatePatronPoints(
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ public static class ConsentEndpoints
|
||||||
|
|
||||||
public static void MapConsent(this IEndpointRouteBuilder app)
|
public static void MapConsent(this IEndpointRouteBuilder app)
|
||||||
{
|
{
|
||||||
app.MapGet(Path, async (ICurrentBifrostActorAccessor actors, BifrostDbContext db, CancellationToken ct) =>
|
app.MapGet(Path, async (HttpContext http, ICurrentBifrostActorAccessor actors, BifrostDbContext db, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var actor = await actors.GetAsync(ct);
|
var actor = await actors.GetAsync(ct);
|
||||||
if (!actor.IsAuthenticated || actor.UserAccount is null)
|
if (!actor.IsAuthenticated || actor.UserAccount is null)
|
||||||
|
|
@ -28,7 +28,7 @@ public static class ConsentEndpoints
|
||||||
return Results.Redirect($"/auth/sign-in?returnUrl={Uri.EscapeDataString(LocalReturnPath.Parse(Path).Value)}");
|
return Results.Redirect($"/auth/sign-in?returnUrl={Uri.EscapeDataString(LocalReturnPath.Parse(Path).Value)}");
|
||||||
}
|
}
|
||||||
|
|
||||||
return await PageAsync(db, actor.UserAccount.Id, null, StatusCodes.Status200OK, ct);
|
return await PageAsync(db, actor.UserAccount.Id, null, StatusCodes.Status200OK, ct, ReturnPathOf(http.Request.Query["returnUrl"]));
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
app.MapPost(Path + "/accept", async (
|
app.MapPost(Path + "/accept", async (
|
||||||
|
|
@ -53,7 +53,7 @@ public static class ConsentEndpoints
|
||||||
var form = await ReadFormAsync(http.Request, ct);
|
var form = await ReadFormAsync(http.Request, ct);
|
||||||
if (form is null || form["version"].ToString() != TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture))
|
if (form is null || form["version"].ToString() != TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture))
|
||||||
{
|
{
|
||||||
return await PageAsync(db, actor.UserAccount.Id, $"Send the version in force, {TrainingNotice.Version}, to agree.", StatusCodes.Status400BadRequest, ct);
|
return await PageAsync(db, actor.UserAccount.Id, $"Send the version in force, {TrainingNotice.Version}, to agree.", StatusCodes.Status400BadRequest, ct, ReturnPathOf(form?["returnUrl"] ?? default));
|
||||||
}
|
}
|
||||||
|
|
||||||
var accountId = actor.UserAccount.Id;
|
var accountId = actor.UserAccount.Id;
|
||||||
|
|
@ -77,7 +77,7 @@ public static class ConsentEndpoints
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Back();
|
return new SeeOther(ReturnPathOf(form["returnUrl"]) ?? Path);
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
app.MapPost(Path + "/withdraw", async (
|
app.MapPost(Path + "/withdraw", async (
|
||||||
|
|
@ -133,9 +133,17 @@ public static class ConsentEndpoints
|
||||||
|
|
||||||
private static IResult Refused() => Results.Text("Cross-site consent changes are refused.", statusCode: StatusCodes.Status403Forbidden);
|
private static IResult Refused() => Results.Text("Cross-site consent changes are refused.", statusCode: StatusCodes.Status403Forbidden);
|
||||||
|
|
||||||
|
/// <summary>Where the consent page sends the member after agreeing: a local path (<see cref="LocalReturnPath"/>) the refused chat authorize names, else the page itself.</summary>
|
||||||
|
internal static string? ReturnPathOf(Microsoft.Extensions.Primitives.StringValues requested) =>
|
||||||
|
requested.ToString() is { Length: > 0 } text ? LocalReturnPath.Parse(text).Value : null;
|
||||||
|
|
||||||
|
/// <summary>The consent page that a refused chat sign-in lands on, carrying the request to resume once the member agrees.</summary>
|
||||||
|
public static string PathFor(string returnPath) => $"{Path}?returnUrl={Uri.EscapeDataString(returnPath)}";
|
||||||
|
|
||||||
private static IResult Back() => new SeeOther(Path);
|
private static IResult Back() => new SeeOther(Path);
|
||||||
|
|
||||||
private static Task<bool> HasLiveReceiptAsync(BifrostDbContext db, Guid accountId, CancellationToken ct) =>
|
/// <summary>The one reading of "may speak": a live receipt for the version in force. A receipt for any other version, or a withdrawn one, does not count.</summary>
|
||||||
|
internal static Task<bool> HasLiveReceiptAsync(BifrostDbContext db, Guid accountId, CancellationToken ct) =>
|
||||||
db.ConsentReceipts.AnyAsync(x => x.UserAccountId == accountId && x.NoticeVersion == TrainingNotice.Version && x.WithdrawnAtUtc == null, ct);
|
db.ConsentReceipts.AnyAsync(x => x.UserAccountId == accountId && x.NoticeVersion == TrainingNotice.Version && x.WithdrawnAtUtc == null, ct);
|
||||||
|
|
||||||
private static async Task<IFormCollection?> ReadFormAsync(HttpRequest request, CancellationToken ct)
|
private static async Task<IFormCollection?> ReadFormAsync(HttpRequest request, CancellationToken ct)
|
||||||
|
|
@ -172,10 +180,10 @@ public static class ConsentEndpoints
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IResult> PageAsync(BifrostDbContext db, Guid accountId, string? error, int status, CancellationToken ct)
|
private static async Task<IResult> PageAsync(BifrostDbContext db, Guid accountId, string? error, int status, CancellationToken ct, string? returnPath = null)
|
||||||
{
|
{
|
||||||
var receipts = await db.ConsentReceipts.AsNoTracking().Where(x => x.UserAccountId == accountId).ToListAsync(ct);
|
var receipts = await db.ConsentReceipts.AsNoTracking().Where(x => x.UserAccountId == accountId).ToListAsync(ct);
|
||||||
return new HtmlPage(ConsentPage.Render(ConsentPage.StateOf(receipts), error), status);
|
return new HtmlPage(ConsentPage.Render(ConsentPage.StateOf(receipts), error, returnPath), status);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class HtmlPage(string html, int status) : IResult
|
private sealed class HtmlPage(string html, int status) : IResult
|
||||||
|
|
|
||||||
|
|
@ -42,25 +42,26 @@ public static class ConsentPage
|
||||||
|
|
||||||
private static string Iso(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture);
|
private static string Iso(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
public static string Render(ConsentState state, string? error)
|
public static string Render(ConsentState state, string? error, string? returnPath = null)
|
||||||
{
|
{
|
||||||
static string E(string? text) => WebUtility.HtmlEncode(text ?? "");
|
static string E(string? text) => WebUtility.HtmlEncode(text ?? "");
|
||||||
var version = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
var version = TrainingNotice.Version.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
var (message, anyLive) = state switch
|
var (message, anyLive) = state switch
|
||||||
{
|
{
|
||||||
ConsentState.Current current => ($"You agreed to version {version} on {Iso(current.AgreedAtUtc)}. Your messages may be used as the notice says.", true),
|
ConsentState.Current current => ($"You agreed to version {version} on {Iso(current.AgreedAtUtc)}. You may speak in a recorded room, and your messages may be used as the notice says.", true),
|
||||||
ConsentState.Older older => ($"You agreed to version {older.Version} on {Iso(older.AgreedAtUtc)}; version {version} is in force and your messages are not used until you agree to it.", true),
|
ConsentState.Older older => ($"You agreed to version {older.Version} on {Iso(older.AgreedAtUtc)}; version {version} is in force; you cannot speak in a recorded room and your messages are not used until you agree to it.", true),
|
||||||
ConsentState.Withdrawn withdrawn => ($"You withdrew on {Iso(withdrawn.WithdrawnAtUtc)}. Your messages are not used.", false),
|
ConsentState.Withdrawn withdrawn => ($"You withdrew on {Iso(withdrawn.WithdrawnAtUtc)}. You cannot speak in a recorded room, and your messages are not used. Lines you already spoke stay.", false),
|
||||||
_ => ("You have not agreed. Your messages are not used.", false)
|
_ => ("You have not agreed. You cannot speak in a recorded room, and your messages are not used.", false)
|
||||||
};
|
};
|
||||||
var summary = error is null ? "" : $"""<div id="errors" role="alert" tabindex="-1"><strong>That did not go through.</strong><p>{E(error)}</p></div>""";
|
var summary = error is null ? "" : $"""<div id="errors" role="alert" tabindex="-1"><strong>That did not go through.</strong><p>{E(error)}</p></div>""";
|
||||||
// Withdraw whenever any live receipt exists (an older one included); Agree whenever none is live for the version in force.
|
// Withdraw whenever any live receipt exists (an older one included); Agree whenever none is live for the version in force.
|
||||||
|
var back = returnPath is null ? "" : $"""<input type="hidden" name="returnUrl" value="{E(returnPath)}" />""";
|
||||||
var withdrawButton = anyLive
|
var withdrawButton = anyLive
|
||||||
? """<form method="post" action="/auth/bifrost/consent/withdraw"><button type="submit">Withdraw</button></form>"""
|
? """<form method="post" action="/auth/bifrost/consent/withdraw"><button type="submit">Withdraw</button></form>"""
|
||||||
: "";
|
: "";
|
||||||
var agreeButton = state is ConsentState.Current
|
var agreeButton = state is ConsentState.Current
|
||||||
? ""
|
? ""
|
||||||
: $"""<form method="post" action="/auth/bifrost/consent/accept"><input type="hidden" name="version" value="{version}" /><button type="submit">Agree to version {version}</button></form>""";
|
: $"""<form method="post" action="/auth/bifrost/consent/accept"><input type="hidden" name="version" value="{version}" />{back}<button type="submit">Agree to version {version}</button></form>""";
|
||||||
var button = agreeButton + withdrawButton;
|
var button = agreeButton + withdrawButton;
|
||||||
|
|
||||||
return $$"""
|
return $$"""
|
||||||
|
|
@ -91,11 +92,11 @@ public static class ConsentPage
|
||||||
<h1>Training consent</h1>
|
<h1>Training consent</h1>
|
||||||
{{summary}}
|
{{summary}}
|
||||||
<p id="state" aria-live="polite">{{E(message)}}</p>
|
<p id="state" aria-live="polite">{{E(message)}}</p>
|
||||||
{{button}}
|
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Training notice, version {{version}}</legend>
|
<legend>Training notice, version {{version}}</legend>
|
||||||
{{TrainingNotice.Html("notice")}}
|
{{TrainingNotice.Html("notice")}}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
{{button}}
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,8 @@ public sealed record RegistrationOutcome(
|
||||||
public sealed class NativeRegistration(
|
public sealed class NativeRegistration(
|
||||||
BifrostIdentityService identities,
|
BifrostIdentityService identities,
|
||||||
RegistrationChallengeService challenges,
|
RegistrationChallengeService challenges,
|
||||||
RegistrationRateLimit rateLimit)
|
RegistrationRateLimit rateLimit,
|
||||||
|
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
|
||||||
{
|
{
|
||||||
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
|
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|
@ -113,6 +114,7 @@ public sealed class NativeRegistration(
|
||||||
{
|
{
|
||||||
var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken);
|
var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, attempt.AcceptedNoticeVersion, cancellationToken);
|
||||||
await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account));
|
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);
|
return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false);
|
||||||
}
|
}
|
||||||
catch (BifrostIdentityException error)
|
catch (BifrostIdentityException error)
|
||||||
|
|
|
||||||
|
|
@ -99,7 +99,7 @@ public static class RegistrationPage
|
||||||
var link = model.ErrorField switch
|
var link = model.ErrorField switch
|
||||||
{
|
{
|
||||||
RegistrationField.Identity => """<ul><li><a href="#identity">Identity name</a></li></ul>""",
|
RegistrationField.Identity => """<ul><li><a href="#identity">Identity name</a></li></ul>""",
|
||||||
RegistrationField.Consent => """<ul><li><a href="#consent">I agree to this notice (optional)</a></li></ul>""",
|
RegistrationField.Consent => """<ul><li><a href="#consent">I agree to this notice, to speak in a recorded room</a></li></ul>""",
|
||||||
_ => ""
|
_ => ""
|
||||||
};
|
};
|
||||||
summary.Append($"""<div id="errors" role="alert" tabindex="-1"><strong>Registration did not go through.</strong><p>{E(model.Error)}</p>{link}</div>""");
|
summary.Append($"""<div id="errors" role="alert" tabindex="-1"><strong>Registration did not go through.</strong><p>{E(model.Error)}</p>{link}</div>""");
|
||||||
|
|
@ -154,8 +154,8 @@ public static class RegistrationPage
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Training notice, version {{notice}}</legend>
|
<legend>Training notice, version {{notice}}</legend>
|
||||||
{{TrainingNotice.Html("notice")}}
|
{{TrainingNotice.Html("notice")}}
|
||||||
<label class="check" for="consent"><input type="checkbox" id="consent" name="consent" value="yes" aria-describedby="notice"{{Invalid(RegistrationField.Consent)}} />I agree to this notice (optional)</label>
|
<label class="check" for="consent"><input type="checkbox" id="consent" name="consent" value="yes" aria-describedby="notice"{{Invalid(RegistrationField.Consent)}} />I agree to this notice, to speak in a recorded room</label>
|
||||||
<p class="hint">Optional. You can create an account without agreeing; then none of your messages are used. You can agree later on your consent page.</p>
|
<p class="hint">You can create an account without agreeing. Agreement is needed to speak in a recorded room, and you can give it later on your consent page. Withdrawing ends future speaking there; lines you have already spoken stay.</p>
|
||||||
<input type="hidden" name="acceptedNoticeVersion" value="{{notice}}" />
|
<input type="hidden" name="acceptedNoticeVersion" value="{{notice}}" />
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<input type="hidden" name="challenge" value="{{E(model.Challenge)}}" />
|
<input type="hidden" name="challenge" value="{{E(model.Challenge)}}" />
|
||||||
|
|
|
||||||
|
|
@ -5,21 +5,22 @@ namespace Bifrost.Web.Features.Registration;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The training notice a person may agree to. Changing the wording in substance means a new <see cref="Version"/> (a
|
/// The training notice a person may agree to. Changing the wording in substance means a new <see cref="Version"/> (a
|
||||||
/// positive integer, no leading zeros), because a receipt records the version the person agreed to; a receipt for an
|
/// positive integer, no leading zeros), because a receipt records the version the person agreed to; a receipt for any
|
||||||
/// older version no longer counts and the person is asked again on the consent page.
|
/// other version no longer counts, the chat sign-in is refused, and the person is asked again on the consent page.
|
||||||
|
/// The text is frozen once served: a test pins its hash per version, so an edit without a version bump fails.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class TrainingNotice
|
public static class TrainingNotice
|
||||||
{
|
{
|
||||||
public const int Version = 2;
|
public const int Version = 1;
|
||||||
|
|
||||||
public const string Text =
|
public const string Text =
|
||||||
"GameCult chat training notice, version 2\n\n" +
|
"GameCult chat training notice, version 1\n\n" +
|
||||||
"GameCult may use messages you post in GameCult chat to train and evaluate AI models that GameCult builds and runs.\n\n" +
|
"GameCult may use messages you post in GameCult chat to train and evaluate AI models that GameCult builds and runs.\n\n" +
|
||||||
"What counts. The text of your messages, with their time and room, tied to your account name. Not your email address, your sign-in details or anything you did not post. Nothing that came from Discord is used, in any form.\n\n" +
|
"What counts. The text of your messages, with their time and room, tied to your account name. Not your email address, your sign-in details or anything you did not post. Nothing that came from Discord is used, in any form.\n\n" +
|
||||||
"It is your choice. You can use GameCult chat without agreeing. If you do not agree, none of your messages are used.\n\n" +
|
"It is your choice. Agreement is needed to speak in a recorded room. You can have a GameCult account, see the members page and vote without agreeing. If you do not agree, you cannot speak in a recorded room and none of your messages are used.\n\n" +
|
||||||
"If you agree, we record your account, this notice's version number and the time. Nothing else is stored with it.\n\n" +
|
"If you agree, we record your account, this notice's version number and the time. Nothing else is stored with it.\n\n" +
|
||||||
"If you withdraw, we leave all your messages out of every training set made after that moment. Withdrawing deletes nothing: your messages stay in chat and on our servers, anything already used to train a model stays used, and a dataset already built is not recalled. We keep the record that you agreed and when you withdrew.\n\n" +
|
"If you withdraw, you can no longer speak in a recorded room, and we leave all your messages out of every training set made after that moment. Lines you have already spoken stay: withdrawing deletes nothing. Your messages stay in chat and on our servers, anything already used to train a model stays used, and a dataset already built is not recalled. We keep the record that you agreed and when you withdrew.\n\n" +
|
||||||
"You can agree or withdraw at any time on your consent page while signed in. If the notice changes, its version changes and we ask again; until you agree to the new version, your messages are not used.";
|
"You can agree or withdraw at any time on your consent page while signed in. If the notice changes, its version changes and we ask again; until you agree to the new version, you cannot speak in a recorded room and your messages are not used.";
|
||||||
|
|
||||||
/// <summary>The text as HTML-encoded paragraphs inside a div with the given id.</summary>
|
/// <summary>The text as HTML-encoded paragraphs inside a div with the given id.</summary>
|
||||||
public static string Html(string id)
|
public static string Html(string id)
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ public sealed class ApplicationBootstrapper(
|
||||||
BifrostDbContext dbContext,
|
BifrostDbContext dbContext,
|
||||||
IOptions<BootstrapOptions> bootstrapOptions,
|
IOptions<BootstrapOptions> bootstrapOptions,
|
||||||
TimeProvider timeProvider,
|
TimeProvider timeProvider,
|
||||||
|
AuditTrailService auditTrailService,
|
||||||
ILogger<ApplicationBootstrapper> logger)
|
ILogger<ApplicationBootstrapper> logger)
|
||||||
{
|
{
|
||||||
public async Task RunAsync(CancellationToken cancellationToken)
|
public async Task RunAsync(CancellationToken cancellationToken)
|
||||||
|
|
@ -40,16 +41,11 @@ public sealed class ApplicationBootstrapper(
|
||||||
|
|
||||||
foreach (var adminUser in adminUsers.Where(x => x.Membership is not null))
|
foreach (var adminUser in adminUsers.Where(x => x.Membership is not null))
|
||||||
{
|
{
|
||||||
var membership = adminUser.Membership!;
|
var before = adminUser.Membership!.Status;
|
||||||
membership.Status = MembershipStatus.Active;
|
if (TryPromoteBootstrapAdmin(adminUser, now, logger) && before != adminUser.Membership.Status)
|
||||||
membership.IsPlatformAdmin = true;
|
{
|
||||||
membership.CanManageProjects = true;
|
await RecordPromotionAsync(auditTrailService, adminUser, before, cancellationToken);
|
||||||
membership.CanManageLedger = true;
|
}
|
||||||
membership.CanModerateMotions = true;
|
|
||||||
membership.ApprovedAtUtc ??= now;
|
|
||||||
|
|
||||||
EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
|
|
||||||
EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dbContext.ChangeTracker.HasChanges())
|
if (dbContext.ChangeTracker.HasChanges())
|
||||||
|
|
@ -58,6 +54,41 @@ public sealed class ApplicationBootstrapper(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The one bootstrap-admin promotion, used at startup and at sign-in. A Suspended account is left exactly as it is (an admin's
|
||||||
|
/// decision; only the suspension service lifts it) and the refusal is logged by account id. Returns whether it promoted.
|
||||||
|
/// </summary>
|
||||||
|
public static bool TryPromoteBootstrapAdmin(UserAccount account, DateTimeOffset now, ILogger logger)
|
||||||
|
{
|
||||||
|
var membership = account.Membership!;
|
||||||
|
if (membership.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Bootstrap admin promotion skipped for suspended account {UserAccountId}.", account.Id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
membership.Status = MembershipStatus.Active;
|
||||||
|
membership.IsPlatformAdmin = true;
|
||||||
|
membership.CanManageProjects = true;
|
||||||
|
membership.CanManageLedger = true;
|
||||||
|
membership.CanModerateMotions = true;
|
||||||
|
membership.ApprovedAtUtc ??= now;
|
||||||
|
|
||||||
|
EnsureRole(membership, MemberRole.PlatformAdmin, null, now, "Bootstrap admin");
|
||||||
|
EnsureRole(membership, MemberRole.StandardMember, null, now, "Default active member role");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The receipt for a bootstrap promotion that changed membership status; saves together with the promotion.</summary>
|
||||||
|
public static Task RecordPromotionAsync(AuditTrailService auditTrailService, UserAccount account, MembershipStatus before, CancellationToken cancellationToken) =>
|
||||||
|
auditTrailService.RecordAsync(
|
||||||
|
null,
|
||||||
|
nameof(Bifrost.Web.Domain.Membership),
|
||||||
|
account.Membership!.Id,
|
||||||
|
"membership.bootstrap-promoted",
|
||||||
|
$"Bootstrap admin promotion of {account.DisplayName} ({before} -> {account.Membership.Status}).",
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
public static void EnsureRole(
|
public static void EnsureRole(
|
||||||
Bifrost.Web.Domain.Membership membership,
|
Bifrost.Web.Domain.Membership membership,
|
||||||
MemberRole role,
|
MemberRole role,
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ public static class BifrostCookies
|
||||||
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
|
public const string Antiforgery = HostPrefix + "bifrost_antiforgery";
|
||||||
public const string Voter = HostPrefix + "bifrost_voter";
|
public const string Voter = HostPrefix + "bifrost_voter";
|
||||||
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
|
public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_";
|
||||||
|
public const string PasskeyTicket = HostPrefix + "bifrost_passkey_ticket";
|
||||||
|
|
||||||
public const string Path = "/";
|
public const string Path = "/";
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -45,18 +45,31 @@ public sealed class CurrentBifrostActorAccessor(
|
||||||
return Cache(httpContext, CurrentBifrostActor.Anonymous);
|
return Cache(httpContext, CurrentBifrostActor.Anonymous);
|
||||||
}
|
}
|
||||||
|
|
||||||
var userAccount = await dbContext.UserAccounts
|
// One credential names one row: identity first, then Heimdall id, then GitHub id; the first hit wins. Two rows matching
|
||||||
|
// one principal must never throw or pick by luck.
|
||||||
|
var accounts = dbContext.UserAccounts
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Include(x => x.MemberProfile)
|
.Include(x => x.MemberProfile)
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.RoleAssignments)
|
.ThenInclude(x => x.RoleAssignments)
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.TierSnapshots)
|
.ThenInclude(x => x.TierSnapshots);
|
||||||
.SingleOrDefaultAsync(
|
|
||||||
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
|
Bifrost.Web.Domain.UserAccount? userAccount = null;
|
||||||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
|
if (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity))
|
||||||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
|
{
|
||||||
cancellationToken);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
|
return Cache(httpContext, new CurrentBifrostActor(true, userAccount));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,7 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
|
||||||
var recentActivity = await dbContext.AuditEvents
|
var recentActivity = await dbContext.AuditEvents
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Include(x => x.ActorUserAccount)
|
.Include(x => x.ActorUserAccount)
|
||||||
.Where(x => !x.Action.StartsWith("membership.suspended") && !x.Action.StartsWith("membership.unsuspended")) // a reason is for admins, not the member dashboard
|
.Where(x => !x.Action.StartsWith("membership.suspended") && !x.Action.StartsWith("membership.unsuspended") && x.Action != "membership.bootstrap-promoted") // suspension reasons and the bootstrap-admin promotion are for admins, not the member dashboard
|
||||||
.OrderByDescending(x => x.OccurredAtUtc)
|
.OrderByDescending(x => x.OccurredAtUtc)
|
||||||
.Take(8)
|
.Take(8)
|
||||||
.Select(x => new DashboardActivity(
|
.Select(x => new DashboardActivity(
|
||||||
|
|
@ -102,76 +102,6 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
|
||||||
x.OccurredAtUtc))
|
x.OccurredAtUtc))
|
||||||
.ToListAsync(cancellationToken);
|
.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
|
var payoutPreviewNominal = await dbContext.LedgerEntries
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(x => x.Status == LedgerEntryStatus.Approved)
|
.Where(x => x.Status == LedgerEntryStatus.Approved)
|
||||||
|
|
@ -186,23 +116,13 @@ public sealed class DashboardSnapshotService(BifrostDbContext dbContext, TimePro
|
||||||
OpenMotions: await dbContext.Motions.AsNoTracking().CountAsync(x => x.Status == MotionStatus.Open && x.ClosesAtUtc >= now, cancellationToken),
|
OpenMotions: await dbContext.Motions.AsNoTracking().CountAsync(x => x.Status == MotionStatus.Open && x.ClosesAtUtc >= now, cancellationToken),
|
||||||
PendingMembershipApprovals: outstandingApprovals,
|
PendingMembershipApprovals: outstandingApprovals,
|
||||||
AssignedToCurrentMember: assignedToMe.Count,
|
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,
|
ApprovedNominalPayoutValue: payoutPreviewNominal,
|
||||||
RecentWorkItems: recentWorkItems,
|
RecentWorkItems: recentWorkItems,
|
||||||
OpenMotionHighlights: openMotions,
|
OpenMotionHighlights: openMotions,
|
||||||
MyAssignedWork: assignedToMe,
|
MyAssignedWork: assignedToMe,
|
||||||
MyVolunteeredWork: volunteeredByMe,
|
MyVolunteeredWork: volunteeredByMe,
|
||||||
MySubmittedWork: submittedByMe,
|
MySubmittedWork: submittedByMe,
|
||||||
RecentActivity: recentActivity,
|
RecentActivity: recentActivity);
|
||||||
RecentBridgeActions: recentBridgeActions,
|
|
||||||
RecentDispatchRuns: recentDispatchRuns,
|
|
||||||
RecentTransportReceipts: recentTransportReceipts,
|
|
||||||
RecentGovernanceReceipts: recentGovernanceReceipts);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -213,19 +133,13 @@ public sealed record DashboardSnapshot(
|
||||||
int OpenMotions,
|
int OpenMotions,
|
||||||
int PendingMembershipApprovals,
|
int PendingMembershipApprovals,
|
||||||
int AssignedToCurrentMember,
|
int AssignedToCurrentMember,
|
||||||
int ActiveBridgeActions,
|
|
||||||
int ActiveDispatchRuns,
|
|
||||||
decimal ApprovedNominalPayoutValue,
|
decimal ApprovedNominalPayoutValue,
|
||||||
IReadOnlyList<DashboardWorkItem> RecentWorkItems,
|
IReadOnlyList<DashboardWorkItem> RecentWorkItems,
|
||||||
IReadOnlyList<DashboardMotion> OpenMotionHighlights,
|
IReadOnlyList<DashboardMotion> OpenMotionHighlights,
|
||||||
IReadOnlyList<DashboardLaneItem> MyAssignedWork,
|
IReadOnlyList<DashboardLaneItem> MyAssignedWork,
|
||||||
IReadOnlyList<DashboardLaneItem> MyVolunteeredWork,
|
IReadOnlyList<DashboardLaneItem> MyVolunteeredWork,
|
||||||
IReadOnlyList<DashboardLaneItem> MySubmittedWork,
|
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(
|
public sealed record DashboardWorkItem(
|
||||||
Guid WorkItemId,
|
Guid WorkItemId,
|
||||||
|
|
@ -258,53 +172,3 @@ public sealed record DashboardActivity(
|
||||||
string Detail,
|
string Detail,
|
||||||
string ActorName,
|
string ActorName,
|
||||||
DateTimeOffset OccurredAtUtc);
|
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);
|
|
||||||
|
|
|
||||||
|
|
@ -15,12 +15,16 @@ public sealed class StartupConfigurationValidator(
|
||||||
IOptions<BifrostHostOptions> hostOptions,
|
IOptions<BifrostHostOptions> hostOptions,
|
||||||
IOptions<ConceptVoteOptions> conceptVoteOptions,
|
IOptions<ConceptVoteOptions> conceptVoteOptions,
|
||||||
IOptions<DeskOptions> deskOptions,
|
IOptions<DeskOptions> deskOptions,
|
||||||
IOptions<RegistrationOptions> registrationOptions)
|
IOptions<RegistrationOptions> registrationOptions,
|
||||||
|
OidcIssuerOptions? oidcOptions = null)
|
||||||
{
|
{
|
||||||
public void Validate()
|
public void Validate()
|
||||||
{
|
{
|
||||||
var failures = new List<string>();
|
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.
|
// Checked in every environment: a bad value here would otherwise pass startup and throw on every cast.
|
||||||
var conceptVotes = conceptVoteOptions.Value;
|
var conceptVotes = conceptVoteOptions.Value;
|
||||||
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
|
if (!NetworkPrefix.IsValidLength(conceptVotes.IPv4PrefixLength, NetworkPrefix.IPv4Bits))
|
||||||
|
|
@ -101,6 +105,13 @@ public sealed class StartupConfigurationValidator(
|
||||||
failures.Add("Heimdall:PatronSupportIntakeSecret is required when patron support intake is enabled.");
|
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.EnableCheckout)
|
||||||
{
|
{
|
||||||
if (!stripeOptions.Value.IsCheckoutConfigured)
|
if (!stripeOptions.Value.IsCheckoutConfigured)
|
||||||
|
|
@ -149,6 +160,12 @@ public sealed class StartupConfigurationValidator(
|
||||||
// mis-attribute answers. Account existence is a request-time question, not a startup one.
|
// mis-attribute answers. Account existence is a request-time question, not a startup one.
|
||||||
private void ValidateDesk(DeskOptions desk, List<string> failures)
|
private void ValidateDesk(DeskOptions desk, List<string> failures)
|
||||||
{
|
{
|
||||||
|
// The desk's bearer is validated against Bifrost's own issuer: without Bifrost:Oidc there is no credential to serve with.
|
||||||
|
if (oidcOptions is null && configuration.GetSection(DeskOptions.SectionName).Exists())
|
||||||
|
{
|
||||||
|
failures.Add("Bifrost:Oidc must be configured when the Desk section exists: the desk validates its bearer tokens against Bifrost's own issuer.");
|
||||||
|
}
|
||||||
|
|
||||||
if (!desk.IsConfigured)
|
if (!desk.IsConfigured)
|
||||||
{
|
{
|
||||||
if (configuration.GetSection(DeskOptions.SectionName).Exists())
|
if (configuration.GetSection(DeskOptions.SectionName).Exists())
|
||||||
|
|
|
||||||
|
|
@ -186,165 +186,6 @@
|
||||||
}
|
}
|
||||||
</article>
|
</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">
|
<article class="panel">
|
||||||
<div class="panel-header">
|
<div class="panel-header">
|
||||||
<div>
|
<div>
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ public sealed class IndexModel(
|
||||||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||||
|
|
||||||
public DashboardSnapshot Snapshot { get; private set; } =
|
public DashboardSnapshot Snapshot { get; private set; } =
|
||||||
new(0, 0, 0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], [], [], [], [], []);
|
new(0, 0, 0, 0, 0, 0, 0m, [], [], [], [], [], []);
|
||||||
|
|
||||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -296,7 +296,3 @@
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@section Scripts {
|
|
||||||
<partial name="_ValidationScriptsPartial" />
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -8,30 +8,37 @@
|
||||||
<section class="panel-grid">
|
<section class="panel-grid">
|
||||||
<article class="panel">
|
<article class="panel">
|
||||||
<span class="eyebrow">Members</span>
|
<span class="eyebrow">Members</span>
|
||||||
<h1>Invite and approval gate</h1>
|
<h1>Chat invites and approval gate</h1>
|
||||||
<p class="panel-intro">
|
<p class="panel-intro">
|
||||||
Invite-first onboarding keeps the alpha intentionally small. Approval remains human
|
Chat is by invitation: mint a single-use link and send it yourself. Approval remains human
|
||||||
because trust and contributor accountability are product concerns, not just auth concerns.
|
because trust and contributor accountability are product concerns, not just auth concerns.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
@if (!string.IsNullOrEmpty(Model.Notice))
|
||||||
|
{
|
||||||
|
<p class="validation-summary-errors" role="alert">@Model.Notice</p>
|
||||||
|
}
|
||||||
|
|
||||||
@if (Model.Actor.CanManageMembership)
|
@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">
|
<form method="post" asp-page-handler="Invite">
|
||||||
<div asp-validation-summary="ModelOnly" class="validation-summary-errors"></div>
|
<div asp-validation-summary="ModelOnly" class="validation-summary-errors"></div>
|
||||||
<div class="form-grid">
|
<div class="form-grid">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label asp-for="Input.GitHubLogin"></label>
|
<label asp-for="Input.Note"></label>
|
||||||
<input asp-for="Input.GitHubLogin" />
|
<input asp-for="Input.Note" />
|
||||||
<span asp-validation-for="Input.GitHubLogin"></span>
|
<span asp-validation-for="Input.Note"></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>
|
</div>
|
||||||
<div class="panel-actions">
|
<div class="panel-actions">
|
||||||
<button class="button" type="submit">Issue invite</button>
|
<button class="button" type="submit">Mint chat invite link</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
|
|
@ -186,6 +193,10 @@
|
||||||
|
|
||||||
@if (Model.Actor.CanManageMembership)
|
@if (Model.Actor.CanManageMembership)
|
||||||
{
|
{
|
||||||
|
@if (user.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
<div class="muted" style="margin-top: 0.8rem;">@(string.IsNullOrWhiteSpace(user.SuspensionReason) ? Bifrost.Web.Pages.App.Members.IndexModel.LegacySuspensionText : "Suspended: " + user.SuspensionReason)</div>
|
||||||
|
}
|
||||||
<form method="post" asp-page-handler="@(user.Status == MembershipStatus.Suspended ? "Unsuspend" : "Suspend")" style="margin-top: 0.8rem;">
|
<form method="post" asp-page-handler="@(user.Status == MembershipStatus.Suspended ? "Unsuspend" : "Suspend")" style="margin-top: 0.8rem;">
|
||||||
<input type="hidden" name="userAccountId" value="@user.UserAccountId" />
|
<input type="hidden" name="userAccountId" value="@user.UserAccountId" />
|
||||||
<input type="text" name="reason" maxlength="500" required placeholder="Reason" />
|
<input type="text" name="reason" maxlength="500" required placeholder="Reason" />
|
||||||
|
|
@ -238,18 +249,20 @@
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
@if (Model.Actor.CanManageMembership)
|
||||||
|
{
|
||||||
|
|
||||||
<section class="table-panel" style="margin-top: 1.5rem;">
|
<section class="table-panel" style="margin-top: 1.5rem;">
|
||||||
<div class="panel-header" style="padding: 1.25rem 1.25rem 0;">
|
<div class="panel-header" style="padding: 1.25rem 1.25rem 0;">
|
||||||
<div>
|
<div>
|
||||||
<h2>Outstanding invites</h2>
|
<h2>Outstanding chat invites</h2>
|
||||||
<p class="table-meta">@Model.Invitations.Count active invitations tracked.</p>
|
<p class="table-meta">@Model.Invitations.Count unredeemed.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (Model.Invitations.Count == 0)
|
@if (Model.Invitations.Count == 0)
|
||||||
{
|
{
|
||||||
<div class="empty-state" style="margin: 1.25rem;">No invitations yet.</div>
|
<div class="empty-state" style="margin: 1.25rem;">No unredeemed invites.</div>
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|
@ -257,24 +270,24 @@
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>GitHub login</th>
|
<th>For</th>
|
||||||
<th>Issued</th>
|
<th>Issued</th>
|
||||||
<th>Accepted</th>
|
<th>Expires</th>
|
||||||
<th>Notes</th>
|
<th></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@foreach (var invitation in Model.Invitations)
|
@foreach (var invite in Model.Invitations)
|
||||||
{
|
{
|
||||||
<tr>
|
<tr>
|
||||||
<td>@invitation.GitHubLogin</td>
|
<td>@invite.Note</td>
|
||||||
<td>@invitation.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
<td>@invite.IssuedAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
||||||
|
<td>@invite.ExpiresAtUtc.ToString("dd MMM yyyy HH:mm") UTC</td>
|
||||||
<td>
|
<td>
|
||||||
@(invitation.AcceptedAtUtc is null
|
<form method="post" asp-page-handler="RevokeInvite" asp-route-inviteId="@invite.Id">
|
||||||
? "Waiting for sign-in"
|
<button class="button secondary" type="submit">Revoke</button>
|
||||||
: invitation.AcceptedAtUtc.Value.ToString("dd MMM yyyy HH:mm") + " UTC")
|
</form>
|
||||||
</td>
|
</td>
|
||||||
<td>@invitation.Notes</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|
@ -282,7 +295,4 @@
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@section Scripts {
|
|
||||||
<partial name="_ValidationScriptsPartial" />
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using Bifrost.Web.Features.Invites;
|
||||||
using Bifrost.Web.Features.Membership;
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
@ -14,19 +15,43 @@ public sealed class IndexModel(
|
||||||
ICurrentBifrostActorAccessor actorAccessor,
|
ICurrentBifrostActorAccessor actorAccessor,
|
||||||
AuditTrailService auditTrailService,
|
AuditTrailService auditTrailService,
|
||||||
MembershipSuspensionService suspension,
|
MembershipSuspensionService suspension,
|
||||||
|
ChatInviteService chatInvites,
|
||||||
TimeProvider timeProvider) : PageModel
|
TimeProvider timeProvider) : PageModel
|
||||||
{
|
{
|
||||||
[BindProperty]
|
[BindProperty]
|
||||||
public InviteMemberInput Input { get; set; } = new();
|
public MintInviteInput Input { get; set; } = new();
|
||||||
|
|
||||||
[BindProperty]
|
[BindProperty]
|
||||||
public UpdateProfileInput Profile { get; set; } = new();
|
public UpdateProfileInput Profile { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Why the last membership action did nothing; one of <see cref="RefusalNotices"/>, carried across the redirect.</summary>
|
||||||
|
[TempData]
|
||||||
|
public string? Notice { get; set; }
|
||||||
|
|
||||||
|
private static readonly IReadOnlyDictionary<SuspensionOutcome, string> RefusalNotices = new Dictionary<SuspensionOutcome, string>
|
||||||
|
{
|
||||||
|
[SuspensionOutcome.NoReason] = "Nothing changed: a reason is required to suspend or unsuspend an account.",
|
||||||
|
[SuspensionOutcome.ProtectedAccount] = "Nothing changed: you cannot suspend yourself or another platform admin.",
|
||||||
|
[SuspensionOutcome.NoSuchAccount] = "Nothing changed: that account or its membership does not exist.",
|
||||||
|
[SuspensionOutcome.NotApplicable] = "Nothing changed: the account is already in that state."
|
||||||
|
};
|
||||||
|
|
||||||
|
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.";
|
||||||
|
|
||||||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||||
|
|
||||||
public IReadOnlyList<MemberDirectoryItem> Users { get; private set; } = [];
|
public IReadOnlyList<MemberDirectoryItem> Users { get; private set; } = [];
|
||||||
|
|
||||||
public IReadOnlyList<MembershipInvitation> Invitations { 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 async Task OnGetAsync(CancellationToken cancellationToken)
|
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|
@ -41,53 +66,30 @@ public sealed class IndexModel(
|
||||||
return Forbid();
|
return Forbid();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ModelState.IsValid)
|
// 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)
|
||||||
{
|
{
|
||||||
|
ModelState.AddModelError($"{nameof(Input)}.{nameof(Input.Note)}", "Say who this invite is for, in at most 500 characters.");
|
||||||
await LoadAsync(cancellationToken);
|
await LoadAsync(cancellationToken);
|
||||||
return Page();
|
return Page();
|
||||||
}
|
}
|
||||||
|
|
||||||
var normalizedLogin = Input.GitHubLogin.Trim().ToUpperInvariant();
|
var (_, token) = await chatInvites.MintAsync(Actor.UserAccount.Id, Input.Note, cancellationToken);
|
||||||
var invitation = await dbContext.MembershipInvitations
|
// The link is shown once, on this response: no redirect, no TempData, nothing stored that could show it again.
|
||||||
.SingleOrDefaultAsync(x => x.NormalizedGitHubLogin == normalizedLogin, cancellationToken);
|
MintedLink = chatInvites.LinkFor(token);
|
||||||
|
await LoadAsync(cancellationToken);
|
||||||
|
return Page();
|
||||||
|
}
|
||||||
|
|
||||||
if (invitation is null)
|
public async Task<IActionResult> OnPostRevokeInviteAsync(Guid inviteId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Actor = await actorAccessor.GetAsync(cancellationToken);
|
||||||
|
if (!Actor.CanManageMembership || Actor.UserAccount is null)
|
||||||
{
|
{
|
||||||
invitation = new MembershipInvitation
|
return Forbid();
|
||||||
{
|
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var existingUser = await dbContext.UserAccounts
|
await chatInvites.RevokeAsync(inviteId, Actor.UserAccount.Id, cancellationToken);
|
||||||
.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();
|
return RedirectToPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -102,11 +104,19 @@ public sealed class IndexModel(
|
||||||
var user = await dbContext.UserAccounts
|
var user = await dbContext.UserAccounts
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.RoleAssignments)
|
.ThenInclude(x => x.RoleAssignments)
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
||||||
if (user.Membership!.Status == MembershipStatus.Suspended)
|
// The chat tier holds no membership by design (docs/oidc-issuer.md); approval refuses rather than inventing one.
|
||||||
|
if (user is null || user.Membership is null)
|
||||||
{
|
{
|
||||||
return RedirectToPage(); // only Unsuspend lifts a suspension
|
Notice = user is null ? RefusalNotices[SuspensionOutcome.NoSuchAccount] : NoMembershipNotice;
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.Membership.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
Notice = ApproveSuspendedNotice; // only Unsuspend lifts a suspension
|
||||||
|
return RedirectToPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.Membership.Status = MembershipStatus.Active;
|
user.Membership.Status = MembershipStatus.Active;
|
||||||
|
|
@ -143,7 +153,13 @@ public sealed class IndexModel(
|
||||||
var outcome = suspend
|
var outcome = suspend
|
||||||
? await suspension.SuspendAsync(Actor, userAccountId, reason, cancellationToken)
|
? await suspension.SuspendAsync(Actor, userAccountId, reason, cancellationToken)
|
||||||
: await suspension.UnsuspendAsync(Actor, userAccountId, reason, cancellationToken);
|
: await suspension.UnsuspendAsync(Actor, userAccountId, reason, cancellationToken);
|
||||||
return outcome == SuspensionOutcome.NotAdmin ? Forbid() : RedirectToPage();
|
if (outcome == SuspensionOutcome.NotAdmin)
|
||||||
|
{
|
||||||
|
return Forbid();
|
||||||
|
}
|
||||||
|
|
||||||
|
Notice = RefusalNotices.GetValueOrDefault(outcome);
|
||||||
|
return RedirectToPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> OnPostToggleRoleAsync(Guid userAccountId, MemberRole role, CancellationToken cancellationToken)
|
public async Task<IActionResult> OnPostToggleRoleAsync(Guid userAccountId, MemberRole role, CancellationToken cancellationToken)
|
||||||
|
|
@ -157,10 +173,29 @@ public sealed class IndexModel(
|
||||||
var user = await dbContext.UserAccounts
|
var user = await dbContext.UserAccounts
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.RoleAssignments)
|
.ThenInclude(x => x.RoleAssignments)
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
{
|
||||||
|
Notice = RefusalNotices[SuspensionOutcome.NoSuchAccount];
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
if (user.Membership is null)
|
if (user.Membership is null)
|
||||||
{
|
{
|
||||||
|
Notice = NoMembershipNotice;
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.Id == Actor.UserAccount.Id && role == MemberRole.PlatformAdmin)
|
||||||
|
{
|
||||||
|
Notice = OwnAdminRoleNotice;
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.Membership.Status == MembershipStatus.Suspended)
|
||||||
|
{
|
||||||
|
Notice = RoleOnSuspendedNotice;
|
||||||
return RedirectToPage();
|
return RedirectToPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -175,8 +210,10 @@ public sealed class IndexModel(
|
||||||
Notes = "Assigned from the member admin page."
|
Notes = "Assigned from the member admin page."
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
else if (!(user.Id == Actor.UserAccount.Id && role == MemberRole.PlatformAdmin))
|
else
|
||||||
{
|
{
|
||||||
|
// Out of the collection too, so the flags below derive from the roles as they will stand after the save.
|
||||||
|
user.Membership.RoleAssignments.Remove(existingAssignment);
|
||||||
dbContext.RoleAssignments.Remove(existingAssignment);
|
dbContext.RoleAssignments.Remove(existingAssignment);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -220,7 +257,13 @@ public sealed class IndexModel(
|
||||||
var user = await dbContext.UserAccounts
|
var user = await dbContext.UserAccounts
|
||||||
.Include(x => x.Membership!)
|
.Include(x => x.Membership!)
|
||||||
.ThenInclude(x => x.TierSnapshots)
|
.ThenInclude(x => x.TierSnapshots)
|
||||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
.SingleOrDefaultAsync(x => x.Id == userAccountId, cancellationToken);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
{
|
||||||
|
Notice = RefusalNotices[SuspensionOutcome.NoSuchAccount];
|
||||||
|
return RedirectToPage();
|
||||||
|
}
|
||||||
|
|
||||||
if (user.Membership is null)
|
if (user.Membership is null)
|
||||||
{
|
{
|
||||||
|
|
@ -339,6 +382,7 @@ public sealed class IndexModel(
|
||||||
user.MemberProfile?.Skills ?? string.Empty,
|
user.MemberProfile?.Skills ?? string.Empty,
|
||||||
user.MemberProfile?.Availability ?? string.Empty,
|
user.MemberProfile?.Availability ?? string.Empty,
|
||||||
user.Membership?.Status ?? MembershipStatus.Authenticated,
|
user.Membership?.Status ?? MembershipStatus.Authenticated,
|
||||||
|
Actor.CanManageMembership ? user.Membership?.SuspensionReason ?? string.Empty : string.Empty,
|
||||||
user.Membership?.RoleAssignments.Select(x => x.Role).OrderBy(x => x.ToString()).ToArray() ?? [],
|
user.Membership?.RoleAssignments.Select(x => x.Role).OrderBy(x => x.ToString()).ToArray() ?? [],
|
||||||
patronTier?.Label ?? string.Empty,
|
patronTier?.Label ?? string.Empty,
|
||||||
patronTier?.Weight ?? 0m,
|
patronTier?.Weight ?? 0m,
|
||||||
|
|
@ -346,11 +390,7 @@ public sealed class IndexModel(
|
||||||
contributorTier?.Weight ?? 0m);
|
contributorTier?.Weight ?? 0m);
|
||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
Invitations = await dbContext.MembershipInvitations
|
Invitations = Actor.CanManageMembership ? await chatInvites.PendingAsync(cancellationToken) : [];
|
||||||
.AsNoTracking()
|
|
||||||
.Where(x => x.RevokedAtUtc == null)
|
|
||||||
.OrderByDescending(x => x.IssuedAtUtc)
|
|
||||||
.ToListAsync(cancellationToken);
|
|
||||||
|
|
||||||
if (Actor.UserAccount is not null)
|
if (Actor.UserAccount is not null)
|
||||||
{
|
{
|
||||||
|
|
@ -380,14 +420,11 @@ public sealed class IndexModel(
|
||||||
membership.CanModerateMotions = membership.IsPlatformAdmin || roles.Contains(MemberRole.Producer) || roles.Contains(MemberRole.Maintainer);
|
membership.CanModerateMotions = membership.IsPlatformAdmin || roles.Contains(MemberRole.Producer) || roles.Contains(MemberRole.Maintainer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class InviteMemberInput
|
public sealed class MintInviteInput
|
||||||
{
|
{
|
||||||
[Required, StringLength(120)]
|
|
||||||
[Display(Name = "GitHub login")]
|
|
||||||
public string GitHubLogin { get; set; } = string.Empty;
|
|
||||||
|
|
||||||
[StringLength(500)]
|
[StringLength(500)]
|
||||||
public string Notes { get; set; } = string.Empty;
|
[Display(Name = "Who is this for")]
|
||||||
|
public string Note { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class UpdateProfileInput
|
public sealed class UpdateProfileInput
|
||||||
|
|
@ -426,6 +463,7 @@ public sealed class IndexModel(
|
||||||
string Skills,
|
string Skills,
|
||||||
string Availability,
|
string Availability,
|
||||||
MembershipStatus Status,
|
MembershipStatus Status,
|
||||||
|
string SuspensionReason,
|
||||||
IReadOnlyList<MemberRole> Roles,
|
IReadOnlyList<MemberRole> Roles,
|
||||||
string PatronTierLabel,
|
string PatronTierLabel,
|
||||||
decimal PatronTierWeight,
|
decimal PatronTierWeight,
|
||||||
|
|
|
||||||
|
|
@ -147,7 +147,3 @@
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@section Scripts {
|
|
||||||
<partial name="_ValidationScriptsPartial" />
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -110,7 +110,3 @@
|
||||||
}
|
}
|
||||||
</article>
|
</article>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@section Scripts {
|
|
||||||
<partial name="_ValidationScriptsPartial" />
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -291,7 +291,3 @@
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@section Scripts {
|
|
||||||
<partial name="_ValidationScriptsPartial" />
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -25,14 +25,6 @@
|
||||||
<span>Assigned to me</span>
|
<span>Assigned to me</span>
|
||||||
<strong>@Model.AssignedToCurrentMember</strong>
|
<strong>@Model.AssignedToCurrentMember</strong>
|
||||||
</article>
|
</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">
|
<article class="metric-card">
|
||||||
<span>Approved nominal payout</span>
|
<span>Approved nominal payout</span>
|
||||||
<strong>@Model.ApprovedNominalPayoutValue.ToString("0.##")</strong>
|
<strong>@Model.ApprovedNominalPayoutValue.ToString("0.##")</strong>
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,12 @@
|
||||||
<code>GitHubOAuth:ClientSecret</code> before using sign-in.
|
<code>GitHubOAuth:ClientSecret</code> before using sign-in.
|
||||||
</div>
|
</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")
|
else if (Model.Auth == "heimdall-error")
|
||||||
{
|
{
|
||||||
<div class="callout warning">
|
<div class="callout warning">
|
||||||
|
|
|
||||||
230
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
Normal file
230
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml
Normal file
|
|
@ -0,0 +1,230 @@
|
||||||
|
@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>
|
||||||
|
}
|
||||||
|
}
|
||||||
295
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
Normal file
295
src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml.cs
Normal file
|
|
@ -0,0 +1,295 @@
|
||||||
|
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>
|
<p class="muted">@Model.StatusMessage</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (Model.Invitation is not null)
|
@if (Model.CanManageLogins)
|
||||||
{
|
{
|
||||||
<div class="callout success">
|
<div class="panel-actions">
|
||||||
Invitation tracked for <code>@Model.Invitation.GitHubLogin</code>.
|
<a class="button secondary" asp-page="/Membership/LinkedAccounts">Linked accounts</a>
|
||||||
Issued @Model.Invitation.IssuedAtUtc.ToString("dd MMM yyyy") UTC.
|
<span class="muted">See, add and remove the provider logins that sign in to this account.</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,19 @@
|
||||||
using Bifrost.Web.Data;
|
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using Bifrost.Web.Features.Membership;
|
||||||
using Bifrost.Web.Features.Shared;
|
using Bifrost.Web.Features.Shared;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Bifrost.Web.Pages.Membership;
|
namespace Bifrost.Web.Pages.Membership;
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public sealed class StatusModel(
|
public sealed class StatusModel(ICurrentBifrostActorAccessor actorAccessor) : PageModel
|
||||||
ICurrentBifrostActorAccessor actorAccessor,
|
|
||||||
BifrostDbContext dbContext) : PageModel
|
|
||||||
{
|
{
|
||||||
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
/// <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 MembershipInvitation? Invitation { get; private set; }
|
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
|
||||||
|
|
||||||
public string StatusLabel => Actor.Membership?.Status switch
|
public string StatusLabel => Actor.Membership?.Status switch
|
||||||
{
|
{
|
||||||
|
|
@ -36,26 +35,14 @@ public sealed class StatusModel(
|
||||||
public string StatusMessage => Actor.Membership?.Status switch
|
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.Active => "You can participate in projects, claim work, vote on motions, and view the ledger console.",
|
||||||
MembershipStatus.PendingApproval => "Your GitHub sign-in matched an invite, but an admin still needs to approve active participation.",
|
MembershipStatus.PendingApproval => "An admin still needs to approve active participation.",
|
||||||
MembershipStatus.Suspended => "Your account is currently suspended from active participation pending an admin review.",
|
MembershipStatus.Suspended => "Your account is currently suspended from active participation pending an admin review.",
|
||||||
MembershipStatus.Authenticated => "You are signed in, but there is no active invite or approval on your account yet.",
|
MembershipStatus.Authenticated => "You are signed in, but there is no approval on your account yet.",
|
||||||
_ => "No membership record was found."
|
_ => "No membership record was found."
|
||||||
};
|
};
|
||||||
|
|
||||||
public async Task OnGetAsync(CancellationToken cancellationToken)
|
public async Task OnGetAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Actor = await actorAccessor.GetAsync(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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
<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,7 +5,6 @@ using System.Text.Json.Serialization;
|
||||||
using Bifrost.Web.Configuration;
|
using Bifrost.Web.Configuration;
|
||||||
using Bifrost.Web.Data;
|
using Bifrost.Web.Data;
|
||||||
using Bifrost.Web.Domain;
|
using Bifrost.Web.Domain;
|
||||||
using Bifrost.Web.Features.Bridge;
|
|
||||||
using Bifrost.Web.Features.ConceptVotes;
|
using Bifrost.Web.Features.ConceptVotes;
|
||||||
using Bifrost.Web.Features.Desk;
|
using Bifrost.Web.Features.Desk;
|
||||||
using Bifrost.Web.Features.GitHub;
|
using Bifrost.Web.Features.GitHub;
|
||||||
|
|
@ -64,16 +63,13 @@ builder.Services
|
||||||
|
|
||||||
builder.Services
|
builder.Services
|
||||||
.AddOptions<HeimdallOptions>()
|
.AddOptions<HeimdallOptions>()
|
||||||
.BindConfiguration(HeimdallOptions.SectionName);
|
.BindConfiguration(HeimdallOptions.SectionName)
|
||||||
|
.PostConfigure<ILogger<HeimdallOptions>>(HeimdallOptions.ResolveAppSecret);
|
||||||
|
|
||||||
builder.Services
|
builder.Services
|
||||||
.AddOptions<StripeOptions>()
|
.AddOptions<StripeOptions>()
|
||||||
.BindConfiguration(StripeOptions.SectionName);
|
.BindConfiguration(StripeOptions.SectionName);
|
||||||
|
|
||||||
builder.Services
|
|
||||||
.AddOptions<BridgeOptions>()
|
|
||||||
.BindConfiguration(BridgeOptions.SectionName);
|
|
||||||
|
|
||||||
builder.Services
|
builder.Services
|
||||||
.AddOptions<ConceptVoteOptions>()
|
.AddOptions<ConceptVoteOptions>()
|
||||||
.BindConfiguration(ConceptVoteOptions.SectionName);
|
.BindConfiguration(ConceptVoteOptions.SectionName);
|
||||||
|
|
@ -92,6 +88,7 @@ builder.Services.AddAntiforgery(options =>
|
||||||
builder.Services.AddRazorPages(options =>
|
builder.Services.AddRazorPages(options =>
|
||||||
{
|
{
|
||||||
options.Conventions.AuthorizePage("/Membership/Status");
|
options.Conventions.AuthorizePage("/Membership/Status");
|
||||||
|
options.Conventions.AuthorizePage("/Membership/LinkedAccounts");
|
||||||
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
|
options.Conventions.AuthorizeFolder("/App", ActiveMemberRequirement.PolicyName);
|
||||||
options.Conventions.AllowAnonymousToFolder("/Mill");
|
options.Conventions.AllowAnonymousToFolder("/Mill");
|
||||||
});
|
});
|
||||||
|
|
@ -120,10 +117,6 @@ builder.Services.AddScoped<ICurrentBifrostActorAccessor, CurrentBifrostActorAcce
|
||||||
builder.Services.AddScoped<AuditTrailService>();
|
builder.Services.AddScoped<AuditTrailService>();
|
||||||
builder.Services.AddScoped<Bifrost.Web.Features.Membership.MembershipSuspensionService>();
|
builder.Services.AddScoped<Bifrost.Web.Features.Membership.MembershipSuspensionService>();
|
||||||
builder.Services.AddScoped<DashboardSnapshotService>();
|
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<MembershipSynchronizationService>();
|
||||||
builder.Services.AddScoped<BifrostIdentityService>();
|
builder.Services.AddScoped<BifrostIdentityService>();
|
||||||
builder.Services.AddScoped<GitHubWebhookService>();
|
builder.Services.AddScoped<GitHubWebhookService>();
|
||||||
|
|
@ -136,8 +129,8 @@ builder.Services.AddOptions<RegistrationOptions>().BindConfiguration(Registratio
|
||||||
builder.Services.AddSingleton<RegistrationChallengeService>();
|
builder.Services.AddSingleton<RegistrationChallengeService>();
|
||||||
builder.Services.AddSingleton<RegistrationRateLimit>();
|
builder.Services.AddSingleton<RegistrationRateLimit>();
|
||||||
builder.Services.AddScoped<NativeRegistration>();
|
builder.Services.AddScoped<NativeRegistration>();
|
||||||
|
builder.Services.AddScoped<Bifrost.Web.Features.Invites.ChatInviteService>();
|
||||||
builder.Services.AddHostedService<SealedBallotCloser>();
|
builder.Services.AddHostedService<SealedBallotCloser>();
|
||||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
|
||||||
builder.Services.AddScoped<PatronageService>();
|
builder.Services.AddScoped<PatronageService>();
|
||||||
builder.Services.AddScoped<StripeWebhookService>();
|
builder.Services.AddScoped<StripeWebhookService>();
|
||||||
builder.Services.AddScoped<HeimdallPatronSupportIntakeService>();
|
builder.Services.AddScoped<HeimdallPatronSupportIntakeService>();
|
||||||
|
|
@ -149,9 +142,13 @@ builder.Services.AddScoped<ReadinessService>();
|
||||||
builder.Services.AddScoped<ApplicationBootstrapper>();
|
builder.Services.AddScoped<ApplicationBootstrapper>();
|
||||||
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
||||||
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
||||||
builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
// The app-secret and member-bearer clients: no redirects (see HeimdallClientServices).
|
||||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
builder.Services.AddHeimdallClients();
|
||||||
.RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
|
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.AddSingleton<HeimdallTokenVerifier>();
|
builder.Services.AddSingleton<HeimdallTokenVerifier>();
|
||||||
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
||||||
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
||||||
|
|
@ -267,13 +264,15 @@ if (oidcOptions is not null)
|
||||||
var deskConfigured = builder.Configuration.GetSection(DeskOptions.SectionName).Exists();
|
var deskConfigured = builder.Configuration.GetSection(DeskOptions.SectionName).Exists();
|
||||||
if (deskConfigured)
|
if (deskConfigured)
|
||||||
{
|
{
|
||||||
builder.Services.AddBifrostDesk();
|
builder.Services.AddBifrostDesk(oidcConfigured: oidcOptions is not null);
|
||||||
}
|
}
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
||||||
|
|
||||||
app.Services.GetRequiredService<StartupConfigurationValidator>().Validate();
|
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 using (var scope = app.Services.CreateAsyncScope())
|
||||||
{
|
{
|
||||||
await scope.ServiceProvider
|
await scope.ServiceProvider
|
||||||
|
|
@ -359,6 +358,76 @@ app.MapPost("/github/webhooks", async (
|
||||||
};
|
};
|
||||||
}).AllowAnonymous();
|
}).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) =>
|
app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuthOptions> gitHubOptions) =>
|
||||||
{
|
{
|
||||||
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
|
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
|
||||||
|
|
@ -376,6 +445,20 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
|
||||||
return;
|
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)
|
if (!gitHubOptions.Value.IsConfigured)
|
||||||
{
|
{
|
||||||
httpContext.Response.Redirect("/?auth=github-not-configured");
|
httpContext.Response.Redirect("/?auth=github-not-configured");
|
||||||
|
|
@ -696,23 +779,6 @@ app.MapPost("/patronage/stripe/webhook", async (
|
||||||
};
|
};
|
||||||
}).AllowAnonymous();
|
}).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,
|
// 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.
|
// and no response before close carries another member's ballot.
|
||||||
var sealedMotions = app.MapGroup("/api/sealed-motions")
|
var sealedMotions = app.MapGroup("/api/sealed-motions")
|
||||||
|
|
@ -818,15 +884,55 @@ app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
||||||
app.MapPost("/auth/heimdall/complete", async (
|
app.MapPost("/auth/heimdall/complete", async (
|
||||||
HttpContext httpContext,
|
HttpContext httpContext,
|
||||||
HeimdallAuthService heimdallAuthService,
|
HeimdallAuthService heimdallAuthService,
|
||||||
|
Bifrost.Web.Features.Invites.ChatInviteService chatInvites,
|
||||||
IOptions<BifrostHostOptions> hostOptions,
|
IOptions<BifrostHostOptions> hostOptions,
|
||||||
ILogger<HeimdallAuthService> logger,
|
ILogger<HeimdallAuthService> logger,
|
||||||
CancellationToken cancellationToken) =>
|
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 form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
|
||||||
var attempt = form?["attempt"].ToString();
|
var attempt = form?["attempt"].ToString();
|
||||||
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
|
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
|
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(
|
var signIn = await heimdallAuthService.CompleteAsync(
|
||||||
hostOptions.Value.PublicBaseUrl,
|
hostOptions.Value.PublicBaseUrl,
|
||||||
attempt,
|
attempt,
|
||||||
|
|
@ -834,6 +940,11 @@ app.MapPost("/auth/heimdall/complete", async (
|
||||||
form?["code"].ToString(),
|
form?["code"].ToString(),
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, signIn.Principal);
|
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());
|
httpContext.Response.Cookies.Delete(held!.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
||||||
return Results.LocalRedirect(signIn.ReturnPath.Value);
|
return Results.LocalRedirect(signIn.ReturnPath.Value);
|
||||||
}
|
}
|
||||||
|
|
@ -845,7 +956,9 @@ app.MapPost("/auth/heimdall/complete", async (
|
||||||
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
|
||||||
}
|
}
|
||||||
|
|
||||||
return Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
return linking
|
||||||
|
? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error))
|
||||||
|
: Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||||
}
|
}
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
|
|
@ -917,6 +1030,10 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
|
||||||
httpContext.Response.ContentType = "text/html; charset=utf-8";
|
httpContext.Response.ContentType = "text/html; charset=utf-8";
|
||||||
var encodedReturnUrl = Uri.EscapeDataString(returnUrl);
|
var encodedReturnUrl = Uri.EscapeDataString(returnUrl);
|
||||||
var escapedReturnUrl = System.Net.WebUtility.HtmlEncode(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($$"""
|
await httpContext.Response.WriteAsync($$"""
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
@ -941,10 +1058,10 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
|
||||||
<h1>Create or use a Bifrost patron account</h1>
|
<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>
|
<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">
|
<div class="providers">
|
||||||
<a href="/auth/sign-in?provider=github&returnUrl={{encodedReturnUrl}}">GitHub <span>OAuth</span></a>
|
{{gitHubChoice}}
|
||||||
<a class="secondary" href="/auth/heimdall/discord?returnUrl={{encodedReturnUrl}}">Discord <span>Heimdall</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/patreon?returnUrl={{encodedReturnUrl}}">Patreon <span>Heimdall</span></a>
|
||||||
<a class="secondary" href="/auth/heimdall/twitch?returnUrl={{encodedReturnUrl}}">Twitch <span>Heimdall</span></a>
|
<a class="secondary" href="/auth/heimdall/google?returnUrl={{encodedReturnUrl}}">Google <span>Heimdall</span></a>
|
||||||
</div>
|
</div>
|
||||||
<p><small>After sign-in, Bifrost returns you to {{escapedReturnUrl}}.</small></p>
|
<p><small>After sign-in, Bifrost returns you to {{escapedReturnUrl}}.</small></p>
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@
|
||||||
"BaseUrl": "https://heimdall.gamecult.org",
|
"BaseUrl": "https://heimdall.gamecult.org",
|
||||||
"AppSlug": "bifrost",
|
"AppSlug": "bifrost",
|
||||||
"AppSecret": "",
|
"AppSecret": "",
|
||||||
|
"AppSecretFile": "",
|
||||||
"DiscordGuildId": "",
|
"DiscordGuildId": "",
|
||||||
"DiscordAllowedRoleIds": [],
|
"DiscordAllowedRoleIds": [],
|
||||||
"PatreonTierTitle": "Inner Sanctum",
|
"PatreonTierTitle": "Inner Sanctum",
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,30 @@
|
||||||
"resolved": "2.4.0",
|
"resolved": "2.4.0",
|
||||||
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
|
"contentHash": "SwXsAV3sMvAU/Nn31pbjhWurYSjJ+/giI/0n6tCrYoupEK34iIHCuk3STAd9fx8yudM85KkLSVdn951vTng/vQ=="
|
||||||
},
|
},
|
||||||
|
"Fido2": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[4.3.3, )",
|
||||||
|
"resolved": "4.3.3",
|
||||||
|
"contentHash": "++G8ohXlhp9AH49FXIvYqziXUAEpuCtT+z5HBevX6+Pl6sYz9zfDHGTgvne6t3UEhM0hudesgMudyNG7RlpaEA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Fido2.Models": "4.3.3",
|
||||||
|
"Microsoft.Extensions.Http": "9.0.0",
|
||||||
|
"Microsoft.IdentityModel.JsonWebTokens": "8.2.0",
|
||||||
|
"NSec.Cryptography": "25.4.0",
|
||||||
|
"System.Formats.Cbor": "9.0.24"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"MessagePack": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[3.1.12, )",
|
||||||
|
"resolved": "3.1.12",
|
||||||
|
"contentHash": "m1QEsd59gUj82ji5tEQbZiyjV6y0F7cYfGVhil6pAlNZpyzR7ze9TucMu4lPpi8cZAV8aNl3D9/T9J1HbFz15Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"MessagePack.Annotations": "3.1.12",
|
||||||
|
"MessagePackAnalyzer": "3.1.12",
|
||||||
|
"Microsoft.NET.StringTools": "17.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Microsoft.EntityFrameworkCore.Design": {
|
"Microsoft.EntityFrameworkCore.Design": {
|
||||||
"type": "Direct",
|
"type": "Direct",
|
||||||
"requested": "[8.0.0, )",
|
"requested": "[8.0.0, )",
|
||||||
|
|
@ -75,17 +99,59 @@
|
||||||
"OpenIddict.Server": "7.7.1"
|
"OpenIddict.Server": "7.7.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"OpenIddict.Validation.AspNetCore": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[7.7.1, )",
|
||||||
|
"resolved": "7.7.1",
|
||||||
|
"contentHash": "9Gpw13k6KRif6LCeIfzS5cfDPxzEvg5I4l8JKwMxNL4mqal8eT00T069RnuXuDY8CwOO43FLD55JY7Wh3an5cg==",
|
||||||
|
"dependencies": {
|
||||||
|
"OpenIddict.Validation": "7.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"OpenIddict.Validation.ServerIntegration": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[7.7.1, )",
|
||||||
|
"resolved": "7.7.1",
|
||||||
|
"contentHash": "tZd5oqlVHftWjo3gthwXRvDE09NGmOjo5yjyRH8W2q4Yw9Hntkfi70+T2ESFKJ++oqueQT4YG5ilyot/o0OBMA==",
|
||||||
|
"dependencies": {
|
||||||
|
"OpenIddict.Server": "7.7.1",
|
||||||
|
"OpenIddict.Validation": "7.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"System.Text.Json": {
|
"System.Text.Json": {
|
||||||
"type": "Direct",
|
"type": "Direct",
|
||||||
"requested": "[8.0.5, )",
|
"requested": "[8.0.5, )",
|
||||||
"resolved": "8.0.5",
|
"resolved": "8.0.5",
|
||||||
"contentHash": "0f1B50Ss7rqxXiaBJyzUu9bWFOO2/zSlifZ/UNMdiIpDYe4cY4LQQicP4nirK1OS31I43rn062UIJ1Q9bpmHpg=="
|
"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": {
|
"Humanizer.Core": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "2.14.1",
|
"resolved": "2.14.1",
|
||||||
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
|
"contentHash": "lQKvtaTDOXnoVJ20ibTuSIOf2i0uO0MPbDhd1jm238I+U/2ZnRENj0cktKZhtchBMtCUSRQ5v4xBCUbKNmyVMw=="
|
||||||
},
|
},
|
||||||
|
"libsodium": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "1.0.20.1",
|
||||||
|
"contentHash": "pkiceEqJDQFHjbga3k/oPfTVX9g+GKJZ1VrkuiLhaymt9YNw1Dr7cX9hNuZuNaWcr9WD0moW55k4pMwzQ7JaZQ=="
|
||||||
|
},
|
||||||
|
"MessagePack.Annotations": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "3.1.12",
|
||||||
|
"contentHash": "LdI67sY7F3KK+JsrG02+DP1XFkowaZSoyfL2M88hjm1MOOsjf8amBLAJolV+zxoPUZf3uGbKzq1cMQD8PlpSpA=="
|
||||||
|
},
|
||||||
|
"MessagePackAnalyzer": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "3.1.12",
|
||||||
|
"contentHash": "iNSNatPh6bafRUbkQKlClExjpPpd8hiZgfZsodGf7bheIlkizGbMzsJ2mPui8jOHRe4Ky9eg5ou/fFzI7CT3fg=="
|
||||||
|
},
|
||||||
"Microsoft.Bcl.AsyncInterfaces": {
|
"Microsoft.Bcl.AsyncInterfaces": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "6.0.0",
|
"resolved": "6.0.0",
|
||||||
|
|
@ -99,6 +165,11 @@
|
||||||
"System.Formats.Asn1": "10.0.2"
|
"System.Formats.Asn1": "10.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.Bcl.Memory": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.14",
|
||||||
|
"contentHash": "laQCcjTM2FnbyznkAu9hwBuQh3z2/OtJKwjGkJOUevylFpFXZIUVq/+MU2jM0HQm1n5wsjjwtLIDOiWJ6Nai3A=="
|
||||||
|
},
|
||||||
"Microsoft.CodeAnalysis.Analyzers": {
|
"Microsoft.CodeAnalysis.Analyzers": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.3.3",
|
"resolved": "3.3.3",
|
||||||
|
|
@ -186,26 +257,43 @@
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"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": {
|
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.0",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==",
|
"contentHash": "lqvd7W3FGKUO1+ZoUEMaZ5XDJeWvjpy2/M/ptCGz3tXLD4HWVaSzjufsAsjemasBEg+2SxXVtYVvGt5r2nKDlg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Configuration.Binder": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "RiScL99DcyngY9zJA2ROrri7Br8tn5N4hP4YNvGdTN/bvg1A3dwvDOxHnNZ3Im7x2SJ5i4LkX1uPiR/MfSFBLQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyInjection": {
|
"Microsoft.Extensions.DependencyInjection": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.1",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==",
|
"contentHash": "MCPrg7v3QgNMr0vX4vzRXvkNGgLg8vKWX0nKCWUxu2uPyMsaRgiRc1tHBnbTcfJMhMKj2slE/j2M9oGkd25DNw==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
|
"contentHash": "+6f2qv2a3dLwd5w6JanPIPs47CxRbnk+ZocMJUhv9NxP88VlOcJYZs9jY+MYSjxvady08bUZn6qgiNh7DadGgg=="
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.DependencyModel": {
|
"Microsoft.Extensions.DependencyModel": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
|
|
@ -216,37 +304,83 @@
|
||||||
"System.Text.Json": "8.0.0"
|
"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": {
|
"Microsoft.Extensions.Logging": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.1",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==",
|
"contentHash": "crjWyORoug0kK7RSNJBTeSE6VX8IQgLf3nUpTB9m62bPXp/tzbnOsnbe8TXEG0AASNaKZddnpHKw7fET8E++Pg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection": "8.0.1",
|
"Microsoft.Extensions.DependencyInjection": "9.0.0",
|
||||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.2",
|
"Microsoft.Extensions.Logging.Abstractions": "9.0.0",
|
||||||
"Microsoft.Extensions.Options": "8.0.2"
|
"Microsoft.Extensions.Options": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Logging.Abstractions": {
|
"Microsoft.Extensions.Logging.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==",
|
"contentHash": "g0UfujELzlLbHoVG8kPKVBaW470Ewi+jnptGS9KUi6jcb+k2StujtK3m26DFSGGwQ/+bVgZfsWqNzlP6YOejvw==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"System.Diagnostics.DiagnosticSource": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Options": {
|
"Microsoft.Extensions.Options": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.2",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==",
|
"contentHash": "y2146b3jrPI3Q0lokKXdKLpmXqakYbDIPDV6r3M8SqvSf45WwOTzkyfDpxnZXJsJQEpAsAqjUq5Pu8RCJMjubg==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
"Microsoft.Extensions.Primitives": "8.0.0"
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "Ob3FXsXkcSMQmGZi7qP07EQ39kZpSBlTcAZLbJLdI4FIf0Jug8biv2HTavWmnTirchctPlq9bl/26CXtQRguzA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Configuration.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Configuration.Binder": "9.0.0",
|
||||||
|
"Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Options": "9.0.0",
|
||||||
|
"Microsoft.Extensions.Primitives": "9.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Microsoft.Extensions.Primitives": {
|
"Microsoft.Extensions.Primitives": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.0.0",
|
"resolved": "9.0.0",
|
||||||
"contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g=="
|
"contentHash": "N3qEBzmLMYiASUlKxxFIISP4AiwuPTHF5uCh+2CWSwwzAJiIYx0kBJsS30cp1nvhSySFAVi30jecD307jV+8Kg=="
|
||||||
},
|
},
|
||||||
"Microsoft.IdentityModel.Abstractions": {
|
"Microsoft.IdentityModel.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
|
|
@ -269,6 +403,14 @@
|
||||||
"Microsoft.IdentityModel.Abstractions": "8.19.2"
|
"Microsoft.IdentityModel.Abstractions": "8.19.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.IdentityModel.Protocols": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.19.2",
|
||||||
|
"contentHash": "sGxSsSrZXNmca6D+jHH2rVRyo2nNRd/g4H9CFbPmLLq0xgoH1U0orLWE5minfijw7+zq49tBs7txenbfAErRoQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.IdentityModel.Tokens": "8.19.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Microsoft.IdentityModel.Tokens": {
|
"Microsoft.IdentityModel.Tokens": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "8.19.2",
|
"resolved": "8.19.2",
|
||||||
|
|
@ -279,6 +421,11 @@
|
||||||
"Microsoft.IdentityModel.Logging": "8.19.2"
|
"Microsoft.IdentityModel.Logging": "8.19.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"Microsoft.NET.StringTools": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "17.11.4",
|
||||||
|
"contentHash": "mudqUHhNpeqIdJoUx2YDWZO/I9uEDYVowan89R6wsomfnUJQk6HteoQTlNjZDixhT2B4IXMkMtgZtoceIjLRmA=="
|
||||||
|
},
|
||||||
"Mono.TextTemplating": {
|
"Mono.TextTemplating": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "2.2.1",
|
"resolved": "2.2.1",
|
||||||
|
|
@ -287,6 +434,14 @@
|
||||||
"System.CodeDom": "4.4.0"
|
"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": {
|
"OpenIddict.Abstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "7.7.1",
|
"resolved": "7.7.1",
|
||||||
|
|
@ -323,6 +478,17 @@
|
||||||
"OpenIddict.Abstractions": "7.7.1"
|
"OpenIddict.Abstractions": "7.7.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"OpenIddict.Validation": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "7.7.1",
|
||||||
|
"contentHash": "09FOsvek+iSKrNbEehH2c1uBWSFurZk1U8vyTKk5aiaCV2bbj+j/68KRA/iHOgSe8qV3+0ZrquhmjFMpcojVSw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Microsoft.Extensions.Logging": "8.0.1",
|
||||||
|
"Microsoft.IdentityModel.JsonWebTokens": "8.19.2",
|
||||||
|
"Microsoft.IdentityModel.Protocols": "8.19.2",
|
||||||
|
"OpenIddict.Abstractions": "7.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"System.CodeDom": {
|
"System.CodeDom": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "4.4.0",
|
"resolved": "4.4.0",
|
||||||
|
|
@ -384,11 +550,21 @@
|
||||||
"System.Composition.Runtime": "6.0.0"
|
"System.Composition.Runtime": "6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"System.Diagnostics.DiagnosticSource": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.0",
|
||||||
|
"contentHash": "ddppcFpnbohLWdYKr/ZeLZHmmI+DXFgZ3Snq+/E7SwcdW4UnvxmaugkwGywvGVWkHPGCSZjCP+MLzu23AL5SDw=="
|
||||||
|
},
|
||||||
"System.Formats.Asn1": {
|
"System.Formats.Asn1": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "10.0.2",
|
"resolved": "10.0.2",
|
||||||
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
|
"contentHash": "9Hee6iQ74pDgdRNIL6lO8Vlx2onVWd5aDnqwk4Pvo0h5FklBd7QwcQDKgxeLuhiy0o3ibzUVO0KFQe0/hPXU+Q=="
|
||||||
},
|
},
|
||||||
|
"System.Formats.Cbor": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "9.0.24",
|
||||||
|
"contentHash": "SEfEvHu6qXcXoDsDKagddLDf8A9iHIhHUD0hGemdmwlP206KLLCI5ksskOpeXMgNpQCs2diB0fOBKcnjySHFUQ=="
|
||||||
|
},
|
||||||
"System.IO.Pipelines": {
|
"System.IO.Pipelines": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "6.0.3",
|
"resolved": "6.0.3",
|
||||||
|
|
|
||||||
125
src/Bifrost.Web/wwwroot/js/passkeys.js
Normal file
125
src/Bifrost.Web/wwwroot/js/passkeys.js
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
// The Linked accounts page's passkey ceremonies (docs/passkeys.md). First-party, no dependency. It asks the server for
|
||||||
|
// WebAuthn options, calls navigator.credentials, and posts back only base64url strings in a same-origin form. Nothing it
|
||||||
|
// reads from the options is shown or evaluated; the server checks the origin, the challenge and the signature.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var status = document.getElementById("passkey-status");
|
||||||
|
|
||||||
|
function say(text) {
|
||||||
|
if (status) {
|
||||||
|
status.textContent = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBytes(value) {
|
||||||
|
var padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
while (padded.length % 4) {
|
||||||
|
padded += "=";
|
||||||
|
}
|
||||||
|
var raw = atob(padded);
|
||||||
|
var bytes = new Uint8Array(raw.length);
|
||||||
|
for (var i = 0; i < raw.length; i++) {
|
||||||
|
bytes[i] = raw.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return bytes.buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toText(buffer) {
|
||||||
|
var bytes = new Uint8Array(buffer);
|
||||||
|
var raw = "";
|
||||||
|
for (var i = 0; i < bytes.length; i++) {
|
||||||
|
raw += String.fromCharCode(bytes[i]);
|
||||||
|
}
|
||||||
|
return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function token(form) {
|
||||||
|
var field = form.querySelector("input[name=__RequestVerificationToken]");
|
||||||
|
return field ? field.value : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Posts to a handler of this page with the form's antiforgery token and returns the parsed JSON, or throws.
|
||||||
|
function options(handler, form, fields) {
|
||||||
|
return fetch(location.pathname + "?handler=" + handler, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "same-origin",
|
||||||
|
headers: { "RequestVerificationToken": token(form), "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams(fields)
|
||||||
|
}).then(function (response) {
|
||||||
|
return response.json().then(function (body) {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body && body.error ? body.error : "error");
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function descriptors(list) {
|
||||||
|
return (list || []).map(function (item) {
|
||||||
|
var copy = { type: item.type, id: toBytes(item.id) };
|
||||||
|
if (item.transports) {
|
||||||
|
copy.transports = item.transports;
|
||||||
|
}
|
||||||
|
return copy;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function set(form, name, value) {
|
||||||
|
form.elements[name].value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function failed(error) {
|
||||||
|
var code = error && error.message ? error.message : "error";
|
||||||
|
location.assign(location.pathname + "?result=" + (/^[a-z_]+$/.test(code) && code !== "error" ? encodeURIComponent(code) : "passkey_failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll("form[data-passkey-enrol]").forEach(function (form) {
|
||||||
|
form.addEventListener("submit", function (event) {
|
||||||
|
if (form.dataset.ready === "1") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
say("Waiting for your device...");
|
||||||
|
options("PasskeyEnrolOptions", form, {}).then(function (created) {
|
||||||
|
created.challenge = toBytes(created.challenge);
|
||||||
|
created.user.id = toBytes(created.user.id);
|
||||||
|
created.excludeCredentials = descriptors(created.excludeCredentials);
|
||||||
|
return navigator.credentials.create({ publicKey: created });
|
||||||
|
}).then(function (credential) {
|
||||||
|
set(form, "id", credential.id);
|
||||||
|
set(form, "rawId", toText(credential.rawId));
|
||||||
|
set(form, "attestationObject", toText(credential.response.attestationObject));
|
||||||
|
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||||
|
set(form, "transports", credential.response.getTransports ? credential.response.getTransports().join(",") : "");
|
||||||
|
form.dataset.ready = "1";
|
||||||
|
form.submit();
|
||||||
|
}).catch(failed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("form[data-passkey-unlink]").forEach(function (form) {
|
||||||
|
form.addEventListener("submit", function (event) {
|
||||||
|
if (form.dataset.ready === "1") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
say("Waiting for your device...");
|
||||||
|
options("PasskeyChallenge", form, { identityId: form.elements.identityId.value }).then(function (requested) {
|
||||||
|
requested.challenge = toBytes(requested.challenge);
|
||||||
|
requested.allowCredentials = descriptors(requested.allowCredentials);
|
||||||
|
return navigator.credentials.get({ publicKey: requested });
|
||||||
|
}).then(function (credential) {
|
||||||
|
set(form, "id", credential.id);
|
||||||
|
set(form, "rawId", toText(credential.rawId));
|
||||||
|
set(form, "authenticatorData", toText(credential.response.authenticatorData));
|
||||||
|
set(form, "clientDataJson", toText(credential.response.clientDataJSON));
|
||||||
|
set(form, "signature", toText(credential.response.signature));
|
||||||
|
set(form, "userHandle", credential.response.userHandle ? toText(credential.response.userHandle) : "");
|
||||||
|
form.dataset.ready = "1";
|
||||||
|
form.submit();
|
||||||
|
}).catch(failed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
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.
|
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue