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