api

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2026 License: AGPL-3.0 Imports: 45 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const MaxAttachmentBytes = 25 * 1024 * 1024

MaxAttachmentBytes caps the ciphertext byte size of a single attachment. The blob is already AES-GCM-encrypted on the client, so the server cannot inspect the plaintext — this ceiling exists for quota/abuse reasons only. Mirrors the client-side cap in `src/lib/attachmentLimits.ts`.

Variables

This section is empty.

Functions

func AdminAPIRoutes

func AdminAPIRoutes(
	store adminStore,
	bootstrapSecret string,
	sessionTTL time.Duration,
	secureCookies bool,
	serviceIdentityMasterKey string,
	hub GlobalBroadcaster,
	cache *InstanceCache,
	roomService livekit.RoomService,
	httpMetrics *HTTPMetrics,
	hubStats HubStatsProvider,
	startedAt time.Time,
) chi.Router

AdminAPIRoutes returns the chi router for /api/admin. Bootstrap and session routes are public; all resource routes use local admin sessions.

httpMetrics and hubStats are optional operator telemetry hooks consumed by the /metrics route; they may be nil in tests where the metrics surface is not under exercise. startedAt overrides the handler's process-start time when non-zero so the uptime-bearing endpoints stay consistent across the admin and metrics surfaces wired by main.go.

func AdminRoutes

func AdminRoutes(store db.Store, jwtSecret string) chi.Router

AdminRoutes mounts instance-operator endpoints (billing stats). Requires authentication; instance-owner check is performed inside handlers.

func AdminUIHandler

func AdminUIHandler(prefix string, adminFS fs.FS) http.Handler

AdminUIHandler returns an http.Handler that serves an embedded SPA at the given prefix (e.g. "/admin/"). Requests matching a real file in adminFS are served directly; all other paths receive index.html for client-side routing.

func AttachmentRoutes

func AttachmentRoutes(store db.Store, backendFactory AttachmentBackendFactory, jwtSecret string) chi.Router

AttachmentRoutes mounts the global download/delete endpoints:

GET    /{id}/download
DELETE /{id}

Mounted at /api/attachments. Auth applied here; channel-membership for download is checked per-row inside the handler.

func AuthRoutes

func AuthRoutes(store db.Store, jwtSecret string, jwtExpiry time.Duration, transparencySvc *transparency.TransparencyService, hub ...GlobalBroadcaster) chi.Router

AuthRoutes returns the chi router for /api/auth. It also starts a background goroutine that purges expired auth nonces every noncePurgeInterval. The goroutine has no shutdown signal - process exit terminates it, consistent with the system_messages cleanup pattern.

transparencySvc may be nil when the transparency log is not configured for this instance. All transparency operations nil-guard before use.

hub may be nil; all broadcast calls within device handlers are nil-checked before use. Pass the *ws.Hub from router setup for WS notifications.

Guest session duration is read from GUEST_SESSION_HOURS (default 1 hour).

func CORSOptions

func CORSOptions() cors.Options

CORSOptions returns the application-wide CORS configuration applied to every API route by cmd/hush/main.go.

AllowedHeaders must enumerate every custom request header the HTTP API actually consumes, because chi/cors echoes only the listed names back in the preflight Access-Control-Allow-Headers response. Anything missing here causes browsers (and Electron renderers running under a non-hosted origin such as `app://localhost`) to fail the preflight with a generic "TypeError: Failed to fetch" before the real request leaves the client.

The link-archive bulk transfer plane carries three custom request headers — X-Upload-Token, X-Download-Token, and X-Chunk-Sha256 — which the OLD-device upload path and the NEW-device download path both rely on. Same-origin browser sessions never trigger a preflight, so these headers worked in the hosted web app, but the packaged desktop renderer's cross-origin fetch from `app://localhost` to the hosted instance does. Excluding them here is what surfaces as the `Failed to fetch` during the LinkDevice flow on desktop.

func ChannelAttachmentRoutes

func ChannelAttachmentRoutes(store db.Store, backendFactory AttachmentBackendFactory) chi.Router

ChannelAttachmentRoutes mounts the per-channel presign endpoint:

POST /presign  -> presign upload, insert row, return { id, uploadUrl, ... }

Mounted by ChannelRoutes under /api/servers/{serverId}/channels/{id}/attachments. Auth + RequireGuildMember are inherited from the parent server router.

func ChannelRoutes

func ChannelRoutes(store db.Store, hub GlobalBroadcaster, attachmentBackend AttachmentBackendFactory) chi.Router

ChannelRoutes returns the router for channels nested under /api/servers/{serverId}. Auth and RequireGuildMember are applied by the parent router; this router only adds channel-specific routes.

attachmentBackend is the factory used to presign attachment uploads for the per-channel `/attachments/presign` endpoint. Pass nil to surface a 503 — the rest of the channel surface keeps working.

func DeviceRoutes

func DeviceRoutes(store db.Store, jwtSecret string, transparencySvc *transparency.TransparencyService, hub GlobalBroadcaster) func(r chi.Router)

DeviceRoutes returns the chi.Router for device management and device-linking endpoints mounted under /api/auth.

Route map:

Public:
  POST /link-request      - new device creates a 5-minute link request
  POST /link-result       - new device consumes the encrypted relay payload

Authenticated:
  GET    /devices            - list authenticated user's devices
  POST   /devices            - certify a new device directly
  DELETE /devices/{deviceId} - revoke a single device
  DELETE /devices?all=true   - revoke all devices
  POST   /link-resolve       - existing device claims a QR/code request
  POST   /link-verify        - existing device certifies + uploads relay payload

transparencySvc may be nil when the transparency log is not configured for this instance. Device certify and revoke operations append synchronously when the service is non-nil (non-fatal on failure).

hub may be nil; all broadcast calls are nil-checked before use.

func EmitSystemMessage

func EmitSystemMessage(ctx context.Context, store db.Store, hub GlobalBroadcaster, serverID string, eventType string, actorID string, targetID *string, reason string, metadata map[string]interface{})

EmitSystemMessage inserts a system message and broadcasts it via WebSocket. Fire-and-forget: logs errors but does not return them (same pattern as audit log).

func GifRoutes

func GifRoutes(apiKey string) chi.Router

GifRoutes mounts the GIF proxy at /api/gif. The handler is mounted under RequireAuth in main.go so anonymous requests do not waste upstream quota.

`q` empty → trending. `q` present → search. Both pass `offset` for infinite scroll. The full Giphy response shape is forwarded to the client so `@giphy/react-components` Grid can consume it directly.

func GuildInviteRoutes

func GuildInviteRoutes(store db.Store) chi.Router

GuildInviteRoutes returns the router for guild-scoped invite creation. Mounted under /api/servers/{serverId}/invites. Auth and RequireGuildMember are applied by the parent router.

func GuildRoutes

func GuildRoutes(store db.Store, hub GlobalBroadcaster, jwtSecret string) chi.Router

GuildRoutes mounts the /api/guilds sub-router. Provides DM creation, guild discovery, and public user search. All routes require authentication.

func HTTPMetricsMiddleware

func HTTPMetricsMiddleware(m *HTTPMetrics) func(http.Handler) http.Handler

HTTPMetricsMiddleware records request volume and per-status-class counts. It does not record latency histograms; that is intentionally out of scope.

func HandshakeHandler

func HandshakeHandler(cache *InstanceCache, voiceEnabled bool) http.HandlerFunc

HandshakeHandler returns an http.HandlerFunc that serves GET /api/handshake. The endpoint is public (no authentication required) and stateless - it reads only from the in-memory cache and version constants, never from the database.

func IPRateLimiter

func IPRateLimiter(r rate.Limit, b int) func(http.Handler) http.Handler

IPRateLimiter returns middleware that limits requests per remote IP address. r is the sustained request rate (tokens per second), b is the burst size. On limit breach, responds 429 with Retry-After: 60 and JSON error body.

func InstanceRoutes

func InstanceRoutes(store db.Store, hub GlobalBroadcaster, jwtSecret string, cache *InstanceCache) chi.Router

InstanceRoutes returns the router for /api/instance. Owner-gated and admin-gated privileged operations have been moved to AdminAPIRoutes. This router serves authenticated user-facing endpoints only.

func LiveKitRoutes

func LiveKitRoutes(store db.Store, jwtSecret string, apiKey, apiSecret string) chi.Router

LiveKitRoutes returns the route for POST /api/livekit/token (mount at /api/livekit).

func LiveKitRoutesWithVoiceState

func LiveKitRoutesWithVoiceState(store db.Store, jwtSecret string, apiKey, apiSecret string, state *VoiceState) chi.Router

LiveKitRoutesWithVoiceState returns the LiveKit API routes backed by the supplied in-memory voice tracker. The tracker is optional for tests that only exercise token issuance.

func LiveKitRoutesWithVoiceStateAndPublicURL

func LiveKitRoutesWithVoiceStateAndPublicURL(store db.Store, jwtSecret string, apiKey, apiSecret, publicURL string, state *VoiceState) chi.Router

LiveKitRoutesWithVoiceStateAndPublicURL returns the LiveKit API routes backed by the supplied in-memory voice tracker and optional public signaling URL.

func LiveKitWebhookHandler

func LiveKitWebhookHandler(hub *ws.Hub, store db.Store, apiKey, apiSecret string) http.HandlerFunc

LiveKitWebhookHandler returns an HTTP handler for LiveKit webhook events. It tracks voice participants in-memory and broadcasts voice_state_update to the guild's WS subscribers via BroadcastToServer. Falls back to BroadcastToAll if the channel's server ID cannot be resolved.

func LiveKitWebhookHandlerWithState

func LiveKitWebhookHandlerWithState(hub *ws.Hub, store db.Store, apiKey, apiSecret string, state *VoiceState) http.HandlerFunc

LiveKitWebhookHandlerWithState returns an HTTP handler backed by the supplied VoiceState tracker. Production passes the same tracker to LiveKitRoutes so clients can fetch a bootstrap snapshot after login.

func MLSRoutes

func MLSRoutes(store db.Store, hub MLSBroadcaster, jwtSecret string, transparencySvc *transparency.TransparencyService) chi.Router

MLSRoutes returns the router for /api/mls (mount at /api/mls). Route order is significant: /key-packages/count must be registered before /key-packages/{userId}/{deviceId} to prevent chi matching "count" as a userId.

transparencySvc may be nil when the transparency log is not configured for this instance. KeyPackage uploads and credential updates append asynchronously when the service is non-nil (fire-and-forget, non-fatal).

func ModerationRoutes

func ModerationRoutes(store db.Store, hub GlobalBroadcaster, roomService livekit.RoomService) chi.Router

ModerationRoutes returns the router for guild-scoped moderation endpoints. Mounted under /api/servers/{serverId}/moderation. Auth and RequireGuildMember are applied by the parent router.

roomService receives best-effort RemoveParticipant calls for any voice channel of the guild after a successful ban or kick. Pass livekit.NoopRoomService{} to disable eviction (e.g. dev / test).

func PublicInviteRoutes

func PublicInviteRoutes(store db.Store, jwtSecret string, hub GlobalBroadcaster) chi.Router

PublicInviteRoutes returns the router for invite resolution and claiming. Mounted at /api/invites. Auth is applied inside for the claim route.

func RequireAdminOrigin

func RequireAdminOrigin() func(http.Handler) http.Handler

RequireAdminOrigin rejects mutating admin requests from unexpected origins.

func RequireAdminRole

func RequireAdminRole(roles ...string) func(http.Handler) http.Handler

RequireAdminRole ensures the authenticated admin has one of the allowed roles.

func RequireAdminSession

func RequireAdminSession(store adminStore) func(http.Handler) http.Handler

RequireAdminSession validates the dashboard session cookie and injects admin identity.

func RequireAuth

func RequireAuth(jwtSecret string, store db.Store) func(http.Handler) http.Handler

RequireAuth returns middleware that validates the bearer JWT, verifies the session against the database, and injects userID and sessionID into the request context. Both jwtSecret and pool are captured at construction time so callers don't need to carry them through handler structs.

func RequireGuildMember

func RequireGuildMember(store db.Store) func(http.Handler) http.Handler

RequireGuildMember extracts {serverId} from the URL, verifies the requesting user is a member of that guild, and injects the guild permission level into the request context. Must be applied after RequireAuth so userID is available.

func SecurityHeaders

func SecurityHeaders(productionMode bool, wsOrigin string) func(http.Handler) http.Handler

SecurityHeaders returns middleware that sets security-related HTTP response headers on every response. productionMode enables HSTS. wsOrigin is the WebSocket origin to allow in the Content-Security-Policy connect-src directive; derive it from CORSOrigin by replacing https:// with wss:// (or http:// with ws://). If CORSOrigin is "*", pass "wss:" to allow all WebSocket origins.

func ServerRoutes

func ServerRoutes(store db.Store, hub GlobalBroadcaster, jwtSecret string, roomService livekit.RoomService, attachmentBackend AttachmentBackendFactory) chi.Router

ServerRoutes mounts guild CRUD, member management, and nested sub-routes (channels, guild invites, moderation). Auth is applied at the top level; RequireGuildMember is applied to all member-only /{serverId} sub-routes. The /join endpoint is intentionally outside RequireGuildMember - the user is not yet a member when they hit that route.

roomService is forwarded to ModerationRoutes for LiveKit eviction after a successful ban or kick. Pass livekit.NoopRoomService{} to disable.

func SystemMessagesRoutes

func SystemMessagesRoutes(store db.Store) chi.Router

SystemMessagesRoutes returns a chi.Router for system message endpoints. Mounted under /api/servers/{serverId}/system-messages.

func TransparencyRoutes

func TransparencyRoutes(svc *transparency.TransparencyService, store db.Store, jwtSecret string) chi.Router

TransparencyRoutes returns a chi.Router for the transparency log API. All routes require JWT authentication.

Route map:

GET /verify - return inclusion proofs for a given Ed25519 public key

func UserRateLimiter

func UserRateLimiter(r rate.Limit, b int) func(http.Handler) http.Handler

UserRateLimiter returns middleware that limits requests per authenticated user ID. r is the sustained request rate (tokens per second), b is the burst size. If no userID is in context (should not happen behind RequireAuth), the request falls through. On limit breach, responds 429 with Retry-After: 60 and JSON error body.

func WSOriginFromCORSOrigin

func WSOriginFromCORSOrigin(corsOrigin string) string

WSOriginFromCORSOrigin derives the WebSocket origin string for the CSP connect-src directive from the configured CORS origin. "https://example.com" -> "wss://example.com" "http://example.com" -> "ws://example.com" "*" -> "wss:"

Types

type AttachmentBackendFactory

type AttachmentBackendFactory func() (storage.Backend, error)

AttachmentBackendFactory constructs the storage Backend used for attachment presign URLs. Injected so tests can hand a fake; in production main.go wires the same singleton it uses for link-archive chunks. A nil factory disables the routes (503).

type GlobalBroadcaster

type GlobalBroadcaster interface {
	BroadcastToAll(message []byte)
	BroadcastToServer(serverID string, message []byte)
	BroadcastToUser(userID string, message []byte)
	DisconnectUser(userID string)
	DisconnectDevice(userID, deviceID string)
}

GlobalBroadcaster is satisfied by *ws.Hub. Used for dependency injection in tests.

type HTTPMetrics

type HTTPMetrics struct {
	// contains filtered or unexported fields
}

HTTPMetrics holds atomic counters for the HTTP layer. It is intentionally a coarse-grained, allocation-free counter set: total requests served, plus per-status-class counters. Designed to feed an operator-facing metrics endpoint, not a full Prometheus surface.

All fields are read via the snapshot accessor; do not read raw atomics.

func NewHTTPMetrics

func NewHTTPMetrics() *HTTPMetrics

NewHTTPMetrics returns a zero-initialized HTTPMetrics.

func (*HTTPMetrics) IncWSAccepted

func (m *HTTPMetrics) IncWSAccepted()

IncWSAccepted increments the accepted-WebSocket-handshake counter.

func (*HTTPMetrics) IncWSRejected

func (m *HTTPMetrics) IncWSRejected()

IncWSRejected increments the rejected-WebSocket-handshake counter.

func (*HTTPMetrics) Snapshot

func (m *HTTPMetrics) Snapshot() HTTPMetricsSnapshot

Snapshot returns the current counter values atomically.

type HTTPMetricsSnapshot

type HTTPMetricsSnapshot struct {
	RequestsTotal uint64 `json:"requestsTotal"`
	Status1xx     uint64 `json:"status1xx"`
	Status2xx     uint64 `json:"status2xx"`
	Status3xx     uint64 `json:"status3xx"`
	Status4xx     uint64 `json:"status4xx"`
	Status5xx     uint64 `json:"status5xx"`
	WSAccepted    uint64 `json:"wsAccepted"`
	WSRejected    uint64 `json:"wsRejected"`
}

HTTPMetricsSnapshot is a point-in-time copy of HTTPMetrics for serialization.

type HubStatsProvider

type HubStatsProvider interface {
	Stats() ws.HubStats
}

HubStatsProvider is satisfied by *ws.Hub. Declared as an interface so the metrics handler is testable without spinning up a real WebSocket Hub.

type InstanceCache

type InstanceCache struct {
	// contains filtered or unexported fields
}

InstanceCache holds a snapshot of the instance_config row in memory so the handshake handler never hits the database. It is populated on server startup and refreshed whenever the instance config is updated via PUT /api/instance.

func NewInstanceCache

func NewInstanceCache() *InstanceCache

NewInstanceCache creates an empty cache. Zero values are safe: name="" - representing a fresh instance before first-user setup. voiceKeyRotationHours defaults to voiceKeyRotationHoursDefault. guildDiscovery defaults to "allowed". serverCreationPolicy defaults to "open".

func (*InstanceCache) Set

func (c *InstanceCache) Set(name string, iconURL *string, regMode string, guildDiscovery string, voiceKeyRotationHours int, serverCreationPolicy string, screenShareResolutionCap ...string)

Set updates the instance configuration fields under a write lock. Called on startup (from GetInstanceConfig) and after updateConfig writes to the database.

serverCreationPolicy must be one of "open", "paid", or "disabled"; defaults to "open" when the empty string is passed.

This method does not touch transparency fields (transparencyURL, logPublicKey). Use SetTransparencyInfo to update those separately after the log signer is loaded.

func (*InstanceCache) SetAttachmentPolicy

func (c *InstanceCache) SetAttachmentPolicy(maxAttachmentBytes int64)

SetAttachmentPolicy updates cache fields that affect attachment UX and upload validation. Called with instance_config on startup and after admin config writes.

func (*InstanceCache) SetTransparencyInfo

func (c *InstanceCache) SetTransparencyInfo(transparencyURL *string, logPublicKey *string)

SetTransparencyInfo stores the transparency log URL and log signer public key in the cache. Called once at startup after the TransparencyService is initialized. Neither field is updated by the admin config endpoint - they change only on restart.

type InviteLandingHandler added in v0.2.0

type InviteLandingHandler struct {
	// contains filtered or unexported fields
}

InviteLandingHandler renders a human-readable join page for browser visits to /invite/{code} and /join/{host}/{code} on a backend-only (self-hosted) instance, where no web client is served at the instance origin.

The page is rendered purely from the request path and serving origin; it performs no database lookup, embeds no credentials, and never overrides the instance origin. See CORE-INVARIANTS "Federation, Instance Routing, and Credential Boundaries".

func NewInviteLandingHandler added in v0.2.0

func NewInviteLandingHandler(webClientURL string) *InviteLandingHandler

NewInviteLandingHandler builds the handler. An empty webClientURL falls back to the documented public convenience client.

func (*InviteLandingHandler) ServeInvite added in v0.2.0

func (h *InviteLandingHandler) ServeInvite(w http.ResponseWriter, r *http.Request)

ServeInvite handles GET /invite/{code}, a same-instance invite whose instance is the serving origin.

func (*InviteLandingHandler) ServeJoin added in v0.2.0

func (h *InviteLandingHandler) ServeJoin(w http.ResponseWriter, r *http.Request)

ServeJoin handles GET /join/{host}/{code}, an invite that names an explicit instance host distinct from the serving origin.

type MLSBroadcaster

type MLSBroadcaster interface {
	BroadcastToUser(userID string, message []byte)
	Broadcast(channelID string, message []byte, excludeClientID string)
}

MLSBroadcaster is satisfied by *ws.Hub. Used for dependency injection in tests.

type VoiceState

type VoiceState struct {
	// contains filtered or unexported fields
}

VoiceState tracks participants per LiveKit room (in-memory, rebuilt from webhooks).

func NewVoiceState

func NewVoiceState() *VoiceState

NewVoiceState returns an empty voice-state tracker shared by the LiveKit webhook handler and the authenticated snapshot endpoint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL