Skip to content

Latest commit

 

History

History
336 lines (326 loc) · 27 KB

AGENTS.md

File metadata and controls

336 lines (326 loc) · 27 KB

equinox — AGENTS.md

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.

Mission — why this backend exists

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.

Terminology

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

Architecture conventions — follow these, don't reinvent them

  • 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 same Service/Handler struct declared in the base file. Mirror this when a module grows (see spaces/ and messages/ for the pattern).
  • Migrations: migrations/NNN_description.cql, zero-padded 3-digit prefix, applied in lexicographic filename order by cmd/migrate (which tracks what it's run in schema_migrations). Additive-only by default — a destructive migration needs a loud comment explaining why. Never replay an already-applied migration against a live keyspace; 019 drops and recreates device_keys, and replaying it once already destroyed real E2EE key material. cmd/migrate refuses an untracked keyspace unless given -adopt — never bypass that check.
  • Permissions: the full Discord-style bitmask lives in internal/modules/permissions/bits.go. Check with permissions.Has(perms, permissions.PermX); resolve effective permissions through each service's own authorize()/EffectiveChannelPermissions helper rather than hand-rolling a check. Some bits (e.g. PermAddReactions, PermUseExternalEmojis) are pre-declared ahead of the feature that enforces them — check bits.go before 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 OAuth2 bot authorize) decodes it as a permissions.Input: a decimal string is the full value (known bits only, else 400 unknown_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 *_full decimal string that a current origin prefers (federation/perm_wire.go). A new write path takes permissions.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.go publish to Redis, which every Stargate instance fans out to subscribed WebSocket clients as an op:3 EVENT frame: 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 / PublishToUsersIn for an event about a space or room sent to users' own channels. The scope is what the frame's space_id / room_id say (and a map payload gets them too); the channel stays the routing. An event that gives its recipients a channel (SPACE_CREATE with its rooms, ROOM_CREATE, SPACE_ROOM_CREATE, THREAD_CREATE, joining a thread) names it with Scope.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. Plain PublishToUser is for account-only events; PublishToSpace is legacy and a test keeps its callers at zero. Event types are SCREAMING_SNAKE_CASE verbs (SPACE_UPDATE, MESSAGE_REACTION_ADD). docs/STARGATE.md documents 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 (see spaceError in spaces/handler.go, reactionError in messages/handler_reactions.go) instead of hand-rolling the mapping in every handler.
  • IN ? lists go through db.Chunks. ScyllaDB refuses a query whose partition-key or clustering-key IN list 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, ListRooms failed 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 Federator interface (AfterMessageCreated, etc.) — calls are best-effort and must never block or fail the local request.
  • Fiber gotcha: UnescapePath is off (the default) — a route param that can contain non-ASCII (e.g. a unicode emoji) arrives at c.Params() still percent-encoded. Decode it explicitly with url.PathUnescape in the handler; don't flip the app-wide config.
  • Background goroutines go through internal/safego (safego.Go for fire-and-forget, safego.Run inside a WaitGroup worker). Fiber's recover middleware only covers the request goroutine; a bare go 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, see deploy/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_confirm link to the new address, email_change_taken to a new address that already has an account, email_change_requested / email_change_done notices to the old address, which carry the new one only masked by auth.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 with GETDEL, 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 when EMAIL_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 no PasswordHash (see cached_user_repo.go); never branch on it after GetByID.
  • Addresses: one validator, one mover, one event. auth.NormalizeEmail is 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。, an xn-- 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 plain ToLower(TrimSpace) so a legacy address can still sign in. Mail errors never name the recipient (mail.SMTP.Send scrubs go-mail's), so logging one next to a user_id stays address-free. An address moves only through auth.ApplyEmailChange (per-user Redis lock, the LWT UserRepository.ChangeEmail that writes email + verified_email in one conditional statement and releases the old claim only if it is still the account's, the revival marker, USER_EMAIL_UPDATE); never call ChangeEmail directly. The address is never in USER_UPDATE, broadcastUserProfile or anything federation sends - only in the self-only USER_EMAIL_UPDATE on stargate.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, then DELETE /instance/users/:id with 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 with take_down_spaces, owned applications and their bots only with delete_applications; a space owned on another instance always blocks), peers get POST /users/delete, and last UserRepository.DeleteAccount removes the users row with its users_by_username and users_by_email claims in one logged batch, so the name and address are free at once. Messages stay and serialize with a deleted: true placeholder 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 and users_by_remote kept, never resurrected). Every step is idempotent and audited in instance_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 Authorization header only — no cookie, no ?token= query parameter. The header carries one of three credentials, all resolved by middleware.RequireAuth: a session Bearer token; an OAuth2 Bearer access token (tried when the token is not a live session, its granted scopes recorded in Locals[middleware.LocalsKeyScopes] and gating scope-limited fields such as the account email in /users/@me); or a Bot <token> bot-account token. The applications/oauth modules inject their resolvers at startup with middleware.SetBotResolver/SetOAuthResolver, so the middleware never imports them (they import auth, which would cycle). The WebSocket gateway is the one exception (browsers cannot set headers on a WebSocket), which is why STARGATE_ALLOWED_ORIGINS is 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, a bot_public switch and optionally a bot user (an auth.User with Bot set, a synthetic bot+<id>@bots.invalid email 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 publishes SESSION_REVOKED so the gateway drops the bot. oauth is the authorization server: authorization-code grant (HTTP Basic or body client auth, form or JSON), scopes identify / 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, and GET /oauth2/@me. Scopes are enforced by the middleware: RequireAuth refuses OAuth2 tokens with 403 insufficient_scope; only routes wrapped in RequireAuthScoped(...) (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. The bot scope 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.join lets a bot with Create Invite add an authorising user (PUT /spaces/:id/members/:user_id). Bots use the gateway with Authorization: Bot on 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 in web.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_flags bitfield on the user (internal/modules/auth/badges.go; append-only bits behind an AllBadges mask). An instance admin assigns them through moderation (instance.SetUserBadges), and every user payload exposes auth.PublicFlags(u) — the Flags column 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-backed voice.State, one room per user), what they may publish (the join token's sources and UpdateParticipant follow 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 through spaces.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.md has the map.
  • Push notifications (internal/modules/push) are standard Web Push only: RFC 8291 aes128gcm bodies encrypted to the device's own key, RFC 8292 VAPID (the instance's key, generated into push_vapid when PUSH_VAPID_PRIVATE_KEY is unset), POSTed to whatever endpoint the session registered (PUT /users/@me/push; one subscription per session, deleted when the session is revoked through auth.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 through internal/safehttp's dial-time guard (as unfurl does). push is a leaf: messages, rooms and voice call its Enqueue* producers (cheap Redis writes onto the push:jobs stream), and the workers learn about users/rooms/spaces through push.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's lib/notifications.ts. deploy/docs/PUSH.md has 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 is PUSHGW_*. 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, type playing, the name cleaned by auth.SanitizeActivityName - the display-text rule space nicknames share - started_at clamped); 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 by POST /federation/v1/users/presence. Never put one in ScyllaDB, UserPresence, the user cache, the outbox or a log line. Both binaries read through the store stargate.SetActivityStore installs (same Redis, same prefix). Attach with auth.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_UPDATE and 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 signed GET /media/v1/external/{sig}/{src} address (HMAC with MEDIA_PROXY_KEY, or a key generated into Redis with SETNX). That route is unauthenticated - the signature is the capability - fetches through safehttp, serves only sniffed PNG/JPEG/GIF/WebP with nosniff and a sandbox CSP, and caches in Nebula's media-cache/ (tracked in Redis, swept, its total held within MEDIA_PROXY_CACHE_MAX_GB by 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 in messages/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 is swh_ + 32 random bytes, stored only as hex(sha256(token)), shown in the answers to create and to POST /webhooks/:id/token and nowhere else (lists and gets never carry it). Execute is POST /webhooks/:id with Authorization: Webhook <token> (preferred: keeps it out of URLs), the token in the path as Discord has it, or Authorization: Bot of the owning bot; the token routes (GET/PATCH/DELETE /webhooks/:id/:token, .../messages/:message_id) work the same way. middleware.RedactPath rewrites /webhooks/<id>/<token> before anything logs a path. Budgets are Redis counters (WEBHOOK_RATE 5/2s per webhook, WEBHOOK_ROOM_RATE 30/10s per room, 30 failed tokens a minute per address, 30 message edits/deletes a minute), and WEBHOOKS_PER_ROOM / WEBHOOKS_PER_SPACE (15 / 200) cap how many exist. A webhook's message is an ordinary message row with webhook_id set, sender_id equal to it and a masquerade snapshot (the name and avatar source URL it posted as): sender_id is a user id unless it equals webhook_id (Message.IsWebhookMessage), and every place that turns a sender into a user checks that first (serializers give Discord's author with bot: 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 403 room_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's allowed_mentions, and @everyone/@here/roles notify only when the webhook's mass_mentions was turned on by someone holding Mention Everyone. Names (the webhook's and a per-message username) pass internal/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 and via: token) and fires WEBHOOKS_UPDATE on 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 and Masquerade type are where bridges (type 4, Masquerade bit 32) plug in.
  • Bridges / masquerade (webhooks/bridge_*.go, messages in messages/bridge.go): a bridge is a webhooks row 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 needs acknowledge_private (409 private_room_ack_required with audience), 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/messages with external_user + external_message_id, claimed with a lightweight transaction so a retry is a duplicate, never a second message): the row's sender_id is the bot, webhook_id the 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 pass internal/masquerade (reserved, staff, role names refused; a member's name allowed with masquerade.lookalike). Puppets and the id map are written USING TTL (BRIDGE_PUPPET_TTL_DAYS 90, refreshed on use; BRIDGE_MAP_TTL_DAYS 30), 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/DELETE with the full object) goes on the driving bot's own user channel (PublishToUserIn), already filtered by messages.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_consent table, 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" sends BRIDGE_OPTOUT with the mapped copies so the driver can delete them. Room viewers get BRIDGE_CREATE/UPDATE/DELETE with the public summary, room objects carry bridges, and create/delete leave bridge_created / bridge_deleted notices (payload actor_id, bridge_id, bridge_name, platform, platform_name?, remote_name?, driver_id, driver_name). Reactor lists and MESSAGE_REACTION_* name a puppet with a puppet block (bridge_id, puppet_id, platform, platform_name). Every bridge, puppet-block and consent-mode change is audit-logged with the target's name in changes.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 in data_migrations with ClaimDataMigration (a lightweight transaction), do the work, release the claim on failure. CQL migrations cannot express "OR a bit into every existing row"; this can.

Verification expectations

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."