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

@@ -5,7 +5,8 @@
*
* - `PUT /api/me/avatar` — signed in. Replaces the caller's avatar (multipart
* `file`, at most 5 MB), sends `user_updated` to everyone, and answers the
* caller's user.
* caller's user. 400 for an account from another instance, whose avatar
* comes from there. The instances the caller signed in to are told.
* - `GET /api/users/:key/avatar` — public. Serves a user's avatar; 404 without
* one.
*
@@ -15,23 +16,17 @@
import { Router } from "@oak/oak";
import { authMiddleware } from "../middleware/auth.ts";
import {
assertLocalUser,
getUserById,
resolveUserKey,
updateUserAvatar,
setUserAvatar,
} from "../services/user-service.ts";
import {
broadcastUserUpdated,
updateClientAvatar,
} from "../services/ws-service.ts";
import { type APIResponse } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { SelfUser } from "../../shared/user.ts";
import { toPublicUser, toSelfUser } from "../model/user.ts";
import {
replaceUploadedFile,
serveUploadedFile,
validateImageUpload,
} from "../lib/upload.ts";
import { toSelfUser } from "../model/user.ts";
import { serveUploadedFile } from "../lib/upload.ts";
import { notifyClients } from "../services/identity-provider-service.ts";
import { AVATARS_DIR } from "../config.ts";
/**
@@ -54,19 +49,12 @@ router.put("/api/me/avatar", authMiddleware, async (ctx) => {
throw new APIException(400, "Missing file field");
}
const data = new Uint8Array(await file.arrayBuffer());
const mime = validateImageUpload(data);
// Written before the record announces it, or clients would fetch it too
// early.
await replaceUploadedFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
updateUserAvatar(authPayload.userId, mime);
updateClientAvatar(authPayload.userId, mime);
const user = getUserById(authPayload.userId);
// Presence alone would update only the online list; `user_updated` reaches
// every avatar on screen, and its bumped `updatedAt` busts their cache.
broadcastUserUpdated(toPublicUser(user));
assertLocalUser(getUserById(authPayload.userId));
const user = await setUserAvatar(
authPayload.userId,
new Uint8Array(await file.arrayBuffer()),
);
await notifyClients(user.id, { type: "update" });
const responseBody: APIResponse<SelfUser> = {
success: true,
data: toSelfUser(user),

149
api/routes/federation.ts Normal file
View File

@@ -0,0 +1,149 @@
/**
* Lets users of other gerbeur instances sign in here with their account
* there, as `federation-service.ts` describes, and lets admins pick the
* instances to trust or block. The login and register pages start a sign-in,
* the `/federation/callback` page finishes it, `/manage` edits the peers, and
* the other instances' servers send their events.
*
* - `POST /api/federation/logins` — public. Starts a sign-in with an account
* on another instance (`FederationLoginRequest`, with an invite unless it
* is trusted), and answers its `/authorize` page to go to. Rate-limited per
* instance.
* - `POST /api/federation/sessions` — public. Finishes it
* (`FederationSessionRequest`) and answers the user and their tokens, as a
* sign-in does. Rate-limited per instance.
* - `POST /api/federation/events` — public, server to server. Applies a
* home instance's signed event about one of its users (`{ event }`).
* - `GET /api/federation/peers` — optional sign-in. Answers the trusted
* instances, or every listed one to `federation:manage`.
* - `PUT /api/federation/peers` — permission `federation:manage`. Trusts or
* blocks an instance (`SetPeerRequest`) and answers it; 502 when it
* doesn't answer as a gerbeur.
* - `DELETE /api/federation/peers/:host` — permission `federation:manage`.
* Takes an instance off the lists.
*
* @module
*/
import { Router } from "@oak/oak";
import type { APIResponse } from "../../shared/api.ts";
import {
type FederationLoginResponse,
type FederationPeer,
parseInstance,
} from "../../shared/federation.ts";
import type { AuthResponse } from "../../shared/user.ts";
import { APIException } from "../lib/api-exception.ts";
import { parseOptionalAuth } from "../lib/auth.ts";
import { issueTokens } from "../lib/jwt.ts";
import { hasPermission } from "../../shared/permissions.ts";
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
import {
type AuthContext,
authMiddleware,
requirePermission,
} from "../middleware/auth.ts";
import { toSelfUser } from "../model/user.ts";
import {
isFederationLoginRequest,
isFederationSessionRequest,
isSetPeerRequest,
} from "../validators/federation.ts";
import {
completeLogin,
receiveEvent,
startLogin,
} from "../services/federation-service.ts";
import {
listPeers,
removePeer,
setPeer,
} from "../services/federation-peer-service.ts";
import { getUserById } from "../services/user-service.ts";
import { fieldOf } from "../validators/user.ts";
/**
* Allows a burst of 30 sign-ins per instance, then one every 2 seconds, so
* that nobody makes this instance hammer another.
*/
const LOGIN_LIMIT: RateLimit = { capacity: 30, refill: 1 / 2 };
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router({ prefix: "/api/federation" });
router.post("/logins", async (ctx) => {
const body: unknown = await ctx.request.body.json();
if (!isFederationLoginRequest(body)) {
throw new APIException(400, "Invalid request");
}
if (!takeToken(`federation:${parseInstance(body.instance)}`, LOGIN_LIMIT)) {
throw new APIException(429, "Too many sign-ins — try again in a minute");
}
const responseBody: APIResponse<FederationLoginResponse> = {
success: true,
data: { authorizeUrl: await startLogin(body) },
};
ctx.response.body = responseBody;
});
router.post("/sessions", async (ctx) => {
const body: unknown = await ctx.request.body.json();
if (!isFederationSessionRequest(body)) {
throw new APIException(400, "Invalid request");
}
const user = await completeLogin(body);
const responseBody: APIResponse<AuthResponse> = {
success: true,
data: { ...await issueTokens(user), user: toSelfUser(user) },
};
ctx.response.body = responseBody;
});
router.post("/events", async (ctx) => {
const event = fieldOf(await ctx.request.body.json(), "event");
if (typeof event !== "string") throw new APIException(400, "Invalid event");
await receiveEvent(event);
ctx.response.status = 204;
});
router.get("/peers", async (ctx) => {
const userId = await parseOptionalAuth(ctx);
const all = !!userId &&
hasPermission(getUserById(userId).role, "federation:manage");
const responseBody: APIResponse<FederationPeer[]> = {
success: true,
data: listPeers(!all),
};
ctx.response.body = responseBody;
});
router.put(
"/peers",
authMiddleware,
requirePermission("federation:manage"),
async (ctx: AuthContext) => {
const body: unknown = await ctx.request.body.json();
if (!isSetPeerRequest(body)) throw new APIException(400, "Invalid request");
const responseBody: APIResponse<FederationPeer> = {
success: true,
data: await setPeer(body.instance, body.status),
};
ctx.response.body = responseBody;
},
);
router.delete(
"/peers/:host",
authMiddleware,
requirePermission("federation:manage"),
(ctx: AuthContext<"/peers/:host">) => {
removePeer(ctx.params.host);
const responseBody: APIResponse<null> = { success: true, data: null };
ctx.response.body = responseBody;
},
);
export default router;

View File

@@ -7,7 +7,8 @@
*
* - `GET /api/me` — signed in. Answers the caller's own user.
* - `PATCH /api/me` — signed in. Changes the caller's description and email,
* and answers their user. A username changes only by `user:manage`, through
* and answers their user. The email of an account from another instance is
* that instance's: 400. A username changes only by `user:manage`, through
* `PATCH /api/users/:key/username`.
* - `GET /api/me/media-token` — signed in. Answers a media token, for a
* session that predates them.
@@ -15,9 +16,17 @@
* - `PATCH /api/me/settings` — signed in. Changes some of the caller's
* settings, and answers them all.
* - `PUT /api/me/password` — signed in, with the current password. Sets a new
* one, ending every other session, and answers fresh tokens.
* one, ending every other session, and answers fresh tokens. 400 for an
* account from another instance, which has no password here.
* - `GET /api/me/playlists?contains=:dumpId` — signed in. Answers each of the
* caller's playlists and whether it holds the dump.
* - `GET /api/me/grants` — signed in. Answers the other instances the caller
* let their account sign in to.
* - `DELETE /api/me/grants/:host` — signed in. Withdraws that grant, which
* ends the caller's sessions there.
*
* A change to the caller's email or password is told to those instances
* (`notifyClients`).
*
* @module
*/
@@ -39,11 +48,21 @@ import { toPublicUser, toSelfUser } from "../model/user.ts";
import { createMediaToken, issueTokens } from "../lib/jwt.ts";
import { verifyPassword } from "../lib/password.ts";
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
import { getUserById, updateUser } from "../services/user-service.ts";
import {
assertLocalUser,
getUserById,
updateUser,
} from "../services/user-service.ts";
import { getSettings, updateSettings } from "../services/settings-service.ts";
import { getPlaylistMembershipsForDump } from "../services/playlist-service.ts";
import { broadcastUserUpdated } from "../services/ws-service.ts";
import { VALIDATION } from "../../shared/validation.ts";
import type { FederationGrant } from "../../shared/federation.ts";
import {
listGrants,
notifyClients,
revokeGrant,
} from "../services/identity-provider-service.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
@@ -65,6 +84,7 @@ router.patch("/", authMiddleware, async (ctx: AuthContext) => {
throw new APIException(400, "Invalid request");
}
const userId = ctx.state.user.userId;
if (body.email !== undefined) assertLocalUser(getUserById(userId));
// Only these fields: a stolen token alone must not change the role or the
// password, which needs the current one.
const updated = await updateUser(userId, {
@@ -72,6 +92,7 @@ router.patch("/", authMiddleware, async (ctx: AuthContext) => {
email: body.email,
});
broadcastUserUpdated(toPublicUser(updated));
if (body.email !== undefined) await notifyClients(userId, { type: "update" });
const responseBody: APIResponse<SelfUser> = {
success: true,
data: toSelfUser(updated),
@@ -127,7 +148,8 @@ router.put("/password", authMiddleware, async (ctx: AuthContext) => {
}
const user = getUserById(ctx.state.user.userId);
const valid = await verifyPassword(currentPassword, user.passwordHash);
assertLocalUser(user);
const valid = await verifyPassword(currentPassword, user.passwordHash ?? "");
if (!valid) {
throw new APIException(403, "Current password is incorrect");
}
@@ -137,6 +159,7 @@ router.put("/password", authMiddleware, async (ctx: AuthContext) => {
const updated = await updateUser(ctx.state.user.userId, {
password: newPassword,
});
await notifyClients(updated.id, { type: "revoke" });
const responseBody: APIResponse<AuthTokens> = {
success: true,
data: await issueTokens(updated),
@@ -154,4 +177,22 @@ router.get("/playlists", authMiddleware, (ctx: AuthContext) => {
ctx.response.body = responseBody;
});
router.get("/grants", authMiddleware, (ctx: AuthContext) => {
const responseBody: APIResponse<FederationGrant[]> = {
success: true,
data: listGrants(ctx.state.user.userId),
};
ctx.response.body = responseBody;
});
router.delete(
"/grants/:host",
authMiddleware,
async (ctx: AuthContext<"/grants/:host">) => {
await revokeGrant(ctx.state.user.userId, ctx.params.host);
const responseBody: APIResponse<null> = { success: true, data: null };
ctx.response.body = responseBody;
},
);
export default router;

78
api/routes/oauth.ts Normal file
View File

@@ -0,0 +1,78 @@
/**
* Lets this instance's users sign in to other gerbeur instances with their
* account here, as `identity-provider-service.ts` describes. The client's
* `/authorize` page calls the first two; the other instance's server calls the
* last.
*
* - `GET /api/oauth/clients?client_id=` — signed in. Answers the instance
* asking to sign the caller in (`OAuthClient`), and whether they already
* let it; 400 for an account from another instance, 403 when that instance
* is blocked here, 502 when it doesn't answer as a gerbeur.
* - `POST /api/oauth/codes` — signed in. Records the caller's consent to the
* request (`AuthorizeRequest`) and answers where to send them, the
* instance's callback page with a code.
* - `POST /api/oauth/tokens` — public, form-encoded, server to server. Trades
* a code and its PKCE verifier for an identity token (`id_token`), bare
* JSON as OAuth has it; 400 when anything doesn't match. Rate-limited per
* client.
*
* @module
*/
import { Router } from "@oak/oak";
import type { APIResponse } from "../../shared/api.ts";
import type {
AuthorizeResponse,
OAuthClient,
} from "../../shared/federation.ts";
import { APIException } from "../lib/api-exception.ts";
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
import { isAuthorizeRequest } from "../validators/federation.ts";
import {
createAuthorizationCode,
describeClient,
exchangeCode,
} from "../services/identity-provider-service.ts";
/** Allows a burst of 30 code trades per client instance, then one a second. */
const TOKEN_LIMIT: RateLimit = { capacity: 30, refill: 1 };
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router({ prefix: "/api/oauth" });
router.get("/clients", authMiddleware, async (ctx: AuthContext) => {
const clientId = ctx.request.url.searchParams.get("client_id");
if (!clientId) throw new APIException(400, "client_id is required");
const responseBody: APIResponse<OAuthClient> = {
success: true,
data: await describeClient(ctx.state.user.userId, clientId),
};
ctx.response.body = responseBody;
});
router.post("/codes", authMiddleware, async (ctx: AuthContext) => {
const body: unknown = await ctx.request.body.json();
if (!isAuthorizeRequest(body)) throw new APIException(400, "Invalid request");
const responseBody: APIResponse<AuthorizeResponse> = {
success: true,
data: {
redirectTo: await createAuthorizationCode(ctx.state.user.userId, body),
},
};
ctx.response.body = responseBody;
});
router.post("/tokens", async (ctx) => {
const params = new URLSearchParams(await ctx.request.body.text());
if (!takeToken(`oauth-token:${params.get("client_id")}`, TOKEN_LIMIT)) {
throw new APIException(429, "Too many requests");
}
ctx.response.headers.set("Cache-Control", "no-store");
ctx.response.body = await exchangeCode(params);
});
export default router;

View File

@@ -31,7 +31,9 @@
* - `PATCH /api/users/:key/role` — permission `user:manage`. Sets another
* user's role.
* - `PATCH /api/users/:key/username` — permission `user:manage`. Renames a
* user, the caller included. It is the only way a name changes.
* user, the caller included. It is the only way a local name changes; a
* user from another instance is named there (400). The instances the user
* signed in to are told.
*
* @module
*/
@@ -64,6 +66,7 @@ import {
import { parseOptionalAuth } from "../lib/auth.ts";
import { parsePagination } from "../lib/pagination.ts";
import {
assertLocalUser,
createUser,
getInviteTree,
renameUser,
@@ -73,6 +76,7 @@ import {
updateUser,
} from "../services/user-service.ts";
import { claimInvite, releaseInvite } from "../services/invite-service.ts";
import { notifyClients } from "../services/identity-provider-service.ts";
import {
broadcastUserUpdated,
updateClientUsername,
@@ -293,9 +297,11 @@ router.patch(
throw new APIException(400, "Invalid request");
}
const user = resolveUserKey(ctx.params.key);
assertLocalUser(user);
const publicUser = toPublicUser(renameUser(user.id, username));
updateClientUsername(publicUser.id, publicUser.username);
broadcastUserUpdated(publicUser);
await notifyClients(publicUser.id, { type: "update" });
const responseBody: APIResponse<PublicUser> = {
success: true,
data: publicUser,

36
api/routes/well-known.ts Normal file
View File

@@ -0,0 +1,36 @@
/**
* Serves what other gerbeur instances read about this one before federated
* sign-in, at the root paths OpenID Connect fixes, which are the one
* exception to the API's `/api/` rule. `remote/gerbeur-instance.ts` reads
* them on the other side.
*
* - `GET /.well-known/openid-configuration` — public. Answers the instance's
* metadata (`InstanceMetadata`): its endpoints, its name and the protocol's
* version. Bare JSON, not the API's envelope.
* - `GET /.well-known/jwks.json` — public. Answers the public keys its tokens
* are signed with. Bare JSON.
*
* @module
*/
import { Router } from "@oak/oak";
import { getInstanceMetadata } from "../services/identity-provider-service.ts";
import { getPublicKeys } from "../services/instance-key-service.ts";
/**
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
* An `APIException` thrown by a handler becomes the JSON error response there.
*/
const router: Router = new Router({ prefix: "/.well-known" });
router.get("/openid-configuration", (ctx) => {
ctx.response.headers.set("Cache-Control", "public, max-age=600");
ctx.response.body = getInstanceMetadata();
});
router.get("/jwks.json", async (ctx) => {
ctx.response.headers.set("Cache-Control", "public, max-age=600");
ctx.response.body = await getPublicKeys();
});
export default router;