Documentation
¶
Overview ¶
Package bubblesclient is the Go SDK for a bubbles server: CA-pinned TLS, messages, alerts, uploads, slash commands, a reconnecting event stream, an outage-tolerant alert queue, mDNS discovery and pairing.
Index ¶
- Constants
- Variables
- func FetchCA(ctx context.Context, onboardingURL string) (der []byte, fingerprint string, err error)
- func FormatFingerprint(fp string) string
- func NormalizeFingerprint(s string) (string, error)
- type APIError
- type AlertQueue
- func (q *AlertQueue) Close()
- func (q *AlertQueue) Done() <-chan struct{}
- func (q *AlertQueue) Dropped() int
- func (q *AlertQueue) Enqueue(a protocol.AlertInput) error
- func (q *AlertQueue) EnqueueResolve(dedupeKey, text string) error
- func (q *AlertQueue) Err() error
- func (q *AlertQueue) Flush(ctx context.Context) error
- func (q *AlertQueue) Len() int
- func (q *AlertQueue) SetOnStop(fn func(error))
- type Client
- func (c *Client) AckAlert(ctx context.Context, id string) (*protocol.Message, error)
- func (c *Client) Bootstrap(ctx context.Context) (*protocol.Bootstrap, error)
- func (c *Client) Config() Config
- func (c *Client) DeviceLogin(ctx context.Context, username, password, deviceName string) (*protocol.DeviceLoginResponse, error)
- func (c *Client) DeviceRegister(ctx context.Context, name, password, deviceName string) (*protocol.DeviceLoginResponse, error)
- func (c *Client) Events(ctx context.Context) (<-chan protocol.Event, error)
- func (c *Client) EventsErr() error
- func (c *Client) HandoffCode(ctx context.Context) (string, error)
- func (c *Client) HandoffURL(code string) string
- func (c *Client) HandoffURLNext(code, next string) string
- func (c *Client) ListAlerts(ctx context.Context, state, channelID, cursor string, limit int) (*protocol.AlertPage, error)
- func (c *Client) ListChannels(ctx context.Context) ([]protocol.Channel, error)
- func (c *Client) ListMessages(ctx context.Context, channel, before string, limit int) (*protocol.MessagePage, error)
- func (c *Client) PostAlert(ctx context.Context, a protocol.AlertInput) (*protocol.Message, error)
- func (c *Client) PostAlertResult(ctx context.Context, a protocol.AlertInput) (*protocol.PostedAlert, error)
- func (c *Client) PostMessage(ctx context.Context, channel string, m protocol.NewMessage) (*protocol.Message, error)
- func (c *Client) RegisterCommands(ctx context.Context, cmds []protocol.Command) error
- func (c *Client) ResolveAlert(ctx context.Context, dedupeKey, text string) error
- func (c *Client) ResolveAlertByID(ctx context.Context, id, text string) (*protocol.Message, error)
- func (c *Client) ResolveAlertKey(ctx context.Context, dedupeKey, text string) (*protocol.Message, error)
- func (c *Client) Respond(ctx context.Context, invocationID string, r protocol.CommandResponse) error
- func (c *Client) RevokeDevice(ctx context.Context, deviceID string) error
- func (c *Client) RevokeSelf(ctx context.Context) error
- func (c *Client) Search(ctx context.Context, query, cursor string, limit int) (*protocol.SearchPage, error)
- func (c *Client) Self(ctx context.Context) (*protocol.AppSelf, error)
- func (c *Client) Status(ctx context.Context) (*protocol.ServerStatus, error)
- func (c *Client) UploadFile(ctx context.Context, name string, r io.Reader) (*protocol.File, error)
- type Config
- type Pairing
- type Server
Constants ¶
const ( // EventResyncRequired: events were missed and cannot be replayed (epoch // change or pruned history). Re-fetch state from the REST API. EventResyncRequired = "sdk.resync_required" // EventInstanceChanged: the server's instance id changed (factory reset or // a different server). Drop all cached state; the token is likely void. EventInstanceChanged = "sdk.instance_changed" )
Synthetic event types emitted by Events (never sent by the server). They tell the app that its cached state is stale.
const DefaultPort = "28225"
DefaultPort is the HTTPS port assumed when a connection string omits it.
const DefaultQueueMax = 1000
DefaultQueueMax is the AlertQueue bound when max <= 0.
const ServiceType = "_bubbles._tcp"
ServiceType is the mDNS service type bubbles servers advertise.
Variables ¶
var ( // (HTTP 401, WebSocket close 4009/4010). The app must re-pair. ErrUnauthorized = errors.New("bubblesclient: unauthorized: token revoked or server reset; re-pair") // ErrServerIdentityChanged means the server's certificate chain does not // end in the pinned CA (CA rotated or an impostor). It is never trusted // automatically; the app must re-pair. ErrServerIdentityChanged = errors.New("bubblesclient: server identity changed: pinned CA fingerprint mismatch") // ErrRateLimited means HTTP 429. ErrRateLimited = errors.New("bubblesclient: rate limited") ErrUnavailable = errors.New("bubblesclient: server unavailable") )
Sentinel errors, comparable with errors.Is.
var ( ErrPairingDenied = errors.New("bubblesclient: pairing request denied") ErrPairingExpired = errors.New("bubblesclient: pairing request expired") ErrPairingClaimed = errors.New("bubblesclient: pairing token was already delivered") // ErrPairingCancelled means the request was withdrawn with // Pairing.Cancel before it delivered a token. ErrPairingCancelled = errors.New("bubblesclient: pairing request cancelled") )
Pairing outcome errors.
var ErrMissingDedupeKey = errors.New("bubblesclient: alert has no dedupe key")
ErrMissingDedupeKey is returned for an alert without a DedupeKey. Such alerts cannot be coalesced safely, so they are rejected instead of queued.
var ErrQueueClosed = errors.New("bubblesclient: alert queue closed")
ErrQueueClosed is returned after Close.
var ErrQueueFull = errors.New("bubblesclient: alert queue full")
ErrQueueFull is returned when the queue is at capacity and holds nothing older than the item in flight.
Functions ¶
func FetchCA ¶
FetchCA downloads the CA certificate from the plain-HTTP onboarding listener (GET /ca.crt) and returns its DER and its fingerprint ("sha256:<64 hex>"). The download itself is unauthenticated: show FormatFingerprint(fingerprint) to the user, who must compare it with the server's admin UI before trusting it.
func FormatFingerprint ¶
FormatFingerprint renders a normalized fingerprint in the grouped upper-case form shown by the server (groups of four, space separated).
func NormalizeFingerprint ¶
NormalizeFingerprint accepts "sha256:<64 hex>", bare hex, or the grouped upper-case form the server UI shows, and returns "sha256:<64 lowercase hex>".
Types ¶
type APIError ¶
type APIError struct {
Status int
Code string
Message string
Details map[string]any
RetryAfter time.Duration
}
APIError is a non-2xx answer from the server's error model.
func (*APIError) FieldErrors ¶
FieldErrors returns the per-field validation messages, or nil.
type AlertQueue ¶
type AlertQueue struct {
// contains filtered or unexported fields
}
AlertQueue delivers alerts in the background so they survive brief server outages. It is bounded, coalesces updates by dedupe key (the newest wins, the position of the first-queued entry is kept) and retries 429, 5xx and network failures, honouring Retry-After. ErrUnauthorized or ErrServerIdentityChanged stop it for good; the cause is available from Err and passed to the OnStop callback. Other 4xx answers drop the item (counted by Dropped).
func NewAlertQueue ¶
func NewAlertQueue(c *Client, max int) *AlertQueue
NewAlertQueue returns a queue sending through c; max <= 0 means 1000.
func (*AlertQueue) Close ¶
func (q *AlertQueue) Close()
Close stops the queue; pending items are discarded.
func (*AlertQueue) Done ¶
func (q *AlertQueue) Done() <-chan struct{}
Done is closed when the queue has stopped (Close or a fatal error).
func (*AlertQueue) Dropped ¶
func (q *AlertQueue) Dropped() int
Dropped counts items discarded for overflow or a permanent rejection.
func (*AlertQueue) Enqueue ¶
func (q *AlertQueue) Enqueue(a protocol.AlertInput) error
Enqueue queues an alert post or update.
func (*AlertQueue) EnqueueResolve ¶
func (q *AlertQueue) EnqueueResolve(dedupeKey, text string) error
EnqueueResolve queues a resolve for the alert with dedupe key.
func (*AlertQueue) Err ¶
func (q *AlertQueue) Err() error
Err returns the error that stopped the queue, or nil.
func (*AlertQueue) Flush ¶
func (q *AlertQueue) Flush(ctx context.Context) error
Flush blocks until the queue is empty, ctx ends, or the queue stops.
func (*AlertQueue) SetOnStop ¶
func (q *AlertQueue) SetOnStop(fn func(error))
SetOnStop registers fn, called once (from the queue goroutine) when the queue stops because of ErrUnauthorized or ErrServerIdentityChanged.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to one bubbles server. It is safe for concurrent use.
func New ¶
New validates cfg and builds a Client. TLS is verified only against the pinned CA fingerprint when one is configured.
func (*Client) AckAlert ¶
AckAlert acknowledges an alert by message id. The server refuses app tokens (403): acknowledging is for people.
func (*Client) Config ¶
Config returns the settings this client was built from (without the custom HTTP client).
func (*Client) DeviceLogin ¶
func (c *Client) DeviceLogin(ctx context.Context, username, password, deviceName string) (*protocol.DeviceLoginResponse, error)
DeviceLogin signs a desktop device in with a username and password (POST /auth/device-login). The client needs no token. The result carries the new device token (shown once) and a one-time handoff code for HandoffURL. A wrong password is an *APIError with status 401, which also matches ErrUnauthorized: tell it apart from a revoked token by the call site, not by the error value.
func (*Client) DeviceRegister ¶ added in v0.2.0
func (c *Client) DeviceRegister(ctx context.Context, name, password, deviceName string) (*protocol.DeviceLoginResponse, error)
DeviceRegister signs a new person up and registers their desktop device in one step (POST /auth/device-register). The client needs no token. It fails with an *APIError: 403 while sign-up is closed, 409 when the name is taken, 429 when this address has tried too often. The result is like DeviceLogin's.
func (*Client) Events ¶
Events opens the WebSocket stream and returns a channel of server events. The connection is re-established automatically (jittered exponential backoff) with resume, instance and epoch so no persisted event is lost or duplicated; the channel closes when ctx ends or the stream can never resume (ErrUnauthorized, ErrServerIdentityChanged; see EventsErr). The first connection is made before Events returns, so a bad token or a pin mismatch is reported directly.
func (*Client) HandoffCode ¶
HandoffCode asks for a new one-time handoff code (POST /auth/handoff-code); the client must carry a device token.
func (*Client) HandoffURL ¶
HandoffURL is the address that turns a handoff code into a web session.
func (*Client) HandoffURLNext ¶
HandoffURLNext is HandoffURL with the same-origin path the server redirects to after signing in, for example "/c/<channel id>". The server ignores a next that is not a plain absolute path; an empty next is left out.
func (*Client) ListAlerts ¶
func (c *Client) ListAlerts(ctx context.Context, state, channelID, cursor string, limit int) (*protocol.AlertPage, error)
ListAlerts returns alert messages, newest first. state (open, acked or resolved) and channelID are optional filters. The token needs messages:read.
func (*Client) ListChannels ¶
ListChannels returns the channels the token's bot belongs to (inside the token's channel allowlist). The token needs channels:read or messages:read.
func (*Client) ListMessages ¶
func (c *Client) ListMessages(ctx context.Context, channel, before string, limit int) (*protocol.MessagePage, error)
ListMessages returns up to limit messages of a channel, oldest first. When before is a message id, only older messages are returned. limit 0 means the server default. The token needs messages:read.
func (*Client) PostAlert ¶
PostAlert creates or updates the alert identified by a.DedupeKey and returns its message. The token needs alerts:write.
func (*Client) PostAlertResult ¶
func (c *Client) PostAlertResult(ctx context.Context, a protocol.AlertInput) (*protocol.PostedAlert, error)
PostAlertResult is PostAlert that also reports the transition (an AlertTransition* constant) the post caused.
func (*Client) PostMessage ¶
func (c *Client) PostMessage(ctx context.Context, channel string, m protocol.NewMessage) (*protocol.Message, error)
PostMessage posts a message to the channel with the given id. The token needs messages:write.
func (*Client) RegisterCommands ¶
RegisterCommands replaces the app's slash commands. Only Name, Description and Usage are sent. The token needs the commands scope.
func (*Client) ResolveAlert ¶
ResolveAlert resolves the open alert with the given dedupe key; text is an optional resolution note.
func (*Client) ResolveAlertByID ¶
ResolveAlertByID resolves an alert by message id. The server refuses app tokens (403); use ResolveAlertKey for the app's own alerts.
func (*Client) ResolveAlertKey ¶
func (c *Client) ResolveAlertKey(ctx context.Context, dedupeKey, text string) (*protocol.Message, error)
ResolveAlertKey resolves the open alert with the dedupe key and returns its message.
func (*Client) Respond ¶
func (c *Client) Respond(ctx context.Context, invocationID string, r protocol.CommandResponse) error
Respond answers a command invocation received as a command.invoked event.
func (*Client) RevokeDevice ¶
RevokeDevice revokes a device token (DELETE /me/devices/{id}). A device token can revoke only itself.
func (*Client) RevokeSelf ¶ added in v0.3.0
RevokeSelf revokes the token this client authenticates with, for a "Disconnect" button: the server closes the token's live connections and answers every later request with it as ErrUnauthorized. The app, its bot and its other tokens stay. Any scope may do this. Forget the stored token afterwards, also when RevokeSelf fails; there is no way to undo it. A server that predates it (bubbles v0.2.0 and earlier) answers an *APIError with status 404 or 405, and the token keeps working there until an admin revokes it.
func (*Client) Search ¶
func (c *Client) Search(ctx context.Context, query, cursor string, limit int) (*protocol.SearchPage, error)
Search runs a search query (see the search grammar) over the channels the bot belongs to. limit 0 means the server default. The token needs messages:read.
func (*Client) Self ¶
Self returns the app and token this client authenticates as. Keep Self().App.ID: a later RequestPairing can name it in ReplacesAppID so the admin reconnects this app instead of creating a new one.
type Config ¶
type Config struct {
// BaseURL is the server root, for example https://192.168.1.20:28225.
BaseURL string
// Token is the app token (bub_...).
Token string
// CAFingerprint pins the server's CA ("sha256:<64 hex>", bare hex or the
// grouped form shown by the server). When empty, normal system-root
// verification applies.
CAFingerprint string
// UserAgent overrides the default User-Agent.
UserAgent string
// HTTPClient is optional; see newHTTPClient for how the pin is applied.
HTTPClient *http.Client
}
Config configures a Client.
func ParseConnectionString ¶
ParseConnectionString parses bubbles://host:port/?token=bub_...&fp=sha256:<64 hex>.
func (Config) ConnectionString ¶
ConnectionString renders cfg as a bubbles:// URL.
type Pairing ¶
type Pairing struct {
// contains filtered or unexported fields
}
Pairing is a pending pairing request.
func RequestPairing ¶
func RequestPairing(ctx context.Context, serverURL, caFingerprint string, req protocol.PairingRequest) (*Pairing, error)
RequestPairing asks the admin for a token. serverURL is the HTTPS base URL; caFingerprint pins the CA (use the fingerprint the user confirmed after FetchCA). Show Code() to the user, then call Wait. An app that was paired before sets req.ReplacesAppID to its app id (Client.Self) so the admin can reconnect that app, keeping its bot and channels, instead of creating a second one; the claim then revokes its old tokens. A server that predates the field (bubbles v0.2.0 and earlier) refuses it as an unknown field; RequestPairing then sends the request once more without it, and that server pairs the app as a new one, as it always did.
func (*Pairing) Cancel ¶ added in v0.3.0
Cancel withdraws the request, for a Cancel button while the user waits for the admin. A pending request, or an approved one whose token was not claimed yet, is cancelled: the admin can no longer approve it, and a Wait still running returns ErrPairingCancelled. Cancelling twice is fine. A request that already delivered its token, or was denied or expired, answers an *APIError with status 409. A server that predates Cancel (bubbles v0.2.0 and earlier) answers an *APIError with status 404 or 405; its request then simply expires.
func (*Pairing) Channels ¶ added in v0.3.0
func (p *Pairing) Channels() []protocol.PairingChannel
Channels returns the channels the app's bot was in when the token was claimed (public and private, not archived, sorted by name), as reported in the answer that carried the token. It is nil before Wait succeeded, and also when the bot is in no channel: an app that posts alerts should then tell the user that an admin must add its bot to a channel. It is safe to call from any goroutine, also while Wait runs.
func (*Pairing) Wait ¶
Wait polls with backoff until the request is approved, denied, expired or cancelled, or ctx ends. On approval it returns a Config carrying the token and the pinned fingerprint; the server hands the token out exactly once. Channels then reports the channels its bot is in. A cancelled request (see Cancel) is ErrPairingCancelled.
type Server ¶
type Server struct {
// Name is the service instance name (the server's instance name).
Name string
// Host is the mDNS host name, for example "bubbles.local".
Host string
// Port is the HTTPS port.
Port int
// Addrs are the advertised addresses.
Addrs []netip.Addr
// FingerprintPrefix is the first 16 hex digits of the CA SHA-256 (TXT fp).
FingerprintPrefix string
// OnboardPort is the plain-HTTP onboarding port (TXT onboard), 0 if unknown.
OnboardPort int
// Version is the TXT record version.
Version string
}
Server is a bubbles server found on the LAN.
func Discover ¶
Discover browses for _bubbles._tcp for up to timeout and returns the servers found, ordered by name. Reaching the timeout is not an error.
func (Server) OnboardingURL ¶
OnboardingURL is the plain-HTTP onboarding base URL, or "" if unknown.