Manage followers from the API and web UI (phase 2, step 6)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 2m4s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

- /api/v1/federation: list followers and requests, approve (Accept),
  decline or remove (Reject), block (Block, and future follows are
  refused), list and remove blocks; settings report follower counts
- The actor now reflects the user's real follow-approval setting and
  the followers collection its accepted count
- Turning sharing off sends every follower a Reject and forgets them;
  while those are being delivered the actor stays fetchable with just
  its key (no name or bio) so other servers can verify them, and
  WebFinger already says not found
- Web UI: a Followers page (requests with Approve/Decline, followers
  with Remove/Block behind a confirm step, blocked accounts with
  Unblock; remote names shown as plain text only), follower counts on
  the Sharing page, and a confirmation before turning sharing off
  when that would remove followers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 21:42:29 +01:00
1 parent 142dc13fea
commit a90cd14f59
12 files changed
+1083 -18

No files matched your search

+461 -3
View File
@@ -1942,7 +1942,7 @@
}
},
"summary": "Change your sharing settings",
"description": "Turning sharing on makes you findable as your handle. Your handle can't change once\npeople follow you. Visibility changes apply to new posts only.",
"description": "Turning sharing on makes you findable as your handle. Your handle can't change once\npeople follow you. Visibility changes apply to new posts only. Turning sharing off\nremoves all your followers (each is told).",
"tags": [
"Federation"
],
@@ -1998,6 +1998,391 @@
}
]
},
"/api/v1/federation/followers": {
"get": {
"parameters": [
{
"in": "query",
"name": "state",
"schema": {
"type": [
"string",
"null"
],
"default": null,
"enum": [
"pending",
"accepted",
null
]
},
"required": false
}
],
"responses": {
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Follower"
}
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Your followers and follow requests",
"description": "Newest first. Filter with `state=pending` (requests) or `state=accepted`.",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/federation/followers/{follower_id}/approve": {
"post": {
"responses": {
"409": {
"description": "Not a pending request",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "No such follower",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Follower"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Approve a follow request",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "follower_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/api/v1/federation/followers/{follower_id}/decline": {
"post": {
"responses": {
"404": {
"description": "No such follower",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"204": {
"description": "No Content"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Decline a follow request",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "follower_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/api/v1/federation/followers/{follower_id}/remove": {
"post": {
"responses": {
"404": {
"description": "No such follower",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"204": {
"description": "No Content"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Remove a follower",
"description": "They stop receiving your posts. They can follow you again; block them to prevent it.",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "follower_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/api/v1/federation/followers/{follower_id}/block": {
"post": {
"responses": {
"404": {
"description": "No such follower",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"204": {
"description": "No Content"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Block a follower",
"description": "Removes them and refuses their future follows.",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "follower_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/api/v1/federation/blocks": {
"get": {
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Block"
}
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Accounts you've blocked",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/federation/blocks/{block_id}": {
"delete": {
"responses": {
"404": {
"description": "No such block",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"204": {
"description": "No Content"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Unblock an account",
"description": "They can follow you again (they aren't re-added).",
"tags": [
"Federation"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "block_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/.well-known/webfinger": {
"get": {
"tags": [
@@ -3693,7 +4078,12 @@
"followers": {
"type": "integer",
"readOnly": true,
"description": "0 until following arrives"
"description": "Accepted followers"
},
"pending_followers": {
"type": "integer",
"readOnly": true,
"description": "Waiting for approval"
}
},
"additionalProperties": false
@@ -3755,7 +4145,12 @@
"followers": {
"type": "integer",
"readOnly": true,
"description": "0 until following arrives"
"description": "Accepted followers"
},
"pending_followers": {
"type": "integer",
"readOnly": true,
"description": "Waiting for approval"
}
},
"additionalProperties": false
@@ -3784,6 +4179,69 @@
}
},
"additionalProperties": false
},
"Follower": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"state": {
"type": "string",
"enum": [
"pending",
"accepted"
]
},
"handle": {
"type": "string",
"example": "@bob@mastodon.example"
},
"display_name": {
"type": [
"string",
"null"
]
},
"actor_url": {
"type": "string"
},
"server": {
"type": "string",
"example": "mastodon.example"
},
"since": {
"type": "string",
"format": "date-time",
"description": "When they followed (or asked to)"
}
},
"additionalProperties": false
},
"Block": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"handle": {
"type": "string"
},
"display_name": {
"type": [
"string",
"null"
]
},
"actor_url": {
"type": "string"
},
"since": {
"type": "string",
"format": "date-time"
}
},
"additionalProperties": false
}
},
"responses": {
+8
View File
@@ -945,3 +945,11 @@ input {
.save-row {
align-items: center;
}
.follower-summary {
margin-top: 0.25rem;
}
.confirm-off .button-row {
margin-top: 0.75rem;
}
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Followers · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/followers.js"></script>
</head>
<body>
<header class="site-header" id="site-header"></header>
<main id="main">
<h1 class="page-title">Followers</h1>
<p class="lede">People on the fediverse who follow your listening. <a href="sharing.html">Sharing settings</a></p>
<div id="messages"></div>
<section aria-labelledby="requests-title" id="requests-section" hidden>
<h2 id="requests-title" class="section-head">Follow requests</h2>
<ul class="rows" id="requests"></ul>
</section>
<section aria-labelledby="followers-title">
<h2 id="followers-title" class="section-head">Followers</h2>
<ul class="rows" id="followers"></ul>
</section>
<section aria-labelledby="blocks-title" id="blocks-section" hidden>
<h2 id="blocks-title" class="section-head">Blocked</h2>
<ul class="rows" id="blocks"></ul>
</section>
</main>
</body>
</html>
+143
View File
@@ -0,0 +1,143 @@
import { api } from "./api.js";
import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js";
import { signedInPage } from "./layout.js";
const messages = document.getElementById("messages");
await signedInPage("sharing.html");
await refresh();
async function refresh() {
let followers, blocks;
try {
[followers, blocks] = await Promise.all([api("/federation/followers"), api("/federation/blocks")]);
} catch (error) {
replace(
messages,
error.status === 404
? h("p", { class: "notice" }, "This server doesn't share to the fediverse.")
: errorBox(error.message),
);
return;
}
const requests = followers.filter((f) => f.state === "pending");
const accepted = followers.filter((f) => f.state === "accepted");
document.getElementById("requests-section").hidden = requests.length === 0;
replace(document.getElementById("requests"), requests.map(requestRow));
replace(
document.getElementById("followers"),
accepted.length
? accepted.map(followerRow)
: h("li", { class: "empty" }, "No followers yet. People can follow you by searching for your handle."),
);
document.getElementById("blocks-section").hidden = blocks.length === 0;
replace(document.getElementById("blocks"), blocks.map(blockRow));
}
// Remote names and handles are shown as plain text only.
function who(person) {
return h(
"span",
{},
h("span", { class: "row-title" }, person.display_name || person.handle),
person.display_name ? h("span", { class: "muted" }, ` ${person.handle}`) : null,
);
}
async function act(path, done) {
try {
await api(path, { method: "POST" });
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, done));
} catch (error) {
replace(messages, errorBox(error.message));
}
await refresh();
}
function requestRow(follower) {
return h(
"li",
{},
h(
"div",
{ class: "row-head" },
who(follower),
h(
"div",
{ class: "confirm" },
h(
"button",
{ type: "button", class: "button", onclick: () => act(`/federation/followers/${follower.id}/approve`, `${follower.handle} now follows you.`) },
"Approve",
),
h(
"button",
{ type: "button", class: "button button-quiet", onclick: () => act(`/federation/followers/${follower.id}/decline`, `Declined ${follower.handle}.`) },
"Decline",
),
),
),
h("p", { class: "muted", title: formatDate(follower.since) }, `Asked ${timeAgo(follower.since)}`),
);
}
function followerRow(follower) {
const actions = h("div", { class: "confirm" });
const reset = () =>
replace(
actions,
h("button", { type: "button", class: "button button-quiet", onclick: askRemove }, "Remove"),
h("button", { type: "button", class: "button button-quiet", onclick: askBlock }, "Block"),
);
const confirm = (question, label, path, done) =>
replace(
actions,
h("span", { class: "muted" }, question),
h("button", { type: "button", class: "button button-danger", onclick: () => act(path, done) }, label),
h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"),
);
const askRemove = () =>
confirm(
"They can follow you again later.",
"Remove follower",
`/federation/followers/${follower.id}/remove`,
`Removed ${follower.handle}.`,
);
const askBlock = () =>
confirm(
"They're removed and can't follow you again.",
"Block",
`/federation/followers/${follower.id}/block`,
`Blocked ${follower.handle}.`,
);
reset();
return h(
"li",
{},
h("div", { class: "row-head" }, who(follower), actions),
h("p", { class: "muted", title: formatDate(follower.since) }, `Following since ${timeAgo(follower.since)}`),
);
}
function blockRow(block) {
const unblock = async () => {
try {
await api(`/federation/blocks/${block.id}`, { method: "DELETE" });
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Unblocked ${block.handle}.`));
} catch (error) {
replace(messages, errorBox(error.message));
}
await refresh();
};
return h(
"li",
{},
h(
"div",
{ class: "row-head" },
who(block),
h("button", { type: "button", class: "button button-quiet", onclick: unblock }, "Unblock"),
),
);
}
+51 -2
View File
@@ -1,5 +1,5 @@
import { api, describeError } from "./api.js";
import { errorBox, h, replace } from "./dom.js";
import { errorBox, h, num, replace } from "./dom.js";
import { signedInPage } from "./layout.js";
const form = document.getElementById("sharing");
@@ -40,6 +40,10 @@ function fill(values) {
}
}
document.getElementById("handle").textContent = values.handle;
const summary = document.getElementById("follower-summary");
const parts = [`${num(values.followers)} ${values.followers === 1 ? "follower" : "followers"}`];
if (values.pending_followers) parts.push(`${num(values.pending_followers)} waiting for approval`);
replace(summary, parts.join(", "), ". ", h("a", { href: "followers.html" }, "See followers"));
replace(
document.getElementById("profile-link"),
"Your public profile page: ",
@@ -52,8 +56,50 @@ function showHandle(on) {
handlePanel.hidden = !on;
}
// Turning sharing off removes every follower, so it's confirmed first.
function confirmTurningOff(followerCount) {
return new Promise((resolve) => {
const box = document.getElementById("confirm-off");
const done = (answer) => {
box.hidden = true;
resolve(answer);
};
replace(
box,
h(
"p",
{},
`Turning sharing off removes your ${num(followerCount)} ${followerCount === 1 ? "follower" : "followers"}. `,
"Each is told, and they'd have to follow you again if you turn it back on.",
),
h(
"div",
{ class: "button-row" },
h("button", { type: "button", class: "button button-danger", onclick: () => done(true) }, "Turn off sharing"),
h(
"button",
{
type: "button",
class: "button button-quiet",
onclick: () => {
form.elements.enabled.checked = true;
showHandle(true);
done(false);
},
},
"Keep sharing",
),
),
);
box.hidden = false;
box.scrollIntoView({ behavior: "smooth", block: "center" });
});
}
async function save(event) {
event.preventDefault();
const turningOff = settings.enabled && !form.elements.enabled.checked;
if (turningOff && settings.followers > 0 && !(await confirmTurningOff(settings.followers))) return;
const button = form.querySelector("button[type=submit]");
const changes = {
enabled: form.elements.enabled.checked,
@@ -70,8 +116,11 @@ async function save(event) {
replace(messages);
try {
const saved = await api("/federation/settings", { method: "PATCH", body: changes });
settings = saved;
fill(saved);
status.textContent = saved.enabled ? `Saved. You're sharing as ${saved.handle}.` : "Saved. Sharing is off.";
status.textContent = saved.enabled
? `Saved. You're sharing as ${saved.handle}.`
: "Saved. Sharing is off, and your followers have been told.";
} catch (error) {
status.textContent = "";
replace(messages, errorBox(describeError(error)));
+2 -1
View File
@@ -24,7 +24,7 @@
<p class="display-status">Your fediverse handle</p>
<p class="approve-app handle" id="handle"></p>
<p class="muted">People can follow you by searching for this in their app. It can't be changed once people follow you.</p>
<p class="notice">Following arrives in a coming update. Until then people can find your profile, and follows wait as requests.</p>
<p class="follower-summary" id="follower-summary"></p>
</div>
<fieldset class="choices">
@@ -74,6 +74,7 @@
<p class="muted" id="profile-link"></p>
</fieldset>
<div class="notice notice-error confirm-off" id="confirm-off" role="alertdialog" aria-live="assertive" hidden></div>
<div class="button-row save-row">
<button class="button" type="submit">Save sharing settings</button>
<span class="muted" id="save-status" role="status"></span>
+143 -2
View File
@@ -4,9 +4,15 @@ from flask import current_app, g
from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.extensions import db
from scrobbler.federation import followers as follower_state
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation import sharing
from scrobbler.federation.models import FederationBlock, FederationFollower
from scrobbler.federation.schemas import (
BlockSchema,
FollowerListArgsSchema,
FollowerSchema,
PublicProfileSchema,
SharingSettingsSchema,
SharingSettingsUpdateSchema,
@@ -33,10 +39,12 @@ def _identity(username: str) -> dict:
def _settings_body(user, settings) -> dict:
counts = follower_state.counts(user.id)
return {
**{field: getattr(settings, field) for field in sharing.EDITABLE},
**_identity(user.username),
"followers": 0,
"followers": counts["accepted"],
"pending_followers": counts["pending"],
}
@@ -60,7 +68,8 @@ def update_settings(changes):
"""Change your sharing settings
Turning sharing on makes you findable as your handle. Your handle can't change once
people follow you. Visibility changes apply to new posts only.
people follow you. Visibility changes apply to new posts only. Turning sharing off
removes all your followers (each is told).
"""
try:
settings, toggled = sharing.update(g.user.id, changes)
@@ -68,6 +77,10 @@ def update_settings(changes):
abort(422, code="invalid_settings", message=str(err))
if toggled is not None:
fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc()
if toggled is False:
# Tell every follower (a Reject each), then forget them
follower_state.reject_all(g.user.id, g.user.username)
db.session.commit()
return _settings_body(g.user, settings)
@@ -91,3 +104,131 @@ def public_profile(username):
"bio": settings.bio,
**{k: v for k, v in _identity(user.username).items() if k != "profile_url"},
}
# --- Followers ---------------------------------------------------------------------------
def _follower_body(follower: FederationFollower) -> dict:
actor = follower.actor
return {
"id": follower.id,
"state": follower.state,
"handle": actor.handle,
"display_name": actor.display_name,
"actor_url": actor.uri,
"server": actor.host,
"since": follower.created_at,
}
def _own_follower(follower_id: int) -> FederationFollower:
follower = db.session.get(FederationFollower, follower_id)
if follower is None or follower.user_id != g.user.id:
abort(404, code="not_found", message="No such follower")
return follower
@blp.route("/followers", methods=["GET"])
@authenticated(blp)
@blp.arguments(FollowerListArgsSchema, location="query")
@blp.response(200, FollowerSchema(many=True))
def list_followers(args):
"""Your followers and follow requests
Newest first. Filter with `state=pending` (requests) or `state=accepted`.
"""
query = db.select(FederationFollower).filter_by(user_id=g.user.id)
if args["state"]:
query = query.filter_by(state=args["state"])
followers = db.session.scalars(query.order_by(FederationFollower.created_at.desc())).all()
return [_follower_body(f) for f in followers]
@blp.route("/followers/<int:follower_id>/approve", methods=["POST"])
@authenticated(blp)
@blp.response(200, FollowerSchema)
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
@blp.alt_response(409, schema=ErrorSchema, description="Not a pending request")
def approve_follower(follower_id):
"""Approve a follow request"""
follower = _own_follower(follower_id)
if follower.state != "pending":
abort(409, code="not_pending", message="That follower isn't waiting for approval.")
follower_state.approve(g.user.username, follower)
db.session.commit()
return _follower_body(follower)
@blp.route("/followers/<int:follower_id>/decline", methods=["POST"])
@authenticated(blp)
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
def decline_follower(follower_id):
"""Decline a follow request"""
follower_state.remove(g.user.username, _own_follower(follower_id))
db.session.commit()
@blp.route("/followers/<int:follower_id>/remove", methods=["POST"])
@authenticated(blp)
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
def remove_follower(follower_id):
"""Remove a follower
They stop receiving your posts. They can follow you again; block them to prevent it.
"""
follower_state.remove(g.user.username, _own_follower(follower_id))
db.session.commit()
@blp.route("/followers/<int:follower_id>/block", methods=["POST"])
@authenticated(blp)
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
def block_follower(follower_id):
"""Block a follower
Removes them and refuses their future follows.
"""
follower_state.block(g.user.username, _own_follower(follower_id))
db.session.commit()
@blp.route("/blocks", methods=["GET"])
@authenticated(blp)
@blp.response(200, BlockSchema(many=True))
def list_blocks():
"""Accounts you've blocked"""
blocks = db.session.scalars(
db.select(FederationBlock)
.filter_by(user_id=g.user.id)
.order_by(FederationBlock.created_at.desc())
).all()
return [
{
"id": b.id,
"handle": b.actor.handle,
"display_name": b.actor.display_name,
"actor_url": b.actor.uri,
"since": b.created_at,
}
for b in blocks
]
@blp.route("/blocks/<int:block_id>", methods=["DELETE"])
@authenticated(blp)
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="No such block")
def unblock(block_id):
"""Unblock an account
They can follow you again (they aren't re-added).
"""
block = db.session.get(FederationBlock, block_id)
if block is None or block.user_id != g.user.id:
abort(404, code="not_found", message="No such block")
db.session.delete(block)
db.session.commit()
+25 -2
View File
@@ -23,8 +23,9 @@ class SharingSettingsSchema(Schema):
handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String(dump_only=True)
profile_url = fields.String(dump_only=True)
followers = fields.Integer(
dump_only=True, metadata={"description": "0 until following arrives"}
followers = fields.Integer(dump_only=True, metadata={"description": "Accepted followers"})
pending_followers = fields.Integer(
dump_only=True, metadata={"description": "Waiting for approval"}
)
@@ -38,3 +39,25 @@ class PublicProfileSchema(Schema):
class SharingSettingsUpdateSchema(SharingSettingsSchema):
"""Any subset of the editable settings (read-only fields are rejected)."""
class FollowerSchema(Schema):
id = fields.Integer()
state = fields.String(validate=validate.OneOf(["pending", "accepted"]))
handle = fields.String(metadata={"example": "@bob@mastodon.example"})
display_name = fields.String(allow_none=True)
actor_url = fields.String()
server = fields.String(metadata={"example": "mastodon.example"})
since = fields.DateTime(metadata={"description": "When they followed (or asked to)"})
class FollowerListArgsSchema(Schema):
state = fields.String(load_default=None, validate=validate.OneOf(["pending", "accepted"]))
class BlockSchema(Schema):
id = fields.Integer()
handle = fields.String()
display_name = fields.String(allow_none=True)
actor_url = fields.String()
since = fields.DateTime()
+21
View File
@@ -67,3 +67,24 @@ def sharing_count() -> int:
return db.session.scalar(
db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True)
)
def farewell_user(username: str):
"""A user who has stopped sharing but still has messages on their way out (the
Rejects telling followers). Their actor stays fetchable, minimally, so other servers
can verify those messages. None otherwise."""
from scrobbler.federation.models import FederationActivity, FederationDelivery
user = accounts.find_user(username)
if user is None:
return None
settings = db.session.get(FederationSettings, user.id)
if settings is None or settings.enabled:
return None
pending = db.session.scalar(
db.select(db.func.count())
.select_from(FederationDelivery)
.join(FederationActivity, FederationActivity.id == FederationDelivery.activity_id)
.filter(FederationActivity.user_id == user.id, FederationDelivery.status == "pending")
)
return user if pending else None
+24 -7
View File
@@ -7,6 +7,7 @@ import json
from flask import Blueprint, Response, current_app, redirect, request
from scrobbler.extensions import db
from scrobbler.federation import followers as follower_state
from scrobbler.federation import inbox, keys, sharing
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationActivity
@@ -110,7 +111,23 @@ def actor(username: str):
return redirect(_profile_page(username), code=302)
found = sharing.shared_user(username)
if found is None:
return _not_found("actor")
leaving = sharing.farewell_user(username)
if leaving is None:
return _not_found("actor")
# Stopped sharing, but Rejects are still on their way: just enough for other
# servers to verify them. No name, bio or other profile details.
_found("actor")
doc = vocab.person(
_urls(leaving.username),
username=leaving.username,
name=leaving.username,
summary=None,
public_key_pem=keys.key_for(leaving.id).public_key_pem,
manually_approves_followers=True,
discoverable=False,
indexable=False,
)
return _json(doc, cache=0)
user, settings = found
_found("actor")
urls = _urls(user.username)
@@ -120,9 +137,7 @@ def actor(username: str):
name=settings.display_name or user.username,
summary=settings.bio,
public_key_pem=keys.key_for(user.id).public_key_pem,
# Phase 1 can't accept follows yet: advertise approval so follows show as
# requests rather than failing silently.
manually_approves_followers=True,
manually_approves_followers=settings.manually_approves_followers,
discoverable=settings.discoverable,
indexable=settings.indexable,
published=settings.created_at.isoformat().replace("+00:00", "Z"),
@@ -130,12 +145,12 @@ def actor(username: str):
return _json(doc)
def _collection(username: str, which: str, items: list | None):
def _collection(username: str, which: str, items: list | None, total: int = 0):
found = sharing.shared_user(username)
if found is None:
return _not_found("actor")
urls = _urls(found[0].username)
return _json(vocab.ordered_collection(getattr(urls, which), 0, items))
return _json(vocab.ordered_collection(getattr(urls, which), total, items))
@bp.get("/users/<username>/outbox")
@@ -145,7 +160,9 @@ def outbox(username: str):
@bp.get("/users/<username>/followers")
def followers(username: str):
return _collection(username, "followers", None) # count only
found = sharing.shared_user(username)
total = follower_state.counts(found[0].id)["accepted"] if found else 0
return _collection(username, "followers", None, total) # the count, not who
@bp.get("/users/<username>/following")
+172
View File
@@ -0,0 +1,172 @@
"""Managing followers: the /api/v1/federation followers and blocks endpoints."""
import pytest
from federation_helpers import RemoteAccount
from scrobbler import worker
from scrobbler.extensions import db
from scrobbler.federation import inbox, sharing
from scrobbler.federation.models import FederationActivity, FederationDelivery, FederationFollower
AP = {"Accept": "application/activity+json"}
@pytest.fixture
def auth_headers(sharing_user):
from scrobbler.services.accounts import issue_ui_token
return {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"}
@pytest.fixture
def accounts(sharing_user, remote):
"""Two remote accounts whose inboxes accept everything."""
made = {}
for name in ("bob", "carol"):
account = RemoteAccount(remote, name)
remote.routes[f"/users/{name}/inbox"] = (202, {}, b"")
made[name] = account
return made
def follow(fed_client, account):
account.deliver(fed_client, account.follow())
while inbox.work_once():
pass
db.session.expire_all()
def sent_types():
return [
a.activity_type
for a in db.session.scalars(
db.select(FederationActivity).order_by(FederationActivity.created_at)
)
]
def api(fed_client, method, path, headers, **kwargs):
return getattr(fed_client, method)(f"/api/v1/federation{path}", headers=headers, **kwargs)
def test_followers_are_listed(fed_client, auth_headers, accounts):
follow(fed_client, accounts["bob"])
[bob] = api(fed_client, "get", "/followers", auth_headers).get_json()
assert (bob["handle"], bob["state"], bob["display_name"]) == (
"@bob@127.0.0.1",
"accepted",
"Bob",
)
assert bob["actor_url"] == accounts["bob"].uri
settings = api(fed_client, "get", "/settings", auth_headers).get_json()
assert (settings["followers"], settings["pending_followers"]) == (1, 0)
def test_requests_can_be_approved(fed_client, auth_headers, accounts, sharing_user):
sharing.update(sharing_user.id, {"manually_approves_followers": True})
follow(fed_client, accounts["bob"])
follow(fed_client, accounts["carol"])
pending = api(fed_client, "get", "/followers?state=pending", auth_headers).get_json()
assert {p["handle"] for p in pending} == {"@bob@127.0.0.1", "@carol@127.0.0.1"}
assert sent_types() == []
bob_id = next(p["id"] for p in pending if p["handle"].startswith("@bob"))
approved = api(fed_client, "post", f"/followers/{bob_id}/approve", auth_headers)
assert approved.get_json()["state"] == "accepted"
assert sent_types() == ["Accept"]
# Approving twice is a conflict, not a second Accept
assert api(fed_client, "post", f"/followers/{bob_id}/approve", auth_headers).status_code == 409
def test_decline_and_remove_send_reject(fed_client, auth_headers, accounts, sharing_user):
sharing.update(sharing_user.id, {"manually_approves_followers": True})
follow(fed_client, accounts["bob"])
[request] = api(fed_client, "get", "/followers", auth_headers).get_json()
assert (
api(fed_client, "post", f"/followers/{request['id']}/decline", auth_headers).status_code
== 204
)
assert sent_types() == ["Reject"]
assert api(fed_client, "get", "/followers", auth_headers).get_json() == []
sharing.update(sharing_user.id, {"manually_approves_followers": False})
follow(fed_client, accounts["carol"])
[carol] = api(fed_client, "get", "/followers", auth_headers).get_json()
assert (
api(fed_client, "post", f"/followers/{carol['id']}/remove", auth_headers).status_code == 204
)
assert sent_types() == ["Reject", "Accept", "Reject"]
def test_block_and_unblock(fed_client, auth_headers, accounts):
follow(fed_client, accounts["bob"])
[bob] = api(fed_client, "get", "/followers", auth_headers).get_json()
assert api(fed_client, "post", f"/followers/{bob['id']}/block", auth_headers).status_code == 204
assert sent_types()[-1] == "Block"
[block] = api(fed_client, "get", "/blocks", auth_headers).get_json()
assert block["handle"] == "@bob@127.0.0.1"
follow(fed_client, accounts["bob"]) # tries again: refused
assert api(fed_client, "get", "/followers", auth_headers).get_json() == []
assert sent_types()[-1] == "Reject"
assert api(fed_client, "delete", f"/blocks/{block['id']}", auth_headers).status_code == 204
follow(fed_client, accounts["bob"]) # now allowed
assert len(api(fed_client, "get", "/followers", auth_headers).get_json()) == 1
def test_other_users_followers_are_off_limits(
fed_client, auth_headers, accounts, make_user, fed_app
):
from scrobbler.services.accounts import issue_ui_token
follow(fed_client, accounts["bob"])
[bob] = api(fed_client, "get", "/followers", auth_headers).get_json()
other = make_user(username="mallory")
mallory = {"Authorization": f"Bearer {issue_ui_token(other)}"}
for action in ("approve", "decline", "remove", "block"):
assert (
api(fed_client, "post", f"/followers/{bob['id']}/{action}", mallory).status_code == 404
)
assert api(fed_client, "get", "/followers", mallory).get_json() == []
def test_turning_sharing_off_rejects_everyone(fed_client, auth_headers, accounts, remote):
follow(fed_client, accounts["bob"])
follow(fed_client, accounts["carol"])
while worker.run_once(): # send the Accepts
pass
api(fed_client, "patch", "/settings", auth_headers, json={"enabled": False})
db.session.expire_all()
assert db.session.scalars(db.select(FederationFollower)).all() == []
assert sent_types().count("Reject") == 2
# While the Rejects are on their way, other servers can still fetch the key to verify
# them, but nothing else about the profile.
actor = fed_client.get("/users/alice", headers=AP).get_json()
assert actor["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----")
assert (actor["name"], actor["summary"]) == ("alice", "")
assert (
fed_client.get("/.well-known/webfinger?resource=acct:alice@scrobble.test").status_code
== 404
)
while worker.run_once(): # deliver the Rejects
pass
db.session.expire_all()
assert {d.status for d in db.session.scalars(db.select(FederationDelivery))} == {"delivered"}
assert fed_client.get("/users/alice", headers=AP).status_code == 404
def test_actor_reflects_approval_setting_and_follower_count(fed_client, accounts, sharing_user):
assert (
fed_client.get("/users/alice", headers=AP).get_json()["manuallyApprovesFollowers"] is False
)
sharing.update(sharing_user.id, {"manually_approves_followers": True})
assert (
fed_client.get("/users/alice", headers=AP).get_json()["manuallyApprovesFollowers"] is True
)
sharing.update(sharing_user.id, {"manually_approves_followers": False})
follow(fed_client, accounts["bob"])
assert fed_client.get("/users/alice/followers", headers=AP).get_json()["totalItems"] == 1
+1 -1
View File
@@ -60,7 +60,7 @@ def test_actor_document(fed_client, sharing_user):
assert doc["summary"] == "<p>Listening.</p>"
assert doc["publicKey"]["id"] == f"{BASE}/users/alice#main-key"
assert doc["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----")
assert doc["manuallyApprovesFollowers"] is True # follows are requests until phase 2
assert doc["manuallyApprovesFollowers"] is False # the user's setting (off by default)
assert (doc["discoverable"], doc["indexable"]) == (False, False)
assert doc["url"] == "http://localhost:8080/profile.html?u=alice"