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:
113
api/lib/jwt.ts
113
api/lib/jwt.ts
@@ -4,12 +4,27 @@
|
||||
* expiry are checked here: `lib/auth.ts` checks a session or media token
|
||||
* against its user.
|
||||
*
|
||||
* It also signs and verifies the tokens instances exchange for federated
|
||||
* sign-in (identity tokens and events), EdDSA with the instance's Ed25519 key,
|
||||
* whose public half other instances fetch: `instance-key-service.ts` keeps
|
||||
* the key, and the federation services pass it in.
|
||||
*
|
||||
* Importing this module throws when `GERBEUR_JWT_SECRET` is unset.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { jwtVerify, SignJWT } from "@panva/jose";
|
||||
import {
|
||||
createLocalJWKSet,
|
||||
exportJWK,
|
||||
generateKeyPair,
|
||||
importJWK,
|
||||
type JSONWebKeySet,
|
||||
type JWK,
|
||||
type JWTPayload,
|
||||
jwtVerify,
|
||||
SignJWT,
|
||||
} from "@panva/jose";
|
||||
|
||||
import {
|
||||
type AuthPayload,
|
||||
@@ -184,3 +199,99 @@ export async function verifyUnsubscribeToken(
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The algorithm of the tokens instances exchange: Ed25519 signatures, short
|
||||
* and fast, with no parameters to get wrong.
|
||||
*/
|
||||
const INSTANCE_ALG = "EdDSA";
|
||||
|
||||
/**
|
||||
* An instance's key, ready to sign, from {@link importInstanceKey}. Its
|
||||
* `kid` names the public half in the instance's JWKS.
|
||||
*/
|
||||
export interface InstanceSigningKey {
|
||||
kid: string;
|
||||
privateKey: CryptoKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new Ed25519 key pair as JWKs, with a random `kid`, for
|
||||
* `instance-key-service.ts` to store when the instance has none. The public
|
||||
* JWK carries the `kid`, `alg` and `use` a JWKS entry needs.
|
||||
*/
|
||||
export async function generateInstanceKey(): Promise<
|
||||
{ kid: string; privateJwk: JWK; publicJwk: JWK }
|
||||
> {
|
||||
const { privateKey, publicKey } = await generateKeyPair(INSTANCE_ALG, {
|
||||
crv: "Ed25519",
|
||||
extractable: true,
|
||||
});
|
||||
const kid = crypto.randomUUID();
|
||||
return {
|
||||
kid,
|
||||
privateJwk: await exportJWK(privateKey),
|
||||
publicJwk: {
|
||||
...await exportJWK(publicKey),
|
||||
kid,
|
||||
alg: INSTANCE_ALG,
|
||||
use: "sig",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns the stored private JWK `privateJwk` as a key to sign with. */
|
||||
export async function importInstanceKey(
|
||||
kid: string,
|
||||
privateJwk: JWK,
|
||||
): Promise<InstanceSigningKey> {
|
||||
const privateKey = await importJWK(privateJwk, INSTANCE_ALG);
|
||||
if (!(privateKey instanceof CryptoKey)) {
|
||||
throw new Error("The instance key is not an asymmetric key");
|
||||
}
|
||||
return { kid, privateKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs `payload` with the instance's key, from `issuer` (this instance) to
|
||||
* `audience` (the instance it is for), valid for `expiresIn`, with a random
|
||||
* `jti`. The identity tokens of `POST /api/oauth/tokens` and the events of
|
||||
* the outbox are signed with it.
|
||||
*/
|
||||
export async function signInstanceToken(
|
||||
payload: JWTPayload,
|
||||
key: InstanceSigningKey,
|
||||
claims: { issuer: string; audience: string; subject: string },
|
||||
expiresIn: string,
|
||||
): Promise<string> {
|
||||
return await new SignJWT(payload)
|
||||
.setProtectedHeader({ alg: INSTANCE_ALG, kid: key.kid })
|
||||
.setIssuer(claims.issuer)
|
||||
.setAudience(claims.audience)
|
||||
.setSubject(claims.subject)
|
||||
.setIssuedAt()
|
||||
.setJti(crypto.randomUUID())
|
||||
.setExpirationTime(expiresIn)
|
||||
.sign(key.privateKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the payload of `token` once its signature checks against `jwks`,
|
||||
* the keys of `issuer`, and it is addressed to `audience` and unexpired.
|
||||
*
|
||||
* @throws {Error} jose's error when it doesn't verify; its `code` is
|
||||
* `ERR_JWKS_NO_MATCHING_KEY` when no key of `jwks` has its `kid`, which
|
||||
* tells the caller to refetch the keys, the issuer having rotated them.
|
||||
*/
|
||||
export async function verifyInstanceToken(
|
||||
token: string,
|
||||
jwks: JSONWebKeySet,
|
||||
claims: { issuer: string; audience: string },
|
||||
): Promise<JWTPayload> {
|
||||
const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
|
||||
issuer: claims.issuer,
|
||||
audience: claims.audience,
|
||||
algorithms: [INSTANCE_ALG],
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ export const RESERVED_SLUGS: readonly string[] = [
|
||||
"settings",
|
||||
"manage",
|
||||
"community",
|
||||
"authorize",
|
||||
"federation",
|
||||
"api",
|
||||
"ws",
|
||||
"assets",
|
||||
@@ -46,7 +48,8 @@ export function isReservedSlug(slug: string): boolean {
|
||||
/**
|
||||
* Renames each category whose slug is now reserved, such as `hot`, to the
|
||||
* first of `<slug>-2`, `<slug>-3`… that is free, and logs it. Migration 0021
|
||||
* runs it for v4's words, and 0022 for `community`.
|
||||
* runs it for v4's words, 0022 for `community`, and 0024 for `authorize` and
|
||||
* `federation`.
|
||||
*/
|
||||
export function renameReservedCategories(db: DatabaseSync): void {
|
||||
const rows = db.prepare(`SELECT id, slug FROM categories;`).all() as {
|
||||
|
||||
Reference in New Issue
Block a user