SDK guide
Signing in and tokens
How the SDK gets, stores, refreshes and recovers credentials, from bot tokens to the OAuth sign-in flow, home sessions and remote sessions.
Specification: 02 Discovery, server metadata and server keys, 03 Client transport, envelopes and errors, 05 Accounts, login, sessions, devices and bots, 06 Federation
Every credential the SDK sends comes from a TokenProvider. This page covers the providers the SDK ships with, the OAuth sign-in flow that creates a home session, how that session is refreshed, stored and ended, and what the SDK does by itself when a server answers 401. The protocol side is in Sign-in, accounts and bots and Federation; the rules are in document 05, document 06 and 03 §3.
Token providers
A TokenProvider is the source of the credential for one client session at one server. FetchHttpClient asks it for the Authorization header, EventSocket asks it for the token of session.hello, and both call it back after a 401 or a 4001 close.
| Member | What it does |
|---|---|
scheme |
Bearer for home and remote sessions, Bot for bot tokens (03 §3.1). |
kind |
home, remote, bot or static. It decides how a 401 is recovered (03 §3.3). |
token(signal?) |
The current token, refreshed first if it is about to expire. |
expiresAt() |
When the current token expires, or null for one that doesn't. The SDK doesn't schedule anything from it: the event socket times session.reauth from the server's authExpiresAt (03 §5.13). |
recover(problem, signal?) |
Called after a 401. Resolves true if a fresh token is ready and the request should be retried once, false for a definitive failure, and rejects for a transient one (network, home server unreachable). |
onChange(listener) |
Called with every new token, so open sockets can send session.reauth. Returns an unsubscribe function. |
The SDK has four implementations:
| Provider | kind |
Use it for |
|---|---|---|
| botToken, botTokenProvider | bot |
A bot at its own home server. |
| staticToken | static |
A token you got some other way and manage yourself. |
| HomeSession | home |
A person's session at their home server, from the sign-in flow below. |
| RemoteSessionProvider | remote |
The same person or bot at any other server. SloppyVoiceClient creates these for you. |
Whatever the provider, the SDK sends a token only to the base URL of the server that issued it, and never in a URL (03 §3.2 rules 1 and 3). It never logs tokens, and you must not either (rule 7).
Bot tokens
A bot authenticates with an svb_ token that its owner created, sent as Authorization: Bot <token> (05 §15.4). The token is valid only at the bot's home server. At every other server the bot gets a remote session from a HomeAssertion, exactly as a person does, and SloppyVoiceClient does that without being asked.
import { SloppyVoiceClient, botTokenProvider } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'ping-bot/1.0',
home: 'sloppyvoice.com',
// Throws sdk.invalid_argument unless the value is svb_ + 43 base64url characters (05 §7.4).
auth: botTokenProvider(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
const home = await sv.home() // Authorization: Bot svb_…
const lobby = await sv.serverFor('publiclobby@sloppyvoice.com') // a remote session, Bearer
console.log(home.tokens?.kind, lobby.tokens?.kind) // "bot" "remote"botToken builds the same provider without checking the token format. Prefer botTokenProvider: it refuses an sva_ access token or an svs_ sign-up token passed by mistake, which would otherwise reach the server with the wrong scheme.
A bot token has no refresh token and doesn't expire unless its owner set expiresAt. A 401 for a bot token means it was revoked, rotated past its grace period or expired, so recover() resolves false and the error reaches your code (03 §3.3, "Bot" column). Report it to the bot's operator; retrying is pointless. Bots never use the OAuth flow and can't call /v1/auth/par (05 §15.5).
Static tokens
staticToken wraps a token that you obtained and manage outside the SDK, with scheme Bearer unless you pass 'Bot'. It never refreshes, and a 401 goes straight to the caller. Use it for tests and short scripts; for a person's session use HomeSession, which refreshes and rotates the token family as 05 §7.6 requires.
import { FetchHttpClient, staticToken } from '@sloppyvoice/sdk'
const http = new FetchHttpClient({
baseUrl: 'https://chat.sloppyvoice.com/server',
tokens: staticToken(process.env.SV_ACCESS_TOKEN!),
})
const me = await http.request({ method: 'GET', path: '/v1/me' })
console.log(me)How sign-in works
A person signs in through their home server with OAuth 2.0: the authorization code grant with PKCE S256, optionally with a pushed authorization request, as a public client with no secret (05 §3.1, §6). The home server runs a second, separate leg with the login provider (Google, GitHub, an OIDC provider); your app only ever speaks to its home server and never sees the provider's tokens.
AuthApi is the client side of that flow. Every ServerClient has one as auth, and you can also build one on a FetchHttpClient for the home server's base URL. It needs no token provider, because every call states its credential.
| Step | SDK call | Wire |
|---|---|---|
1. Make a PKCE verifier and state, push the parameters |
auth.beginSignIn(options) |
POST /v1/auth/par |
| 2. Open the authorize URL in a browser | pending.authorizeUrl |
GET /v1/auth/authorize (navigation, never fetched) |
3. Receive the redirect back, check state and iss |
auth.completeAuthorization(pending, callbackUrl, device) |
05 §6.6 |
| 4. Redeem the code | (same call) | POST /v1/auth/token |
| 5. For a new person, create the account | auth.signup(signupToken, body) |
POST /v1/auth/signup |
| 6. Keep the session | HomeSession.fromTokenResponse(…) |
beginSignIn returns a PendingAuthorization: plain JSON holding the issuer, client ID, redirect URI, state, the PKCE verifier and authorizeUrl. It contains the verifier, so don't log it or put it in a URL. Pushing is optional for a login and required for re-authentication, because only a pushed request can carry the session's access token (05 §6.1). The SDK pushes by default; pass pushed: false to get an authorize URL with every parameter in it instead.
Three clocks run during the flow:
- the pushed
request_uriis single use and valid 60 s, so openauthorizeUrlat once (pending.requestUriExpiresAtsays when it lapses, 05 §6.1); - the authorization code is single use and valid 60 s (05 §6.6), and
completeAuthorizationredeems it at once; - the server discards the whole transaction 10 minutes after it starts (05 §6.7).
Before you draw the sign-in screen, read the providers from the home server's metadata: one button per entry of metadata.auth.providers, in the admin's order with the provider last used on this device first, and the entry's id passed as provider (05 §3.3, §8.8). Without provider the server shows its own chooser. registrationPolicyOf and providerAllowsSignup read auth.registration and a provider's signup flag with the spec's defaults for unknown values.
The redirect back
completeAuthorization checks the redirect before it does anything else. The spec requires the client to check that state equals the value it sent and iss equals the base URL it started with, and to discard the response otherwise (05 §6.6), so a mismatch throws sdk.verification_failed and no code is redeemed. A failure redirect throws a SloppyVoiceError whose code is the server's sv_code, for example auth.access_denied when the person pressed Cancel, with the OAuth error and error_description in data. Errors at the token endpoint, such as auth.registration_closed, are thrown the same way (05 §7.8).
For a login, the third argument is required: platform (desktop, web, ios or android), clientSoftware (<product>/<version>, 1–64 printable ASCII characters), and optionally deviceName and sharedComputer (05 §7.3). The server creates the device record from them.
The result is one of:
{ type: 'session' }: an existing account.responseis the full token response withaccountanddevice.{ type: 'signup' }: the external identity isn't linked to any account yet. No device exists; continue with sign-up below.{ type: 'reauth' }and{ type: 'link' }: only for the fresh-authentication and provider-linking flows.
Desktop sign-in
A desktop app uses the client ID urn:sloppyv:client:loopback (LOOPBACK_CLIENT_ID) and a loopback redirect. It listens on 127.0.0.1 (or [::1]) on an ephemeral port for the duration of the flow only, and opens the authorize URL in the default browser (05 §6.8). The redirect URI must use the literal address: localhost is refused (05 §5.2). Embedded web views aren't an option, because the major providers block them.
import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import {
HomeSession,
LOOPBACK_CLIENT_ID,
SloppyVoiceClient,
type HomeSessionState,
type ServerPinStore,
type SessionTokenResponse,
} from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
// Your app provides these.
declare const pins: ServerPinStore
declare function openInDefaultBrowser(url: string): Promise<void>
declare function askForName(suggested: string | undefined, termsUrl: string | undefined): Promise<string>
declare function saveToKeychain(state: HomeSessionState): Promise<void>
const sv = new SloppyVoiceClient({ client: 'my-app/1.0', home: 'sloppyvoice.com', txt: nodeTxtResolver(), discovery: { pins } })
const home = await sv.home() // anonymous: no credential yet
// Listen on an ephemeral loopback port, only for this flow (05 §6.8).
const listener = createServer()
await new Promise<void>((resolve) => listener.listen(0, '127.0.0.1', resolve))
const redirectUri = `http://127.0.0.1:${(listener.address() as AddressInfo).port}/callback`
const callback = new Promise<URL>((resolve) => {
listener.on('request', (req, res) => {
const url = new URL(req.url ?? '/', redirectUri)
if (url.pathname !== '/callback') return void res.writeHead(404).end()
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end('You can close this tab and return to My App.')
resolve(url)
})
})
const provider = home.metadata.auth.providers[0]!.id
const pending = await home.auth.beginSignIn({ clientId: LOOPBACK_CLIENT_ID, redirectUri, provider })
await openInDefaultBrowser(pending.authorizeUrl)
const callbackUrl = await callback
listener.close()
const device = { platform: 'desktop', clientSoftware: 'my-app/1.0', deviceName: 'Work laptop' } as const
const result = await home.auth.completeAuthorization(pending, callbackUrl, device)
let response: SessionTokenResponse
if (result.type === 'session') {
response = result.response
} else if (result.type === 'signup') {
const { suggestedName, termsUrl, inviteRequired } = result.signup
if (inviteRequired) throw new Error('This server needs an invite code to sign up')
const name = await askForName(suggestedName, termsUrl)
response = await home.auth.signup(result.signupToken, {
name,
...(termsUrl === undefined ? {} : { acceptTerms: true }),
...device,
})
} else {
throw new Error(`Unexpected ${result.type} result for a login`)
}
const session = HomeSession.fromTokenResponse(home.auth, pending.clientId, response, { persist: saveToKeychain })
await saveToKeychain(session.state()) // the first state; later refreshes call persist themselves
await sv.close()The anonymous client above uses the same durable pin store you will use once signed in, so the pin made during sign-in is still there on the next start; a client must keep a pin for every server where it holds a session token (02 §10.6).
Mobile apps run the same flow with a metadata-document client ID and a claimed HTTPS redirect or a private-use scheme such as org.example.sloppy:/oauth, through ASWebAuthenticationSession or Custom Tabs (05 §6.8).
Sign-up
When completeAuthorization answers type: 'signup', the person has no account yet. result.signupToken is an svs_ token usable only at POST /v1/auth/signup, and result.signup says what the "Choose your name" screen needs (05 §8.2):
suggestedName: a display-name suggestion from the provider's profile;inviteRequired: the server's registration isinvite, andinviteCodeis required;termsUrl: when present,acceptTerms: trueis required, so link the terms on the screen;providerLabel: "You signed in with Google as …".
auth.signup() sends the token as Bearer to that one endpoint and refuses any other kind of token. It answers the same full token response as a login, so the rest of the code doesn't care which path it took. The local part of the address is derived from name; a taken or reserved local part comes back as an address.* error, and the person picks another name with the same sign-up token, at most 5 attempts per token (05 §8.2, §8.4).
The sign-up token is single use and a lost 201 can't be replayed. On auth.identity_already_linked or auth.signup_token_invalid, restart the login flow from the beginning, which signs in to the account if an earlier attempt created it (05 §8.4). restartsLogin tells you whether an error is one of those two.
Home sessions
HomeSession is one device record and its token family: an sva_ access token that lives 900 s and an svr_ refresh token that rotates on every use (05 §7.5, §7.6). It is a TokenProvider with kind: 'home'.
token()refreshes first when the access token expires withinrefreshMarginMs(default 120 s, the margin 03 §5.13 gives sockets). If the refresh fails transiently while the old token is still valid, the old token is returned.- Refreshes are single-flight. A refresh whose response is lost (a network error, or a retryable answer such as 429) is repeated with the same refresh token inside the server's 30 s retry window (rule 2 of 05 §7.6):
maxRefreshAttemptsattempts in all (default 3), and none later than 25 s after the first. persistis called with the new HomeSessionState after every refresh, before the new token is used. The old refresh token is rotated from the moment the server answers, so a state you fail to store can't be recovered after a restart. An error thrown bypersistgoes to theonErroroption and doesn't fail the refresh.onChangelisteners get every new access token; the SDK's own sockets use it to sendsession.reauth.onEndlisteners learn once that the session is over, andendedsays why.
The session ends on auth.session_revoked, auth.refresh_reused, auth.invalid_grant, auth.invalid_client and account.deleted, and on your own sign-out. It forgets both tokens at once, and token() throws from then on. account.suspended fails the refresh without ending the session (05 §7.6 rule 5).
Starting from a stored session
On the next start, pass the stored state to SloppyVoiceClient as auth: { session, options } (SignInSessionAuth). The client builds the HomeSession itself, refreshes it through the home server's /v1/auth/token, and shares it with every remote session it creates.
import { HomeSession, SloppyVoiceClient, type HomeSessionState, type ServerPinStore } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
declare const pins: ServerPinStore
declare function loadFromKeychain(): Promise<HomeSessionState | null>
declare function saveToKeychain(state: HomeSessionState): Promise<void>
declare function deleteAccountData(): Promise<void>
declare function showSignInScreen(reason: string | null): void
const stored = await loadFromKeychain()
if (!stored) throw new Error('Not signed in')
const sv = new SloppyVoiceClient({
client: 'my-app/1.0',
home: 'sloppyvoice.com',
txt: nodeTxtResolver(),
discovery: { pins }, // required with stored credentials (02 §10.6)
auth: { session: stored, options: { persist: saveToKeychain } },
})
const home = await sv.home()
if (home.tokens instanceof HomeSession) {
home.tokens.onEnd(async (ended) => {
// Revoked elsewhere, refresh token reused, or signed out: 05 §14.1.
await sv.close()
await deleteAccountData()
showSignInScreen(ended.reason)
})
}
const me = await home.me.get()
console.log(me.account.address)The stored state carries baseUrl, the base URL that issued the token family. The SDK sends the tokens only there, or to a new base URL that your pin for the home server accepted as a move; otherwise sv.home() fails with discovery.peer_suspended (data.reason: 'token_binding'), sends nothing, and leaves your stored state alone (02 §10.6, 03 §3.2 rule 3). Don't show the sign-in screen for that error: the spec treats the home server as temporarily unreachable and offers no sign-in prompt (02 §10.6). The check needs pins that survive a restart, so the client refuses stored credentials unless you pass a ServerPinStore as discovery.pins; it can't tell whether your store is durable, so make sure it is.
Right after sign-in you can also pass the HomeSession itself as auth. A provider passed directly skips the binding check, because the SDK can't tell where it was issued; use that form only within the run that created it.
When a session ends because the device was revoked, a secure account has one more step before deleting its keys: mustCheckPublicIdentity says whether to fetch the public IdentityState first (05 §14.1 step 2).
Where tokens live
05 §7.7 sets the storage rules, and they differ by platform.
| Platform | Refresh token | Access token |
|---|---|---|
| Desktop and mobile | The platform's secure storage: Keychain, Android Keystore-backed storage, Windows Credential Manager or DPAPI, libsecret. | In memory only (SHOULD). |
| Web | IndexedDB (SHOULD), under the same non-extractable wrapping key as other secrets for a secure account. Never localStorage or cookies. |
Never localStorage or cookies. |
| Web or desktop in shared-computer mode | In memory only. | In memory only. |
HomeSessionState holds both tokens, and the SDK needs both to restart a session and to adopt another process's refresh, so store the whole object in the place the refresh token belongs. On desktop and mobile that puts the access token in secure storage too, not in memory only as 05 §7.7 recommends. Notification extensions and web service workers must not hold, use or refresh session tokens, because a second refresher races the app and trips reuse detection; they use the fetch token of 19 §9.3 instead.
Several tabs or processes
A refresh token can be presented once. If two tabs or two processes refresh the same session at the same time, the second presentation invalidates the tokens the first one just received, and the next refresh with them counts as reuse, which revokes the device (05 §7.6 rules 2a and 3). Clients must therefore serialize refreshes across everything that shares the session (05 §7.7). Give HomeSession two options for that:
lockruns each refresh exclusively. In browsers, webLocks uses the Web Locks API; elsewhere, supply a lock your processes share. The default only serializes within oneHomeSessionobject.loadreads the newest stored state inside the lock, so a refresh another tab already did is adopted instead of repeated.
Web clients
A web client's client_id is the URL of a Client ID Metadata Document on its own origin, and its redirect URI is an HTTPS URL on that origin (05 §5.1, §5.2). Before navigating to the authorize URL it stores the pending authorization in sessionStorage; on return it checks state and iss, removes the stored values, and redeems the code with a cross-origin fetch (05 §6.8). Tokens never go in URLs, and the implicit flow is not allowed.
import { AuthApi, FetchHttpClient, HomeSession, webLocks, type HomeSessionState, type PendingAuthorization } from '@sloppyvoice/sdk'
declare function idbGet(key: string): Promise<HomeSessionState | null>
declare function idbPut(key: string, state: HomeSessionState): Promise<void>
const auth = new AuthApi(new FetchHttpClient({ baseUrl: 'https://chat.sloppyvoice.com/server' }))
const clientId = 'https://app.example.org/client-metadata.json'
const redirectUri = 'https://app.example.org/oauth/callback'
export async function startSignIn(provider: string): Promise<void> {
const pending = await auth.beginSignIn({ clientId, redirectUri, provider })
sessionStorage.setItem('sv.pending', JSON.stringify(pending))
location.assign(pending.authorizeUrl) // top-level navigation
}
export async function finishSignIn(sharedComputer: boolean): Promise<HomeSession> {
const raw = sessionStorage.getItem('sv.pending')
sessionStorage.removeItem('sv.pending')
if (!raw) throw new Error('No sign-in in progress')
const pending = JSON.parse(raw) as PendingAuthorization
const callbackUrl = new URL(location.href)
history.replaceState(null, '', '/') // the code leaves the address bar
const result = await auth.completeAuthorization(pending, callbackUrl, { platform: 'web', clientSoftware: 'my-web-app/1.0', sharedComputer })
if (result.type !== 'session') throw new Error(`Handle ${result.type} as on the desktop`)
const session = HomeSession.fromTokenResponse(auth, clientId, result.response, {
persist: (s) => idbPut('sv.session', s), // never called in shared-computer mode
lock: webLocks('sv.session.refresh'),
load: () => idbGet('sv.session'),
})
if (sharedComputer) {
addEventListener('pagehide', () => session.signOutOnPageHide())
} else {
await idbPut('sv.session', session.state())
}
return session
}Shared-computer mode is the unchecked "This is a shared or public computer" box on the sign-in screen of web and desktop clients (05 §12.6). When it is on, the session's state has sharedComputer: true, persist is never called, and the server revokes the device 12 hours after its last activity. signOutOnPageHide() sends a best-effort POST /v1/auth/logout with keepalive: true and ends the session at once, so a reload needs a new sign-in; it is synchronous so it can run inside the pagehide handler.
A web app that can't query DNS passes its home server's base URL to SloppyVoiceClient as homeBaseUrl, which selects web discovery through {home}/v1/resolve (02 §5.4). In browsers the SDK sends every request with credentials: 'omit', because no cookie or other ambient credential may authorize an API request (03 §3.2 rule 2).
Server-side code
Code that runs unattended on a server, such as a bot, an integration or a moderation tool, signs in as a bot with a bot token (05 §15), not as a person. There is no confidential-client variant of the sign-in flow: leg A has only public clients (05 §3.1).
- Keep the token in your secret store, out of URLs and out of logs (03 §3.2 rules 1 and 7).
- Outside browsers the SDK sends
User-Agent: <client> sloppyvoice-sdk/<version>when theclientoption has the form<product>/<version>, andsloppyvoice-sdk/<version>alone otherwise (03 §2.3 item 6). - After a lost response to a token-issuing request, the owner tool lists the bot's tokens and revokes the one it doesn't know, because a bot token is shown only once (05 §15.4). Bot token management is
ServerClient.bots.
Fresh authentication
Some operations need a recent sign-in: signing out other devices, revoking another device, linking or unlinking a provider, deleting the account, and creating bot tokens, among others. The server refuses them with 403 auth.reauth_required when the session's authAt is older than the operation's limit, 10 minutes for most (05 §9.1). session.isFresh() predicts the answer from the device clock; the server decides.
The fix keeps the device and its refresh token and only renews authAt (05 §9.2): session.beginReauth() pushes a request with intent=reauth and the current access token, you open authorizeUrl exactly as for a sign-in, and session.completeReauth() adopts the new access token. Then retry the original request once.
import { HomeSession, isSloppyVoiceError } from '@sloppyvoice/sdk'
declare const session: HomeSession
declare const redirectUri: string
declare function runBrowserLeg(authorizeUrl: string): Promise<URL>
async function signOutEverywhereElse(): Promise<string[]> {
try {
return (await session.signOutOthers()).revoked
} catch (e) {
if (!isSloppyVoiceError(e, 'auth.reauth_required')) throw e
const pending = await session.beginReauth({ redirectUri })
await session.completeReauth(pending, await runBrowserLeg(pending.authorizeUrl))
return (await session.signOutOthers()).revoked
}
}
console.log(await signOutEverywhereElse())Remote sessions
A home access token is valid only at the home server. At every other server the account needs a remote session: the home server signs a HomeAssertion for that server, the client presents it to POST /v1/federation/sessions, and the remote server issues its own token, valid for one hour (06 §4, §6.4). SloppyVoiceClient gives each non-home server a RemoteSessionProvider that does all of this the first time a request needs it.
The provider follows 06 §6.10 without asking the user anything:
- it creates the session lazily, with at most one creation request in flight per server;
- it renews at a random moment between 600 s and 300 s before
expiresAtwith a fresh assertion, and itsonChangelisteners sendsession.reauthon that server's socket; - when the home server is unreachable it retries every 60 s and, once fewer than 900 s remain and at least two attempts 30 s or more apart have failed, asks the remote server to extend the session;
- it handles
federation.session_endedfrom the socket: withretry: trueit creates a new session (at most 3 times per 10 minutes), otherwise it stops.
An enrolled device of a secure account also signs a DeviceProof with every session request (06 §5); pass its signer and DeviceCertificate as device. When a device becomes enrolled, call renew() on each remote provider so the sessions gain secure access at once (rule 6).
Remote session tokens are stored like home tokens, in secure storage (06 §6.10 rule 8). Use onRemoteSession to save each new or renewed session together with the base URL it is bound to, and remoteSessions to hand them back on the next start:
import { SloppyVoiceClient, type HomeSessionState, type PersistedRemoteSession, type ServerPinStore } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
declare const pins: ServerPinStore
declare const stored: HomeSessionState
declare const remoteStore: {
all(): Promise<Record<string, PersistedRemoteSession>>
put(domain: string, record: PersistedRemoteSession | null): void
}
declare function showStatusLine(domain: string, status: string): void
const sv = new SloppyVoiceClient({
client: 'my-app/1.0',
home: 'sloppyvoice.com',
txt: nodeTxtResolver(),
discovery: { pins },
auth: { session: stored },
remoteSessions: await remoteStore.all(),
onRemoteSession: (domain, record) => remoteStore.put(domain, record), // null: forget it
onRemoteStatus: (domain, status) => showStatusLine(domain, status),
})
const lobby = await sv.serverFor('publiclobby@sloppyvoice.com')
console.log((await lobby.channels.list()).items.length)A restored session is sent only to the base URL it is bound to, or to one your pin accepted as a move; otherwise the SDK drops it, reports null through onRemoteSession, and creates a new one. onRemoteStatus reports RemoteSessionStatus values such as home_unreachable, extended, blocked and sign_in_required, for the status line of 06 §15. Never show lastError codes to the user.
Signing out
Signing out revokes this device at the home server (05 §14). Do it in this order:
- End the remote session at every server you used (
DELETE /v1/federation/sessions/current, 06 §6.5). A provider that was signed out stays stopped, even if the same SloppyVoiceClient creates the server client again. - Close each server client with
discardPositions: true, because stream positions belong to the session (03 §7.3 rule 5). - Sign out the home session.
signOut()first refreshes an access token that has expired or is withinrefreshMarginMsof expiring, because the server answers 204 to any token forscope: current(03 §3.2 rule 8(b)) and only a valid token actually revokes the device. The session ends locally even if the request fails; the request's error is rethrown so you know the server may not have heard. - Delete the stored tokens, the account's keys and cached content, and show the sign-in screen.
import { HomeSession, RemoteSessionProvider, SloppyVoiceClient } from '@sloppyvoice/sdk'
declare function deleteAccountData(): Promise<void>
export async function signOut(sv: SloppyVoiceClient): Promise<void> {
const home = await sv.home()
for (const server of sv.servers()) {
if (server.tokens instanceof RemoteSessionProvider) await server.tokens.signOut().catch(() => {})
if (!server.isHome) await server.close({ discardPositions: true })
}
await home.close({ discardPositions: true })
try {
if (home.tokens instanceof HomeSession) await home.tokens.signOut()
} finally {
await sv.close()
await deleteAccountData()
}
}A bot signs out its own device the same way with auth.logout({ scheme: 'Bot', token }); it can't use scope: others (05 §15.5). Signing out the account's last enrolled device has a confirmation the spec requires, covered in Secure accounts.
What happens on a 401
You don't handle a 401 yourself unless recovery fails. FetchHttpClient calls recover() on the request's provider once and, if it resolves true, retries the request once with the new token, whatever the method, because a 401 means the server didn't process it (03 §3.3). A request with a streaming body can't be replayed and isn't retried. What recover() does depends on the provider:
| Answer | Home session | Remote session | Bot or static token |
|---|---|---|---|
core.token_expired |
Refresh, retry once. | Create a new session from a fresh assertion, retry once. | Error thrown. |
core.unauthenticated |
Try one refresh, retry once. If the refresh is refused for good (for example auth.refresh_reused), the session ends (onEnd runs) and the 401, with userAction: 'sign_in', is thrown; any other refresh failure, such as a network error or account.suspended, is thrown as it is. |
Create a new session, at most once per 60 s per server. Within that window the SDK throws a retryable core.unavailable with userAction: 'wait', never the remote server's sign_in. |
Error thrown. |
auth.session_revoked, auth.refresh_reused |
The session ends: onEnd runs and the error is thrown. |
— | Error thrown. |
federation.session_ended |
— | With data.retry: true, a new session (3 per 10 minutes); otherwise the provider stops and the error is thrown. |
— |
A remote server can't send your user to the sign-in screen. Only the home server's answer may do that (03 §10.2 scope rules 1 and 2), so on any server client other than the home, the SDK reports a sign_in problem with userAction: 'wait' and keeps the server's own value in error.problem.userAction. If the home server itself can't issue an assertion because the home session is gone, the remote provider throws the home server's error, and that one does carry sign_in. The rule for your UI is therefore simple: show the sign-in screen when an error's userAction is sign_in, or when the home session's onEnd runs.
The event socket follows the same rules. After every new token it sends session.reauth in-band without reconnecting, and before the authentication deadline it asks the provider for a fresh token (03 §5.13). On a 4001 close it calls recover(); if that resolves false or rejects with a final error, the socket's lifecycle emits stopped with reason unauthenticated, and a transient rejection is retried on the normal reconnect schedule. The Event WebSocket page has the full close-code table.