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

@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
.get() as {
n: number;
};
assertEquals(applied.n, 23);
assertEquals(applied.n, 24);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
23,
24,
);
db.close();
});

View File

@@ -0,0 +1,43 @@
import "../../setup.ts";
import { assertEquals, assertThrows } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { up as up0024 } from "../../../db/migrations/0024_federation.ts";
Deno.test("migration 0024 adds federation and frees remote accounts' emails", () => {
const db = new DatabaseSync(":memory:");
db.exec(`
CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT, password_hash TEXT, email TEXT);
CREATE UNIQUE INDEX idx_users_email_lower ON users(lower(email));
CREATE TABLE categories (id TEXT PRIMARY KEY, slug TEXT);
INSERT INTO users VALUES ('a', 'ann', 'h.s', 'a@x.test');
INSERT INTO categories VALUES ('c', 'authorize'), ('d', 'music');
`);
up0024(db);
up0024(db); // idempotent
// Two accounts without a password may share an address with a local one.
db.exec(`
INSERT INTO users VALUES ('b', 'ann@one.test', '', 'a@x.test');
INSERT INTO users VALUES ('c', 'ann@two.test', '', 'A@x.test');
`);
assertThrows(() =>
db.exec(`INSERT INTO users VALUES ('d', 'dup', 'h.s', 'a@X.test');`)
);
const slugs = db.prepare(`SELECT slug FROM categories ORDER BY id;`)
.all() as { slug: string }[];
assertEquals(slugs.map((r) => r.slug), ["authorize-2", "music"]);
for (
const table of [
"federation_keys",
"user_identities",
"federation_peers",
"federation_logins",
"oauth_codes",
"federation_grants",
"federation_outbox",
]
) {
db.prepare(`SELECT COUNT(*) FROM ${table};`).get();
}
db.close();
});

View File

@@ -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 ────────────────────────────────────────────────────────────────────
/**

View File

@@ -0,0 +1,326 @@
import {
createUser,
db,
del,
type FakeInstance,
fakeInstance,
formWithFile,
get,
patch,
PNG,
post,
put,
stubNetwork,
test,
} from "../helpers.ts";
import { assert, assertEquals, assertMatch } from "@std/assert";
import type {
FederationLoginResponse,
FederationPeer,
} from "../../../shared/federation.ts";
import type { AuthResponse, SelfUser } from "../../../shared/user.ts";
const HOME = "https://home.test";
/** Puts `fake` behind the network, every other host answering 404. */
function network(...fakes: FakeInstance[]) {
return stubNetwork((url, init) => {
for (const fake of fakes) {
const res = fake.handle(url, init);
if (res) return res;
}
return new Response("", { status: 404 });
});
}
async function trust(issuer: string, status = "trusted") {
const admin = await createUser({ role: "admin" });
return await put<FederationPeer>("/api/federation/peers", {
auth: admin.auth,
json: { instance: issuer, status },
});
}
/** Signs in through `home` as `identity`, as the pages would. */
async function signIn(
home: FakeInstance,
identity: {
sub: string;
preferred_username: string;
email: string;
picture?: string;
},
inviteToken?: string,
) {
const start = await post<FederationLoginResponse>("/api/federation/logins", {
json: { instance: new URL(home.origin).host, inviteToken },
});
if (start.status !== 200) return start;
const authorizeUrl = start.data.authorizeUrl;
const code = home.issue(authorizeUrl, identity);
return await post<AuthResponse>("/api/federation/sessions", {
json: { code, state: new URL(authorizeUrl).searchParams.get("state") },
});
}
const ALICE = {
sub: "alice-id",
preferred_username: "alice",
email: "alice@home.example",
picture: `${HOME}/api/users/alice-id/avatar?v=1`,
};
test("federation: a trusted instance's user signs in as name@host, once made", async () => {
const home = await fakeInstance(HOME);
using net = network(home);
assertEquals((await trust("home.test")).data.name, "Fake home.test");
const start = await post<FederationLoginResponse>("/api/federation/logins", {
json: { instance: "home.test" },
});
const url = new URL(start.data.authorizeUrl);
assertEquals(url.origin + url.pathname, `${HOME}/authorize`);
assertEquals(url.searchParams.get("client_id"), "http://gerbeur.test");
assertEquals(
url.searchParams.get("redirect_uri"),
"http://gerbeur.test/federation/callback",
);
assertEquals(url.searchParams.get("code_challenge_method"), "S256");
const first = await signIn(home, ALICE);
const { user, token } = first.data as AuthResponse;
assertEquals(user.username, "alice@home.test");
assertEquals(user.email, "alice@home.example");
assertEquals(user.role, "user");
assertEquals(user.avatarMime, "image/png");
assert(net.calls.some((u) => u.pathname === "/api/users/alice-id/avatar"));
const me = await get<SelfUser>("/api/me", {
auth: { Authorization: `Bearer ${token}` },
});
assertEquals(me.data.id, user.id);
// The same identity signs in to the same account.
const again = await signIn(home, ALICE);
assertEquals((again.data as AuthResponse).user.id, user.id);
// It has no password here.
const login = await post("/api/sessions", {
json: { username: "alice@home.test", password: "" },
});
assertEquals(login.status, 401);
assertEquals(
(await get<SelfUser>("/api/users/@alice@home.test")).data.id,
user.id,
);
// The client encodes the handle's `@`.
assertEquals(
(await get<SelfUser>("/api/users/@alice%40home.test")).data.id,
user.id,
);
});
test("federation: a login works once, with the code the home made for it", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
await trust(HOME);
const start = await post<FederationLoginResponse>("/api/federation/logins", {
json: { instance: HOME },
});
const state = new URL(start.data.authorizeUrl).searchParams.get("state");
const wrong = await post("/api/federation/sessions", {
json: { code: "made-up", state },
});
assertEquals(wrong.status, 502);
// The failed try used the login up.
const code = home.issue(start.data.authorizeUrl, ALICE);
const replay = await post("/api/federation/sessions", {
json: { code, state },
});
assertEquals(replay.status, 400);
});
test("federation: an instance on neither list needs an invite, claimed on joining", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
const refused = await signIn(home, ALICE);
assertEquals(refused.status, 403);
const inviter = await createUser();
const { token } = (await post<{ token: string }>("/api/invites", {
auth: inviter.auth,
})).data;
const joined = await signIn(home, ALICE, token);
const { user } = joined.data as AuthResponse;
assertEquals(user.username, "alice@home.test");
const row = db.prepare(`SELECT invited_by FROM users WHERE id = ?;`).get(
user.id,
) as { invited_by: string };
assertEquals(row.invited_by, inviter.id);
assertEquals((await get(`/api/invites/${token}`)).status, 404);
// Once here, no invite is needed; another user of that instance still
// needs one.
assertEquals((await signIn(home, ALICE)).status, 200);
const bob = { ...ALICE, sub: "bob-id", preferred_username: "bob" };
assertEquals((await signIn(home, bob)).status, 403);
});
test("federation: blocking an instance refuses its users and ends their sessions", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
await trust(HOME);
const { token } = (await signIn(home, ALICE)).data as AuthResponse;
const auth = { Authorization: `Bearer ${token}` };
assertEquals((await get("/api/me", { auth })).status, 200);
await trust(HOME, "blocked");
assertEquals((await get("/api/me", { auth })).status, 401);
assertEquals((await signIn(home, ALICE)).status, 403);
const admin = await createUser({ role: "admin" });
const peers = await get<FederationPeer[]>("/api/federation/peers", {
auth: admin.auth,
});
assertEquals(peers.data.map((p) => p.status), ["blocked"]);
assertEquals((await get<FederationPeer[]>("/api/federation/peers")).data, []);
assertEquals(
(await del("/api/federation/peers/home.test", { auth: admin.auth }))
.status,
200,
);
assertEquals((await get("/api/me", { auth })).status, 200);
});
test("federation: only admins edit the peers, which must answer as gerbeurs", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
const user = await createUser();
const admin = await createUser({ role: "admin" });
assertEquals(
(await put("/api/federation/peers", {
auth: user.auth,
json: { instance: HOME, status: "trusted" },
})).status,
403,
);
for (const instance of ["elsewhere.test", "https://home.test/path"]) {
const res = await put("/api/federation/peers", {
auth: admin.auth,
json: { instance, status: "trusted" },
});
assert(res.status >= 400, instance);
}
assertEquals(
(await put("/api/federation/peers", {
auth: admin.auth,
json: { instance: "http://gerbeur.test", status: "trusted" },
})).status,
400,
);
});
test("federation: the home's events rename, update and sign out its users", async () => {
const home = await fakeInstance(HOME);
const other = await fakeInstance("https://other.test");
using _net = network(home, other);
await trust(HOME);
const { user, token } = (await signIn(home, ALICE)).data as AuthResponse;
const auth = { Authorization: `Bearer ${token}` };
const update = await home.event(ALICE.sub, {
type: "update",
claims: { ...ALICE, preferred_username: "alicia", email: "a@new.example" },
});
assertEquals(
(await post("/api/federation/events", { json: { event: update } }))
.status,
204,
);
const renamed = await get<SelfUser>("/api/me", { auth });
assertEquals(renamed.data.username, "alicia@home.test");
assertEquals(renamed.data.email, "a@new.example");
// The old handle still leads to them.
assertEquals(
(await get<SelfUser>("/api/users/@alice@home.test")).data.id,
user.id,
);
// Another instance can't speak for this one's users.
const forged = await other.event(ALICE.sub, { type: "revoke" });
assertEquals(
(await post("/api/federation/events", { json: { event: forged } }))
.status,
400,
);
// Revoking a little later than the token was issued, as it would be.
await new Promise((r) => setTimeout(r, 1100));
const revoke = await home.event(ALICE.sub, { type: "revoke" });
assertEquals(
(await post("/api/federation/events", { json: { event: revoke } }))
.status,
204,
);
assertEquals((await get("/api/me", { auth })).status, 401);
});
test("federation: an account from another instance changes its password, email, avatar and name there", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
await trust(HOME);
const { user, token } = (await signIn(home, ALICE)).data as AuthResponse;
const auth = { Authorization: `Bearer ${token}` };
const admin = await createUser({ role: "admin" });
assertEquals(
(await put("/api/me/password", {
auth,
json: { currentPassword: "", newPassword: "long-enough" },
})).status,
400,
);
assertEquals(
(await patch("/api/me", { auth, json: { email: "x@example.test" } }))
.status,
400,
);
assertEquals(
(await patch<SelfUser>("/api/me", { auth, json: { description: "hi" } }))
.data.description,
"hi",
);
assertEquals(
(await put("/api/me/avatar", { auth, form: formWithFile(PNG) })).status,
400,
);
assertEquals(
(await patch(`/api/users/${user.id}/username`, {
auth: admin.auth,
json: { username: "bob" },
})).status,
400,
);
});
test("federation: an email may be both a local account's and a remote one's", async () => {
const home = await fakeInstance(HOME);
using _net = network(home);
await trust(HOME);
const local = await createUser({ email: ALICE.email });
const res = await signIn(home, ALICE);
assertMatch((res.data as AuthResponse).user.username, /@home\.test$/);
// A reset by that address reaches the local account only.
const row = db.prepare(
`SELECT COUNT(*) AS n FROM users WHERE lower(email) = lower(?);`,
).get(ALICE.email) as { n: number };
assertEquals(row.n, 2);
assertEquals(
(await post("/api/password-resets", { json: { email: ALICE.email } }))
.status,
200,
);
const tokens = db.prepare(`SELECT user_id FROM password_reset_tokens;`)
.all() as { user_id: string }[];
assert(tokens.every((t) => t.user_id === local.id));
});

View File

@@ -0,0 +1,268 @@
import {
app,
BASE_URL,
createUser,
db,
del,
type FakeInstance,
fakeInstance,
get,
patch,
post,
put,
stubNetwork,
test,
} from "../helpers.ts";
import { assert, assertEquals } from "@std/assert";
import { createHash } from "node:crypto";
import { decodeJwt, type JSONWebKeySet } from "@panva/jose";
import { verifyInstanceToken } from "../../lib/jwt.ts";
import type {
AuthorizeResponse,
FederationGrant,
InstanceMetadata,
OAuthClient,
} from "../../../shared/federation.ts";
const CLIENT = "https://client.test";
const CALLBACK = `${CLIENT}/federation/callback`;
function network(fake: FakeInstance, events?: () => Response) {
return stubNetwork((url, init) => {
if (events && url.pathname === "/api/federation/events") return events();
return fake.handle(url, init) ?? new Response("", { status: 404 });
});
}
/** A PKCE pair: the verifier, and the challenge the request carries. */
function pkce() {
const verifier = crypto.randomUUID() + crypto.randomUUID();
return {
verifier,
challenge: createHash("sha256").update(verifier).digest("base64url"),
};
}
function authorize(
auth: { Authorization: string },
challenge: string,
overrides: Record<string, string> = {},
) {
return post<AuthorizeResponse>("/api/oauth/codes", {
auth,
json: {
clientId: CLIENT,
redirectUri: CALLBACK,
state: "the-state",
codeChallenge: challenge,
codeChallengeMethod: "S256",
nonce: "the-nonce",
...overrides,
},
});
}
/** Trades `code` at the token endpoint, as the client's server would. */
async function trade(code: string, verifier: string, client = CLIENT) {
const res = await app.handle(
new Request(`${BASE_URL}/api/oauth/tokens`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
client_id: client,
redirect_uri: CALLBACK,
code_verifier: verifier,
}),
}),
);
return { status: res!.status, body: await res!.json() };
}
async function until(check: () => boolean) {
for (let i = 0; i < 50 && !check(); i++) {
await new Promise((r) => setTimeout(r, 10));
}
}
test("identity provider: metadata and keys are served at the well-known paths", async () => {
const meta = await get("/.well-known/openid-configuration");
const body = JSON.parse(
new TextDecoder().decode(meta.bytes),
) as InstanceMetadata;
assertEquals(body.issuer, BASE_URL);
assertEquals(body.authorization_endpoint, `${BASE_URL}/authorize`);
assertEquals(body.gerbeur_redirect_uri, `${BASE_URL}/federation/callback`);
assertEquals(body.gerbeur_federation, 1);
const jwks = await get("/.well-known/jwks.json");
const keys = JSON.parse(new TextDecoder().decode(jwks.bytes)).keys;
assertEquals(keys[0].crv, "Ed25519");
assertEquals(keys[0].d, undefined);
});
test("identity provider: a consenting user's code trades once for their identity", async () => {
const fake = await fakeInstance(CLIENT);
using _net = network(fake);
const user = await createUser({ username: "carol" });
const client = await get<OAuthClient>(
`/api/oauth/clients?client_id=${encodeURIComponent(CLIENT)}`,
{ auth: user.auth },
);
assertEquals(client.data, {
clientId: CLIENT,
host: "client.test",
name: "Fake client.test",
granted: false,
});
const { verifier, challenge } = pkce();
const redirect = new URL(
(await authorize(user.auth, challenge)).data
.redirectTo,
);
assertEquals(redirect.origin + redirect.pathname, CALLBACK);
assertEquals(redirect.searchParams.get("state"), "the-state");
assertEquals(redirect.searchParams.get("iss"), BASE_URL);
const code = redirect.searchParams.get("code")!;
assertEquals((await trade(code, pkce().verifier)).status, 400);
// A failed trade used the code up too.
assertEquals((await trade(code, verifier)).status, 400);
const { challenge: c2, verifier: v2 } = pkce();
const code2 = new URL((await authorize(user.auth, c2)).data.redirectTo)
.searchParams.get("code")!;
assertEquals((await trade(code2, v2, "https://elsewhere.test")).status, 400);
const { challenge: c3, verifier: v3 } = pkce();
const code3 = new URL((await authorize(user.auth, c3)).data.redirectTo)
.searchParams.get("code")!;
const traded = await trade(code3, v3);
assertEquals(traded.status, 200);
const keys = JSON.parse(
new TextDecoder().decode((await get("/.well-known/jwks.json")).bytes),
) as JSONWebKeySet;
const claims = await verifyInstanceToken(traded.body.id_token, keys, {
issuer: BASE_URL,
audience: CLIENT,
});
assertEquals(claims.sub, user.id);
assertEquals(claims.preferred_username, "carol");
assertEquals(claims.email, user.email);
assertEquals(claims.nonce, "the-nonce");
const again = await get<OAuthClient>(
`/api/oauth/clients?client_id=${encodeURIComponent(CLIENT)}`,
{ auth: user.auth },
);
assertEquals(again.data.granted, true);
const grants = await get<FederationGrant[]>("/api/me/grants", {
auth: user.auth,
});
assertEquals(grants.data.map((g) => g.host), ["client.test"]);
});
test("identity provider: codes are only for a known client's own callback", async () => {
const fake = await fakeInstance(CLIENT);
using _net = network(fake);
const user = await createUser();
const admin = await createUser({ role: "admin" });
const { challenge } = pkce();
assertEquals(
(await authorize(user.auth, challenge, {
redirectUri: "https://evil.test/cb",
})).status,
400,
);
assertEquals(
(await authorize(user.auth, challenge, { clientId: BASE_URL })).status,
400,
);
assertEquals(
(await authorize(user.auth, challenge, { codeChallengeMethod: "plain" }))
.status,
400,
);
assertEquals(
(await authorize(user.auth, challenge, {
clientId: "https://nowhere.test",
})).status,
502,
);
await put("/api/federation/peers", {
auth: admin.auth,
json: { instance: CLIENT, status: "blocked" },
});
assertEquals((await authorize(user.auth, challenge)).status, 403);
});
test("identity provider: an account from another instance doesn't sign in elsewhere from here", async () => {
const fake = await fakeInstance(CLIENT);
using _net = network(fake);
const user = await createUser();
db.prepare(`UPDATE users SET password_hash = '' WHERE id = ?;`).run(user.id);
assertEquals((await authorize(user.auth, pkce().challenge)).status, 400);
});
test("identity provider: the instances a user signed in to hear of their changes", async () => {
const fake = await fakeInstance(CLIENT);
using _net = network(fake);
const user = await createUser({ username: "dave" });
const admin = await createUser({ role: "admin" });
await authorize(user.auth, pkce().challenge);
await patch(`/api/users/${user.id}/username`, {
auth: admin.auth,
json: { username: "david" },
});
await until(() => fake.received.length === 1);
const update = decodeJwt(fake.received[0]);
assertEquals(update.type, "update");
assertEquals(update.sub, user.id);
assertEquals(update.aud, CLIENT);
assertEquals(
(update.claims as { preferred_username: string }).preferred_username,
"david",
);
await put("/api/me/password", {
auth: user.auth,
json: { currentPassword: "correct-horse", newPassword: "new-password" },
});
await until(() => fake.received.length === 2);
assertEquals(decodeJwt(fake.received[1]).type, "revoke");
const token = (await post<{ token: string }>("/api/sessions", {
json: { username: "david", password: "new-password" },
})).data.token;
const auth = { Authorization: `Bearer ${token}` };
assertEquals(
(await del("/api/me/grants/client.test", { auth })).status,
200,
);
await until(() => fake.received.length === 3);
assertEquals(decodeJwt(fake.received[2]).type, "revoke");
assertEquals(
(await get<FederationGrant[]>("/api/me/grants", { auth })).data,
[],
);
});
test("identity provider: an event an instance fails to take waits in the outbox", async () => {
const fake = await fakeInstance(CLIENT);
using _net = network(fake, () => new Response("", { status: 503 }));
const user = await createUser();
await authorize(user.auth, pkce().challenge);
await patch("/api/me", { auth: user.auth, json: { email: "e@new.test" } });
let row: { attempts: number } | undefined;
await until(() => {
row = db.prepare(`SELECT attempts FROM federation_outbox;`).get() as
| { attempts: number }
| undefined;
return (row?.attempts ?? 0) > 0;
});
assert(row);
assertEquals(row.attempts, 1);
});