SDK guide
Communities, roles and moderation
Read and change a community, join and leave it, manage channels, invites, roles and overwrites, compute permissions locally, moderate, ban, handle reports and the audit log, and upgrade a channel or server to secure.
Specification: 01 Addresses, display names and links, 09 Communities, membership, channels and security transitions, 10 Roles, permissions, moderation and reports, 13 MLS profile
Every Sloppy Voice server is exactly one community, named by its canonical domain (09 §3.1). So there is no community ID in the SDK: you get the ServerClient for the community's server and use its resource APIs. Each of them talks to that one server.
| Property | API | What it covers |
|---|---|---|
community |
CommunityApi | The Community object, settings, icon, joining, leaving, members, categories and layout, the server upgrade |
myCommunities |
MyCommunitiesApi | The account's community list (home server only) |
channels |
ChannelsApi | Channels, channel membership, the channel upgrade |
invites |
InvitesApi | Creating, listing, previewing and revoking invites |
roles |
RolesApi | Roles, role grants and channel overwrites |
moderation |
ModerationApi | Message deletion, kicks, timeouts, server mutes, the anti-spam policy |
bans |
BansApi | Bans by address or domain |
reports |
ReportsApi | Filing reports and working the queue |
auditLog |
AuditLogApi | The audit log |
sv.server(domain) gives the client for a community's server, and sv.serverFor(address) the client for the server hosting a channel or account address. For a server other than your home server the SDK creates a remote session the first time a request needs one (federation). The protocol side of this page is in Communities and channels and Roles, permissions and moderation.
Community info
CommunityApi.get returns the public Community object. It needs no authentication, so the SDK sends it without a credential unless you pass { auth: 'session' }. The name is free text that any server can choose, so always show the domain next to it wherever someone decides whether to join, and in the community header (09 §3.7).
import { SloppyVoiceClient, botToken, effectiveJoinPolicy } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'community-tool/1.0',
home: 'sloppyvoice.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
const server = await sv.server('sloppyvoice.com')
const community = await server.community.get()
console.log(`${community.name} (${community.domain}), ${community.memberCount} members`)
// An unknown joinPolicy is treated as "invite" (09 §3.2).
console.log('Join policy:', effectiveJoinPolicy(community.joinPolicy))
console.log('Secure:', community.secure)
if (community.icon) {
// Fetches icon.url without the session and checks icon.sha256, as clients MUST (09 §3.4).
const icon = await server.community.fetchIcon(community.icon)
console.log(icon.mediaType, icon.bytes.length)
}CommunityApi.update changes settings and needs manage_community (09 §3.6). Name only the members you change. Pass ifVersion so you don't overwrite someone else's change: a stale version fails with 409 community.version_conflict, and its data.current holds the current Community. The upgrade members (secure, dryRun, planVersion, confirmDomain, deletePreUpgradeHistory) are refused with sdk.invalid_argument; they belong to the upgrade. setIcon and deleteIcon replace and remove the icon.
import { isSloppyVoiceError, type Community, type CommunityVersionConflictData, type ServerClient } from '@sloppyvoice/sdk'
export async function setRules(server: ServerClient, seen: Community, rulesText: string): Promise<Community> {
try {
// Changing rulesText increases rulesVersion by 1 (09 §3.6).
return await server.community.update({ rulesText, requireRulesAcceptance: true, ifVersion: seen.version })
} catch (e) {
if (isSloppyVoiceError(e, 'community.version_conflict')) {
const { current } = e.data as unknown as CommunityVersionConflictData
// Someone changed the settings since `seen`: show `current` and let the person decide again.
console.log('Changed by someone else; now at version', current.version)
}
throw e
}
}Joining and leaving
CommunityApi.join calls POST /v1/community/join (09 §4.3) with an optional invite code (any input form; the SDK normalizes it) and the rulesVersion the person accepted. The result is the response body plus status: 200 when the account is a member (active or needs_encryption), 202 when it is waiting for approval (pending). Joining is idempotent, and an existing member can record a rules acceptance the same way.
Two things are your client's job:
- When
requireRulesAcceptanceis on, a join without the currentrulesVersionfails withcommunity.rules_acceptance_required, whosedatacarriesrulesVersionandrulesText. Show the rules with one button, "Agree and join", and send the join again withacceptRules(09 §4.3). - After a 200 or 202, the client MUST add the community to the account's community list at the home server (09 §5.1). communityListEntryFromJoin builds the entry from the join response. The home server keeps the entry for its own community itself, and refuses a
PUTfor it.
import {
communityListEntryFromJoin,
isSloppyVoiceError,
type JoinCommunityResult,
type RulesAcceptanceRequiredData,
type SloppyVoiceClient,
} from '@sloppyvoice/sdk'
/** Join the community at `domain`. Resolves null if the person declines the rules. */
export async function joinCommunity(
sv: SloppyVoiceClient,
domain: string,
invite: string | undefined,
agreeToRules: (rulesText: string) => Promise<boolean>,
): Promise<JoinCommunityResult | null> {
const server = await sv.server(domain)
let acceptRules: number | undefined
for (;;) {
try {
const result = await server.community.join({ invite, acceptRules })
if (!server.isHome) {
const home = await sv.home()
await home.myCommunities.put(server.domain, communityListEntryFromJoin(result))
}
if (result.status === 202) console.log('Waiting for approval')
return result
} catch (e) {
if (!isSloppyVoiceError(e, 'community.rules_acceptance_required')) throw e
const { rulesVersion, rulesText } = e.data as unknown as RulesAcceptanceRequiredData
if (!(await agreeToRules(rulesText))) return null
acceptRules = rulesVersion
}
}
}A refused join is a SloppyVoiceError with one of the gate codes of 09 §9.2. Each has one fixed client reaction (09 §9.5), listed under How a client reacts; community.closed, community.invite_required and the invite.* codes get one plain sentence and no retry. An invite is consumed only when the join makes the account active: a refused join, a pending request and a join by an existing member consume nothing (09 §8.5). Where the policy doesn't need an invite (open, or a local account while localAccountsAreMembers is on), an invalid one is reported in inviteIgnored instead of failing the join (09 §9.2 step C8).
CommunityApi.leave leaves the community, or withdraws a pending request. It works even for an account in upgrade_required. Afterwards, and whenever member.removed or member.rejected ends the membership, the client MUST remove the entry with home.myCommunities.remove(domain) (09 §5.1). As with joining, skip this for the home server's own community, whose entry the home server keeps itself.
Members
CommunityApi.listMembers pages through CommunityMember records ordered by address; iterate it with for await, or call page() for one page. Only members may list (09 §4.7). The default states are active and needs_encryption; listing pending needs manage_invites, banned needs ban_members and left needs view_audit_log. q (1 to 64 characters) matches a prefix of the local part or of any word of the display name.
import { effectiveCommunityMemberState, type ServerClient } from '@sloppyvoice/sdk'
export async function reviewRequests(server: ServerClient, approveIf: (addr: string) => boolean) {
for await (const m of server.community.listMembers({ state: ['pending'] })) {
// Approving a bot also needs manage_bots (09 §4.4).
if (approveIf(m.addr)) await server.community.approve(m.addr)
else await server.community.reject(m.addr)
}
const bob = await server.community.getMember('bob@a.com')
// An unknown state is treated as "left" (09 §4.1).
console.log(bob.name, effectiveCommunityMemberState(bob.state), bob.roles)
for await (const m of server.community.listMembers({ q: 'car' })) console.log(m.addr, m.name)
}accountSecurity is present only in answers to the member itself and to holders of manage_channels or manage_community. Clients MUST NOT display another member's value in channel or community UI (09 §18 item 9).
Channels
ChannelsApi.list returns every channel the caller can view, with the categories, in one response that is never paged (09 §6.6). For someone who isn't a member yet it holds the channels that are visible in previews. sortChannelsForDisplay applies the normative display order of 09 §6.5: uncategorized channels first, then each category, everything by position with ties broken by ctx.
import { channelSecurityStatus, effectiveChannelKind, sortChannelsForDisplay, type Channel, type ServerClient } from '@sloppyvoice/sdk'
export async function printSidebar(server: ServerClient) {
const { items, categories } = await server.channels.list()
const order = sortChannelsForDisplay(items, categories)
// Unknown kinds are text with no call; an unknown security value means "can't use here" (09 §6.1).
const line = (c: Channel) => `${c.name} [${effectiveChannelKind(c.kind)}, ${channelSecurityStatus(c.security)}]`
for (const c of order.uncategorized) console.log(line(c))
for (const group of order.categories) {
console.log(group.category.name)
for (const c of group.channels) console.log(' ' + line(c))
}
}Channel membership is explicit but silent: call ChannelsApi.join the first time the person opens a channel's timeline or joins its call, with no prompt (09 §4.5). It is idempotent, and so is leave. Channel methods take a channel ID as a UUIDv7 or a ch: reference.
Creating, changing and deleting channels needs manage_channels (09 §6.4). ChannelsApi.create always sends an Idempotency-Key and reuses it on its own retries, so a lost response doesn't create a second channel; to retry in a later call, pass your own idempotencyKey. The server derives the channel's address from its name, and an unavailable name fails with the matching address.* error (09 §6.3). kind can't change after creation, and the SDK refuses a patch that names it. Categories and the one-step layout change are on server.community.
import type { ServerClient } from '@sloppyvoice/sdk'
export async function bookClub(server: ServerClient) {
const clubs = await server.community.createCategory({ name: 'Clubs' })
const channel = await server.channels.create({
name: 'Book Club',
kind: 'text',
topic: 'One chapter a week',
categoryId: clubs.id,
})
console.log(channel.address, channel.security) // the server's mode unless you set `security`
const updated = await server.channels.update(channel.ctx, { topic: 'Two chapters a week', ifVersion: channel.version })
for await (const m of server.channels.listMembers(updated.ctx)) console.log(m.addr, m.state)
// Ends the call, retires the group and keeps a tombstone for at least 400 days (09 §6.4).
await server.channels.delete(updated.ctx)
await server.community.deleteCategory(clubs.id)
}CommunityApi.updateLayout replaces the order of every category and channel at once; it must list each exactly once (09 §6.5).
Invites and links
InvitesApi.create needs create_invites in the target channel (or in defaultChannel, or at community level when that is null) and fails with invite.not_allowed under joinPolicy: closed (09 §8.3). Defaults: valid for 7 days, unlimited uses. maxAgeMs is 300,000 to 31,536,000,000, or null for never, which needs manage_invites; maxUses is 1 to 10,000. The SDK checks the ranges before sending.
The returned Invite carries its link twice: uri is the sloppyv:// URI and shareLink the HTTPS link from the server's links.join template, or null when the server publishes none. Show codes in three groups of four with formatInviteCode (09 §8.2).
import { formatInviteCode, toChannelRef, type ServerClient } from '@sloppyvoice/sdk'
export async function inviteToChannel(server: ServerClient, channelId: string) {
const invite = await server.invites.create({
channel: toChannelRef(channelId),
maxAgeMs: 86_400_000, // 1 day
maxUses: 10,
})
console.log('Code:', formatInviteCode(invite.code)) // 7KQ2-M9XP-4HRT
console.log('Link:', invite.shareLink ?? invite.uri)
// manage_invites holders see every invite; others see their own.
for await (const i of server.invites.list()) console.log(i.code, i.state, i.uses)
await server.invites.revoke(invite.code) // resolves the Invite with state "revoked"
}To regenerate a link yourself, for example in the IRI form for text people copy (form: 'iri'), use formatSloppyvUri from @sloppyvoice/sdk/address with the target ({ address } for the channel's canonical address, or { domain } for the community) and { invite: code }. It builds the URI as 01 §10.3 says; a client that re-shares a link MUST generate a fresh one this way rather than copy the one it received (01 §10.4). For an HTTPS link built from the target server's template, use shareLinkFor.
Opening a link follows 09 §8.6. canonicalize accepts sloppyv:// and web+sloppyv: URIs and HTTPS share links, runs discovery, and returns the canonical domain and the invite code; the SloppyVoiceClient itself is a valid resolver. InvitesApi.preview fetches the public preview without signing in; an invalid code throws sdk.invalid_argument without a request, since the server would answer invite.not_found (09 §8.2). After the person signs in, fetch the preview again with { auth: 'session' }.
import { communityListEntryFromJoin, type SloppyVoiceClient } from '@sloppyvoice/sdk'
import { canonicalize, displayDomain } from '@sloppyvoice/sdk/address'
export async function openInviteLink(sv: SloppyVoiceClient, link: string, tapJoin: (label: string) => Promise<boolean>) {
// Step 1. fetchShareLinks only because the person opened this link (01 §11.4 step 3).
const target = await canonicalize(link, { resolver: sv, fetchShareLinks: true })
if (target.invite === undefined) throw new Error('Not an invite link')
const server = await sv.server(target.domain)
// Step 2. Always show the domain with the community name (09 §3.7).
const preview = await server.invites.preview(target.invite)
const label = `${preview.community.name} (${displayDomain(preview.community.domain)})`
if (!(await tapJoin(label))) return
// Step 4. Rules acceptance works as in joinCommunity above.
const joined = await server.community.join({ invite: target.invite })
// Step 5. Record the community, then open the channel, which joins it silently.
if (!server.isHome) await (await sv.home()).myCommunities.put(server.domain, communityListEntryFromJoin(joined))
if (joined.status === 200 && joined.openChannel) await server.channels.join(joined.openChannel)
}A preview whose channel or community is secure creates a secure-state pin (09 §13.3), and every client keeps pins, in the AccountVault or in device-local storage (09 §13.1). For the channel, feed channelStatementFromInvitePreview to applyChannelStatement; for the community, pass a CommunityStatement with source: 'invite_preview' built from preview.community to applyCommunityStatement. Invites are bearer tokens: anyone holding the link can join while it is active (09 §18 item 7).
Roles and overwrites
Every community has the system roles everyone (position 0) and admin (the highest position), plus a pre-created ordinary "Moderator" role (10 §4.2). RolesApi.all fetches every Role ordered by position. For a system role, show a localized name from system and ignore name.
Role changes need manage_roles and follow the hierarchy of 10 §4.3: you can create, edit, grant and remove only roles below your own top position, and only with permissions you hold yourself. A few things the SDK does for you:
- create and reorder send a generated
Idempotency-Key. - update accepts
addPermissionsandremovePermissions, which you should prefer to a wholepermissionslist because they keep permission names your client doesn't know (10 §3.3). The SDK refuses a body that mixes the two forms. - stepDown removes one of your own roles, which needs no permission; the last admin can't step down (
role.last_admin).
Before granting admin, clients MUST show a confirmation that says the person will be able to do everything, naming them by full address, such as carol@c.com (10 §4.2 item 2).
Overwrites adjust channel-scoped permissions for one role or one member in one channel (10 §5). setRoleOverwrite and setMemberOverwrite replace the whole overwrite and resolve null when both lists are empty, because the server then deletes it. A name can't be in both allow and deny.
import type { ServerClient } from '@sloppyvoice/sdk'
/** Make `ctx` an announcements channel: only Helpers post, everyone reads. */
export async function announcements(server: ServerClient, ctx: string) {
const helpers = await server.roles.create({
name: 'Helpers',
permissions: ['manage_messages', 'timeout_members'],
color: '#2a9d8f',
})
await server.roles.update(helpers.id, { addPermissions: ['mute_members'], ifVersion: helpers.version })
await server.roles.grant(helpers.id, 'bob@a.com')
const everyone = (await server.roles.all()).find((r) => r.system === 'everyone')!
await server.roles.setRoleOverwrite(ctx, everyone.id, { allow: [], deny: ['send_messages'] })
await server.roles.setRoleOverwrite(ctx, helpers.id, { allow: ['send_messages'], deny: [] })
for (const o of await server.roles.overwrites(ctx)) console.log(o.targetType, o.roleId ?? o.address, o.allow, o.deny)
}RolesApi.memberRoles returns the server's own computation for one member ('me' for yourself): roles, top position, effective permissions, and with ctx those in that channel. Clients SHOULD compute permissions locally and use this endpoint to resynchronize or to show another member's powers (10 §7.2).
Computing permissions locally
Clients MUST use the effective-permission algorithm of 10 §6.1 when deciding which controls to show. The SDK implements it, and the checks that decide which error the server would answer, as pure functions with no I/O. The server stays authoritative; these predict its answer.
| Function | Answers |
|---|---|
| computePermissions | The effective permissions in a channel, or in the community without one, in registry order |
| hasPermission | Whether the member effectively holds one permission |
| checkPermission | The refusal (code, status, data) the server would give for a request needing a permission, or null, in the order of 10 §6.3 |
| checkModeration | The same for a kick, ban, timeout or mute of a given target, with the hierarchy rule |
| checkRoleAction, checkRoleReorder, checkOverwriteChange | The same for role and overwrite changes |
| previewVisible | Whether a channel is shown to prospective members |
The input is a PermissionInput: the member (a MemberLike), every role, the channel's overwrites, and the anti-spam policy for the new-member restriction. Roles and overwrites from the API can be passed as they are. Pass now from the server-corrected clock, because timeouts and restrictions are judged by the server's clock (10 §6.2).
import {
checkModeration,
checkPermission,
computePermissions,
type MemberLike,
type ServerClient,
} from '@sloppyvoice/sdk'
export async function channelControls(server: ServerClient, me: string, ctx: string) {
const [roles, overwrites, record, mine, policy] = await Promise.all([
server.roles.all(),
server.roles.overwrites(ctx),
server.community.getMember(me),
server.roles.memberRoles('me'),
server.moderation.policy(),
])
const member: MemberLike = {
address: record.addr,
state: record.state,
roleIds: record.roles,
kind: record.kind,
joinedAt: record.joinedAt,
timeoutUntil: mine.timeoutUntil ?? null,
}
const base = { member, roles, policy, now: server.serverClock.now() }
const here = computePermissions({ ...base, channel: { overwrites } })
const showComposer = here.includes('send_messages')
const attach = checkPermission({ ...base, channel: { overwrites } }, 'attach_files')
// e.g. { code: 'moderation.new_member_restricted', status: 403, data: { permission, until } }
const carol = await server.community.getMember('carol@c.com')
const target: MemberLike = { address: carol.addr, state: carol.state, roleIds: carol.roles }
const showKick = checkModeration(base, 'kick_members', target) === null
return { showComposer, attachRefusal: attach, showKick }
}A timed-out member keeps only view_channel; admins are never affected by timeouts or restrictions, and overwrites don't apply to them (10 §6.1, §6.2). The algorithm never depends on the security mode: a needs_encryption member keeps every permission, and secure content is refused by the security gates instead.
Moderation actions
ModerationApi covers the actions of 10 §8. Every action takes an optional reason (0 to 512 characters, stored in the audit log), showReason (show the reason to the target; default false) and reportId (link the audit entry to a report) (10 §8.2). The target must rank below you (moderation.target_protected) and can't be you (moderation.self_target); admins can't be moderated through the protocol.
Clients MUST send an Idempotency-Key with every POST under /v1/moderation/ and /v1/bans (10 §8.2 rule 6). The SDK generates one per call and reuses it on its own retries. To retry across calls, for example after your process restarted, pass your own idempotencyKey and the server returns the stored response.
| Method | Action | Needs |
|---|---|---|
| deleteMessages | Delete 1 to 100 messages by ID in ctx, or an author's messages from the last withinMs (60,000 to 604,800,000) |
manage_messages in the channel |
| deleteAllMessages | The author form, repeated while the server answers more: true (it stops at 10,000 messages per request) |
As above |
| kick | End the membership (left, reason kicked), optionally deleting recent messages |
kick_members |
| timeout, liftTimeout | Read-only for 60,000 ms (1 minute) to 2,419,200,000 ms (28 days) | timeout_members |
| serverMute, liftServerMute | Silence audio in every voice channel, for a time or until lifted | mute_members at community level |
| member | One member's timeout, server mute, ban and open reports, filtered by your permissions | Any of timeout_members, mute_members, ban_members, manage_reports |
Clients SHOULD offer the timeout presets of 10 §8.5: 1 minute, 10 minutes, 1 hour, 1 day and 1 week, in TIMEOUT_PRESETS_MS. To stop someone's voice, screen share and webcam in one channel only, RolesApi.denySpeakAndShare adds speak_and_share to the deny of their member overwrite and keeps the rest, which a mute_members holder may do without manage_roles (10 §5.2, §8.7). If the overwrite's allow held speak_and_share, the SDK drops it from there too, and that second change needs manage_roles.
import { TIMEOUT_PRESETS_MS, type ServerClient } from '@sloppyvoice/sdk'
export async function handleSpam(server: ServerClient, reportId: string, voiceCtx: string) {
const timeout = await server.moderation.timeout({
member: 'carol@c.com',
durationMs: TIMEOUT_PRESETS_MS[2], // 1 hour
reason: 'Posting the same link everywhere',
showReason: true,
reportId,
})
console.log('Timed out until', timeout.until)
// Delete her messages from the last day in every channel where you hold manage_messages.
const results = await server.moderation.deleteAllMessages({
author: 'carol@c.com',
withinMs: 86_400_000,
allChannels: true,
reportId,
})
// An author who ranks at or above you fails the whole request with moderation.target_protected.
const deleted = results.reduce((n, r) => n + r.deleted.length, 0)
console.log(deleted, 'deleted')
await server.roles.denySpeakAndShare(voiceCtx, 'dan@d.com')
await server.moderation.kick({ member: 'erin@e.com', deleteMessagesWithinMs: 3_600_000 })
}Bans
BansApi.create bans one address or one domain, given in any form canonicalize accepts; the server stores the canonical form, so one ban covers every alias domain of the target's server (10 §9.2). Scope community (the default) needs ban_members and leaves DMs hosted on the server working; scope server is for admins, takes address targets only, and also covers DMs and remote sessions (10 §9.3). There is no server-scope domain ban: to cut off a whole server, admins use a federation block. durationMs is at least 3,600,000 (1 hour), or absent for a permanent ban.
The answer is 201 with a new Ban, or 200 with the existing ban of the same target and scope, updated if the body differs (10 §9.6); the SDK resolves the Ban in both cases and doesn't tell you which. Lifting a ban makes the membership left; it doesn't restore roles, overwrites or deleted messages (10 §9.5).
import { uuidv7, type ServerClient } from '@sloppyvoice/sdk'
export async function banSpammers(server: ServerClient) {
// Keep the key with your pending work so a retry after a restart returns the same ban.
const key = uuidv7()
const ban = await server.bans.create(
{ address: 'spammer@spam.example', durationMs: 7 * 86_400_000, deleteMessagesWithinMs: 86_400_000, reason: 'Spam' },
{ idempotencyKey: key },
)
await server.bans.create({ domain: 'spam.example', reason: 'Spam server' })
for await (const b of server.bans.list({ targetType: 'address' })) console.log(b.address, b.expiresAt ?? 'permanent')
await server.bans.update(ban.id, { expiresAt: null }) // make it permanent
await server.bans.lift(ban.id)
}Every refusal caused by a ban is 403 moderation.banned, with data.scope, data.expiresAt and the reason if it is shown. Show one plain sentence with the end date and reason, never who banned the person (10 §9.6).
Reports
ReportsApi.file sends POST /v1/reports to the server hosting the context, and resolves the reporter view (ReporterView). Before sending, the client MUST show the disclosure line of 10 §10.11, which says who will see what. The SDK checks the body first: ctx is required (null for a member report from a profile outside any context), a messages report needs at least one reported item, context items are at most 20 in all (the spec allows 10 before and 10 after; the server checks the sides), each mid appears once, and categories are the ten of 10 §10.3.
Include as context only messages the person has already loaded or decrypted, never one they couldn't read (10 §10.3 step 3). In a secure context each item carries its kMsg, and each attachment of a reported item its fileKey; never send copies of insecure messages. The SDK sends a generated Idempotency-Key, so its own retries get the stored 201; a new call for the same messages while your earlier report isn't resolved or withdrawn fails with 409 report.duplicate and data.reportId (10 §10.4 step 3). A message request that wasn't accepted, and a DM hosted on the target's own home server, are reported at the reporter's home server instead (10 §10.10): use the reports of await sv.home() for them.
import type { ServerClient } from '@sloppyvoice/sdk'
export async function reportHarassment(server: ServerClient, ctx: string, mid: string, before: string[], after: string[]) {
const report = await server.reports.file({
ctx,
kind: 'messages',
category: 'harassment',
note: 'This has been going on for a week.',
items: [
...before.slice(-10).map((m) => ({ mid: m, role: 'context' as const })),
{ mid, role: 'reported' },
...after.slice(0, 10).map((m) => ({ mid: m, role: 'context' as const })),
],
})
console.log(report.id, report.status) // "open"
for await (const mine of server.reports.mine()) console.log(mine.category, mine.status, mine.outcome)
}Moderators work the queue with ReportsApi.queue, which needs manage_reports or the admin role and lists only reports the caller may see (10 §10.5). claim, reopen and resolve follow the status machine of 10 §10.6; an invalid transition fails with report.status_conflict. Show an item's content only for the results verified and plaintext; reportItemPresentation gives the presentation for each item, and withheld means the evidence comes from a secure context and this session can't read it: show G1 or G2 in its place (10 §10.8).
import { reportItemPresentation, type ServerClient } from '@sloppyvoice/sdk'
export async function workQueue(server: ServerClient) {
for await (const report of server.reports.queue({ status: 'open' })) {
const claimed = await server.reports.claim(report.id, report.version)
for (const item of claimed.items) {
switch (reportItemPresentation(item)) {
case 'verified': console.log('Verified: sent by this person\'s device', item.content); break
case 'plaintext': console.log(`As stored by ${claimed.host}`, item.content); break
case 'plaintext_from_origin': console.log(`As stored by ${claimed.originServer}; can't be checked here`, item.content); break
case 'withheld': console.log('Set up encryption to read this'); break
default: console.log("Couldn't be verified")
}
}
await server.reports.resolve(claimed.id, 'action_taken', { resolutionNote: 'Timed out for 1 h', ifVersion: claimed.version })
}
}Admins may forward a messages report to the target's home server with ReportsApi.forward when every condition of 10 §10.9 holds; otherwise it fails with report.not_forwardable and data.reason. Use isModeratorView to tell the two shapes of ReportsApi.get apart.
Audit log
AuditLogApi.list pages through the audit log newest first, filtered by any of action, actor, targetAddress, targetType, ctx, reportId, since and until; limit is 1 to 100 (10 §11.4). It needs view_audit_log, and entries with restricted: true (server-scope bans, DM moderation, forwarding and a few more) are returned only to admins. Each page also carries retentionDays. Show an unknown action as "Other change", and an actor of unknown kind as "System" (10 §11.2); operator is a known kind, for actions taken outside the protocol.
import type { ServerClient } from '@sloppyvoice/sdk'
export async function recentBans(server: ServerClient) {
const first = await server.auditLog.list({ action: 'member_banned', limit: 20 }).page()
console.log(`Entries are kept for ${first.retentionDays} days`)
for await (const entry of server.auditLog.list({ targetAddress: 'carol@c.com', since: '2026-12-01T00:00:00.000Z' })) {
const who = entry.actor.kind === 'member' ? entry.actor.address : entry.actor.kind === 'operator' ? 'Operator' : 'System'
console.log(entry.at, entry.action, who, entry.reason ?? '')
}
}Upgrading to secure
A channel or a whole server goes from insecure to secure through one dry run, one W5 confirmation and one switch, and there is no way back (09 §10, §11, §12). The SDK has no downgrade call. Both flows have the same shape:
- The dry run changes nothing and returns a plan: who can't follow (
cannotFollow, up to 100 named, plus a count), the secure bots that will follow, how many messages exist for the deletion option, and whether a call will restart. - Show W5 with that plan. The checkbox that deletes the messages sent before encryption is off by default (09 §10.3).
- Confirm with the plan's
planVersion. If the set of people who can't follow changed in between, the confirmation fails with…upgrade_plan_staleanddata.planholds the new plan: show W5 again with it.
The dry run is allowed to an insecure admin, so you can show who would be affected; the confirmation needs a secure account on an enrolled device and fails with security.account_required or security.device_not_enrolled otherwise. After G1 or G2, the client runs the dry run again and shows W5 again; it never confirms an upgrade by itself (09 §9.6).
Server upgrade. It needs the admin role and a local account (09 §11.1); manage_community is not enough. CommunityApi.planUpgrade answers the ServerUpgradePlan, or the Community when the server is already secure; isServerUpgradePlan tells them apart. CommunityApi.upgrade also needs confirmDomain, the canonical domain as typed or confirmed in W5, always sends an Idempotency-Key, and waits up to 120 s for the answer, because the server finishes the whole switch before answering (09 §11.4).
import {
isServerUpgradePlan,
isSloppyVoiceError,
type Community,
type CommunityUpgradePlanStaleData,
type ServerClient,
type ServerUpgradePlan,
} from '@sloppyvoice/sdk'
type W5Answer = { confirmDomain: string; deletePreUpgradeHistory: boolean } | null
export async function upgradeServer(server: ServerClient, showW5: (plan: ServerUpgradePlan) => Promise<W5Answer>): Promise<Community | null> {
const first = await server.community.planUpgrade()
if (!isServerUpgradePlan(first)) return first // already secure
let plan: ServerUpgradePlan = first
for (;;) {
const answer = await showW5(plan)
if (!answer) return null
try {
return await server.community.upgrade({ planVersion: plan.planVersion, ...answer })
} catch (e) {
if (!isSloppyVoiceError(e, 'community.upgrade_plan_stale')) throw e
plan = (e.data as unknown as CommunityUpgradePlanStaleData).plan
}
}
}Channel upgrade. It needs manage_channels for the channel (09 §10.1). ChannelsApi.planUpgrade returns the ChannelUpgradePlan. The confirmation, ChannelsApi.upgrade, also carries the caller's one-member MLS group as a GroupBootstrap (13 §7.4): create the group with your MLS provider and build the bootstrap with groupBootstrapFor, generation 1 for a channel's first upgrade (see MLS and sealed messages). The caller becomes a channel member and its device the group's only leaf.
A 409 channel.already_secure carries the channel and the existing group. alreadySecureIsOwnGroup tells you whether it is your own group, because your confirmation succeeded and only its response was lost; if it isn't, discard your group and join the existing one (09 §10.4).
import {
alreadySecureIsOwnGroup,
isSloppyVoiceError,
type ChannelAlreadySecureData,
type ChannelUpgradePlan,
type ChannelUpgradePlanStaleData,
type ServerClient,
type UpgradeGroupBootstrap,
} from '@sloppyvoice/sdk'
export async function upgradeChannel(
server: ServerClient,
ctx: string,
showW5: (plan: ChannelUpgradePlan) => Promise<{ deletePreUpgradeHistory: boolean } | null>,
createGroup: () => Promise<UpgradeGroupBootstrap>, // from your MlsProvider, via groupBootstrapFor()
) {
let plan = await server.channels.planUpgrade(ctx)
for (;;) {
const answer = await showW5(plan)
if (!answer) return null
const bootstrap = await createGroup()
try {
const channel = await server.channels.upgrade(ctx, { planVersion: plan.planVersion, bootstrap, ...answer })
return { channel, keepGroup: true }
} catch (e) {
if (isSloppyVoiceError(e, 'channel.upgrade_plan_stale')) {
plan = (e.data as unknown as ChannelUpgradePlanStaleData).plan
continue
}
if (isSloppyVoiceError(e, 'channel.already_secure')) {
const data = e.data as unknown as ChannelAlreadySecureData
return { channel: data.channel, keepGroup: alreadySecureIsOwnGroup(data, bootstrap) }
}
throw e
}
}
}Afterwards the server sends channel.security_changed (or community.security_changed). Members who can't follow become needs_encryption: they keep their membership and roles, can read the channel up to the upgrade unless that history was deleted, and see G1; when their account turns on encryption they become active again and the client resumes by itself. A post rejected with 409 channel.plaintext_rejected MUST NOT be sent again as plaintext (09 §10.5).