@sloppyvoice/sdk/testing contains MockServer, an in-memory Sloppy Voice server for insecure-mode flows, and MockNetwork, which connects several of them. A mock server answers through a fetch function, a WebSocket class and a TXT resolver that you hand to SloppyVoiceClient, so the SDK's real discovery resolver, HTTP client and event socket run against it unchanged. Nothing leaves the process: no DNS, no sockets, no ports.

The mock builds its responses from the SDK's wire types and follows the specification for the parts it implements, but it is not a conforming server. Use it to test your own code's handling of the protocol (replies, retries, reconnects, error paths), and test against a real server before you ship. What the mock does not implement lists the gaps.

A server and a client

MockServer.create is async because it generates the server's Ed25519 keys first. Give the client the server's fetch, WebSocket and txt, and set allowSpecialUseDomains:

import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
const bot = server.createBot({ local: 'helper', name: 'Helper' })

const sv = new SloppyVoiceClient({
  client: 'my-bot-tests/1.0',
  home: 'alpha.test',
  auth: botToken(bot.token),
  fetch: server.fetch,
  WebSocket: server.WebSocket,
  txt: server.txt,
  allowSpecialUseDomains: true,
  // Optional: no retry jitter, and retries that don't wait.
  random: () => 0,
  sleep: async () => {},
})

const home = await sv.home()
const me = await home.me.get()
console.log(me.account.address) // helper@alpha.test

await sv.close()
server.close()

Special-use domains

Give mock servers special-use names such as alpha.test and beta.test, so a test can never reach a real server by mistake. Discovery refuses those names by default: a queried domain must not be a special-use name such as test, example, localhost or invalid, and fails with discovery.invalid_domain otherwise (02 §5.1). The spec allows a development setting that permits them, which MUST be off by default and MUST NOT be available in release builds of clients. allowSpecialUseDomains: true is that setting; set it only in test configuration.

Server options

MockServerOptions:

Option Default Meaning
domain required The canonical domain, a lowercase A-label such as alpha.test.
baseUrl https://chat.<domain>/server The base URL (02 §3.3).
aliases none Further domains the server accepts (02 §8).
name the domain Server and community name.
delegation txt txt: the network's TXT resolver answers _sloppyv.<domain> (02 §3). wellknown: no TXT record, only https://<domain>/.well-known/sloppyv (02 §4).
joinPolicy open The community's join policy (09 §3.3). Use invite to test invite flows for remote accounts. The mock implements open, invite and closed; a join under request without an invite gets 501 core.unsupported_feature.
limits see below Advertised limits, merged over the mock's defaults (maxMessageBytes 16,384, maxSubscriptions 1,000, maxGroupDmParticipants 25, and others).
maxReplayEvents 5,000 Events kept per stream for replay (03 §7.4). Values below the spec's floor of 1,000 are non-conforming, but make replay and resync tests cheap.
pingIntervalMs 30,000 session.ping interval (03 §5.9); null sends no pings.
headsIntervalMs 2,000 Minimum spacing of session.heads per socket (03 §5.7).
remoteSessionLifetimeMs 3,600,000 Lifetime of remote sessions issued by this server (06 §6.4).
clock Date.now The server's clock. Share one fake clock between servers and client to move time forward.
timers global setTimeout Timers for pings and heads.
network a new one The MockNetwork to join.

Most tests want pingIntervalMs: null, so that no ping arrives in the middle of an assertion. The mock's timers are unreferenced and never keep Node running, but call MockServer.close anyway: it closes every socket with 1001 and removes the server from its network.

Accounts, channels and posts

The mock has no sign-in flow and no account management API. You create accounts on the server object, and each comes with a ready credential (MockCredentials):

  • createUser makes a local user with a static access token sva_… (05 §7.5). Send it with staticToken(user.token), which uses the Bearer scheme. The mock's access tokens never expire and can't be refreshed.
  • createBot makes a bot with a bot token svb_… (05 §15.4). Send it with botToken(bot.token), which uses the Bot scheme. The mock refuses a bot token under Bearer with 401 core.unauthenticated, as 05 §15.4 requires, and it also refuses an access token under Bot the same way.

Both take { local, name?, admin? }. local goes through the address profile of document 01, so an invalid local part throws, and a taken address throws. Every local account, bots included, is an active community member from the start. That differs from the spec for bots: 09 §4.4 makes only local users automatic members, and a real server admits a bot only with the approval of a manage_bots holder (until then its join gives a pending record). The mock also makes a remote bot that joins an active member at once, so test bot admission against a real server.

The mock has no roles. As a stand-in for document 10, an admin account holds every permission and every other account holds the defaults. The first account you create, user or bot, is an admin unless you pass admin: false; later accounts are not admins unless you pass admin: true. A non-admin that creates a channel through the API gets 403 core.forbidden with data.permission manage_channels.

createChannel creates a channel as the first admin, or as opts.by, and emits channel.created on the community stream (09 §14.2). It returns the Channel; you need its ctx. The creator does not join it: every account that posts must join first, through its client (home.channels.join(ctx)), or the post fails with channel.join_required.

post posts a text message as a local account, through the same acceptance procedure as POST /v1/contexts/{ctx}/messages (11 §4.5), so the same membership rules apply. It is useful for producing traffic without a second client:

import { SloppyVoiceClient, staticToken } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
server.createBot({ local: 'helper' }) // the first account: an admin
const alice = server.createUser({ local: 'alice', name: 'Alice' })
const general = server.createChannel('General', { topic: 'Anything goes' })

const aliceSv = new SloppyVoiceClient({
  client: 'tests/1.0',
  home: 'alpha.test',
  auth: staticToken(alice.token),
  fetch: server.fetch,
  WebSocket: server.WebSocket,
  txt: server.txt,
  allowSpecialUseDomains: true,
})
const aliceHome = await aliceSv.home()
await aliceHome.channels.join(general.ctx)

// 20 messages from Alice, without 20 HTTP requests.
for (let i = 1; i <= 20; i++) server.post(alice.address, general.ctx, `message ${i}`)
const page = await aliceHome.messages.page(general.ctx, { limit: 5 })
console.log(page.headSeq, page.hasMore)

await aliceSv.close()
server.close()

Inspecting what happened

Member What it holds
requests Every HTTP request the server answered: method, path relative to the base URL, the Authorization header as received, and the status.
network.log Every URL fetched through the network, discovery and /meta included, with its Authorization header.
headSeq(stream) The head seq of a stream: community, a context reference, or me:<address> (03 §7.1).
socketCount The number of open event sockets.
pings and pongs Every session.ping sent, and every session.pong received with whether it answered a ping on that connection (03 §5.9). pingAll sends a ping on every ready socket now.

requests is the place to check retry behaviour (the statuses of every attempt) and that credentials went only where they should (see Several servers).

Fault injection

failNext

failNext makes the next matching request fail with a problem object (03 §10). An InjectedFailure has:

  • code, required. The status, retryable and userAction default to the code's entry in the error registry, so core.unavailable gives 503 with retryable: true. A code the mock doesn't know defaults to 400.
  • method and path, to narrow the match. path is relative to the base URL and has no query string (/v1/me), or a RegExp (/\/messages$/). Without them, any request matches.
  • status, detail, retryAfterMs and data, to override the problem's members.
  • times, how many matching requests fail. Default 1.

The check runs before authentication and routing, so it applies to every path under /v1/, including endpoints the mock doesn't implement. It doesn't apply to /meta or /.well-known/sloppyv. For core.rate_limited the mock also sets Retry-After, RateLimit and RateLimit-Policy headers, retryAfterMs (default 1,000 ms) and data.policy session, as a real 429 carries them (03 §15.2).

What the client then does follows 03 §2.7: it retries a problem automatically only when the problem says retryable: true and the request is idempotent (GET, PUT, DELETE, or a POST or PATCH with a client-generated ID or Idempotency-Key), never sooner than retryAfterMs, and it stops after 5 attempts, the first included, so times: 5 or more makes the error reach your code. A message send carries its mid, so it is retried with the same mid; invites.create sends no Idempotency-Key unless you pass idempotencyKey, so its error reaches your code:

import assert from 'node:assert/strict'
import { SloppyVoiceClient, botToken, isSloppyVoiceError } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
const bot = server.createBot({ local: 'helper' })
const slept: number[] = []
const sv = new SloppyVoiceClient({
  client: 'tests/1.0',
  home: 'alpha.test',
  auth: botToken(bot.token),
  fetch: server.fetch,
  WebSocket: server.WebSocket,
  txt: server.txt,
  allowSpecialUseDomains: true,
  sleep: async (ms) => {
    slept.push(ms)
  },
})
const home = await sv.home()

// A GET is retried, never sooner than retryAfterMs.
server.failNext({ method: 'GET', path: '/v1/me', code: 'core.rate_limited', retryAfterMs: 1500, times: 2 })
await home.me.get()
assert.deepEqual(server.requests.filter((r) => r.path === '/v1/me').map((r) => r.status), [429, 429, 200])
assert.ok(slept.every((ms) => ms >= 1500))

// A send is retried with the same mid.
const ch = server.createChannel('General')
await home.channels.join(ch.ctx)
server.failNext({ method: 'POST', path: /\/messages$/, code: 'core.unavailable', retryAfterMs: 10 })
await home.messages.send(ch.ctx, 'eventually')

// A POST without a client ID or Idempotency-Key is not retried.
server.failNext({ method: 'POST', path: '/v1/invites', code: 'core.rate_limited', retryAfterMs: 4000 })
await assert.rejects(home.invites.create({}), (e) => isSloppyVoiceError(e, 'core.rate_limited') && e.retryAfterMs === 4000)

await sv.close()
server.close()

Rate limits

setRateLimit turns on a real limiter instead of a scripted failure: at most limit requests per windowMs, counted per session (unauthenticated requests share one count). Over the limit the server answers 429 core.rate_limited with retryAfterMs set to the rest of the window and the headers of 03 §15.2. setRateLimit(null) turns it off. The limiter reads the server's clock, so either let real time pass in your sleep, or move a shared fake clock forward.

Revoked and expired tokens

Control Effect Client recovery (03 §3.3)
revokeToken(token) Later requests with the token get 401 core.unauthenticated; a session.hello with it gets an error with that code and a close with 4001. Open sockets stay open. A bot stops and reports. A home session tries one refresh, then needs sign-in. A remote session is recreated silently from a new HomeAssertion.
expireToken(token) The token's expiry moves to now, so the next use gets 401 core.token_expired. Meant for remote-session tokens. A remote session is recreated silently and the request retried once (06 §6.10).
endSession(token, opts) Ends the session now. On each of its sockets the server sends federation.session_ended (remote sessions only), an error with the problem and session.closing with reason session_ended, then closes with 4004 (03 §5.10, 06 §6.8). opts.retry sets the event's retry. With retry: true a remote session is recreated silently and the socket reconnects with the new token (06 §6.10).

The recovery column is what the spec asks of a client. The tokens the mock hands out can't be refreshed, so staticToken and botToken give up at once: a 401 reaches your code, and an event socket whose next session.hello is refused stops with reason unauthenticated. Only the remote-session rows are recovered silently on the mock.

revokeToken and endSession also make post for that account throw, since the account no longer has a session.

Disconnects and replay

  • disconnectAll(code, closing?) closes every event socket with code, after a session.closing when closing is given. disconnectAll(1012, { reason: 'server_shutdown', reconnect: true, retryAfterMs: 50 }) simulates a restart: the client backs off, reconnects and resumes (03 §5.11). Events posted while it was away are replayed in order, once.
  • expireEvents(stream, throughSeq) forgets a stream's retained events up to throughSeq. A resume from before that point then gets session.resync_required with reason expired (03 §7.4, §7.5), which the SDK reports as the resync lifecycle event of EventSocket.
import { SloppyVoiceClient, botToken, type ResyncRequest } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
const bot = server.createBot({ local: 'helper' })
const sv = new SloppyVoiceClient({
  client: 'tests/1.0',
  home: 'alpha.test',
  auth: botToken(bot.token),
  fetch: server.fetch,
  WebSocket: server.WebSocket,
  txt: server.txt,
  allowSpecialUseDomains: true,
})
const home = await sv.home()
const ch = server.createChannel('General')
await home.channels.join(ch.ctx)

const events = home.events({ subscribe: [ch.ctx] })
const resyncs: ResyncRequest[] = []
events.lifecycle.on('resync', (r) => resyncs.push(r))
await events.connect()

server.disconnectAll(1012, { reason: 'server_shutdown', reconnect: true, retryAfterMs: 100 })
await home.messages.send(ch.ctx, 'while the socket is down')
server.expireEvents(ch.ctx, server.headSeq(ch.ctx))
// The reconnect's resume finds the missed event gone.
while (resyncs.length === 0) await new Promise((r) => setTimeout(r, 10))
console.log(resyncs[0]!.stream === ch.ctx, resyncs[0]!.reason) // true expired

await sv.close()
server.close()

Several servers

A MockNetwork is the "internet" of several mock servers. Create one, pass it as network to each MockServer.create, and give the client the network's fetch, WebSocket and txt (each server's members of the same names return its network's, so either works). Two servers in one network can't share a domain.

The network routes each request by URL. A request to a server's base URL goes to that server; https://<domain>/.well-known/sloppyv is answered for every domain of a server with delegation: 'wellknown'; any other path at a server's domain or base host gets a plain 404; and a request to a host no server uses fails the way an unknown host does, so discovery treats it as having no address (02 §4.2). It speaks HTTPS and WSS only. serverFor(domain) finds a server by any of its domains, and remove takes one off the network so its URLs stop answering, which is how you test a server that moved or went away.

Across servers the mock implements federation from document 06: the home server signs HomeAssertions with its server key (06 §4), and the other server verifies them against that key and issues remote sessions, with renewal, …/sessions/current and expiry (06 §6). The client does all of this itself when you call sv.server(domain) or sv.serverFor(address).

import assert from 'node:assert/strict'
import { SloppyVoiceClient, botToken, staticToken } from '@sloppyvoice/sdk'
import { MockNetwork, MockServer } from '@sloppyvoice/sdk/testing'

const network = new MockNetwork()
const alpha = await MockServer.create({ domain: 'alpha.test', network, pingIntervalMs: null })
const beta = await MockServer.create({ domain: 'beta.test', network, delegation: 'wellknown', joinPolicy: 'invite', pingIntervalMs: null })
const bot = alpha.createBot({ local: 'helper' })
const owner = beta.createUser({ local: 'owner' })
const lobby = beta.createChannel('Lobby')

const client = (auth: ReturnType<typeof botToken>) =>
  new SloppyVoiceClient({
    client: 'tests/1.0',
    home: 'alpha.test',
    auth,
    fetch: network.fetch,
    WebSocket: network.WebSocket,
    txt: network.txt,
    allowSpecialUseDomains: true,
  })
const sv = client(botToken(bot.token))
const ownerSv = new SloppyVoiceClient({
  client: 'tests/1.0',
  home: 'beta.test',
  auth: staticToken(owner.token),
  fetch: network.fetch,
  WebSocket: network.WebSocket,
  txt: network.txt,
  allowSpecialUseDomains: true,
})

// beta's owner invites the bot; the bot joins from its home at alpha.
const invite = await (await ownerSv.home()).invites.create({ channel: lobby.ctx })
const remote = await sv.serverFor('lobby@beta.test')
await remote.community.join({ invite: invite.code })
await remote.channels.join(lobby.ctx)
await remote.messages.send(lobby.ctx, 'hello from alpha')

// The bot token went only to alpha; beta saw a remote-session token (03 §3.2).
assert.ok(network.log.every((r) => !r.authorization?.includes(bot.token) || r.url.startsWith(alpha.baseUrl)))
assert.ok(beta.requests.some((r) => r.authorization?.startsWith('Bearer rs_')))

await ownerSv.close()
await sv.close()
network.close()

To test expiry and renewal, give both servers and the client one fake clock ({ now: () => t }), call expireToken or move t past remoteSessionLifetimeMs, and check beta.requests for a second POST /v1/federation/sessions. After expireToken, move the clock at least 2 s forward before the next request: the SDK treats a 401 within 2 s of getting a session as a race with that new session and retries with it instead of creating another, so the request fails.

Servers in a network never deliver events to each other: server-to-server requests and event delivery (06 §8, §9) are not implemented. A client that wants beta's events opens an event socket at beta with its remote session (remote.events()), which works.

What the mock does not implement

A request to a path under /v1/ that the mock doesn't route gets 404 core.not_found with data.reason unknown_endpoint, as a server without the feature answers (03 §2.1, §12.3). Some missing parts answer differently:

  • A method the mock doesn't implement on a path it does route, such as PATCH /v1/community or PATCH /v1/channels/{id}, gets 405 core.method_not_allowed.
  • The around and changedAfter timeline queries, a join under the request policy and creating a secure channel get 501 core.unsupported_feature.
  • A message with attachments gets attachment.not_found, since the mock stores none.

The missing parts are:

  • Secure mode and everything that depends on it: identity (document 07), device setup (document 08), MLS (document 13), sealed messages and history (document 14). A sealed carrier is refused with sealed.not_secure.
  • OAuth sign-in and token refresh (05 §6 to §8); the devices, bot management and profile APIs.
  • Roles, moderation and reports (document 10); admin accounts stand in for permissions. Bot admission by a manage_bots holder (09 §4.4) is missing too: bots become members at once.
  • Presence, attachments, webhooks, calls (document 15), notifications and push (document 19). The mock's /meta still lists the voice-dc/1 and video-dc/1 features, so don't rely on it to test feature detection for calls.
  • Community settings changes, categories, member lists, DM participant changes, settings, blocks and message requests.
  • The around and changedAfter timeline queries, and join requests (the request policy).
  • Server-to-server requests and event delivery between mock servers.
  • The event socket's authentication deadline and idle timeout, backpressure (close code 4011) and per-socket message rate limits.

What it does implement: discovery (TXT, .well-known, /meta with real server keys, GET /v1/resolve), the HTTPS rules of document 03 (problem objects, CORS, Idempotency-Key replay and conflict, opaque cursors), static access and bot tokens, remote sessions, the community with joining, channels and invites, insecure messaging (messages, edits, reactions, deletes, paging, read state, typing), insecure DMs and the DM index, and the event socket with subscriptions, resume and replay, resync, heads, pings and session.reauth.

A complete test

A ping bot and its test, with node:test. Node 22.18 or later runs a .ts test file directly with node --test ping-bot.test.ts; on earlier versions add --experimental-strip-types or compile first.

// ping-bot.test.ts
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { SloppyVoiceClient, botToken, isWithheldPayload, staticToken, type CtxRef, type ServerClient, type TokenProvider } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

/** The code under test: answer "!ping" with "pong" in one channel. */
async function startPingBot(server: ServerClient, ctx: CtxRef): Promise<void> {
  await server.channels.join(ctx)
  const events = server.events({ subscribe: [ctx] })
  events.on('message.created', async (e) => {
    if (isWithheldPayload(e.d) || e.d.content?.text !== '!ping') return
    await server.messages.send(ctx, 'pong', { replyTo: { mid: e.d.mid, author: e.d.sender.addr! } })
  })
  await events.connect()
}

function clientFor(server: MockServer, auth: TokenProvider): SloppyVoiceClient {
  return new SloppyVoiceClient({
    client: 'ping-bot-tests/1.0',
    home: server.domain,
    auth,
    fetch: server.fetch,
    WebSocket: server.WebSocket,
    txt: server.txt,
    allowSpecialUseDomains: true,
    random: () => 0,
  })
}

test('the bot answers !ping with a reply', async () => {
  const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
  const bot = server.createBot({ local: 'pingbot', name: 'Ping bot' })
  const alice = server.createUser({ local: 'alice', name: 'Alice' })
  const general = server.createChannel('General')
  const botSv = clientFor(server, botToken(bot.token))
  const aliceSv = clientFor(server, staticToken(alice.token))
  try {
    await startPingBot(await botSv.home(), general.ctx)

    const home = await aliceSv.home()
    await home.channels.join(general.ctx)
    const events = home.events({ subscribe: [general.ctx] })
    const reply = new Promise<{ text: string | undefined; replyTo: string | undefined }>((resolve) => {
      events.on('message.created', (e) => {
        if (isWithheldPayload(e.d) || e.d.sender.addr !== bot.address) return
        resolve({ text: e.d.content?.text, replyTo: e.d.content?.replyTo?.mid })
      })
    })
    await events.connect()

    const ping = await home.messages.send(general.ctx, '!ping')
    assert.deepEqual(await reply, { text: 'pong', replyTo: ping.mid })
  } finally {
    await aliceSv.close()
    await botSv.close()
    server.close()
  }
})

test('a send that fails once with 503 is retried with the same mid', async () => {
  const server = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
  const bot = server.createBot({ local: 'pingbot' })
  const general = server.createChannel('General')
  const sv = clientFor(server, botToken(bot.token))
  try {
    const home = await sv.home()
    await home.channels.join(general.ctx)
    server.failNext({ method: 'POST', path: /\/messages$/, code: 'core.unavailable', retryAfterMs: 10 })
    const ack = await home.messages.send(general.ctx, 'eventually')
    assert.equal(ack.kind, 'message')
    const posts = server.requests.filter((r) => r.method === 'POST' && r.path.endsWith('/messages'))
    assert.deepEqual(posts.map((r) => r.status), [503, 201])
    const page = await home.messages.page(general.ctx)
    assert.equal(page.items.filter((i) => i.type === 'message').length, 1)
  } finally {
    await sv.close()
    server.close()
  }
})

The first test exercises the real path end to end: discovery through the TXT record, session.hello, the subscription, message.created delivery to both sockets and the reply's replyTo. The second shows the pattern for error paths: inject the failure, run your code, and assert on requests and on the state the server ended up in.