apps

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: 26 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

Overview

Package apps is the integration domain: app accounts (a bot user plus the app row), their scoped bearer tokens, the bearer authenticator, per-token rate limits and the pairing flow that hands a new app its first token.

Like the other domain services, every mutation runs in one store transaction together with its audit entry and events; the Tx variants join the caller's transaction.

Index

Constants

View Source
const (
	ActionAppCreate      = "app.create"
	ActionAppUpdate      = "app.update"
	ActionAppDisable     = "app.disable"
	ActionAppEnable      = "app.enable"
	ActionTokenCreate    = "token.create"
	ActionTokenRevoke    = "token.revoke"
	ActionPairingApprove = "pairing.approve"
	ActionPairingDeny    = "pairing.deny"
)

Audit actions written by this package. Detail never carries a token, a poll secret or a pairing ciphertext.

View Source
const (
	MaxNameChars        = 64
	MaxDescriptionChars = 500
)

Limits of app fields.

View Source
const (
	MaxPendingPerApp     = 100
	MaxPendingPerInvoker = 20
)

Pending invocation caps: an app may have MaxPendingPerApp invocations awaiting an answer, and one invoker MaxPendingPerInvoker across all apps.

View Source
const (
	// PairingTTL is how long a request waits for the admin.
	PairingTTL = 10 * time.Minute
	// ClaimWindow is how long an approved request stays claimable. It starts
	// at the approval, so an approval in the last seconds of the TTL is not
	// lost to the app's polling interval.
	ClaimWindow = 5 * time.Minute
	// MaxPendingPairings caps the open requests; more are answered 429.
	MaxPendingPairings = 20
	// PairingCreatesPerMinute limits POST /pairing/requests per source IP.
	PairingCreatesPerMinute = 5
	// PairingPollsPerSecond (burst PairingPollBurst) limits polling per IP.
	PairingPollsPerSecond = 2
	PairingPollBurst      = 20
)

Pairing limits (plan pipeline step 14).

View Source
const (
	ScopeMessagesRead  = protocol.ScopeMessagesRead
	ScopeMessagesWrite = protocol.ScopeMessagesWrite
	ScopeAlertsWrite   = protocol.ScopeAlertsWrite
	ScopeFilesWrite    = protocol.ScopeFilesWrite
	ScopeChannelsRead  = protocol.ScopeChannelsRead
	ScopeEventsRead    = protocol.ScopeEventsRead
	ScopeCommands      = protocol.ScopeCommands
	ScopeDMWrite       = protocol.ScopeDMWrite
	ScopeMCP           = protocol.ScopeMCP
)

The scopes an app token can carry (see protocol.AppScopes).

View Source
const (
	// PrefixLen is the number of leading token characters stored (and shown)
	// to identify a token: "bub_" and four characters of the secret.
	PrefixLen = 8

	// LastUsedInterval throttles last_used_at writes per token.
	LastUsedInterval = time.Minute
)
View Source
const (
	TokenRatePerSecond = 10
	TokenBurst         = 30
)

Per-token request limit.

View Source
const InvocationTTL = 15 * time.Minute

InvocationTTL is how long an app may answer an invocation.

Variables

View Source
var ErrAppOffline = errors.New("app is offline")

ErrAppOffline is returned by Invoke when the command's app has no live connection; the REST layer answers 503 unavailable.

Functions

func HasScope

func HasScope(scopes []string, scope string) bool

HasScope reports whether scopes contains scope.

func NormalizeFingerprint

func NormalizeFingerprint(fp string) string

NormalizeFingerprint returns fp as lower-case hex without separators.

func NormalizeScopes

func NormalizeScopes(field string, scopes []string) ([]string, error)

NormalizeScopes validates scopes and returns them without duplicates in the canonical order of protocol.AppScopes. Unknown scopes are a validation error on field.

func ValidScope

func ValidScope(s string) bool

ValidScope reports whether s names a scope.

Types

type CreateAppInput

type CreateAppInput struct {
	Name        string
	Description string
	// Username is the bot's username; empty derives one from Name.
	Username string
	// OwnerID is the admin who created the app.
	OwnerID string
}

CreateAppInput are the inputs of CreateApp.

type Endpoint

type Endpoint struct {
	// Host is the address clients should use (the first LAN address).
	Host string
	// Port is the HTTPS port.
	Port int
	// Fingerprint is the SHA-256 fingerprint of the CA certificate in any
	// common notation (hex, optionally with spaces or colons).
	Fingerprint string
}

Endpoint says how clients reach this server; it fills the connection string of a new token.

func (Endpoint) ConnectionString

func (e Endpoint) ConnectionString(token string) string

ConnectionString returns bubbles://<host>:<port>/?token=...&fp=sha256:<hex>. An endpoint without a fingerprint leaves fp out.

type IssueTokenInput

type IssueTokenInput struct {
	Scopes []string
	// ChannelIDs restricts the token to these channels; nil leaves it
	// unrestricted (the channels the bot is a member of).
	ChannelIDs []string
	// ExpiresAt is optional; it must lie in the future.
	ExpiresAt *time.Time
}

IssueTokenInput are the inputs of IssueToken.

type IssuedToken

type IssuedToken struct {
	Secret string
	Info   protocol.AppToken
}

IssuedToken is a new token: Secret is shown once and never stored.

type Options

type Options struct {
	DB   *store.DB
	Chat *chat.Service
	// Now is the clock of the limiters, token expiry and pairing; nil means
	// time.Now. It should be the clock the store uses.
	Now    func() time.Time
	Logger *slog.Logger
	// Realtime delivers the ephemeral command events and reports which apps are
	// connected; it is the events hub. nil disables command invocation.
	Realtime Realtime
}

Options configure a Service.

type PendingLimitError

type PendingLimitError struct {
	RetryAfter time.Duration
}

PendingLimitError reports that the app or the invoker already has the maximum of invocations awaiting an answer. The REST layer answers 429 with Retry-After set from RetryAfter.

func (*PendingLimitError) Error

func (e *PendingLimitError) Error() string

type Realtime

type Realtime interface {
	Publish(e events.Event)
	Subscribers(userID string) int
}

Realtime is the part of the events hub the command service needs: it publishes ephemeral events (seq 0, never stored) and knows which accounts have a live connection.

type Service

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

Service is the apps domain service.

func New

func New(o Options) *Service

New returns a Service. DB and Chat are required.

func (*Service) ApprovePairing

ApprovePairing creates the app, its bot and its first token for a pending request, adds the bot to the chosen channels (and to a new public "<app>-alerts" channel when asked), and records the approved scopes on the request. No token is created here: the app's first poll after the approval mints it (see PollPairing). admin must be an admin; audit actor is the admin too.

func (*Service) Authenticator

func (s *Service) Authenticator() auth.Authenticator

Authenticator returns the auth.Authenticator for `Authorization: Bearer bub_...` headers. It resolves the token by the SHA-256 of the secret and answers (nil, nil), which the REST layer turns into a generic 401, for anything that is not a live token: unknown, revoked, expired, an app that is disabled or a bot account that is deactivated. Only a database failure is an error.

func (*Service) CreateApp

func (s *Service) CreateApp(ctx context.Context, actor audit.Actor, in CreateAppInput) (protocol.App, error)

CreateApp creates an app and its bot account (kind app, role member, no password, so it can never sign in with a cookie).

func (*Service) CreateAppTx

func (s *Service) CreateAppTx(tx *store.Tx, actor audit.Actor, in CreateAppInput) (protocol.App, error)

CreateAppTx is CreateApp inside the caller's transaction.

func (*Service) CreatePairing

CreatePairing opens a pairing request from the app at ip. The poll secret is returned here only; the database keeps its SHA-256.

func (*Service) DenyPairing

func (s *Service) DenyPairing(ctx context.Context, aud audit.Actor, id string) error

DenyPairing rejects a pending request.

func (*Service) GetApp

func (s *Service) GetApp(ctx context.Context, id string) (protocol.App, error)

GetApp returns one app with its tokens, or ErrNotFound.

func (*Service) Invoke

Invoke runs a slash command typed by a person in a channel. Built-ins run here and their private notice, if any, goes to the invoker. For an app command it tells the app's connections and returns the invocation id; an app with no live connection is ErrAppOffline, with an ephemeral notice to the invoker.

func (*Service) IssueToken

func (s *Service) IssueToken(ctx context.Context, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)

IssueToken creates a token for the app. Only the SHA-256 of the secret and its 8-character prefix are stored.

func (*Service) IssueTokenTx

func (s *Service) IssueTokenTx(tx *store.Tx, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)

IssueTokenTx is IssueToken inside the caller's transaction.

func (*Service) Limiter

func (s *Service) Limiter() *auth.BucketLimiter

Limiter is the per-token request limit (10 per second, burst 30), keyed by auth.TokenGrant.ID. The REST layer applies it to every bearer request.

func (*Service) ListApps

func (s *Service) ListApps(ctx context.Context) ([]protocol.App, error)

ListApps returns every app with its tokens, oldest first.

func (*Service) ListCommands

func (s *Service) ListCommands(ctx context.Context) ([]protocol.Command, error)

ListCommands returns the built-ins followed by the commands of every enabled app, by name.

func (*Service) ListPending

func (s *Service) ListPending(ctx context.Context, caFingerprint string) ([]protocol.PendingPairing, error)

ListPending returns the open pairing requests, oldest first, each marked with caFingerprint (the one the app shows, for the admin to compare).

func (*Service) PollPairing

func (s *Service) PollPairing(ctx context.Context, ip, id, secret string) (protocol.PairingStatus, error)

PollPairing answers the app's poll. The poll secret must match, else the request is ErrNotFound (a wrong secret reveals nothing, not even that the id exists). No token exists before the first poll after the approval: that poll mints it in the same transaction that moves the request to claimed, so the token is returned once and never stored in any recoverable form.

func (*Service) Respond

Respond answers an invocation as the app. An ephemeral answer reaches only the invoker's connections and is not stored; any other is a normal message of the app's bot in the channel (and thread) the command ran in, with mentions disabled.

func (*Service) RevokeToken

func (s *Service) RevokeToken(ctx context.Context, actor audit.Actor, appID, tokenID string) error

RevokeToken revokes one token of the app. Revoking a revoked token does nothing; a token of another app is ErrNotFound. The token's live connections are closed when the change commits.

func (*Service) Self

func (s *Service) Self(ctx context.Context, appID, tokenID string) (protocol.AppSelf, error)

Self returns the app and token behind a bearer principal. The app's token list is left empty.

func (*Service) SetCommands

func (s *Service) SetCommands(ctx context.Context, g *auth.TokenGrant, in []protocol.CommandInput) ([]protocol.Command, error)

SetCommands replaces the command set of the token's app atomically. Names are unique across all apps and must not shadow a built-in; a clash is a conflict that names the owner.

func (*Service) SetRealtime

func (s *Service) SetRealtime(rt Realtime)

SetRealtime installs the realtime hub after construction (the composition root and tests build the services first). Call it before serving requests.

func (*Service) UpdateApp

func (s *Service) UpdateApp(ctx context.Context, actor audit.Actor, id string, in UpdateAppInput) (protocol.App, error)

UpdateApp renames an app, edits its description, or disables and enables it. A disabled app's tokens are rejected on their next request and its live connections are closed; nothing is revoked, so enabling the app restores them.

type UpdateAppInput

type UpdateAppInput struct {
	Name        *string
	Description *string
	Disabled    *bool
}

UpdateAppInput are the optional changes of UpdateApp.

Jump to

Keyboard shortcuts

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