SloppyVoiceClient is the entry point of the SDK. You give it a client name, your home domain, a credential and a way to look up DNS. It gives you one ServerClient per server you talk to, each with its own base URL, metadata, credential, resource APIs and event socket.

Behind that, the client does three things for you:

  • Discovery. It turns a domain into a base URL and validated ServerMetadata, and keeps the caches and pins that document 02 requires.
  • Credentials. It sends your credential only to your home server, and gets a separate remote session at every other server (03 §3.2 rule 3).
  • Lifetime. It caches server clients by canonical domain, renews remote sessions in the background and stops everything when you close it.

The protocol side of this is on Discovery and server metadata and Federation.

Creating a client

A Node bot needs four options:

import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: 'sloppyvoice.com',
  auth: botToken(process.env.SV_BOT_TOKEN!),
  txt: nodeTxtResolver(),
})

const home = await sv.home()
console.log(home.domain, home.baseUrl, home.metadata.name)

The constructor checks client, the home domain, the shape of auth and remoteSessions, and that discovery has a way to run, and throws sdk.invalid_argument at once; it does no I/O. The first network request happens when you ask for a server.

The options of SloppyVoiceClientOptions:

Option Meaning
client Product and version, 1 to 128 printable ASCII characters, such as my-bot/1.0. Sent as client in session.hello (03 §5.4) and in remote-session requests (06 §6.1). Outside browsers, a value of the form product/version is also sent as the first User-Agent product, before the SDK's own (03 §2.3 item 6). Required.
home Your home server's domain. Defaults to the domain of address.
address The account's canonical address (01). Its domain is the home domain unless home says otherwise.
auth The account credential, used only at the home server. A TokenProvider such as botToken(…) or a HomeSession, a stored sign-in session { session, options?, authApi? }, or a factory that builds a provider once the home server is known. Without it, every server is used anonymously.
txt A TxtResolver. Without homeBaseUrl it selects native discovery: use nodeTxtResolver() on Node, Deno and Bun. With homeBaseUrl it is the optional DNS-over-HTTPS fallback.
homeBaseUrl The home server's base URL, for web clients that can't query DNS. Selects web discovery through /v1/resolve.
discovery A DiscoveryResolver to share between clients, or extra DiscoveryResolverOptions for the one the client builds: pins, publicSuffixList, wellKnownCheck, onPinConflict, onPinChanged and others.
features Features to offer in session.hello (03 §12.2). Default none.
device The enrolled device's DSK signer and DeviceCertificate, for remote sessions of a secure account (06 §5).
remoteSessions, onRemoteSession Restore remote sessions from secure storage, and persist new ones. See Keeping remote sessions across restarts.
onRemoteStatus, onRemoteDiagnostic Status changes and failed steps of remote sessions, for status lines and diagnostics (06 §6.10 rule 7, §15).
seqStore A function that returns, for a server's canonical domain, the store that keeps that server's event-stream positions (03 §7.3). Default: in memory.
fetch, WebSocket, clock, timers, sleep, random Injected platform functions, for tests and unusual runtimes. Defaults are the globals and a CSPRNG.
headers Extra headers on every HTTP request, such as Accept-Language. Never Authorization.
timeoutMs Per-attempt HTTP timeout. Default 30 s (03 §2.3 item 5).
allowSpecialUseDomains Allow names such as *.test for local development. Must be off in release builds (02 §5.1).
allowInsecureHttp Allow http: base URLs. Non-conforming (03 §2.2 item 1); for local test servers only.

The client needs either txt or homeBaseUrl, because discovery has no other way to find a server (02 §5.2, §5.4).

Getting server clients

Four methods turn a name into a server:

Method Returns
home() The home server's client, authenticated with auth. Resolved once and cached.
server(domain) The client for any domain. For the home server, under any of its domains, this is the home client. For any other server it is a client with its own remote session, or an anonymous one when auth is not set. A remote session needs home or address; without them the call fails with sdk.invalid_argument.
serverFor(address) server() for the domain of an address (01 §2.2). Works for user, bot and channel addresses.
resolve(domain) The DiscoveryResult for a domain, without creating a client.
import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: 'sloppyvoice.com',
  auth: botToken(process.env.SV_BOT_TOKEN!),
  txt: nodeTxtResolver(),
})

// The server that hosts a channel or account address.
const lobby = await sv.serverFor('publiclobby@sloppyvoice.com')

// An alias of the home server gives the home client, not a remote session.
const alias = await sv.server('chat.sloppyvoice.com')
console.log(alias === (await sv.home())) // true when chat.sloppyvoice.com is an alias

// Look before you connect: name, icon and canonical domain for a sign-in screen.
const r = await sv.resolve('guild.sloppyvoice.com')
console.log(r.canonicalDomain, r.baseUrl, r.evidence, r.metadata.name)

for (const s of sv.servers()) console.log(s.domain, s.isHome)
console.log(lobby.isHome)

Domains are converted to lowercase A-labels before anything else (01 §4.1); a string that isn't a domain fails with sdk.invalid_argument, and a valid name that can't be queried, such as an IP address or a special-use name like example.test, fails with discovery.invalid_domain (02 §5.1). Server clients are cached by canonical domain, so server('chat.sloppyvoice.com') and server('sloppyvoice.com') give the same object when one is an alias of the other (02 §8). servers() lists every server client that is open, home first; a closed one is dropped from the list.

home(), server(), serverFor() and resolve() take { signal }. Concurrent calls for one domain share one resolution (02 §5.2 step 3), so aborting stops only your own wait; the shared work is bounded by the 30 s resolution limit (02 §5.5) and the HTTP timeout. A failed call is not cached as a client: the next call resolves again, subject to the negative cache described below.

ServerClient

A ServerClient is one server. Its own members:

Member Meaning
domain The server's canonical domain (02 §5.3). Store and display this, never the alias you typed.
isHome Whether this is the account's home server.
baseUrl The normalized base URL (02 §3.3). Changes only when the client follows a move its pin accepted.
metadata The validated ServerMetadata (02 §7), from the latest cached resolution.
discovery The latest DiscoveryResult, including evidence, stale and pin.
http The HttpClient for this server: base URL, credential, retries and problem mapping (03 §2, §10). Use it for endpoints the SDK has no method for.
tokens The credential this server issued, or null when used anonymously. At a remote server it is a RemoteSessionProvider.
serverClock The clock offset estimate from this server's Date headers (03 §2.3 item 4).
events() The event WebSocket for this server, typed by EventMap.
close() Close the socket and stop background work for this server.

Its resource APIs, one property per resource group:

Area Properties
Account (05) me, devices, bots, profiles, providers, auth
Addresses and discovery (01, 02) addresses, resolve
Communities (09) community, myCommunities, channels, invites
Roles and moderation (10) roles, moderation, bans, reports, auditLog
Messaging (11) messages, reactions, readState, typing, presence, attachments, webhooks
Direct messages (12) dms
Identity and devices (07, 08) identity, pairing, backup, vault
MLS and history (13, 14) mls, keyPackages, history
Calls (15) calls
Notifications (19) notifications, push
Federation (06) federation

Every property is present on every server client, but some only work at the account's home server. A remote server refuses a remote-session token on me, devices, bots and providers with 403 auth.home_session_required (05 §3.2), and myCommunities, notifications, push and the DM index (dms.index, dms.settings, dms.blocks, dms.requests) are kept only at the home server (09 §5.1, 19 §7, §9, 12 §9). Check isHome before you call them.

events() needs a credential: on an anonymous server client it throws sdk.invalid_argument. There is at most one socket per client session per server (03 §5.12 item 1), so a second call returns the same socket and ignores its options. The socket checks /meta before it connects (03 §5.1 item 5), passes discovery.metadata_changed to the resolver (02 §16.1) and, at a remote server, passes federation.session_ended to the session provider (06 §6.8). The Event WebSocket page covers the protocol.

How discovery runs

Every home(), server() and resolve() call goes through one DiscoveryResolver, available as sv.discovery. It runs one of two procedures.

Native clients, bots and servers

With a txt resolver and no homeBaseUrl, the resolver follows 02 §5.2:

  1. Query _sloppyv.<domain> TXT and process the record set (02 §3.4).
  2. If there is no record, or DNS failed temporarily, fetch https://<domain>/.well-known/sloppyv (02 §4.3). A malformed record is an error and never falls back.
  3. Fetch and validate GET {base}/meta (02 §7.4).
  4. Check that the queried domain is in metadata.domains (02 §8), and that the canonical domain resolves to the same base URL (02 §5.3).
  5. Apply the client's pin (02 §10.6), cache the result and return it.

nodeTxtResolver() uses node:dns/promises. It can't see TTLs, DNSSEC status or the negative TTL of NXDOMAIN, so delegations are cached for the 300 s minimum, not_found uses the 300 s default, and no delegation ever gets dnssec evidence. Pass servers to query a validating resolver you trust (02 §3.5); the evidence still won't be dnssec. Set discovery: { wellKnownCheck: true }, or a function of the domain, to run the .well-known agreement check (case W-c), which native clients should do for their home server at sign-in (02 §4.3). Without a publicSuffixList the SDK can't rule out a same-site record, so it skips the check when the record's host shares its last two labels with the domain.

Web clients

Browsers can't send DNS queries. With homeBaseUrl, the resolver follows 02 §5.4: it asks the home server through GET /v1/resolve (without a token), then fetches and validates /meta itself and checks that the queried domain is in domains and that canonicalDomain matches the home server's answer. The home server is trusted for the delegation, as DNS would be, but it never supplies the keys, the domain list or the canonical domain.

A DNS-over-HTTPS resolver, given as txt, is used only when the home server gives no usable answer: a network error, a timeout, a 5xx without a discovery.* problem, or core.unavailable. Any discovery.* answer from the home server, and any other answer such as 429 core.rate_limited, is final for that attempt, because falling back to DoH would bypass the home server's pins exactly when they detect an attack (PD-02-4). Without txt, a home server that gives no usable answer fails the resolution with discovery.server_unreachable. The SDK ships no default DoH endpoint; the one you configure must allow CORS.

import { SloppyVoiceClient, dohTxtResolver, type HomeSessionState, type ServerPinRecord, type ServerPinStore } from '@sloppyvoice/sdk'

/** Pins in origin storage (02 §10.6, "Web clients"). */
class LocalStoragePinStore implements ServerPinStore {
  readonly #prefix = 'sv.pin.'
  async get(domain: string): Promise<ServerPinRecord | null> {
    const v = localStorage.getItem(this.#prefix + domain)
    return v ? (JSON.parse(v) as ServerPinRecord) : null
  }
  async set(pin: ServerPinRecord): Promise<void> {
    localStorage.setItem(this.#prefix + pin.domain, JSON.stringify(pin))
  }
  async delete(domain: string): Promise<void> {
    localStorage.removeItem(this.#prefix + domain)
  }
  async list(): Promise<ServerPinRecord[]> {
    const pins: ServerPinRecord[] = []
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      if (key?.startsWith(this.#prefix)) pins.push(JSON.parse(localStorage.getItem(key)!) as ServerPinRecord)
    }
    return pins
  }
}

const stored = sessionStorage.getItem('sv.session')
const session: HomeSessionState | null = stored ? (JSON.parse(stored) as HomeSessionState) : null

const sv = new SloppyVoiceClient({
  client: 'web-client/2.3',
  home: 'sloppyvoice.com',
  homeBaseUrl: 'https://chat.sloppyvoice.com/server',
  txt: dohTxtResolver({ url: 'https://dns.example.net/dns-query' }),
  discovery: { pins: new LocalStoragePinStore() },
  auth: session && {
    session,
    options: { persist: (s) => sessionStorage.setItem('sv.session', JSON.stringify(s)) },
  },
})

const home = await sv.home()
console.log(home.metadata.name)

Sign-in itself, and where a stored session comes from, is covered by Accounts and sign-in. Through /v1/resolve the result carries the evidence the home server reported. On the DoH path a web client records only same-site, wellknown or dns-only evidence, never dnssec, because it can't validate DNSSEC itself (02 §5.4 step 3).

Caching

The resolver caches each result while both halves are fresh (02 §13.1):

  • a TXT delegation for the smallest TTL in the DNS answer, clamped to 300 s to 86,400 s;
  • a .well-known delegation and the metadata for their max-age, else Expires, else 3,600 s, clamped the same way (at most 300 s for a .well-known delegation used after a DNS failure);
  • the metadata is revalidated with If-None-Match when it has an ETag;
  • a delegation from /v1/resolve until its expiresAt, at most 86,400 s.

After a temporary failure (discovery.dns_failure, discovery.server_unreachable) an expired result is still returned for up to 7 days with stale: true (02 §13.2), so a server that is down for a while doesn't make the client forget it. A definitive failure such as discovery.not_found or discovery.domain_not_served drops the cached result and creates a negative entry: 300 s for most errors, the DNS negative TTL clamped to 60 s to 900 s for not_found, and 30 s doubling to 300 s for temporary failures (02 §13.3). Until the entry expires, the same domain fails at once with the same error, or, after a temporary failure, returns the stale result. discovery.invalid_domain is never cached.

The resolver refreshes early on the triggers of 02 §13.4: a discovery.metadata_changed event received on a server client's event socket (/meta only, after a random wait of up to 30 s, or 5 s when urgent), and a network or TLS failure on the base URL or a 404 or 410 without a problem object (delegation, then metadata). Each refresh happens at most once per 60 s per domain. Server clients report those transport failures to the resolver themselves.

To act on caches directly, use the resolver:

Method Use
resolve(domain, { userRetry: true }) A person pressed "Try again": bypass a negative entry, at most once per 10 s per domain (02 §13.3).
recheck(domain) Bypass every cache and send Cache-Control: no-cache (02 §5.2 step 2).
cached(domain) The cached result without any I/O, or null.
invalidate(domain) Drop every cached value for the domain, keeping its pin.
forget(domain) Drop the pin too; the next contact is a first use.
lookupViaHome(domain) Ask only the home server's /v1/resolve, for flows that must not contact a server yet, such as a message request before Accept (02 §5.8). Needs the resolver's home option, which homeBaseUrl sets.

Pins

A client must keep a pin for every server where it holds a session token (02 §10.6). The pin records the canonical domain, base URL, secure flag, evidence and keys from first contact. A later resolution that changes them is accepted only under the change rules of 02 §10.2: for example, a new base URL needs strong evidence or a KeyRotation bound to that URL, and a secure downgrade is never accepted.

By default the client keeps pins in a MemoryServerPinStore, which is lost on restart. That is enough for a bot that signs in fresh on every start. When you restore credentials (a stored sign-in session or remoteSessions), pass a durable ServerPinStore in discovery.pins. The constructor refuses restored credentials when discovery.pins is not set (it can't tell whether the store you pass is durable), because a pin that vanishes on restart turns every start into a first use, and a stored token would then follow any spoofed delegation.

What the pin decides shows up in DiscoveryResult.pin:

pin Meaning
created First contact; a new pin was stored.
unchanged The result matches the pin.
updated The pin accepted a change under 02 §10.2, such as new keys or a new base URL. If the base URL changed, server clients and their tokens follow the move (02 §15.6); you are not signed out.
none Pinning is off: the resolver has no pin store, or its shouldPin option excludes the domain.

A change the pin rejects fails with discovery.peer_suspended: the server is treated as temporarily unreachable, no stale result is served, and the domain keeps failing with that error until its negative entry expires (30 s, doubling to 300 s), when the next call resolves afresh. The resolver calls onPinConflict with a ready-made diagnostic; the SDK doesn't send it, so report it to your home server as a pin_conflict diagnostic with CallsApi.sendDiagnostics (15 §14.4). Never show a security warning for it (02 §5.7). For servers other than the home server, recoverPin(domain) adopts the home server's /v1/resolve answer when it is not stale and the client's own /meta check agrees; like lookupViaHome, it needs the resolver's home option. A rejected change of the home server itself has no automatic recovery.

Discovery errors

Discovery failures are SloppyVoiceErrors with discovery.* codes (02 §17), plus core.unsupported_version when every protocol version the server lists is newer than the SDK's (02 §7.4 step 5). Show them as 02 §5.7 says: "no server here" for a missing or invalid domain, "doesn't host that address" for domain_not_served, "not set up correctly" for configuration errors, "update required" for core.unsupported_version, and "unreachable for now" for everything else. discoveryErrorPresentation maps a code to one of these categories.

import { SloppyVoiceClient, discoveryErrorPresentation, isSloppyVoiceError } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

const sv = new SloppyVoiceClient({ client: 'lookup/1.0', txt: nodeTxtResolver() })

function describe(e: unknown, domain: string): string {
  if (!isSloppyVoiceError(e)) return `Can't reach ${domain} right now. Retrying.`
  // A string that isn't a domain at all fails locally, before discovery runs.
  const code = e.code === 'sdk.invalid_argument' ? 'discovery.invalid_domain' : e.code
  switch (discoveryErrorPresentation(code)) {
    case 'no_server':
      return `There's no Sloppy Voice server at ${domain}. Check the spelling.`
    case 'not_hosted':
      return `${domain} doesn't host that address.`
    case 'misconfigured':
      return `The server for ${domain} isn't set up correctly right now.`
    case 'update_required':
      return `Update the app to use ${domain}.`
    case 'unreachable':
      return `Can't reach ${domain} right now. Retrying.`
  }
}

const domain = 'guild.sloppyvoice.com'
try {
  const r = await sv.resolve(domain)
  console.log(`${r.metadata.name} (${r.canonicalDomain})${r.stale ? ', last known' : ''}`)
} catch (e) {
  console.log(describe(e, domain))
} finally {
  await sv.close()
}

The exact user-facing copy belongs to document 20; the strings above only show which errors share a message.

Remote sessions

Your credential is only ever sent to the server that issued it (03 §3.2 rule 3). A home-session token never goes to a remote server, a bot token never leaves the bot's home server (05 §15.4), and a remote server's token never goes anywhere else. Otherwise any server you visit could replay your token at your home server or at a third server and act as you.

So when you call server() for a server that isn't your home, the client builds a RemoteSessionProvider for it. The first request that needs a token runs 06 §6.10:

  1. Resolve the remote domain and learn its canonical domain.
  2. Ask the home server for a HomeAssertion with that audience: POST /v1/federation/assertions with your home credential. An assertion is single-use and lives at most 300 s (06 §4.3).
  3. Present it to the remote server: POST /v1/federation/sessions, with a DeviceProof when the device is enrolled (06 §5). The remote server verifies the assertion against your home server's published keys and issues its own Bearer token, valid for 3,600 s (06 §6.4).

The assertion proves to the remote server who you are without giving it anything it could reuse elsewhere: it names exactly one audience and can be used once. Bots work the same way: the bot token stays at the home server, and the bot gets remote sessions like any account (03 §3.1).

From then on the provider keeps the session alive without asking anyone anything (06 §6.10 rule 8):

  • It renews at a random moment between expiresAt − 600 s and expiresAt − 300 s, and tells the event socket to send session.reauth with the new token (03 §5.13).
  • After a 401 from the remote server it creates a new session and retries the request once (03 §3.3). You see sign_in only when the home server also refuses, because only then is your home session really gone. A remote server that keeps asking for sign-in gets one new session per 60 s; within that window the request fails with a retryable core.unavailable instead (03 §10.2).
  • While the home server is unreachable it retries every 60 s. Once fewer than 900 s remain and two attempts at least 30 s apart have failed, it asks the remote server to extend the session (06 §6.6, §6.10 rule 5).
  • It follows the error table of 06 §6.10 rule 7, including the stop on federation.blocked, account.suspended and security.upgrade_required.

Read the state through tokens and the client's callbacks:

import { RemoteSessionProvider, SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: 'sloppyvoice.com',
  auth: botToken(process.env.SV_BOT_TOKEN!),
  txt: nodeTxtResolver(),
  onRemoteStatus: (domain, status) => console.log(`${domain}: ${status}`),
  onRemoteDiagnostic: (domain, d) => console.log(`${domain}: ${d.phase} failed with ${d.code}`),
})

const guild = await sv.server('guild.sloppyvoice.com')
if (guild.tokens instanceof RemoteSessionProvider) {
  const session = await guild.tokens.ensure() // create it now instead of on the first request
  console.log(session.sessionId, session.state, session.expiresAt, session.secureAccess)
}

RemoteSessionStatus has the values your status line needs: idle (no session yet), active, extended, home_unreachable, remote_unreachable, unreachable, sign_in_required, blocked, stopped and ended (06 §15). The provider's status and lastError hold the current values; never show lastError codes to people.

When a device becomes enrolled, call renew() on each remote provider so its sessions gain secure access at once (06 §6.10 rule 6).

Keeping remote sessions across restarts

A native client that restarts often can restore its remote sessions instead of asking for new assertions every time. Store each one in the platform's secure storage, together with the base URL that issued it:

import { SloppyVoiceClient, botToken, type PersistedRemoteSession, type ServerPinStore } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

// Your application's secure storage and durable pin store.
declare const pins: ServerPinStore
declare function loadSecret(name: string): Record<string, PersistedRemoteSession>
declare function saveSecret(name: string, value: Record<string, PersistedRemoteSession>): void

const saved = loadSecret('remote-sessions')

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: 'sloppyvoice.com',
  auth: botToken(process.env.SV_BOT_TOKEN!),
  txt: nodeTxtResolver(),
  discovery: { pins },
  remoteSessions: saved,
  onRemoteSession: (domain, record) => {
    if (record) saved[domain] = record
    else delete saved[domain]
    saveSecret('remote-sessions', saved)
  },
})

onRemoteSession is called with every new, renewed or rebound session, and with null when one is dropped. A restored session is sent only to the base URL it is bound to, or to a new one this client's pin accepted as a move (02 §10.6 token binding). If discovery now gives another base URL that the pin didn't accept, the stored token is dropped unsent and a new session is created there.

Closing

Three levels of shutdown, from least to most:

Call Effect
server.close() Closes that server's event socket and stops its remote-session timers. The next server() call for the domain builds a new client. Pass { discardPositions: true } on sign-out to forget stream positions (03 §7.3 rule 5).
sv.close() Closes every server client and, when the client built its own resolver, the resolver's timers. Any later home() or server() call throws sdk.invalid_argument.
provider.signOut() Ends a remote session at its server with reason signed_out (06 §6.5) and stops creating new ones there until provider.reset(), even if the server client is closed and built again.

Closing does not end sessions at the servers. When the person signs out of the device, sign out of every remote server and then of the home session:

import { HomeSession, RemoteSessionProvider, type SloppyVoiceClient } from '@sloppyvoice/sdk'

export async function signOutEverywhere(sv: SloppyVoiceClient): Promise<void> {
  const servers = sv.servers()
  for (const s of servers) {
    if (s.tokens instanceof RemoteSessionProvider) await s.tokens.signOut().catch(() => {})
  }
  for (const s of servers) await s.close({ discardPositions: true })
  const home = servers.find((s) => s.isHome)
  if (home?.tokens instanceof HomeSession) await home.tokens.signOut()
  await sv.close()
}

Signing out of the home session revokes the device (05 §14), and a remote server ends that device's sessions only once the revocation reaches it (06 §6.8). Until then each stays usable, so the client ends each one itself first, as 06 §6.5 asks. A bot signs out with AuthApi.logout and the Bot scheme, which revokes that bot token's device (05 §14); the owner can also revoke bot tokens at the home server (05 §15.4).