~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Groups moderate what is theirs: reports, labels, and the queue between

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/moderation
crates/group-host/src/lib.rs+25−0
@@ -27,6 +27,7 @@ pub mod identity;
pub mod index;
pub mod index_api;
pub mod lifecycle;
pub mod moderation;
pub mod oauth;
pub mod oauth_clients;
pub mod oauth_dpop;
@@ -356,6 +357,30 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.getActorGroups",
get(actors::get_actor_groups),
)
.route(
"/xrpc/fyi.opensocial.applyLabel",
post(moderation::apply_label),
)
.route(
"/xrpc/fyi.opensocial.negateLabel",
post(moderation::negate_label),
)
.route(
"/xrpc/fyi.opensocial.listSubjects",
get(moderation::list_subjects),
)
.route(
"/xrpc/fyi.opensocial.getSubjectHistory",
get(moderation::get_subject_history),
)
.route(
"/xrpc/fyi.opensocial.resolveSubject",
post(moderation::resolve_subject),
)
.route(
"/xrpc/com.atproto.moderation.createReport",
post(moderation::create_report),
)
.route("/oauth/authorize", get(oauth::authorize))
.route(
"/console/client-metadata.json",
crates/group-host/src/moderation.rsnew+498−0
498 lines changed: not loaded until asked for.
crates/group-host/src/store.rs+26−0
@@ -294,6 +294,30 @@ pub const MIGRATIONS: &[&str] = &[
did TEXT PRIMARY KEY,
at INTEGER NOT NULL
);
",
"
CREATE TABLE mod_subject (
grp TEXT NOT NULL REFERENCES account (did),
subject TEXT NOT NULL,
status TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (grp, subject)
);
CREATE INDEX mod_subject_updated ON mod_subject (grp, updated_at);
CREATE TABLE mod_event (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
grp TEXT NOT NULL REFERENCES account (did),
subject TEXT NOT NULL,
kind TEXT NOT NULL,
actor TEXT,
reason_type TEXT,
reason TEXT,
val TEXT,
note TEXT,
created_at INTEGER NOT NULL
);
CREATE INDEX mod_event_subject ON mod_event (grp, subject, seq);
",
];
@@ -412,6 +436,8 @@ const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1";
/// What goes with an account, in an order its references allow.
const FORGET_ACCOUNT: &[&str] = &[
"DELETE FROM mod_event WHERE grp = ?1",
"DELETE FROM mod_subject WHERE grp = ?1",
"DELETE FROM app_password WHERE grp = ?1",
"DELETE FROM group_activity WHERE grp = ?1",
"DELETE FROM oauth_token WHERE grp = ?1",
crates/group-host/tests/moderation.rsnew+486−0
486 lines changed: not loaded until asked for.
crates/group-host/tests/serve.rs+2−2
@@ -50,8 +50,8 @@ async fn answers_health_and_refuses_unknown_methods() {
assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
for req in [
http.get(format!("{}/xrpc/fyi.opensocial.listSubjects", host.1)),
http.post(format!("{}/xrpc/fyi.opensocial.applyLabel", host.1)),
http.get(format!("{}/xrpc/fyi.opensocial.noSuchQuery", host.1)),
http.post(format!("{}/xrpc/fyi.opensocial.noSuchProcedure", host.1)),
] {
let res = req.send().await.unwrap();
assert_eq!(res.status(), 501);
docs/design/moderation.mdnew+51−0
@@ -0,0 +1,51 @@
# Moderation
A group moderates what is in its spaces, and who is in it, itself: reports
come in, labels go out, and a queue sits between (`moderation.rs`).
## Labels
A label is a record the group writes, `fyi.opensocial.label`, naming its
subject, its value, and the rule it is under if one. It lives beside what
it labels: a label on a record goes in the space the record is in, so
whoever may read the record may read its labels, and nobody else; a label
on an account has no content to sit beside, and goes in the members
space. A group labels only what is in its own spaces: another group's
content is that group's to moderate.
`applyLabel` writes one, for a role holding `label`; the values that
remove content, `!hide` and `!takedown`, take `takedown`. `negateLabel`
takes one back with a second record, `neg: true`, rather than deleting
the first: that a label was applied is part of what happened.
## The queue
Each subject (a record, by its URI; an account, by its DID) is open,
escalated or resolved, with what happened to it in order: reports,
labels, negations, notes, and the moderators' decisions. The queue is the
host's to keep, not the group's to publish: its statuses are a group's
moderators' working state.
- `listSubjects` (for `mod.read`): the queue, of a status if asked, the
latest changed first, a page at a time.
- `getSubjectHistory` (for `mod.read`): one subject, and what happened to
it.
- `resolveSubject` (for `mod.resolve`): resolve it, escalate it, or note
something on it, which changes nothing else.
A label opens a subject nobody reported, and leaves a resolved one
resolved: labelling is the moderators acting, not someone asking them to.
## Reports
`com.atproto.moderation.createReport` takes a report from anyone, member
or not, as their PDS sends it on: of a record in one of a group's spaces
here, into that group's queue. A report on a resolved subject opens it
again.
## From the prototype
- The host's own queue, for what its sites module shared with everyone
(templates, their likes), is not here, with the sites module.
- A report is of a record; an account is labelled by the group, not
reported to it, as the prototype had it.
docs/design/README.md+3−2
@@ -119,8 +119,9 @@ says otherwise.
passwords; done): the console's pages in
`apps/web/src/pages`. Each is used end to end in `harness/e2e`.
8. **Moderation, recovery and moving.** Reports, labels, subjects and
history; recovery keys; importing an account; migrating a group to
another host and moving the host itself:
history, and the console's moderation page (`moderation.rs`; done, see
[moderation](moderation.md)); then recovery keys; importing an
account; migrating a group to another host and moving the host itself:
`methods/{moderation,recovery,importAccount,migration}.ts`,
`hostLabels.ts`, `scripts/move-host.ts`.
9. **MCP and the command.** The MCP tools over what steps 4 to 8 brought,
harness/e2e/flows.spec.mjs+20−0
@@ -157,6 +157,26 @@ test('making an app password, and ending what it signed in', async () => {
expect((await signIn()).status).toBe(401)
})
test('moderating: a label, and the queue', async () => {
await page.goto(url('/g/hikers.groups.test'))
await page.getByRole('link', { name: 'Moderation' }).click()
await expect(page.getByText('Nothing to look at')).toBeVisible()
await page.getByRole('textbox', { name: 'Their handle' }).fill('bob.test')
await page.getByRole('textbox', { name: 'Label' }).fill('troll')
await page.getByRole('button', { name: 'Label them' }).click()
const subject = page.locator('.subject', { hasText: who.bob.did })
await expect(subject.locator('.status')).toHaveText('open')
await expect(subject.locator('.events')).toContainText('label: troll')
await subject.getByRole('button', { name: 'Escalate' }).click()
await expect(page.locator('.subject', { hasText: who.bob.did }).locator('.status')).toHaveText('escalated')
await page.locator('.subject', { hasText: who.bob.did }).getByRole('textbox', { name: 'Note' }).fill('Asked him to stop')
await page.locator('.subject', { hasText: who.bob.did }).getByRole('button', { name: 'Add the note' }).click()
await expect(page.locator('.subject', { hasText: who.bob.did }).locator('.events')).toContainText('note: Asked him to stop')
await page.locator('.subject', { hasText: who.bob.did }).getByRole('button', { name: 'Resolve' }).click()
await page.goto(url('/g/hikers.groups.test/moderation?status=resolved'))
await expect(page.locator('.subject', { hasText: who.bob.did }).locator('.status')).toHaveText('resolved')
})
test('signing an app in as her group', async () => {
const app = await new App('atproto repo:app.bsky.feed.post').listen()
await page.goto(await app.push())
web/src/lib/organisms/LabelForm.sveltenew+9−0
@@ -0,0 +1,9 @@
<script lang="ts">
/** Labelling someone, by their handle, as the group: a value, and the rule it is under. */
</script>
<form class="stack" method="post" action="?/label">
<label class="field">Their handle <input name="handle" required /></label>
<label class="field">Label <input name="val" required maxlength="128" placeholder="spam" /></label>
<button type="submit">Label them</button>
</form>
web/src/lib/organisms/ModerationQueue.sveltenew+40−0
@@ -0,0 +1,40 @@
<script lang="ts">
import Empty from '#lib/molecules/Empty.svelte';
type Event = { kind: string; actor?: string; reason?: string; val?: string; note?: string; createdAt: string };
type Subject = { subject: string; status: string; reportCount?: number; events: Event[] };
/**
* A group's moderation queue: each subject, where it stands, what
* happened to it; for one who may, resolved, escalated, or noted on.
*/
let { subjects, canResolve }: { subjects: Subject[]; canResolve: boolean } = $props();
const said = (e: Event) => [e.val, e.reason, e.note].filter(Boolean).join(': ');
</script>
{#if subjects.length}
<ul class="queue">
{#each subjects as s (s.subject)}
<li class="stack subject">
<span class="mono">{s.subject}</span>
<span class="status">{s.status}</span>{#if s.reportCount}<span class="mute"> · reported {s.reportCount} times</span>{/if}
<ol class="events">
{#each s.events as e, i (i)}<li><span class="mute">{e.createdAt}</span> {e.kind}{said(e) ? `: ${said(e)}` : ''}</li>{/each}
</ol>
{#if canResolve}
<form method="post" action="?/resolve">
<input type="hidden" name="subject" value={s.subject} />
<button type="submit" name="action" value="resolve">Resolve</button>
<button type="submit" name="action" value="escalate">Escalate</button>
</form>
<form method="post" action="?/resolve">
<input type="hidden" name="subject" value={s.subject} />
<input type="hidden" name="action" value="note" />
<label>Note <input name="note" required maxlength="1000" /></label>
<button type="submit">Add the note</button>
</form>
{/if}
</li>
{/each}
</ul>
{:else}
<Empty title="Nothing to look at">Reports and labels show here.</Empty>
{/if}
web/src/routes/g/[handle]/moderation/+page.server.tsnew+55−0
@@ -0,0 +1,55 @@
import type * as resolveHandle from '#lib/lexicons/com/atproto/identity/resolveHandle.ts';
import type * as getGroup from '#lib/lexicons/fyi/opensocial/getGroup.ts';
import type * as getSubjectHistory from '#lib/lexicons/fyi/opensocial/getSubjectHistory.ts';
import type * as listSubjects from '#lib/lexicons/fyi/opensocial/listSubjects.ts';
import type { Actions, PageServerLoad } from './$types';
import { fail } from '@sveltejs/kit';
import { act, xrpc } from '#lib/data.ts';
type Handle = `${string}.${string}`;
type Event = { fetch: typeof fetch; params: { handle?: string } };
async function groupOf(event: Event) {
const handle = (event.params.handle ?? '') as Handle;
return (await xrpc<typeof resolveHandle.main>(event, 'com.atproto.identity.resolveHandle', { handle })).did;
}
/** A group's queue, by status, each subject with its history, for one who may read it. */
export const load: PageServerLoad = async (event) => {
const group = await groupOf(event);
const { group: view } = await xrpc<typeof getGroup.main>(event, 'fyi.opensocial.getGroup', { group });
const actions = view.viewer?.actions ?? [];
if (!actions.includes('mod.read')) return { group: view, actions, subjects: null };
const status = event.url.searchParams.get('status') ?? undefined;
const { subjects } = await xrpc<typeof listSubjects.main>(event, 'fyi.opensocial.listSubjects', { group, ...(status ? { status } : {}) });
const withEvents = await Promise.all(
subjects.map(async (s) => {
const { events } = await xrpc<typeof getSubjectHistory.main>(event, 'fyi.opensocial.getSubjectHistory', { group, subject: s.subject });
return { ...s, events };
})
);
return { group: view, actions, subjects: withEvents };
};
export const actions: Actions = {
resolve: async (event) => {
const group = await groupOf(event);
const form = await event.request.formData();
const note = String(form.get('note') ?? '').trim();
return act(event, 'fyi.opensocial.resolveSubject', {
group,
subject: String(form.get('subject')),
action: String(form.get('action')),
...(note ? { note } : {})
});
},
label: async (event) => {
const group = await groupOf(event);
const form = await event.request.formData();
const handle = String(form.get('handle') ?? '').trim().replace(/^@/, '').toLowerCase();
const found = await event.fetch(`/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`);
if (!found.ok) return fail(400, { failed: `We cannot find ${handle}.` });
const { did } = await found.json();
return act(event, 'fyi.opensocial.applyLabel', { group, subject: { did }, val: String(form.get('val') ?? '').trim() });
}
};
web/src/routes/g/[handle]/moderation/+page.sveltenew+27−0
@@ -0,0 +1,27 @@
<script lang="ts">
import LabelForm from '#lib/organisms/LabelForm.svelte';
import ModerationQueue from '#lib/organisms/ModerationQueue.svelte';
import Page from '#lib/templates/Page.svelte';
let { data, form } = $props();
const g = $derived(data.group);
</script>
<svelte:head><title>Moderation · {g.displayName ?? g.handle} · opensocial</title></svelte:head>
<Page title={`${g.displayName ?? g.handle}: moderation`}>
<p><a href={`/g/${g.handle}`}>Back to the group</a></p>
{#if form?.failed}<p class="danger">{form.failed}</p>{/if}
{#if data.subjects}
<p>
<a href="?">Everything</a> · <a href="?status=open">Open</a> · <a href="?status=escalated">Escalated</a> ·
<a href="?status=resolved">Resolved</a>
</p>
<ModerationQueue subjects={data.subjects} canResolve={data.actions.includes('mod.resolve')} />
{:else}
<p>Nothing here is yours to see.</p>
{/if}
{#if data.actions.includes('label')}
<h2>Label someone</h2>
<LabelForm />
{/if}
</Page>
web/src/routes/g/[handle]/+page.svelte+5−1