equinox is StrafeChat's Go/Fiber backend: the REST API plus stargate, the realtime
WebSocket gateway (its own binary under cmd/stargate, sharing ScyllaDB and Redis with
the API). If you only have this repo checked out, read this whole file before making
changes — it's self-contained. The full project (this repo, the web client, object
storage, deployment) is normally developed side by side; if you have that workspace too,
its root AGENTS.md has the complete picture.
StrafeChat is a Discord-alternative built around: privacy (minimum data collection, no
trackers, no silent telemetry), real end-to-end encryption (an actual Double
Ratchet/Megolm, not a static-key stand-in — the E2EE layer is mid-overhaul toward
vodozemac; see internal/modules/devices), federation (independent instances talk
over signed HTTP, see docs/FEDERATION.md), self-hosting (env-var configuration,
docker-compose.yml, deploy/), and client customization. Don't trade any of these
away for convenience — flag the conflict instead.
We reuse Discord's interaction model, never its names. Use these everywhere — schema, Go identifiers, error strings, docs:
| Discord term | Our term |
|---|---|
| Server / Guild | Space (spaces module, SpaceID) |
| Channel | Room (rooms module; a space's rooms are space_rooms) |
| Category | Section — not built yet; use this name when it is |
| DM | PM (RoomType 1 = PM, 2 = group PM) |
| AFK channel | AFK room in code is fine; user-facing copy says "inactive voice channel" |
| Server Widget | New copy says "space widget"; existing widget_* fields can stay as-is |
- Module layout:
internal/modules/<domain>/{model.go, repo.go, service.go, handler.go}. A domain that outgrows one file splits by feature, not by layer:service_invites.go,handler_invites.go,service_emoji.go, etc., all extending the sameService/Handlerstruct declared in the base file. Mirror this when a module grows (seespaces/andmessages/for the pattern). - Migrations:
migrations/NNN_description.cql, zero-padded 3-digit prefix, applied in lexicographic filename order bycmd/migrate(which tracks what it's run inschema_migrations). Additive-only by default — a destructive migration needs a loud comment explaining why. Never replay an already-applied migration against a live keyspace;019drops and recreatesdevice_keys, and replaying it once already destroyed real E2EE key material.cmd/migraterefuses an untracked keyspace unless given-adopt— never bypass that check. - Permissions: the full Discord-style bitmask lives in
internal/modules/permissions/bits.go. Check withpermissions.Has(perms, permissions.PermX); resolve effective permissions through each service's ownauthorize()/EffectiveChannelPermissionshelper rather than hand-rolling a check. Some bits (e.g.PermAddReactions,PermUseExternalEmojis) are pre-declared ahead of the feature that enforces them — checkbits.gobefore assuming a permission doesn't exist yet. Bits 31 and up (Manage Webhooks 31, Masquerade 32) are past what a client doing 32-bit bitwise maths can hold, so every endpoint that writes a permission value (role create/update, room role/user overrides, the OAuth2botauthorize) decodes it as apermissions.Input: a decimal string is the full value (known bits only, else 400unknown_permission_bits), a JSON number is the legacy form - only its low 31 bits count and the stored value's bits 31+ are kept (Input.Resolve(stored)), so an old client saving a role can never strip a bit it cannot see. Responses stay numbers (exact below 2^53). Federation forwards (role.create,role.update,override.put,bot.install) carry the number (low 31 bits, all an older origin reads) plus a*_fulldecimal string that a current origin prefers (federation/perm_wire.go). A new write path takespermissions.Input, never a bare int64. - Audit log: every moderator-facing mutation (kick, ban, role/room/emoji/invite
changes) calls
s.audit(ctx, spaceID, actorID, ActionType, targetID, changes, reason)(internal/modules/spaces/audit.go) — best-effort, logs on failure, never blocks the request. High-frequency, non-moderation actions (reactions, typing, read receipts) deliberately skip this. - Realtime events: the scoped helpers in
internal/stargate/publish_scoped.gopublish to Redis, which every Stargate instance fans out to subscribed WebSocket clients as anop:3 EVENTframe:PublishToRoom(ctx, redis, stargate.InRoom(room.SpaceID, roomID), "EVENT_TYPE", data, region)for a room's channel,PublishToSpaceChannel(..., stargate.InSpace(spaceID), ...)for a space's own,PublishToUserIn/PublishToUsersInfor an event about a space or room sent to users' own channels. The scope is what the frame'sspace_id/room_idsay (and a map payload gets them too); the channel stays the routing. An event that gives its recipients a channel (SPACE_CREATE with itsrooms, ROOM_CREATE, SPACE_ROOM_CREATE, THREAD_CREATE, joining a thread) names it withScope.Subscribing(...): the gateway subscribes every socket the event reaches before it reads the next message, then checks a per-user grant off the receive loop (stargate/grant.go). Publish such an event right after the write and before anything else about the change (a join notice, SPACE_MEMBER_ADD), and give any new way of gaining access one. PlainPublishToUseris for account-only events;PublishToSpaceis legacy and a test keeps its callers at zero. Event types areSCREAMING_SNAKE_CASEverbs (SPACE_UPDATE,MESSAGE_REACTION_ADD).docs/STARGATE.mddocuments the READY payload shape and every event type — keep it updated when you add one. - Error handling: define sentinel errors per service (
ErrXNotFound,ErrForbidden, ...) and map them to HTTP status in one central switch per module (seespaceErrorinspaces/handler.go,reactionErrorinmessages/handler_reactions.go) instead of hand-rolling the mapping in every handler. IN ?lists go throughdb.Chunks. ScyllaDB refuses a query whose partition-key or clustering-keyINlist holds more than 100 values (db.MaxINValues). A batched read over a list that grows with an account (its rooms, the people in them, its spaces) that skips the chunking works in tests and then fails outright for whoever crosses 100 first. It did: past 100 rooms,ListRoomsfailed and READY went out with no PMs, friends or unread state for that one account.- Federation hooks: services that touch cross-instance state implement a small
Federatorinterface (AfterMessageCreated, etc.) — calls are best-effort and must never block or fail the local request. - Fiber gotcha:
UnescapePathis off (the default) — a route param that can contain non-ASCII (e.g. a unicode emoji) arrives atc.Params()still percent-encoded. Decode it explicitly withurl.PathUnescapein the handler; don't flip the app-wide config. - Background goroutines go through
internal/safego(safego.Gofor fire-and-forget,safego.Runinside a WaitGroup worker). Fiber's recover middleware only covers the request goroutine; a barego func()that panics takes the whole API process down. - Email (
internal/mail+auth/service_email.go): the API only ever speaks SMTP to one configured server (SMTP_HOST; the compose deployment bundles a send-only maddy relay, seedeploy/docs/EMAIL.md) - never direct-to-MX, never a provider API. The mails are the verification link, the password-reset link, and the four email-change mails (email_change_confirmlink to the new address,email_change_takento a new address that already has an account,email_change_requested/email_change_donenotices to the old address, which carry the new one only masked byauth.MaskEmail). Verify and reset are 32-byte tokens stored hashed in Redis with a TTL (24 h / 1 h) together with the address and the time they were issued; a reset is burned withGETDEL, a verify is not (mail scanners prefetch links), and redeem re-reads the account uncached and refuses a token older than the account's last address change (email:changed:<uid>). Login refuses an unverified account only whenEMAIL_VERIFICATION=true, after the password check (so nothing leaks to a stranger), and re-sends the link under a one-a-minute cooldown. Forgot-password answers 200 for every well-formed address and sends off the request goroutine - a synchronous SMTP round trip would be a timing oracle for which addresses exist. A user loaded through the cache has noPasswordHash(seecached_user_repo.go); never branch on it afterGetByID. - Addresses: one validator, one mover, one event.
auth.NormalizeEmailis the only validator for an address about to be claimed (registration, the self-service change, the admin tool). It refuses a domain IDNA's lookup mapping would fold onto another (yopmail.com, a zero-width character,yopmail.com。, anxn--A-label): relays deliver those to the folded domain, so they would dodge the blocklist and claim a second index key for one inbox. Login and forgot-password keep plainToLower(TrimSpace)so a legacy address can still sign in. Mail errors never name the recipient (mail.SMTP.Sendscrubs go-mail's), so logging one next to auser_idstays address-free. An address moves only throughauth.ApplyEmailChange(per-user Redis lock, the LWTUserRepository.ChangeEmailthat writesemail+verified_emailin one conditional statement and releases the old claim only if it is still the account's, the revival marker,USER_EMAIL_UPDATE); never callChangeEmaildirectly. The address is never inUSER_UPDATE,broadcastUserProfileor anything federation sends - only in the self-onlyUSER_EMAIL_UPDATEonstargate.PublishToUser. The self-service change (/users/@me/email*,auth/service_email_change.go) needs a person's session, the password and the second factor (TOTP or a recovery code), waits for a link opened from that same session when mail is on, and revokes no sessions. - Account deletion (
instance/account_delete.go) and identity by id. An instance administrator deletes a local account or bot (GET /instance/users/:id/deletion-preview, thenDELETE /instance/users/:idwith the exact username): access is cut first (sessions, bot token,SESSION_REVOKED {"reason":"deleted"}), everything that was only the account's goes through each module's own leave / unfriend / revoke path (owned spaces only withtake_down_spaces, owned applications and their bots only withdelete_applications; a space owned on another instance always blocks), peers getPOST /users/delete, and lastUserRepository.DeleteAccountremoves theusersrow with itsusers_by_usernameandusers_by_emailclaims in one logged batch, so the name and address are free at once. Messages stay and serialize with adeleted: trueplaceholder author; a 1:1 PM keeps the deleted participant (so the partner's client never takes it for Notes) and refuses sends and calls (recipient_deleted). A developer deleting their application deletes its bot account through the same pipeline. On a peer, a deleted remote account's shadow becomes a tombstone (users.deleted_at, row andusers_by_remotekept, never resurrected). Every step is idempotent and audited ininstance_audit_log. Two rules follow from it: never key anything by username - identity is the snowflake id / FID everywhere, and the one handle-keyed cache,user:name:<name>, is purged on delete and on every new claim (CachedUserRepository.Create); and beware the zombie row: an `UPDATE users SET x = x- ...
(or any blindSET) on a deleted id recreates a partial row, because a Cassandra UPDATE is an upsert - read the row first, or only remove from sets.DeleteAccount` runs a sweep 20 s later that removes such a row again (never touching claims that are someone else's now).
- ...
- Auth is the
Authorizationheader only — no cookie, no?token=query parameter. The header carries one of three credentials, all resolved bymiddleware.RequireAuth: a sessionBearertoken; an OAuth2Beareraccess token (tried when the token is not a live session, its granted scopes recorded inLocals[middleware.LocalsKeyScopes]and gating scope-limited fields such as the account email in/users/@me); or aBot <token>bot-account token. Theapplications/oauthmodules inject their resolvers at startup withmiddleware.SetBotResolver/SetOAuthResolver, so the middleware never imports them (they importauth, which would cycle). The WebSocket gateway is the one exception (browsers cannot set headers on a WebSocket), which is whySTARGATE_ALLOWED_ORIGINSis required whenever federation is on — without an origin check, any site could open an authenticated gateway connection in a signed-in user's name. - Developer platform (
internal/modules/applications+internal/modules/oauth): OAuth2 applications and bot accounts, modelled on Discord. An application owns redirect URIs, a hashed client secret, abot_publicswitch and optionally a bot user (anauth.UserwithBotset, a syntheticbot+<id>@bots.invalidemail so it never collides on the empty-email login key, and the application's id as its user id so an install link needs no lookup). Client secrets and bot tokens are hashed at rest with the session-token scheme (hex(sha256(hex-decoded raw))) and shown exactly once at mint/reset; a bot token reset publishesSESSION_REVOKEDso the gateway drops the bot.oauthis the authorization server: authorization-code grant (HTTP Basic or body client auth, form or JSON), scopesidentify/email/spaces/spaces.join/bot, single-use codes, one live access+refresh pair per (user, app) - refresh and re-authorisation replace it, so a grant revoke is total - RFC 7009 revoke, andGET /oauth2/@me. Scopes are enforced by the middleware:RequireAuthrefuses OAuth2 tokens with403 insufficient_scope; only routes wrapped inRequireAuthScoped(...)(GET /users/@me,GET /users/@me/spaces,GET /oauth2/@me) admit them, so a new endpoint is closed to third-party apps unless it opts in. Thebotscope installs the bot into a space the consenting user manages (spaces.Service.InstallBot: owner, Administrator or Manage Space; permissions masked to what they may grant) with a managed role (space_roles.bot_id, position 1, undeletable, unassignable, removed with the bot);spaces.joinlets a bot with Create Invite add an authorising user (PUT /spaces/:id/members/:user_id). Bots use the gateway withAuthorization: Boton the handshake (header only) and are auto-subscribed to everything in READY (ReadyData.ChannelIDs), and to what they gain later by the same grants as everyone (a bot installed while connected hears the space at once). The developer documentation for all of this is the docs site inweb.strafe.chat/docs/pages/(served at/docs/on every instance) - update it in the same change when an endpoint, scope, event or permission changes. - Profile badges are a
public_flagsbitfield on the user (internal/modules/auth/badges.go; append-only bits behind anAllBadgesmask). An instance admin assigns them through moderation (instance.SetUserBadges), and every user payload exposesauth.PublicFlags(u)— theFlagscolumn masked to known bits — never the raw column. - Voice/video (
internal/modules/voice): LiveKit carries the media; this module is the authority on who is in which voice room (Redis-backedvoice.State, one room per user), what they may publish (the join token's sources andUpdateParticipantfollow the space's voice permission bits and moderator mute/deafen - LiveKit enforces them, the client only mirrors them), PM call ringing, and cleanup (LiveKit webhooks plus a 30 s reconciler). Moderator actions go throughspaces.Service.RecordAudit. New voice behaviour belongs here, gated by a permission bit and enforced at LiveKit where it can be, not in the client.docs/VOICE.mdhas the map. - Push notifications (
internal/modules/push) are standard Web Push only: RFC 8291aes128gcmbodies encrypted to the device's own key, RFC 8292 VAPID (the instance's key, generated intopush_vapidwhenPUSH_VAPID_PRIVATE_KEYis unset), POSTed to whatever endpoint the session registered (PUT /users/@me/push; one subscription per session, deleted when the session is revoked throughauth.SetSessionRevokedHook). An instance never holds Google/Apple credentials - the FCM/APNs relay is the app publisher's gateway (cmd/pushgateway). Never put content in the clear anywhere on that path, never send a body preview for an end-to-end encrypted room (the server has no plaintext; the push says who wrote where), never log an endpoint beyond its host. Outbound requests go throughinternal/safehttp's dial-time guard (as unfurl does).pushis a leaf: messages, rooms and voice call itsEnqueue*producers (cheap Redis writes onto thepush:jobsstream), and the workers learn about users/rooms/spaces throughpush.Directory(push/pushdir). A new place that creates a message, advances a read cursor or starts/stops ringing must call a producer, and the notify decision must keep mirroring the web client'slib/notifications.ts.deploy/docs/PUSH.mdhas the protocol and the operator side. - The push gateway (
cmd/pushgateway,internal/pushgateway) is a separate stateless binary run by whoever publishes an app build (it holds that build's APNs key and Firebase service account), never by instances. Its only config isPUSHGW_*. It must never decrypt or log push bodies, device tokens or sealed endpoints; instances speak plain Web Push to it and its endpoints are sealed (AES-GCM) so an instance never learns a device token. - Activities ("Playing X":
auth/activity.go,stargate/activity*.go) are presence, not profile. A client reports one over gateway op 9 (at most one, typeplaying, the name cleaned byauth.SanitizeActivityName- the display-text rule space nicknames share -started_atclamped); the per-connection worker applies reports in order, coalescing over budget. They live in Redis only: a hash<prefix>presence:activity:<user>with one field per gateway connection (Client.connID, never the session id), cleared a grace period after the socket closes and purged at gateway start, and a remote user's relayed one under...:fed:<user>, written only byPOST /federation/v1/users/presence. Never put one in ScyllaDB,UserPresence, the user cache, the outbox or a log line. Both binaries read through the storestargate.SetActivityStoreinstalls (same Redis, same prefix). Attach withauth.WithActivities(nothing while the presence reads offline) on exactly these surfaces: READY's own user,GET /users/@me(not to OAuth2 tokens), friend relationship entries (never requests or blocks), space member payloads,PRESENCE_UPDATEand the outbound/users/presence. A change while the user reads offline to others goes to their own channel only (stargate.PublishActivityChange): no frame to friends, spaces or peers, which would give an invisible user away. - Image proxy (
internal/modules/media): a client is never told to load an external picture from its source (embed images and thumbnails, author/footer icons). The serializers' one helper (messages.Service.mediaURL) hands out this instance's CDN URL for its own files, else a signedGET /media/v1/external/{sig}/{src}address (HMAC withMEDIA_PROXY_KEY, or a key generated into Redis with SETNX). That route is unauthenticated - the signature is the capability - fetches throughsafehttp, serves only sniffed PNG/JPEG/GIF/WebP withnosniffand a sandbox CSP, and caches in Nebula'smedia-cache/(tracked in Redis, swept, its total held withinMEDIA_PROXY_CACHE_MAX_GBby a byte count kept beside the index; past it an image is served without being kept). Fetches for views share 32 slots per process (past them, 503), apart from warming's own bound. A message written with embeds warms its images in the background (bounded) and writes the sizes learned back with a compare-and-set. Proxy URLs are computed at serialize time and never stored. - Room webhooks (
internal/modules/webhooks, messages inmessages/webhook.go): Discord-compatible incoming webhooks for a space's text rooms (and a voice room's text), made with Manage Webhooks (bit 31, room-scoped) or managed by the bot of the application that created one. The token isswh_+ 32 random bytes, stored only ashex(sha256(token)), shown in the answers to create and toPOST /webhooks/:id/tokenand nowhere else (lists and gets never carry it). Execute isPOST /webhooks/:idwithAuthorization: Webhook <token>(preferred: keeps it out of URLs), the token in the path as Discord has it, orAuthorization: Botof the owning bot; the token routes (GET/PATCH/DELETE /webhooks/:id/:token,.../messages/:message_id) work the same way.middleware.RedactPathrewrites/webhooks/<id>/<token>before anything logs a path. Budgets are Redis counters (WEBHOOK_RATE5/2s per webhook,WEBHOOK_ROOM_RATE30/10s per room, 30 failed tokens a minute per address, 30 message edits/deletes a minute), andWEBHOOKS_PER_ROOM/WEBHOOKS_PER_SPACE(15 / 200) cap how many exist. A webhook's message is an ordinary message row withwebhook_idset,sender_idequal to it and amasqueradesnapshot (the name and avatar source URL it posted as):sender_idis a user id unless it equalswebhook_id(Message.IsWebhookMessage), and every place that turns a sender into a user checks that first (serializers give Discord'sauthorwithbot: true, webhook: true; push names it; read state, thread auto-join and the federation sender skip it). It skips membership, slowmode, verification and automod (Discord's rule) but never the room rules: never in an end-to-end encrypted room (refused at create with 409, at execute with 403room_encrypted; turning encryption on stops a room's webhooks,spaces.WebhookHooks), never a PM, never a channel hosted on another instance. Pings go through Discord'sallowed_mentions, and@everyone/@here/roles notify only when the webhook'smass_mentionswas turned on by someone holding Mention Everyone. Names (the webhook's and a per-messageusername) passinternal/masquerade: no reserved, staff or role names, compared on a confusable-folded skeleton. Every mutation is audit-logged (webhook_*; with the token itself, actor 0 andvia: token) and firesWEBHOOKS_UPDATEon the room. Webhooks live on the space's origin; a mirror stores their messages from the relay (MessageEvent.webhook/.masquerade, accepted only from the origin; older mirrors refuse them, see FEDERATION.md). The same table, columns andMasqueradetype are where bridges (type 4, Masquerade bit 32) plug in. - Bridges / masquerade (
webhooks/bridge_*.go, messages inmessages/bridge.go): a bridge is awebhooksrow of type 4 that a bot drives (P2: bot-driven only;sbr_token bridges are a later phase), created by that bot with Manage Webhooks and Masquerade in a plaintext space text room (never a thread, a voice room, a PM or an encrypted room; 3 per room / 20 per space, inside the webhook caps). A room not everyone can view needsacknowledge_private(409private_room_ack_requiredwithaudience), and a room that narrows pauses its bridges (became_private). Every driver request rechecks View + Send + Masquerade from the snapshot: losing one pauses the bridge (driver_lost_permission) and regaining it resumes it. The bot posts as a puppet (POST /bridges/:id/messageswithexternal_user+external_message_id, claimed with a lightweight transaction so a retry is aduplicate, never a second message): the row'ssender_idis the bot,webhook_idthe bridge,masquerade{k: bridge, name, avatar, bridge, puppet, platform, ...}; external user ids are never in any reader's JSON. A puppet is held to what @everyone may do in the room (send, files, embeds, reactions), slowmode and automod per puppet (slow:<room>:p<puppet>), never pings anyone but the replied-to person (reply_pings), and names passinternal/masquerade(reserved, staff, role names refused; a member's name allowed withmasquerade.lookalike). Puppets and the id map are writtenUSING TTL(BRIDGE_PUPPET_TTL_DAYS90, refreshed on use;BRIDGE_MAP_TTL_DAYS30), blocks (bridge_blocks, Kick Members or Manage Messages) are by external id so they outlive the puppet. The driver's feed (BRIDGE_MESSAGE_*,BRIDGE_REACTION_*,BRIDGE_OPTOUT,BRIDGE_PUPPET_*,BRIDGE_CREATE/UPDATE/DELETEwith the full object) goes on the driving bot's own user channel (PublishToUserIn), already filtered bymessages.BridgeFeed: never the bridge's own messages, other bridges' or bots' unless the settings say so, threads, system messages, members of other instances (fail closed), or anyone whose consent says no. Consent (bridge_consenttable,users.bridge_consent,spaces.bridge_consent_mode, cached in a Redis hash per space) is: per-space choice, else the account default if "deny", else the space's mode (opt-out by default, Manage Space may switch to opt-in, audit-logged); going to "deny" sendsBRIDGE_OPTOUTwith the mapped copies so the driver can delete them. Room viewers getBRIDGE_CREATE/UPDATE/DELETEwith the public summary, room objects carrybridges, and create/delete leavebridge_created/bridge_deletednotices (payloadactor_id, bridge_id, bridge_name, platform, platform_name?, remote_name?, driver_id, driver_name). Reactor lists andMESSAGE_REACTION_*name a puppet with apuppetblock (bridge_id, puppet_id, platform, platform_name). Every bridge, puppet-block and consent-mode change is audit-logged with the target's name inchanges.name. The bot leaving the space (or its application going) deletes its bridges. Federation: bridges are the origin's; mirrors take the masquerade and puppet reactions only from it (FEDERATION.md "Bridged messages"). - One-shot data fixes (
spaces/backfill.go): claim a name indata_migrationswithClaimDataMigration(a lightweight transaction), do the work, release the claim on failure. CQL migrations cannot express "OR a bit into every existing row"; this can.
Before calling backend work done: go build ./..., go vet ./..., go test ./..., and
for anything with real request/response behavior, an actual smoke test (curl against the
running dev server, or the equivalent) — not just "it compiles."