v4: users sign in to one gerbeur instance with their account on another — topic instances, each with its own admins, domain and data, had no way to share accounts. Sign-in is federated over a subset of OpenID Connect, the authorization code flow with PKCE: each instance is an identity provider for its own users and a client for the others', and signs what it tells them with an Ed25519 key kept in federation_keys and published at /.well-known/jwks.json, beside its metadata at /.well-known/openid-configuration. Only sign-in is federated: an account from another instance is a local users row linked to (issuer, subject) in user_identities, with no password (password_hash ''), so sessions, roles, permissions, the socket and every foreign key work as before.

A remote user is name@host here, in users.username, in paths (/@alice@music.example) and in mentions, through one handle rule in shared/validation.ts that paths, MENTION_RE and Markdown all build on; Markdown undoes GFM's email autolink of a handle. Their name, email and avatar come from their home at each sign-in and by its signed events (federation_outbox, delivered by the federation job with backoff): a rename at home leaves the old handle an alias here, and a password change or a withdrawn grant ends their sessions here. Their password, email, avatar and name can't change here (assertLocalUser), nor can they sign in elsewhere from here.

An admin keeps the trusted and blocked instances on /manage (federation:manage): a trusted instance's users sign in from a button on the login page, a blocked one's can't and are signed out at once, and any other's join with an invite from the register page. The /authorize page asks the user once per instance, and /settings lists the instances their account signs in to, each disconnectable; /login?next= brings a signed-out visitor back to /authorize. Emails stay unique among local accounts only, and migration 0024 adds the tables, makes that index partial and reserves authorize and federation as category slugs. remote/gerbeur-instance.ts is the only way to other instances: https and public addresses only, no redirects, no certificate fallback, unless GERBEUR_FEDERATION_ALLOW_PRIVATE lets two instances on one machine talk.

298 backend tests and 702 frontend tests pass, and deno check, deno fmt, deno lint, tsc, eslint, doc:lint and i18n:compile --strict are clean; checked end to end with two built instances on one machine: sign-in through the other's login and consent pages, consent skipped once granted and asked again after disconnecting, a rename and a password change at home reaching the other, and blocking; screenshots of the login, consent, profile, settings and manage pages at 1280 and 390px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-09 14:23:00 +00:00
parent 2d26d0aada
commit c0d03e9aaa
67 changed files with 5261 additions and 339 deletions

View File

@@ -0,0 +1,119 @@
/**
* Renders the way in for users of another gerbeur instance, under the login
* form and, with the invite, under the register form.
*
* @module
*/
import { useEffect, useState } from "react";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { FormProvider } from "react-hook-form";
import { API_URL } from "../../config/api.ts";
import type { Wire } from "../../../shared/api.ts";
import type {
FederationLoginRequest,
FederationLoginResponse,
FederationPeer,
} from "../../../shared/federation.ts";
import { dataOr, expectOk } from "../../utils/shared/api.ts";
import { deserializeFederationPeer } from "../../utils/shared/deserialize.ts";
import { useApiForm } from "../../hooks/form/useApiForm.ts";
import { FormError } from "../form/FormError.tsx";
import { SubmitButton } from "../form/SubmitButton.tsx";
import { TextField } from "../form/TextField.tsx";
/** Passed to {@link FederatedSignIn} by `UserLogin` and `UserRegister`. */
export interface FederatedSignInProps {
/**
* The invite the register page was opened with, which lets a user of any
* instance join; the login page has none, and offers the trusted instances.
*/
inviteToken?: string;
}
interface Values {
instance: string;
}
/**
* Renders a button per trusted instance (`GET /api/federation/peers`) and a
* field for any other's address. Either starts the sign-in
* (`POST /api/federation/logins`) and leaves for that instance's `/authorize`
* page, which sends the user back to `/federation/callback`.
*/
export function FederatedSignIn(
{ inviteToken }: FederatedSignInProps,
): React.JSX.Element {
const [peers, setPeers] = useState<FederationPeer[]>([]);
const form = useApiForm<Values>({ defaultValues: { instance: "" } });
useEffect(() => {
if (inviteToken) return;
const controller = new AbortController();
fetch(`${API_URL}/api/federation/peers`, { signal: controller.signal })
.then((res) => dataOr<Wire<FederationPeer>[]>(res, []))
.then((list) => setPeers(list.map(deserializeFederationPeer)))
.catch(() => {});
return () => controller.abort();
}, [inviteToken]);
const onSubmit = form.submit(async ({ instance }) => {
const { authorizeUrl } = await expectOk<FederationLoginResponse>(
await fetch(`${API_URL}/api/federation/logins`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
{
instance: instance.trim(),
inviteToken,
} satisfies FederationLoginRequest,
),
}),
);
globalThis.location.assign(authorizeUrl);
});
return (
<div className="auth-federated">
<p className="auth-federated-title">
{inviteToken
? <Trans>Or join with your account on another gerbeur</Trans>
: <Trans>Or log in with your account on another gerbeur</Trans>}
</p>
<FormProvider {...form}>
{peers.map((peer) => (
<button
key={peer.issuer}
type="button"
className="btn-secondary auth-federated-peer"
disabled={form.formState.isSubmitting}
onClick={() => {
form.setValue("instance", peer.issuer);
onSubmit();
}}
>
<Trans>Log in with {peer.name ?? peer.host}</Trans>
<span className="auth-federated-host">{peer.host}</span>
</button>
))}
<form onSubmit={onSubmit} className="form">
<FormError title={t`Couldn't reach that instance`} />
<TextField<Values>
name="instance"
placeholder={t`Its address, like music.example`}
autoComplete="url"
rules={{ required: true }}
/>
<SubmitButton
className="btn-secondary"
pendingLabel={<Trans>Connecting…</Trans>}
>
<Trans>Continue</Trans>
</SubmitButton>
</form>
</FormProvider>
</div>
);
}

View File

@@ -0,0 +1,101 @@
/**
* Renders the other gerbeur instances the signed-in user let their account
* sign in to, on `/settings`.
*
* @module
*/
import { useCallback, useEffect, useState } from "react";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../../config/api.ts";
import type { Wire } from "../../../shared/api.ts";
import type { FederationGrant } from "../../../shared/federation.ts";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
import { deserializeFederationGrant } from "../../utils/shared/deserialize.ts";
import { relativeTime } from "../../utils/shared/relativeTime.ts";
import { ErrorCard } from "../shared/ErrorCard.tsx";
import { SettingRow } from "../profile/SettingRow.tsx";
/**
* Renders each instance (`GET /api/me/grants`), when it last signed the user
* in, and a button that withdraws it (`DELETE /api/me/grants/:host`), which
* signs them out there; signing in there again asks them again.
*/
export function GrantList(): React.JSX.Element {
const { authFetch } = useAuth();
const [grants, setGrants] = useState<FederationGrant[] | null>(null);
const [error, setError] = useState<string | null>(null);
const fetchGrants = useCallback(
async () =>
(await expectOk<Wire<FederationGrant>[]>(
await authFetch(`${API_URL}/api/me/grants`),
)).map(deserializeFederationGrant),
[authFetch],
);
useEffect(() => {
fetchGrants()
.then(setGrants)
.catch((err) => setError(friendlyFetchError(err)));
}, [fetchGrants]);
const revoke = async (grant: FederationGrant) => {
setError(null);
try {
await expectOk(
await authFetch(
`${API_URL}/api/me/grants/${encodeURIComponent(grant.host)}`,
{ method: "DELETE" },
),
);
setGrants(await fetchGrants());
} catch (err) {
setError(friendlyFetchError(err));
}
};
return (
<>
{grants && grants.length > 0 && (
<div className="profile-appearance-grid">
{grants.map((grant) => (
<SettingRow
key={grant.clientId}
label={
<span className="peer-name">
{grant.name ?? grant.host}
<span className="peer-host">{grant.host}</span>
</span>
}
>
<span className="peer-controls">
<span className="form-hint">
<Trans>last used {relativeTime(grant.lastUsedAt)}</Trans>
</span>
<button
type="button"
className="btn btn--ghost"
onClick={() => revoke(grant)}
>
<Trans>Disconnect</Trans>
</button>
</span>
</SettingRow>
))}
</div>
)}
{grants?.length === 0 && (
<p className="form-hint">
<Trans>
You haven't signed in to another gerbeur with this account yet.
</Trans>
</p>
)}
{error && <ErrorCard title={t`Failed to save`} message={error} />}
</>
);
}

View File

@@ -0,0 +1,177 @@
/**
* Renders the list of the other gerbeur instances an admin trusts or blocks,
* on `/manage`, for those who hold `federation:manage`.
*
* @module
*/
import { useCallback, useEffect, useState } from "react";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { FormProvider } from "react-hook-form";
import { API_URL } from "../../config/api.ts";
import type { Wire } from "../../../shared/api.ts";
import type {
FederationPeer,
PeerStatus,
SetPeerRequest,
} from "../../../shared/federation.ts";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { useApiForm } from "../../hooks/form/useApiForm.ts";
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
import { deserializeFederationPeer } from "../../utils/shared/deserialize.ts";
import { FormError } from "../form/FormError.tsx";
import { SubmitButton } from "../form/SubmitButton.tsx";
import { TextField } from "../form/TextField.tsx";
import { ErrorCard } from "../shared/ErrorCard.tsx";
import { Segmented, type SegmentedOption } from "../shared/Segmented.tsx";
import { SettingRow } from "../profile/SettingRow.tsx";
const STATUS_OPTIONS: SegmentedOption<PeerStatus>[] = [
{ value: "trusted", label: <Trans>Trusted</Trans> },
{ value: "blocked", label: <Trans>Blocked</Trans> },
];
interface Values {
instance: string;
}
/**
* Renders each listed instance with its status, which a click changes
* (`PUT /api/federation/peers`), and a button that takes it off the lists
* (`DELETE /api/federation/peers/:host`), then a field that adds one. The
* server checks that it answers as a gerbeur, and the permission again.
*/
export function PeerManager(): React.JSX.Element {
const { authFetch } = useAuth();
const [peers, setPeers] = useState<FederationPeer[] | null>(null);
const [error, setError] = useState<string | null>(null);
const form = useApiForm<Values>({ defaultValues: { instance: "" } });
const fetchPeers = useCallback(
async () =>
(await expectOk<Wire<FederationPeer>[]>(
await authFetch(`${API_URL}/api/federation/peers`),
)).map(deserializeFederationPeer),
[authFetch],
);
const load = async () => setPeers(await fetchPeers());
useEffect(() => {
fetchPeers()
.then(setPeers)
.catch((err) => setError(friendlyFetchError(err)));
}, [fetchPeers]);
const save = async (instance: string, status: PeerStatus) => {
await expectOk<Wire<FederationPeer>>(
await authFetch(`${API_URL}/api/federation/peers`, {
method: "PUT",
body: JSON.stringify({ instance, status } satisfies SetPeerRequest),
}),
);
await load();
};
/** Runs a change from a row, whose failure shows above the form. */
const change = async (run: () => Promise<void>) => {
setError(null);
try {
await run();
} catch (err) {
setError(friendlyFetchError(err));
}
};
const remove = (peer: FederationPeer) =>
change(async () => {
await expectOk(
await authFetch(
`${API_URL}/api/federation/peers/${encodeURIComponent(peer.host)}`,
{ method: "DELETE" },
),
);
await load();
});
const add = (status: PeerStatus) =>
form.submit(async ({ instance }) => {
await save(instance.trim(), status);
form.reset();
});
return (
<div className="peer-manager">
{peers === null && !error && (
<p className="index-status">
<Trans>Loading…</Trans>
</p>
)}
{peers && peers.length > 0 && (
<div className="profile-appearance-grid">
{peers.map((peer) => (
<SettingRow
key={peer.issuer}
label={
<span className="peer-name">
{peer.name ?? peer.host}
<span className="peer-host">{peer.host}</span>
</span>
}
>
<span className="peer-controls">
<Segmented
options={STATUS_OPTIONS}
value={peer.status}
onChange={(status) => change(() => save(peer.issuer, status))}
/>
<button
type="button"
className="btn--ghost peer-remove"
onClick={() => remove(peer)}
title={t`Remove ${peer.host}`}
aria-label={t`Remove ${peer.host}`}
>
✕
</button>
</span>
</SettingRow>
))}
</div>
)}
{error && <ErrorCard title={t`Failed to save`} message={error} />}
<FormProvider {...form}>
<form className="form peer-add" onSubmit={add("trusted")}>
<FormError title={t`Couldn't add that instance`} />
<TextField<Values>
name="instance"
placeholder={t`An instance's address, like music.example`}
autoComplete="url"
rules={{ required: true }}
/>
<div className="peer-add-actions">
<SubmitButton pendingLabel={<Trans>Checking…</Trans>}>
<Trans>Trust</Trans>
</SubmitButton>
<button
type="button"
className="btn-secondary"
disabled={form.formState.isSubmitting}
onClick={add("blocked")}
>
<Trans>Block</Trans>
</button>
</div>
</form>
</FormProvider>
<p className="form-hint">
<Trans>
Users of a trusted instance sign in here with their account there.
Those of a blocked one can't. Users of any other instance need an
invite.
</Trans>
</p>
</div>
);
}