Documentation
¶
Overview ¶
Package websocket provides a campaign-scoped WebSocket hub for real-time bidirectional communication between Chronicle and external clients (Foundry VTT). The hub broadcasts domain events (entity changes, map updates, calendar advances) to all connections in a campaign, enabling live sync without polling.
Index ¶
- Constants
- func HandleUpgrade(hub *Hub, auth Authenticator, allowedOrigins []string, ...) echo.HandlerFunc
- type APIKeyAuthenticator
- type Authenticator
- type CampaignRoleLookup
- type Client
- type DynamicOrigins
- type EventBus
- type Hub
- func (h *Hub) Broadcast(msg *Message)
- func (h *Hub) BrowserUserIDs(campaignID string) []string
- func (h *Hub) CampaignClientCount(campaignID string) int
- func (h *Hub) FoundryPresence(campaignID string) (lastSeen *time.Time, connected bool)
- func (h *Hub) MarkBrowserSeen(campaignID, userID string)
- func (h *Hub) MarkFoundrySeen(campaignID string)
- func (h *Hub) RecentBrowserUsers(campaignID string, within time.Duration) []string
- func (h *Hub) RegisterClient(conn WSConn, campaignID, userID, source string, role int, isDmGranted bool, ...) *Client
- func (h *Hub) RevokeAPIKeyClients(campaignID string)
- func (h *Hub) RevokeAll()
- func (h *Hub) RevokeCampaign(campaignID string)
- func (h *Hub) RevokeNotesAppClients(campaignID, userID string)
- func (h *Hub) RevokeNotesAppClientsEverywhere(userID string)
- func (h *Hub) RevokeUser(campaignID, userID string)
- func (h *Hub) RevokeUserEverywhere(userID string)
- func (h *Hub) Run()
- func (h *Hub) TotalClientCount() int
- type Message
- type MessageType
- type MultiAuthenticator
- type NotesGrantAuthenticator
- type SessionAuthenticator
- type WSConn
Constants ¶
const BrowserSource = "browser"
BrowserSource tags a socket opened by a signed-in Chronicle page.
const NotesAppSource = "notes-app"
NotesAppSource tags a socket opened with a notes grant. The hub sends such a socket note events only, since the grant reaches nothing else.
const NotesGrantProtocolPrefix = "chronicle.grant."
NotesGrantProtocolPrefix prefixes the offered subprotocol carrying the grant token. Grant tokens are base64url, which is valid in a subprotocol.
const NotesSubprotocol = "chronicle.notes"
NotesSubprotocol is the WebSocket subprotocol a notes frame asks for, and the one the server answers with. The grant itself travels as a second offered subprotocol, NotesGrantProtocolPrefix + token: a browser can't set headers on a WebSocket, and a token in the URL would land in access logs.
Variables ¶
This section is empty.
Functions ¶
func HandleUpgrade ¶
func HandleUpgrade(hub *Hub, auth Authenticator, allowedOrigins []string, dynamicOrigins DynamicOrigins) echo.HandlerFunc
HandleUpgrade returns an Echo handler that upgrades HTTP connections to WebSocket and registers them with the hub. Authentication is delegated to the Authenticator. The allowedOrigins parameter specifies which origins are permitted for browser clients (typically the app's BaseURL). The optional dynamicOrigins function provides additional origins from the admin CORS whitelist at runtime. API-key-authenticated connections bypass origin checks.
Types ¶
type APIKeyAuthenticator ¶
type APIKeyAuthenticator interface {
// AuthenticateKeyForWS validates a raw API key and returns its campaign,
// owner, owner-level role, and expiry (nil if the key never expires).
AuthenticateKeyForWS(ctx context.Context, rawKey string) (campaignID, userID string, role int, expiresAt *time.Time, err error)
}
APIKeyAuthenticator authenticates API key tokens for WebSocket connections. Implemented by the syncapi service.
type Authenticator ¶
type Authenticator interface {
// AuthenticateWS resolves identity from the upgrade request: campaign,
// user, source, role, DM-grant status, and the key's expiry if any
// (nil for a session or an unexpiring key).
AuthenticateWS(r *http.Request) (campaignID, userID, source string, role int, isDmGranted bool, expiresAt *time.Time, err error)
}
Authenticator resolves a WebSocket upgrade request into campaign/user identity. Implemented by the syncapi plugin for API key auth and by the auth plugin for browser session auth.
type CampaignRoleLookup ¶
type CampaignRoleLookup interface {
// GetUserCampaignRole returns the user's role in the campaign (0 if not a member).
GetUserCampaignRole(ctx context.Context, campaignID, userID string) (int, error)
// IsUserDmGranted returns true if the campaign Owner has granted this
// user dm_only visibility via CampaignSettings.DmGrantIDs. Lets the
// hub deliver RequiresDM messages to trusted non-Owner members.
IsUserDmGranted(ctx context.Context, campaignID, userID string) (bool, error)
}
CampaignRoleLookup resolves a user's role and DM-grant status in a campaign. Implemented by the campaigns service.
type Client ¶
type Client struct {
// ID is a unique identifier for this connection.
ID string
// CampaignID scopes this client to a specific campaign's message stream.
CampaignID string
// UserID is the authenticated user (from session or API key owner).
UserID string
// Source identifies the client type ("browser" or "foundry").
Source string
// Role is the user's campaign role (for permission filtering).
Role int
// IsDmGranted mirrors campaigns.CampaignContext.IsDmGranted —
// non-Owner members the campaign Owner has granted dm_only
// visibility to via CampaignSettings.DmGrantIDs. The hub's
// broadcast gate (see hub.go) treats Role>=Owner OR IsDmGranted as
// "may receive RequiresDM messages." Resolved once at registration
// from the auth path so the gate is a per-message constant-time
// check; revoking a grant requires the user to reconnect.
IsDmGranted bool
// ExpiresAt is the API key's expiry, if any (nil for a session or an
// unexpiring key). Rechecked after connect so an expiry crossed
// mid-connection still cuts the socket off.
ExpiresAt *time.Time
// contains filtered or unexported fields
}
Client represents a single WebSocket connection to the hub. Each client belongs to one campaign and has an optional user/API key identity.
type DynamicOrigins ¶
type DynamicOrigins func() []string
DynamicOrigins is an optional function that returns additional allowed origins at runtime (e.g., from the admin CORS whitelist in the database).
type EventBus ¶
type EventBus interface {
// Publish sends a message to all clients in the specified campaign,
// excluding the sender if SenderID is set.
Publish(msg *Message)
}
EventBus is the interface services use to emit domain events to WebSocket clients. Services depend on this interface (not the Hub directly) to avoid tight coupling and simplify testing.
func NewEventBus ¶
NewEventBus creates an EventBus backed by the given Hub.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub manages all WebSocket connections across campaigns. It routes messages to clients in the same campaign and handles connection lifecycle.
The hub is safe for concurrent use. Services call Broadcast() to push domain events to connected clients without importing the WebSocket library.
func NewHub ¶
func NewHub() *Hub
NewHub creates a new WebSocket hub. Call Run() to start processing.
func (*Hub) Broadcast ¶
Broadcast sends a message to all clients in the specified campaign. This is the primary method services use to push domain events. It is safe for concurrent use from any goroutine.
func (*Hub) BrowserUserIDs ¶
BrowserUserIDs lists the users with a signed-in browser socket open in the campaign, each once. Foundry, notes-grant and sync-key sockets are left out: they say a tool is connected, not that this person is looking at Chronicle.
func (*Hub) CampaignClientCount ¶
CampaignClientCount returns the number of connected clients for a campaign.
func (*Hub) FoundryPresence ¶
FoundryPresence returns the last-seen timestamp and whether the Foundry-module connection is considered live for the given campaign. A nil lastSeen means we've never recorded a Foundry-module connection for this campaign; connected is true when lastSeen is within the foundryPresenceTTL window.
func (*Hub) MarkBrowserSeen ¶
MarkBrowserSeen records that userID just loaded a page of the campaign. It is one map write under a mutex; once a minute it also drops entries older than the retention window.
func (*Hub) MarkFoundrySeen ¶
MarkFoundrySeen records activity from a Foundry-module connection for the campaign. Called on connect and on pong receipt so the presence window slides with the live heartbeat.
func (*Hub) RecentBrowserUsers ¶
RecentBrowserUsers lists the users who loaded a page of the campaign within the window, sorted.
func (*Hub) RegisterClient ¶
func (h *Hub) RegisterClient(conn WSConn, campaignID, userID, source string, role int, isDmGranted bool, expiresAt *time.Time) *Client
RegisterClient creates a new client and starts its read/write pumps. isDmGranted and expiresAt are both resolved once at auth time and cached on the client rather than looked up per message or per tick.
func (*Hub) RevokeAPIKeyClients ¶
RevokeAPIKeyClients force-disconnects every outside-app client in the campaign: Foundry's sync sockets and the notes frames' grant sockets. Call this when a sync key is revoked or Sync API is switched off, so a socket from before the change can't keep receiving. A notes frame dropped by a key revoke reconnects on its own if its grant still works.
func (*Hub) RevokeAll ¶
func (h *Hub) RevokeAll()
RevokeAll force-disconnects every client in every campaign. Call this when the database is about to be replaced: nothing connected before can be trusted to still belong to a campaign afterwards, and clients reconnect (or are refused) through the normal handshake.
func (*Hub) RevokeCampaign ¶
RevokeCampaign force-disconnects every client in campaignID, regardless of user or source. Call this once a campaign is deleted — its members and addon state are gone, so nothing should keep receiving on that socket.
func (*Hub) RevokeNotesAppClients ¶
RevokeNotesAppClients force-disconnects userID's notes grant sockets in the campaign. Call this when one of the player's grants is revoked; their other frames reconnect with grants that still work.
func (*Hub) RevokeNotesAppClientsEverywhere ¶
RevokeNotesAppClientsEverywhere force-disconnects userID's notes grant sockets in every campaign. Call this when all the user's grants end at once; their signed-in tabs and sync-key sockets stay up.
func (*Hub) RevokeUser ¶
RevokeUser force-disconnects every client belonging to userID in the campaign, regardless of source. Call this whenever that user's access in the campaign is lowered, so a cached role or grant can't outlive it.
func (*Hub) RevokeUserEverywhere ¶
RevokeUserEverywhere force-disconnects userID's sockets across ALL campaigns. Call this when an account is disabled: unlike RevokeUser, there's no single campaign to scope to, so every client map is swept.
func (*Hub) Run ¶
func (h *Hub) Run()
Run starts the hub's event loop. It should be called in a goroutine. The hub processes register, unregister, and broadcast events sequentially to avoid race conditions on the clients map.
func (*Hub) TotalClientCount ¶
TotalClientCount returns the total number of connected clients.
type Message ¶
type Message struct {
Type MessageType `json:"type"`
CampaignID string `json:"campaignId"`
ResourceID string `json:"resourceId,omitempty"` // ID of the affected resource.
SenderID string `json:"senderId,omitempty"` // Connection ID of sender (for echo suppression).
Payload json.RawMessage `json:"payload,omitempty"` // Type-specific data.
// Seq is the change-feed sequence number, stamped by the recording bus for
// allowlisted types. A client that tracks the highest seq it has seen can
// resume from GET /sync/changes?since=<seq> after a dropped connection.
Seq int64 `json:"seq,omitempty"`
// RequiresDM marks a message that must only be delivered to clients
// with DM-equivalent visibility (campaign Owner or IsDmGranted=true).
// Set by emitters whose source row carries dm_only / hidden state (a
// dm_only marker or drawing, a hidden token, any fog event). The hub's
// broadcast loop drops the message for non-DM connections at delivery
// time — see hub.go. JSON-omitted so unaffected payloads are unchanged.
RequiresDM bool `json:"requiresDm,omitempty"`
// AllowedUsers and DeniedUsers narrow a message's audience beyond the
// binary RequiresDM gate: the per-user visibility_rules a map marker
// or drawing can carry (ADR-055 rule 3 applied to this channel). A
// "specific" visibility marker isn't dm_only — RequiresDM is false for
// it — but it must still only reach the users its rules admit.
//
// Populated by the emitter that holds the source row (mapEventPublisherAdapter,
// which parses maps.Marker/Drawing's VisibilityRules), consumed only by
// the hub's broadcast loop, which drops the message per-recipient the
// same way it does for RequiresDM. `json:"-"`: this is server-side
// audience metadata, never client-facing — echoing back which user IDs
// are denied would itself be evidence that hidden content exists. A
// recipient outside the audience gets nothing: no message, no stub.
AllowedUsers []string `json:"-"`
DeniedUsers []string `json:"-"`
// StrictAudience makes AllowedUsers/DeniedUsers bind DM-equivalent
// clients too, instead of letting them bypass. For content that is
// private to named people — a player's private journal note — where "the
// GM sees everything" does not hold. Set only with a non-empty
// AllowedUsers: an empty allowlist still means everyone.
StrictAudience bool `json:"-"`
// AdmitScribes lets co-DMs (RoleScribe and up) past AllowedUsers the
// way DM-equivalent clients already pass, for content written for
// "the DM and co-DMs". Ignored under StrictAudience.
AdmitScribes bool `json:"-"`
// Public says the publisher checked that every member may receive this
// message, still narrowed by AllowedUsers/DeniedUsers. A message that is
// neither Public nor addressed to named users is treated as RequiresDM:
// a publisher that forgets to choose an audience reaches the GM side
// only, never players' sockets.
Public bool `json:"-"`
// Sources narrows delivery to sockets of these kinds (BrowserSource,
// foundry_vtt.ModuleSource, ...): a cut scene is for a person's open
// page, and its Foundry relay is for the module alone. Empty means every
// kind, as before. It narrows only; the audience gates above still
// apply. `json:"-"`: server-side routing, never sent.
Sources []string `json:"-"`
}
Message is the envelope for all WebSocket communication. Clients and servers exchange these JSON messages over the WS connection.
func NewMessage ¶
func NewMessage(msgType MessageType, campaignID, resourceID string, payload any) *Message
NewMessage creates a Message with the given type, campaign, and payload. The payload is marshaled to JSON. If marshaling fails, payload is set to null.
func (*Message) AudienceAllows ¶
AudienceAllows reports whether userID is in m's audience per its AllowedUsers/DeniedUsers lists. Callers must apply this only to non-DM-equivalent clients — Owners/DM-granted users bypass it entirely, same as the HTTP list path.
Mirrors maps.VisibilityRules' SQL predicate (ListMarkers, ListDrawings): an explicit deny always excludes (and, per permissions.DeniesAnonymous / ADR-049, so does a non-empty deny list against an anonymous userID); a non-empty AllowedUsers is a strict allowlist; an empty (or absent) rule set means "everyone". List-membership logic is deliberately duplicated rather than imported from maps, since this package is generic transport infrastructure — but the anonymous-deny rule is shared via permissions.DeniesAnonymous so the two can't drift apart on that point. Exported so the duplication can be pinned: internal/app/map_audience_parity_test.go runs one table of cases through this and through maps.VisibilityRules.Allows, asserting they agree.
func (*Message) DeliversTo ¶
DeliversTo is the per-recipient gate of the broadcast loop.
type MessageType ¶
type MessageType string
MessageType identifies the kind of event being broadcast.
const ( MsgEntityCreated MessageType = "entity.created" MsgEntityUpdated MessageType = "entity.updated" MsgEntityDeleted MessageType = "entity.deleted" )
Entity sync messages.
const ( MsgMapUpdated MessageType = "map.updated" MsgDrawingCreated MessageType = "drawing.created" MsgDrawingUpdated MessageType = "drawing.updated" MsgDrawingDeleted MessageType = "drawing.deleted" MsgTokenCreated MessageType = "token.created" MsgTokenMoved MessageType = "token.moved" MsgTokenUpdated MessageType = "token.updated" MsgTokenDeleted MessageType = "token.deleted" MsgMarkerCreated MessageType = "marker.created" MsgMarkerUpdated MessageType = "marker.updated" MsgMarkerDeleted MessageType = "marker.deleted" // Fog and layer messages split into per-lifecycle types so clients // can discriminate create / update / delete without re-fetching the // full sub-resource list. The original MsgFogUpdated / MsgLayerUpdated // constants stay valid for actual updates; the *Created / *Deleted // types are added alongside. MsgFogCreated MessageType = "fog.created" MsgFogUpdated MessageType = "fog.updated" MsgFogDeleted MessageType = "fog.deleted" MsgLayerCreated MessageType = "layer.created" MsgLayerUpdated MessageType = "layer.updated" MsgLayerDeleted MessageType = "layer.deleted" )
Map sync messages.
const ( MsgCalendarEventCreated MessageType = "calendar.event.created" MsgCalendarEventUpdated MessageType = "calendar.event.updated" MsgCalendarEventDeleted MessageType = "calendar.event.deleted" MsgCalendarDateAdvanced MessageType = "calendar.date.advanced" MsgCalendarSeasonChanged MessageType = "calendar.season.changed" MsgCalendarMoonPhaseChanged MessageType = "calendar.moon.phase_changed" MsgCalendarWeatherChanged MessageType = "calendar.weather.changed" MsgCalendarStructureUpdated MessageType = "calendar.structure.updated" MsgCalendarEraChanged MessageType = "calendar.era.changed" // Cycle + festival mutations fan out a sub-resource event in addition // to the umbrella structure.updated, so a subscriber can act at the // granularity it needs. MsgCalendarCycleChanged MessageType = "calendar.cycle.changed" MsgCalendarFestivalChanged MessageType = "calendar.festival.changed" MsgCalendarWorldstateChanged MessageType = "calendar.worldstate.changed" MsgCalendarWeatherZonesChanged MessageType = "calendar.weather.zones.changed" )
Calendar sync messages.
const ( MsgEntityTypeCreated MessageType = "entity_type.created" MsgEntityTypeUpdated MessageType = "entity_type.updated" MsgEntityTypeDeleted MessageType = "entity_type.deleted" )
Entity type sync messages.
const ( MsgRelationCreated MessageType = "relation.created" MsgRelationDeleted MessageType = "relation.deleted" MsgRelationMetadataUpdated MessageType = "relation.metadata_updated" )
Relation sync messages, one per relation row written. ResourceID is the row's source entity, so a client can follow one entity's relations (a character's inventory) and the change feed collapses them per entity.
const ( MsgNoteCreated MessageType = "note.created" MsgNoteUpdated MessageType = "note.updated" MsgNoteDeleted MessageType = "note.deleted" )
Note sync messages.
const ( MsgEntityNoteCreated MessageType = "entity_note.created" MsgEntityNoteUpdated MessageType = "entity_note.updated" MsgEntityNoteDeleted MessageType = "entity_note.deleted" )
Entity notes sync messages (player-notes addon). Distinct from note.* because the data model + audience semantics are different — these fire from internal/widgets/entity_notes, those from internal/widgets/notes.
const ( MsgStashMoved MessageType = "stash.moved" MsgStashRequested MessageType = "stash.requested" MsgStashSettled MessageType = "stash.settled" MsgStashMoneyChanged MessageType = "stash.money_changed" MsgDowntimeChanged MessageType = "downtime.changed" )
Stash and downtime messages. Payloads carry ids and statuses only.
const ( // MsgNPCSpotlight asks Foundry to spotlight the NPC page's token. // ResourceID is the entity id; always published RequiresDM. MsgNPCSpotlight MessageType = "npc.spotlight" // MsgSystemStateUpdated tells the GM side that a page's per-system // state changed. ResourceID is the entity id; the payload names the // system and key only, never the state. Always published RequiresDM // and deliberately not a change-feed type: the state is read through // its own route, not replayed from the feed. MsgSystemStateUpdated MessageType = "system_state.updated" // MsgHeroLayersChanged tells the GM side that a layer was put on or // taken off a page. ResourceID is the entity id and there is no // payload; the layers are read through their own route. Always // published RequiresDM, and recorded in the change feed as // `hero_layers` so a reconnecting module re-reads only those heroes. MsgHeroLayersChanged MessageType = "hero_layers.changed" // MsgCreatureAddRequested asks Foundry to make the actor for a creature // page now, from the page's "Add to Foundry" button. ResourceID is the // entity id and there is no payload. Always published RequiresDM, and // recorded in the change feed as `creature_add` so a world that was // closed makes the actor when it next connects. MsgCreatureAddRequested MessageType = "creature_add.requested" )
Foundry table messages. Sent to the campaign's Foundry module only to act at the table; never recorded in the sync change feed.
const ( // MsgQuestUpdated says a quest sheet was saved. ResourceID is the page id. MsgQuestUpdated MessageType = "quest.updated" // MsgNoticeBoardsUpdated says a home's notice boards changed. ResourceID // is the page id, or the category id for a category's boards. MsgNoticeBoardsUpdated MessageType = "notice_boards.updated" )
Quest messages. They carry ids only (and a quest's version), so a page reading them fetches again through its own route; not change-feed types.
const ( // MsgCutsceneShow puts a showing on its viewers' browser screens. Payload // {showingId, scene}; AllowedUsers is the viewers with StrictAudience, so // the Director's own tabs are taken over only when they picked // themselves, and Sources is the browser only. MsgCutsceneShow MessageType = "cutscene.show" // MsgCutsceneStop takes a showing off those screens. Payload {showingId}; // the same audience as the show. MsgCutsceneStop MessageType = "cutscene.stop" // MsgCutsceneFoundry hands a showing to the campaign's Foundry module, // which plays it for the viewers' linked Foundry users. Payload // {showingId, viewers, scene, rewatchUntil}; RequiresDM and Sources the // module only, so no browser socket ever learns who else it was for. MsgCutsceneFoundry MessageType = "cutscene.foundry" // MsgCutsceneFoundryStop relays a stop to the module. Payload {showingId}. MsgCutsceneFoundryStop MessageType = "cutscene.foundry_stop" )
Cut scene messages. None is a change-feed type: a reconnecting screen asks GET /campaigns/:id/cutscenes/mine for what it may still play, so a scene is never replayed from the feed.
const ( MsgSyncStatus MessageType = "sync.status" MsgSyncError MessageType = "sync.error" MsgSyncConflict MessageType = "sync.conflict" )
Sync control messages.
const MsgDecksChanged MessageType = "decks.changed"
MsgDecksChanged tells a client that its own view of the card decks changed, so it fetches its hand again. It carries no payload and no id of any deck, card or copy, and its audience is decided only from facts the receiver could already read (see the decks plugin's audience rule), so receiving one says nothing about what moved. Not a change-feed type: the fragments are read through their own routes.
const MsgDecksMoment MessageType = "decks.moment"
MsgDecksMoment tells the Directors that a card's moment opened, changed or closed, so their Table fetches the moments again. It carries no payload and no id: it is always published RequiresDM, because that a moment came, and for which card, is the Director's alone. Not a change-feed type.
const MsgHexChanged MessageType = "hex.changed"
MsgHexChanged tells map viewers that a map's hex layer changed. The payload is {map_id, version, party_path?} and never cell contents: clients refetch the role-filtered read, so who may see what is decided in one place. party_path rides along only when every hex on it is explored. Not a change-feed type: the filtered read is the source of truth.
const MsgMapItemsChanged MessageType = "map.items.changed"
MsgMapItemsChanged tells map viewers that a map's pins, drawings, tokens or shadows changed. The payload is {map_id, kind} with kind one of "markers", "drawings", "tokens" or "shadows", and never any item content: a viewer refetches the role-filtered read, so a player only ever learns what their own refetch returns. It goes to every client of the campaign, like hex.changed, because it tells a viewer who may not see the item nothing. Not a change-feed type: the filtered read is the source of truth.
const MsgPageChanged MessageType = "page.changed"
MsgPageChanged tells a reader's open page to fetch itself again. It carries no content, so it can go to every member, but only for pages everyone may read: a hidden page never announces itself to a player's socket.
const MsgRollMade MessageType = "roll.made"
MsgRollMade carries one roll of the campaign's roll log, already shaped for its audience (a blind roll's roller gets a copy without the result). Not a change-feed type: a reconnect never replays old rolls; the log is read through its own route.
const MsgTableShown MessageType = "table.shown"
MsgTableShown carries one thing a running scene showed, to everyone or to one player (and the DM team). Not a change-feed type: a player who was offline reads the night's list through its own route.
type MultiAuthenticator ¶
type MultiAuthenticator struct {
// contains filtered or unexported fields
}
MultiAuthenticator combines API key, notes grant and session authentication for WS upgrades. It checks the query parameter "token" for API key auth first, then a notes grant offered as a subprotocol, then falls back to session cookie auth. A "campaign" query parameter is required for session auth.
func NewMultiAuthenticator ¶
func NewMultiAuthenticator(apiKey APIKeyAuthenticator, session SessionAuthenticator, roles CampaignRoleLookup) *MultiAuthenticator
NewMultiAuthenticator creates an authenticator that supports both auth methods.
func (*MultiAuthenticator) AuthenticateWS ¶
func (a *MultiAuthenticator) AuthenticateWS(r *http.Request) (campaignID, userID, source string, role int, isDmGranted bool, expiresAt *time.Time, err error)
AuthenticateWS implements the Authenticator interface. Priority: API key (via ?token= query param) > notes grant (subprotocol) > Session cookie.
func (*MultiAuthenticator) SetNotesGrantAuth ¶
func (a *MultiAuthenticator) SetNotesGrantAuth(n NotesGrantAuthenticator)
SetNotesGrantAuth enables notes grant sockets. Without it a grant offered as a subprotocol is refused.
type NotesGrantAuthenticator ¶
type NotesGrantAuthenticator interface {
// AuthenticateNotesGrantForWS returns the grant's campaign and player,
// or an error when the token is unknown, revoked, idle too long, or the
// campaign has outside apps turned off.
AuthenticateNotesGrantForWS(ctx context.Context, token string) (campaignID, userID string, err error)
}
NotesGrantAuthenticator authenticates a player's notes grant, the token an outside app's notes frame holds instead of a sign-in. Implemented in internal/app over the notes widget's grant service and the campaign's outside-apps switch.
type SessionAuthenticator ¶
type SessionAuthenticator interface {
// AuthenticateSessionForWS validates a session cookie and returns user identity.
AuthenticateSessionForWS(r *http.Request) (userID string, err error)
}
SessionAuthenticator authenticates browser sessions for WebSocket connections. Implemented by the auth service.