bubblesclient

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 25 Imported by: ? 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

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

View Source
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.

View Source
const DefaultPort = "28225"

DefaultPort is the HTTPS port assumed when a connection string omits it.

View Source
const DefaultQueueMax = 1000

DefaultQueueMax is the AlertQueue bound when max <= 0.

View Source
const ServiceType = "_bubbles._tcp"

ServiceType is the mDNS service type bubbles servers advertise.

Variables

View Source
var (
	// ErrUnauthorized means the token was revoked or the server was reset
	// (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 means the server could not be reached or answered 5xx.
	ErrUnavailable = errors.New("bubblesclient: server unavailable")
)

Sentinel errors, comparable with errors.Is.

View Source
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.

View Source
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.

View Source
var ErrQueueClosed = errors.New("bubblesclient: alert queue closed")

ErrQueueClosed is returned after Close.

View Source
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

func FetchCA(ctx context.Context, onboardingURL string) (der []byte, fingerprint string, err error)

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

func FormatFingerprint(fp string) string

FormatFingerprint renders a normalized fingerprint in the grouped upper-case form shown by the server (groups of four, space separated).

func NormalizeFingerprint

func NormalizeFingerprint(s string) (string, error)

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) Error

func (e *APIError) Error() string

func (*APIError) FieldErrors

func (e *APIError) FieldErrors() map[string]string

FieldErrors returns the per-field validation messages, or nil.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is maps the HTTP status onto the sentinel errors.

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) Len

func (q *AlertQueue) Len() int

Len is the number of pending dedupe keys.

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

func New(cfg Config) (*Client, error)

New validates cfg and builds a Client. TLS is verified only against the pinned CA fingerprint when one is configured.

func (*Client) AckAlert

func (c *Client) AckAlert(ctx context.Context, id string) (*protocol.Message, error)

AckAlert acknowledges an alert by message id. The server refuses app tokens (403): acknowledging is for people.

func (*Client) Bootstrap

func (c *Client) Bootstrap(ctx context.Context) (*protocol.Bootstrap, error)

Bootstrap fetches the client snapshot (GET /bootstrap).

func (*Client) Config

func (c *Client) Config() 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

func (c *Client) Events(ctx context.Context) (<-chan protocol.Event, error)

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) EventsErr

func (c *Client) EventsErr() error

EventsErr returns why the most recent Events stream ended, or nil.

func (*Client) HandoffCode

func (c *Client) HandoffCode(ctx context.Context) (string, error)

HandoffCode asks for a new one-time handoff code (POST /auth/handoff-code); the client must carry a device token.

func (*Client) HandoffURL

func (c *Client) HandoffURL(code string) string

HandoffURL is the address that turns a handoff code into a web session.

func (*Client) HandoffURLNext

func (c *Client) HandoffURLNext(code, next string) string

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

func (c *Client) ListChannels(ctx context.Context) ([]protocol.Channel, error)

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

func (c *Client) PostAlert(ctx context.Context, a protocol.AlertInput) (*protocol.Message, error)

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

func (c *Client) RegisterCommands(ctx context.Context, cmds []protocol.Command) error

RegisterCommands replaces the app's slash commands. Only Name, Description and Usage are sent. The token needs the commands scope.

func (*Client) ResolveAlert

func (c *Client) ResolveAlert(ctx context.Context, dedupeKey, text string) error

ResolveAlert resolves the open alert with the given dedupe key; text is an optional resolution note.

func (*Client) ResolveAlertByID

func (c *Client) ResolveAlertByID(ctx context.Context, id, text string) (*protocol.Message, error)

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

func (c *Client) RevokeDevice(ctx context.Context, deviceID string) error

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.

func (*Client) Self

func (c *Client) Self(ctx context.Context) (*protocol.AppSelf, error)

Self returns the app and token this client authenticates as.

func (*Client) Status added in v0.2.0

func (c *Client) Status(ctx context.Context) (*protocol.ServerStatus, error)

Status fetches the public server status (GET /status): the instance name and whether sign-up is open. It works without a token.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, name string, r io.Reader) (*protocol.File, error)

UploadFile streams r as a multipart upload and returns the stored file, which can be attached to a message through NewMessage.FileIDs. The token needs files:write.

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

func ParseConnectionString(s string) (Config, error)

ParseConnectionString parses bubbles://host:port/?token=bub_...&fp=sha256:<64 hex>.

func (Config) ConnectionString

func (c Config) ConnectionString() (string, error)

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.

func (*Pairing) Code

func (p *Pairing) Code() string

Code is the short code to show the user; the admin compares it.

func (*Pairing) ExpiresAt

func (p *Pairing) ExpiresAt() time.Time

ExpiresAt is when the request lapses (zero if unknown).

func (*Pairing) Wait

func (p *Pairing) Wait(ctx context.Context) (Config, error)

Wait polls with backoff until the request is approved, denied or expired, or ctx ends. On approval it returns a Config carrying the token and the pinned fingerprint; the server hands the token out exactly once.

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

func Discover(ctx context.Context, timeout time.Duration) ([]Server, error)

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

func (s Server) OnboardingURL() string

OnboardingURL is the plain-HTTP onboarding base URL, or "" if unknown.

func (Server) URL

func (s Server) URL() string

URL is the HTTPS base URL, preferring the first IPv4 address.

Jump to

Keyboard shortcuts

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