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:
@@ -4,7 +4,13 @@ import { TEST_DIR } from "./setup.ts";
|
||||
import { stub } from "@std/testing/mock";
|
||||
import { app } from "../main.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { createJWT, createMediaToken } from "../lib/jwt.ts";
|
||||
import {
|
||||
createJWT,
|
||||
createMediaToken,
|
||||
generateInstanceKey,
|
||||
importInstanceKey,
|
||||
signInstanceToken,
|
||||
} from "../lib/jwt.ts";
|
||||
import { hashPassword } from "../lib/password.ts";
|
||||
import { uniqueSlug } from "../lib/slugify.ts";
|
||||
import { slugify } from "../../shared/slug.ts";
|
||||
@@ -12,6 +18,7 @@ import { dumpPath, playlistPath } from "../../shared/paths.ts";
|
||||
import { canonicalizeUrl } from "../lib/canonical-url.ts";
|
||||
import { clearRichContentCache } from "../services/rich-content-service.ts";
|
||||
import { clearImageCache } from "../remote/image-proxy.ts";
|
||||
import { clearInstanceCaches } from "../remote/gerbeur-instance.ts";
|
||||
import {
|
||||
type OutgoingEmail,
|
||||
setEmailTransport,
|
||||
@@ -24,6 +31,12 @@ export { app, db, TEST_DIR };
|
||||
// ── Database ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const TABLES = [
|
||||
"user_identities",
|
||||
"federation_peers",
|
||||
"federation_logins",
|
||||
"oauth_codes",
|
||||
"federation_grants",
|
||||
"federation_outbox",
|
||||
"dump_backlinks",
|
||||
"dump_categories",
|
||||
"playlist_dumps",
|
||||
@@ -393,6 +406,7 @@ export function stubNetwork(
|
||||
// A new network: metadata cached from the last one no longer describes it.
|
||||
clearRichContentCache();
|
||||
clearImageCache();
|
||||
clearInstanceCaches();
|
||||
const fetchStub = stub(
|
||||
globalThis,
|
||||
"fetch",
|
||||
@@ -419,6 +433,137 @@ export function stubNetwork(
|
||||
};
|
||||
}
|
||||
|
||||
// ── Federation ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A user of a {@link FakeInstance}, as its identity tokens describe them. */
|
||||
export interface FakeIdentity {
|
||||
sub: string;
|
||||
preferred_username: string;
|
||||
email: string;
|
||||
picture?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Another gerbeur instance at `origin`, answering through {@link stubNetwork}
|
||||
* (`stubNetwork((url, init) => fake.handle(url, init) ?? ...)`): its metadata,
|
||||
* its keys, a token endpoint that trades the codes the test `issue`s, an
|
||||
* events endpoint recording what it receives, and avatars.
|
||||
*/
|
||||
export interface FakeInstance {
|
||||
origin: string;
|
||||
/**
|
||||
* Makes a code for `identity`, answering the authorize URL `authorizeUrl`
|
||||
* (this instance's request) as the home would after consent.
|
||||
*/
|
||||
issue(authorizeUrl: string, identity: FakeIdentity): string;
|
||||
/** Signs an event about `sub` for this instance, as its outbox would. */
|
||||
event(sub: string, payload: Record<string, unknown>): Promise<string>;
|
||||
/** The events posted to it, as their JWTs. */
|
||||
received: string[];
|
||||
/** Answers a request to it, or null when `url` isn't on it. */
|
||||
handle(url: URL, init?: RequestInit): Promise<Response> | null;
|
||||
}
|
||||
|
||||
/** Makes a {@link FakeInstance} at `origin` with a fresh key. */
|
||||
export async function fakeInstance(origin: string): Promise<FakeInstance> {
|
||||
const { kid, privateJwk, publicJwk } = await generateInstanceKey();
|
||||
const key = await importInstanceKey(kid, privateJwk);
|
||||
const codes = new Map<
|
||||
string,
|
||||
{ identity: FakeIdentity; nonce: string; challenge: string; client: string }
|
||||
>();
|
||||
const received: string[] = [];
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
const handle = async (url: URL, init?: RequestInit): Promise<Response> => {
|
||||
switch (url.pathname) {
|
||||
case "/.well-known/openid-configuration":
|
||||
return json({
|
||||
issuer: origin,
|
||||
authorization_endpoint: `${origin}/authorize`,
|
||||
token_endpoint: `${origin}/api/oauth/tokens`,
|
||||
jwks_uri: `${origin}/.well-known/jwks.json`,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code"],
|
||||
subject_types_supported: ["public"],
|
||||
id_token_signing_alg_values_supported: ["EdDSA"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
scopes_supported: ["openid", "profile", "email"],
|
||||
gerbeur_federation: 1,
|
||||
gerbeur_site_name: `Fake ${new URL(origin).host}`,
|
||||
gerbeur_redirect_uri: `${origin}/federation/callback`,
|
||||
gerbeur_events_endpoint: `${origin}/api/federation/events`,
|
||||
});
|
||||
case "/.well-known/jwks.json":
|
||||
return json({ keys: [publicJwk] });
|
||||
case "/api/oauth/tokens": {
|
||||
const form = new URLSearchParams(String(init?.body));
|
||||
const entry = codes.get(form.get("code") ?? "");
|
||||
codes.delete(form.get("code") ?? "");
|
||||
const verifier = form.get("code_verifier") ?? "";
|
||||
const hash = new Uint8Array(
|
||||
await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
new TextEncoder().encode(verifier),
|
||||
),
|
||||
);
|
||||
const challenge = btoa(String.fromCharCode(...hash))
|
||||
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
if (
|
||||
!entry || entry.challenge !== challenge ||
|
||||
entry.client !== form.get("client_id")
|
||||
) {
|
||||
return json({ error: "invalid_grant" }, 400);
|
||||
}
|
||||
const { sub, ...claims } = entry.identity;
|
||||
return json({
|
||||
id_token: await signInstanceToken(
|
||||
{ ...claims, nonce: entry.nonce },
|
||||
key,
|
||||
{ issuer: origin, audience: entry.client, subject: sub },
|
||||
"5m",
|
||||
),
|
||||
});
|
||||
}
|
||||
case "/api/federation/events":
|
||||
received.push(JSON.parse(String(init?.body)).event);
|
||||
return new Response(null, { status: 204 });
|
||||
default:
|
||||
if (url.pathname.endsWith("/avatar")) {
|
||||
return new Response(PNG, {
|
||||
headers: { "content-type": "image/png" },
|
||||
});
|
||||
}
|
||||
return json({ error: "not found" }, 404);
|
||||
}
|
||||
};
|
||||
return {
|
||||
origin,
|
||||
received,
|
||||
issue(authorizeUrl, identity) {
|
||||
const q = new URL(authorizeUrl).searchParams;
|
||||
const code = crypto.randomUUID();
|
||||
codes.set(code, {
|
||||
identity,
|
||||
nonce: q.get("nonce") ?? "",
|
||||
challenge: q.get("code_challenge") ?? "",
|
||||
client: q.get("client_id") ?? "",
|
||||
});
|
||||
return code;
|
||||
},
|
||||
event: (sub, payload) =>
|
||||
signInstanceToken(payload, key, {
|
||||
issuer: origin,
|
||||
audience: BASE_URL,
|
||||
subject: sub,
|
||||
}, "1h"),
|
||||
handle: (url, init) => url.origin === origin ? handle(url, init) : null,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Email ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user