bridge

package
v0.3.0-rc.55 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 42 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 bridge closes the loop between the alerts and the people on call.

The router hands each alert group to the bridge. A new group becomes a Feishu card in the alert chat (or a plain message from the group's custom bot, for low severities or when the app's API quota runs low). Buttons on the card acknowledge the alert or silence it; the card changes in place, and turns green when the alert resolves. A critical alert nobody acknowledges is escalated: a buzz in the Feishu app, then a Pushover emergency alert that repeats on the phone until someone acknowledges it there (which also counts as an acknowledgement here).

The same operations are offered to the REST API and the MCP server, so an agent can see and act on alerts; their writes are audited and echoed to the chat.

Index

Constants

View Source
const (
	AlertsFiring         = "firing"
	AlertsUnacknowledged = "unacknowledged"
	AlertsSilenced       = "silenced"
	AlertsResolved       = "resolved"
	AlertsAll            = "all"
)

The states a list of alerts may ask for.

View Source
const AgentRunScope = "alerts:report"

AgentRunScope allows execution reports and first-drill configuration checks for a hook that names the reporting principal.

View Source
const MaintenancePrefix = "maintenance:"

MaintenancePrefix begins the comment of every silence that is a maintenance window.

View Source
const OwnSource = "beacon"

Beacon's own changes, a drill and Beacon itself starting on another version, go in as change events too, so that the evidence of an alert they cause says so; OwnSource is the source they carry, which no sender may use (the gateway refuses it).

View Source
const ShareScope = "accounts:write"

Variables

View Source
var (
	ErrAgentRunNotFound = errors.New("no reportable hook delivery with this id on the alert")
	ErrAgentRunConflict = errors.New("the delivery already has a different terminal report")
)
View Source
var (
	ErrNotFound       = errors.New("no such alert group")
	ErrNotFiring      = errors.New("the alert group is not firing")
	ErrBadInput       = errors.New("bad input")
	ErrAckChanged     = errors.New("the alert acknowledgement changed")
	ErrTakeOverDenied = errors.New("only a person can take over an alert")
	ErrEpisodeChanged = errors.New("the alert incident changed")
)

ErrNotFound and ErrNotFiring are returned for unknown or finished alert groups.

View Source
var (
	ErrNoMaintenance    = errors.New("no such maintenance window")
	ErrMaintenanceEnded = errors.New("the maintenance window has ended")
)

ErrNoMaintenance means there is no maintenance window with that id; ErrMaintenanceEnded that it has ended, or was called off, already.

View Source
var (
	ErrProbeBusy        = probenow.ErrBusy
	ErrProbeNotFound    = probenow.ErrNotFound
	ErrProbeUnavailable = errors.New("probing on demand is not available: this Beacon has no gateway for probes")
	ErrProbeNotRecorded = errors.New("could not save the check for this incident")
)

Errors of probing on demand. The board reports busy and not found. Checks are unavailable without a board, and an incident check requires a confirmed write of its result and audit entry.

View Source
var (
	ErrShareNotFound = errors.New("no such alert or session")
	ErrShareDisabled = errors.New("signed page links are unavailable")
)
View Source
var (
	ErrTokenTooSoon      = store.ErrTooSoon
	ErrTokenNotRenewable = store.ErrNotRenewable
	// ErrOAuthNotRenewable means the caller came with an OAuth access token, which its client refreshes.
	ErrOAuthNotRenewable = errors.New("an OAuth access token is refreshed by the client that holds it; there is nothing to renew")
)

Token errors the API and MCP turn into answers.

AlertStates are the states a list may ask for.

View Source
var ErrDrillHookNotFound = errors.New("no active drill hook assigned to this reporter")

ErrDrillHookNotFound applies both to missing hooks and hooks assigned to a different reporter.

View Source
var ErrForbidden = errors.New("not allowed")

ErrForbidden means the caller may not act on this.

View Source
var ErrNoHook = errors.New("no agent hook with this name in the settings")

ErrNoHook is a hook that is not in the settings in force.

View Source
var ErrNotMember = errors.New("the person is not in the group")

ErrNotMember means the person is not in the group.

View Source
var ErrOutcomeNotFound = errors.New("no such incident outcome")
View Source
var ErrUnrecorded = errors.New("the audit log cannot be written now, so nothing was changed; try again once it can")

ErrUnrecorded means a change that gives access was undone, or never made, because its audit entry could not be written: access is never given without a record.

Functions

func GroupID

func GroupID(groupKey string) string

GroupID is the short, stable id of a group key.

func MachineChoice

func MachineChoice(access *string, machines *[]string) (*store.MachineAccess, error)

MachineChoice reads a machine access sent to the API or MCP: access is all or named, machines the machines named. Neither sent is nil: nothing to change. machines alone names those machines; an empty list names none, which reaches no machine. Nothing sent ever means all.

func MachineScope

func MachineScope(a store.MachineAccess) string

MachineScope is the machine access in the older words of whoami: all (every machine that is not critical, and the critical machines in machines), listed (only those in machines) or none.

func PushTokenName

func PushTokenName(id string) string

PushTokenName is the name of a push monitor's token. Heartbeats enrolled before monitors had the same name, so their jobs keep pushing.

func Revocable

func Revocable(t store.Token) bool

Revocable reports whether a token may be deleted from the console, the API and MCP: one that reaches machines through the SSH channel (machines:ssh), or any agent's token. Deleting it stops one agent's credential at once, without stopping the others; the agent itself stays. The tokens of machines and services (probes, hosts, heartbeats, the rule engine, change senders, metrics readers) stay with the admin socket, where they were made: revoking one of them from a page could silence monitoring, and no alert may be lost.

func TokenRefusal

func TokenRefusal(err error, name string) error

TokenRefusal is what the API and MCP tell a caller that may not revoke the token called name: one answer, store.ErrNotFound, whether no token has that name, the token is one only the host revokes, or the caller lacks the right to this token. So a refusal says nothing about which tokens exist. A caller that may delete no token at all keeps that answer (ErrForbidden). Other errors, and nil, pass through.

Types

type AckOptions

type AckOptions struct {
	TakeOver bool
	Expected string
}

AckOptions are what an acknowledgement may also ask. TakeOver says the caller means to take the alert over from whoever holds it now, which only a person may (ErrTakeOverDenied): an agent's or a token's acknowledgement is only ever recorded beside a person's. Expected is the ack_version the caller read; when the acknowledgement has changed since (someone else acknowledged, or the alert fired anew), it is refused with ErrAckChanged, so that nobody takes over from someone they did not see.

type Actor

type Actor struct {
	Name string
	Via  string
	Key  string
	Cred string // the credential it came with (store.Principal.Cred), for the SSH channel's later checks
	// From is where the request came from (store.Principal.From), for access rules limited to source
	// addresses; invalid when not known.
	From netip.Addr
}

Actor is who performs an operation: Name as the audit log and the chat name it (a person, "person / agent" for an agent, or a token's name), Via how (api, mcp, console, cli), and Key the principal (store.Principal.Key), for checks made later; none for the command line.

func ActorOf

func ActorOf(p store.Principal, via string) Actor

ActorOf is the actor a principal is when it comes through via.

type AgentCreated

type AgentCreated struct {
	Agent    AgentView       `json:"agent"`
	Token    *AgentTokenView `json:"token,omitempty"`
	Secret   string          `json:"secret,omitempty"`
	Snippets []Snippet       `json:"snippets,omitempty"`
}

AgentCreated is an agent just made, or given a new token: the token's secret, shown once, and the snippets that use it.

type AgentInput

type AgentInput struct {
	Name     string
	Owner    string
	Preset   string
	Scopes   []string // PresetCustom only; see checkCustom
	Machines store.MachineAccess
	Forever  []string
	SSHKeys  []string // authorized_keys lines
	TTL      time.Duration
}

AgentInput makes an agent. Owner defaults to the person making it; Preset to the strongest their role allows; TTL is its first token's lifetime (zero: no token, as for an OAuth client). Machines is its machine access, none unless given; a critical machine named in it is reached for store.CriticalGrantTTL unless it gives an end, or Forever names the machine.

type AgentRunInput

type AgentRunInput struct {
	Status   string `json:"status" jsonschema:"running, succeeded, failed, timed_out or not_started"`
	ExitCode *int   `json:"exit_code,omitempty" jsonschema:"exit status from 0 to 255, when known"`
}

AgentRunInput is a programme phase or outcome. Only a normal exit has a numeric exit code.

type AgentSilencer

type AgentSilencer interface {
	CreateAgentSilence(ctx context.Context, labels map[string]string, start, end time.Time, createdBy, comment string) (string, error)
}

AgentSilencer is a Silencer that keeps agents' silences apart: recorded and listed, muting nothing. An agent cannot silence through a Silencer without it.

type AgentTokenView

type AgentTokenView struct {
	Name     string    `json:"name"`
	Created  time.Time `json:"created"`
	Expires  time.Time `json:"expires"`
	Lifetime string    `json:"lifetime"`
	Renewed  time.Time `json:"renewed,omitzero"`
}

AgentTokenView is one of an agent's static tokens.

type AgentUpdate

type AgentUpdate struct {
	Preset   *string
	Machines *store.MachineAccess
	Forever  []string
	Scopes   []string
}

AgentUpdate changes an agent. A nil field stays as it is. Scopes is nil to keep them; a non-nil list sets the custom scopes (and is refused when it is empty). Scopes are applied only when the result is custom; a preset clears them. Machines is the new machine access; a machine it keeps keeps its end, and a critical machine newly named ends as for AgentInput, unless Forever names it.

type AgentView

type AgentView struct {
	Name   string   `json:"name"`
	Owner  string   `json:"owner"`
	Actor  string   `json:"actor"`
	Preset string   `json:"preset"`
	Wanted []string `json:"wanted"`
	Scopes []string `json:"scopes"`
	MachineAccessView
	SSHKeys   []SSHKeyView     `json:"ssh_keys,omitempty"`
	Tokens    []AgentTokenView `json:"tokens,omitempty"`
	Grants    []GrantView      `json:"grants,omitempty"`
	Client    string           `json:"client,omitempty"`
	Created   time.Time        `json:"created"`
	CreatedBy string           `json:"created_by,omitempty"`
}

AgentView is an agent as its owner sees it: what its preset asks for (Wanted) and what it may do now (Scopes, within its owner's role), its machine access (as it was given; never more than its owner reaches), keys and credentials.

type AlertBrief

type AlertBrief struct {
	ID          string            `json:"id"`
	Episode     string            `json:"episode,omitempty"`
	Status      string            `json:"status"`
	Severity    string            `json:"severity"`
	Title       string            `json:"title"`
	Description string            `json:"description,omitempty"`
	Service     string            `json:"service,omitempty"`
	Services    []string          `json:"services,omitempty"` // a group of several services
	Labels      map[string]string `json:"labels"`             // the labels its alerts share
	Alerts      int               `json:"alerts"`             // alerts firing
	StartsAt    time.Time         `json:"starts_at"`
	ResolvedAt  *time.Time        `json:"resolved_at,omitempty"`
}

AlertBrief is an alert group as the evidence, the timeline and the hooks show it. Its text is made from labels, so it is cleaned.

type AlertDetail

type AlertDetail struct {
	Alert    GroupView               `json:"alert"`
	Evidence Evidence                `json:"evidence"`
	Timeline Timeline                `json:"timeline"`
	Silences []alertmanager.Silence  `json:"silences"`
	Outcomes []store.IncidentOutcome `json:"outcomes"`
}

AlertDetail is one alert group with everything about it: the group, its evidence (each location's result and reason, related alerts, changes, what was done), its timeline, the silences that cover it and the outcomes of its resolved episodes.

type AlertFilter

type AlertFilter struct {
	State, Severity, Service, Query string
	Since                           time.Time
	Limit                           int
}

AlertFilter chooses alert groups: by state (firing by default), severity, service (a monitor's id), a text in the title or the service, and those started since a time.

type AlertLinks struct {
	Alert     string `json:"alert"`
	Evidence  string `json:"evidence"`
	Timeline  string `json:"timeline"`
	MCP       string `json:"mcp"`
	Runbook   string `json:"runbook,omitempty"`
	Dashboard string `json:"dashboard,omitempty"`
	Page      string `json:"page,omitempty"`
}

AlertLinks are where to read more: the REST routes (status:read), the MCP endpoint (get_evidence, get_timeline and add_note take the group's id), the runbook, the dashboard, and the alert's page for people (Page: a signed link that needs no token, to hand to a person).

type AlertList

type AlertList struct {
	Alerts  []GroupView    `json:"alerts"`
	Counts  map[string]int `json:"counts"`
	History *OutcomePage   `json:"history,omitempty"`
}

AlertList is the alert groups a filter chooses, the newest first, with the count of each state over the groups Beacon holds; with resolved, also a page of the retained history of resolved episodes.

type Barker

type Barker interface {
	Send(ctx context.Context, title, body, link string) error
}

Barker is a ringing iOS push.

type Bridge

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

Bridge is the alert bridge.

func New

func New(d Deps) *Bridge

New creates a bridge.

func (*Bridge) Ack

func (b *Bridge) Ack(ctx context.Context, id string, who Actor, note string) (GroupView, error)

Ack acknowledges a firing group for an API or MCP caller.

func (*Bridge) AckWith

func (b *Bridge) AckWith(ctx context.Context, id string, who Actor, note string, o AckOptions) (GroupView, error)

AckWith acknowledges a firing group with options: taking it over, and only as it was read.

func (*Bridge) AddGroupMembers

func (b *Bridge) AddGroupMembers(ctx context.Context, who Actor, name string, usernames []string) (store.UserGroup, error)

AddGroupMembers adds people to a group; those in it already stay as they are.

func (*Bridge) AddNote

func (b *Bridge) AddNote(ctx context.Context, id string, who Actor, text string) (GroupView, error)

AddNote leaves a note on an alert group, firing or resolved. The card shows it; it is audited and echoed to the alert chat. A note does not acknowledge the group.

func (*Bridge) AddSSHKey

func (b *Bridge) AddSSHKey(ctx context.Context, who Actor, agent, line, comment string) (SSHKeyView, error)

AddSSHKey gives an agent or the caller a public key for the SSH channel. A key for an agent, other than by the agent itself, is added by its owner, or an admin who holds what the agent may use (mayEquip).

func (*Bridge) Agent

func (b *Bridge) Agent(who Actor, name string) (AgentView, error)

Agent returns one agent, for its owner or an admin.

func (*Bridge) Agents

func (b *Bridge) Agents(who Actor, owner string) ([]AgentView, error)

Agents lists the agents who may see: an admin everyone's (or owner's), a person their own.

func (*Bridge) AlertDetail

func (b *Bridge) AlertDetail(ctx context.Context, p store.Principal, id, before string) (AlertDetail, error)

AlertDetail reads one alert group with its evidence and timeline over a window opening before (such as 30m, the default) its start, for whoever p is.

func (*Bridge) AlertPage

func (b *Bridge) AlertPage(id string) string

AlertPage is the signed link to an alert group's page.

func (*Bridge) AnnounceRulesTokenRotated

func (b *Bridge) AnnounceRulesTokenRotated(ctx context.Context, who Actor)

AnnounceRulesTokenRotated echoes a rule engine token rotation to the alert chat.

func (*Bridge) AnnounceSettingsChange

func (b *Bridge) AnnounceSettingsChange(ctx context.Context, who Actor, version int64)

AnnounceSettingsChange echoes a system settings commit to the alert chat.

func (*Bridge) ArchivedIncidentID

func (b *Bridge) ArchivedIncidentID(group, episode string) (string, error)

ArchivedIncidentID finds the incident's private summary when the live group holds a later episode.

func (*Bridge) Audit

func (b *Bridge) Audit(limit int) []store.AuditEntry

Audit returns the latest audit entries.

func (*Bridge) AuditQuery

func (b *Bridge) AuditQuery(f store.AuditFilter) ([]store.AuditEntry, int, error)

AuditQuery is the audit log with a filter and pagination: the entries matching f, newest first, and how many match in all.

func (*Bridge) CanProbeNow

func (b *Bridge) CanProbeNow() bool

CanProbeNow reports whether this Beacon has a gateway for on-demand checks.

func (*Bridge) ChangePassword

func (b *Bridge) ChangePassword(_ context.Context, who Actor, current, password, keep string) error

ChangePassword changes the caller's own password; the console session keep stays signed in.

func (*Bridge) Changes

func (b *Bridge) Changes(q ChangeQuery) ([]store.Change, error)

Changes lists change events, the newest first.

func (*Bridge) CheckDrillHook

func (b *Bridge) CheckDrillHook(name string, who Actor) (DrillHookCheck, error)

CheckDrillHook checks only the named hook and only for its configured reporter.

func (*Bridge) ClaimToken

func (b *Bridge) ClaimToken(ctx context.Context, who Actor, token, owner, agent, preset string) (AgentView, error)

ClaimToken makes a legacy token an agent's of owner (an admin only): see store.ClaimToken.

func (*Bridge) CountFeishuCall

func (b *Bridge) CountFeishuCall()

CountFeishuCall records one Feishu API call against this month's budget.

func (*Bridge) CreateAgent

func (b *Bridge) CreateAgent(ctx context.Context, who Actor, in AgentInput) (AgentCreated, error)

CreateAgent makes an agent for a person (in.Owner; the caller when it is a person), with a first token when in.TTL is set, and returns the token's secret, shown once, with the snippets that use it. A person makes agents for themself; an admin for anyone. The preset may not exceed the owner's role. A named preset's scopes, and the machine access, must be within what the caller may give (withinCaller); custom scopes go through checkCustom. The command line is exempt.

func (b *Bridge) CreateShareLink(ctx context.Context, who Actor, kind, id string) (SharedLink, error)

CreateShareLink issues a signed URL for the current alert episode or the selected session.

func (*Bridge) CreateUserGroup

func (b *Bridge) CreateUserGroup(ctx context.Context, who Actor, name, description string, members []string) (store.UserGroup, error)

CreateUserGroup makes a group.

func (*Bridge) DeleteAgent

func (b *Bridge) DeleteAgent(ctx context.Context, who Actor, name string) error

DeleteAgent forgets an agent with all its credentials, for its owner or an admin.

func (*Bridge) DeleteToken

func (b *Bridge) DeleteToken(ctx context.Context, who Actor, name string) error

DeleteToken deletes a token: an agent's by the agent itself, its owner or an administrator who manages that owner, as on the agent's page (no machines:write needed); any other revocable token as RevokeToken allows.

func (*Bridge) DeleteUser

func (b *Bridge) DeleteUser(ctx context.Context, who Actor, username string) ([]string, error)

DeleteUser removes a person with their agents and every credential those have (store.DeleteAccount); what they did stays on record. Nobody removes their own account here, and Beacon keeps an owner.

func (*Bridge) DeleteUserGroup

func (b *Bridge) DeleteUserGroup(ctx context.Context, who Actor, name string) error

DeleteUserGroup deletes a group: what named it no longer reaches anyone through it.

func (*Bridge) Delivery

func (b *Bridge) Delivery() DeliverySetup

Delivery reports the configured routes for a new critical alert.

func (*Bridge) Echo

func (b *Bridge) Echo(ctx context.Context, text string)

Echo posts a plain message to the alert chat, as every recorded change is.

func (*Bridge) EndMaintenance

func (b *Bridge) EndMaintenance(ctx context.Context, id string, who Actor) (store.Maintenance, error)

EndMaintenance ends a maintenance window now, or calls it off before it began: its silences end, and the pages say so.

func (*Bridge) EndUserSessions

func (b *Bridge) EndUserSessions(ctx context.Context, who Actor, username string) (int, error)

EndUserSessions ends every console session of a person, and reports how many there were. What they may do is unchanged: they can sign in again.

func (*Bridge) EnrollNode

func (b *Bridge) EnrollNode(ctx context.Context, who Actor, kind, subject string, rotate bool) (EnrolledNode, error)

EnrollNode issues or rotates a subject-bound gateway token for a probe location, host, heartbeat sender or rule engine. Requires a person or standalone credential with machines:write and config:write.

func (*Bridge) Evidence

func (b *Bridge) Evidence(ctx context.Context, id, before string) (Evidence, error)

Evidence gathers what an agent needs to judge the alert group id, over a window that opens before (30m by default, at most 24h) ahead of the group's start.

func (*Bridge) EvidenceFor

func (b *Bridge) EvidenceFor(ctx context.Context, p store.Principal, id, before string) (Evidence, error)

EvidenceFor applies the authenticated principal's machine and session scopes to the evidence.

func (*Bridge) ExpireSilence

func (b *Bridge) ExpireSilence(ctx context.Context, silenceID string, who Actor) error

ExpireSilence ends a silence.

func (*Bridge) FilterSessionAudit

func (b *Bridge) FilterSessionAudit(p store.Principal, entries []store.AuditEntry)

FilterSessionAudit removes command previews when the reader has limited session access. The audit records name the machine but carry no enrolment identifier. A machine-bound reader can retrieve commands from the corresponding authorised session instead. A reader with access to all machines keeps the previews of every machine but the critical ones it does not reach.

func (*Bridge) Group

func (b *Bridge) Group(id string) (GroupView, error)

Group returns one alert group.

func (*Bridge) Groups

func (b *Bridge) Groups(firingOnly bool) []GroupView

Groups lists alert groups; with firingOnly, only those firing.

func (*Bridge) HandleAction

func (b *Bridge) HandleAction(ctx context.Context, a feishu.Action) feishu.Response

HandleAction answers a click on a card.

func (*Bridge) HandleWebhook

func (b *Bridge) HandleWebhook(ctx context.Context, w alertmanager.Webhook) error

HandleWebhook takes one alert group (from the router, in Alertmanager's webhook form).

func (*Bridge) HasPushToken

func (b *Bridge) HasPushToken(id string) bool

HasPushToken reports whether a push monitor has its token.

func (*Bridge) InMaintenance

func (b *Bridge) InMaintenance(id string, at time.Time) bool

InMaintenance reports whether a person's maintenance covers the monitor (a service label's value) at a time. Maintenance an agent planned is announced but quiets nothing.

func (*Bridge) IncidentOutcome

func (b *Bridge) IncidentOutcome(id string) (OutcomeResult, error)

IncidentOutcome reads the bounded, private summary of a resolved episode.

func (*Bridge) IncidentOutcomes

func (b *Bridge) IncidentOutcomes(group, before string, limit int) (OutcomePage, error)

IncidentOutcomes pages through retained alert episodes that reached rule recovery.

func (*Bridge) IncidentOutcomesFor

func (b *Bridge) IncidentOutcomesFor(p store.Principal, query OutcomeQuery) (OutcomePage, error)

IncidentOutcomesFor returns retained outcomes with related sessions within the machine selection.

func (*Bridge) IncidentPageFor

func (b *Bridge) IncidentPageFor(ctx context.Context, id, episode string, p store.Principal) (GroupView, Evidence, Timeline, error)

IncidentPageFor reads the evidence and timeline from one group snapshot under the same session policy.

func (*Bridge) Incidents

func (b *Bridge) Incidents() []store.Incident

Incidents lists the alert groups that may be incidents on a status page, the newest first.

func (*Bridge) Invite

func (b *Bridge) Invite(ctx context.Context, who Actor, role, note string) (LinkView, error)

Invite makes an invitation to join with role, valid for a day; the link is shown only now. The caller must hold every scope of the role and reach what it reaches (withinRole), and the invitation works only while it still does. It is made with its audit entry, or not at all (ErrUnrecorded).

func (*Bridge) Join

func (b *Bridge) Join(ctx context.Context, code, username, displayName, password string) (store.Account, error)

Join creates an account with a setup link or an invitation. The account is made with its audit entry, or not at all (ErrUnrecorded), and the link then still works.

func (*Bridge) LastSuccess

func (b *Bridge) LastSuccess(ctx context.Context, names []string) (map[string]time.Time, string)

LastSuccess reads when each of the heartbeats called names last succeeded, as VictoriaMetrics knows it now (within 31 days); the error, if the query failed, is said in a line.

func (*Bridge) LatestCriticalDeliveries

func (b *Bridge) LatestCriticalDeliveries() map[string]DeliveryAttempt

LatestCriticalDeliveries prefers the newest result for each configured destination. If no attempt can be matched, the latest historical record still explains why the current route is unverified.

func (*Bridge) LegacyTokens

func (b *Bridge) LegacyTokens() []store.Token

LegacyTokens lists the tokens from before accounts that nobody has claimed (store.Legacy).

func (*Bridge) ListAlerts

func (b *Bridge) ListAlerts(p store.Principal, f AlertFilter, before string) (AlertList, error)

ListAlerts lists the alert groups f chooses. The history of resolved episodes, when asked for, is paged with before (a cursor from the page before) and filtered by severity and since.

func (*Bridge) ListChanges

func (b *Bridge) ListChanges(q ChangeQuery) (ChangeList, error)

ListChanges lists change events as Changes does, marking the fields that hold the senders' text.

func (*Bridge) MaintenanceWindows

func (b *Bridge) MaintenanceWindows() []store.Maintenance

MaintenanceWindows lists the maintenance windows kept, the latest to start first.

func (*Bridge) MonitorLatency

func (b *Bridge) MonitorLatency(ctx context.Context, id string, from, to time.Time, step time.Duration) ([]LatencySeries, bool)

MonitorLatency reads a monitor's response times by location from VictoriaMetrics, over from to to at step, as the probes wrote them. ok is false when VictoriaMetrics cannot be read.

func (*Bridge) NewAgentToken

func (b *Bridge) NewAgentToken(ctx context.Context, who Actor, name string, ttl time.Duration) (AgentCreated, error)

NewAgentToken gives an agent another static token, for its owner, or an admin who holds what the agent may use (mayEquip).

func (*Bridge) OAuthAgent

func (b *Bridge) OAuthAgent(ctx context.Context, who Actor, clientID, clientName, name, preset string, machines store.MachineAccess, until time.Time) (store.Agent, store.MachineAccess, error)

OAuthAgent makes or reuses the agent a person allows an OAuth client to act as, and says what the grant may do: a new agent is made with the preset and machine access allowed; an existing agent of the person's, by its name, is never changed, and the grant may do no more than it may (a preset no stronger than its own, machine access within its own), so that allowing a client never widens an agent or its other credentials. The preset may not exceed the person's role, and the machine access is held to the person as any other (withinCaller): only an owner names a critical machine, and it is reached for store.CriticalGrantTTL at most. It returns the agent and the grant's machine access. Audited and echoed to the chat.

func (*Bridge) OAuthReplayed

func (b *Bridge) OAuthReplayed(ctx context.Context, agent, client, what string)

OAuthReplayed records that an authorization code or a refresh token was sent again after it was used, so that someone else may hold it: the grant it gave was revoked. what is code or refresh_token. Audited and echoed to the chat.

func (*Bridge) OnChannelRoutes

func (b *Bridge) OnChannelRoutes(fn func(service string) []string)

OnChannelRoutes tells the bridge which notification channels hear of a service's alerts (with "", the default channels), so that the delivery summary and the first drill's check count them as a way to people.

func (*Bridge) OnTransition

func (b *Bridge) OnTransition(fn func(Transition))

OnTransition makes fn hear of every new firing episode and recovery, after the group is stored.

func (*Bridge) OwnAccount

func (b *Bridge) OwnAccount(p store.Principal) (store.Account, bool)

OwnAccount is the account behind p: the person, or the person an agent acts for; false for a token of no one's.

func (*Bridge) PersonTokens

func (b *Bridge) PersonTokens(username string) []store.Token

PersonTokens lists the static tokens of a person's agents that have not expired: what a new password leaves working.

func (*Bridge) ProbeNow

func (b *Bridge) ProbeNow(ctx context.Context, who Actor, in ProbeNowInput) (ProbeNow, error)

ProbeNow has every location that probes the input's targets probe them again at once, waits for their answers (in.Wait seconds, 45 by default and at most 90) and returns them per location.

func (*Bridge) Probes

func (b *Bridge) Probes(ctx context.Context, svcs []string, w Window, limit int) ProbeEvidence

Probes is what the probes of the services svcs saw over w, as the evidence has it: one result per location, target and module (naming the service when there are several), failing first, at most limit of them (Truncated says when there were more).

func (*Bridge) PushToken

func (b *Bridge) PushToken(ctx context.Context, who Actor, id string, rotate bool) (EnrolledNode, error)

PushToken issues a push monitor's token, or replaces it with rotate: it writes only that monitor's pushes (heartbeat:write, the monitor as its subject). The secret is shown once, here.

func (*Bridge) Ready

func (b *Bridge) Ready() (bool, []string)

Ready checks the alerting pipeline's Watchdog and the configured notification providers. The console translates the reasons by their text (frontend/src/areas/monitoring/overview.tsx): change both.

func (*Bridge) Recheck

func (b *Bridge) Recheck()

Recheck closes what is open on the SSH channel for whoever may no longer reach it (Deps.Recheck).

func (*Bridge) RecordChange

func (b *Bridge) RecordChange(_ context.Context, c store.Change, by string) (store.Change, error)

RecordChange stores a change event that the token called by posted. What its sender says is cleaned and cut, being untrusted; a change without a time happened now.

func (*Bridge) RecordDrill

func (b *Bridge) RecordDrill(ctx context.Context, until time.Time, by string) error

RecordDrill records a drill that by started, failing the drill service until until, or ended (until is zero). The summary says when a drill ends by itself, since an agent working the alert cannot end it.

func (*Bridge) RecordStart

func (b *Bridge) RecordStart(ctx context.Context, version string) error

RecordStart records Beacon starting on a version other than the one it last ran; the first start with a version recorded counts as such.

func (*Bridge) RecordStatsCleared

func (b *Bridge) RecordStatsCleared(ctx context.Context, who Actor, id string) error

RecordStatsCleared writes the audit entry for clearing a monitor's statistics, before they are cleared, and echoes it to the alert chat: history is never forgotten without a record of who had it forgotten.

func (*Bridge) RemoveGroupMember

func (b *Bridge) RemoveGroupMember(ctx context.Context, who Actor, name, username string) (store.UserGroup, error)

RemoveGroupMember takes a person out of a group (ErrNotMember when they are not in it).

func (*Bridge) RemoveSSHKey

func (b *Bridge) RemoveSSHKey(ctx context.Context, who Actor, agent, fp string) error

RemoveSSHKey takes a key, by its fingerprint, from an agent or from the caller.

func (*Bridge) RenewToken

func (b *Bridge) RenewToken(ctx context.Context, p store.Principal, via string) (Renewed, error)

RenewToken gives the caller's token a new secret that expires its lifetime from now; the old secret keeps working for store.RenewGrace. At most once every store.RenewEvery; never for an enrolled machine's token or an OAuth access token. Echoed to the chat, as every write is, and renewed only with its audit entry (ErrUnrecorded otherwise: the token keeps the secret it had).

func (*Bridge) ReportAgentRun

func (b *Bridge) ReportAgentRun(ctx context.Context, id, delivery string, who Actor, in AgentRunInput) (store.AgentRun, error)

ReportAgentRun writes an execution report independently of the hook's delivery response. Neither a start nor a terminal report changes the group's escalation, ownership or recovery state.

func (*Bridge) Reset

func (b *Bridge) Reset(ctx context.Context, code, password string, revokeTokens bool) (store.Account, error)

Reset gives an account a new password with a reset link (store.ResetAccount): its console sessions and the OAuth sign-ins of its agents end, its own SSH keys are removed, and what those had open on machines is closed. With revokeTokens the tokens of its agents are revoked too; otherwise they keep working.

func (b *Bridge) ResetLink(ctx context.Context, who Actor, username string) (LinkView, error)

ResetLink makes a one-time link, valid 30 minutes, with which username chooses a new password. The caller must hold every scope of the account's role and reach what the person reaches (withinRole), and the link works only while it still does. It is made with its audit entry, or not at all (ErrUnrecorded).

func (b *Bridge) ResetLinks(who Actor) ([]LinkView, error)

ResetLinks lists the password reset links that still work, the newest first; for an admin only. Their codes are never shown again.

func (*Bridge) ResetTwoFactor

func (b *Bridge) ResetTwoFactor(ctx context.Context, who Actor, username string) error

ResetTwoFactor takes a person's second factor off their account, for someone who lost their authenticator and their recovery codes. They sign in with their password alone next, and are asked to set it up again when the owner requires it. Their console sessions end.

func (*Bridge) RevokeGrant

func (b *Bridge) RevokeGrant(ctx context.Context, who Actor, id string) error

RevokeGrant revokes an OAuth grant, for its agent's owner or an admin.

func (*Bridge) RevokePushToken

func (b *Bridge) RevokePushToken(id string)

RevokePushToken revokes a removed push monitor's token, if it has one.

func (b *Bridge) RevokeShareLinks(ctx context.Context, who Actor, kind, id string) error

RevokeShareLinks invalidates every outstanding signed URL for this alert group or session.

func (*Bridge) RevokeToken

func (b *Bridge) RevokeToken(ctx context.Context, who Actor, name string) error

RevokeToken deletes the token called name for who (the console, the API and MCP), ends its console sessions and closes what it has open on machines, records it in the audit log and echoes it to the chat, as every write is. Only Revocable tokens, and only by someone who may (mayRevoke).

func (*Bridge) Run

func (b *Bridge) Run(ctx context.Context, ping func(ctx context.Context, ok bool) error)

Run ticks until ctx is done and pings the healthchecks.io check every minute when ready.

func (*Bridge) SSHConfig

func (b *Bridge) SSHConfig(agent string) string

SSHConfig is the ssh configuration for an agent that has a key: a block for each machine it reaches and the known_hosts line; empty without a key or without the channel.

func (*Bridge) SSHKeys

func (b *Bridge) SSHKeys(who Actor, agent string) ([]SSHKeyView, error)

SSHKeys lists an agent's keys or those of the caller when agent is empty.

func (*Bridge) ScheduleMaintenance

func (b *Bridge) ScheduleMaintenance(ctx context.Context, who Actor, in MaintenanceInput) (store.Maintenance, error)

ScheduleMaintenance plans a maintenance window: its silences, its record, an audit entry and an echo to the alert chat.

func (*Bridge) SessionPage

func (b *Bridge) SessionPage(id string) string

SessionPage is the signed link to a session's page, with its replay.

func (*Bridge) SetCriticalMachines

func (b *Bridge) SetCriticalMachines(ctx context.Context, who Actor, username string, named store.MachineAccess) (UserView, error)

SetCriticalMachines names the critical machines a person who is not an owner reaches, each until its end if it has one; named with no machines takes them all away. Only an owner, or beacon on the host, does it. A machine named already keeps its end unless named gives another. What the person and their agents have open on machines they no longer reach is closed. Audited and echoed to the chat.

func (*Bridge) SetLanguage

func (b *Bridge) SetLanguage(p store.Principal, via string, lang i18n.Lang) error

SetLanguage keeps the console's language for the person p is (en or zh), audited (preferences). An agent or a token has no preferences of its own (ErrForbidden).

func (b *Bridge) SetupLink(via string) (LinkView, error)

SetupLink makes the one-time link that creates the first account, an owner, valid 30 minutes; only while Beacon has no account (store.ErrHasAccounts). via is start (written to the log) or cli.

func (*Bridge) ShareTarget

func (b *Bridge) ShareTarget(who Actor, kind, id string) (ShareTarget, error)

ShareTarget returns the current target, without issuing a credential.

func (*Bridge) SignIns

func (b *Bridge) SignIns(who Actor, f store.SignInFilter) ([]store.SignIn, int, error)

SignIns reads the sign-in log: an administrator (an owner, a standalone token with accounts:write) reads everyone's; a person only their own, whatever the filter names. Agents read none.

func (*Bridge) Silence

func (b *Bridge) Silence(ctx context.Context, id string, d time.Duration, who Actor, comment string) (GroupView, error)

Silence silences a firing group for d (at most 24 hours) with a comment.

func (*Bridge) SilenceLabels

func (b *Bridge) SilenceLabels(ctx context.Context, labels map[string]string, d time.Duration, who Actor, comment string) (alertmanager.Silence, error)

SilenceLabels silences every alert whose labels equal all of labels for d (at most 24 hours) with a comment, as `beacon silence create -matchers` does; the router stops delivering what matches. A firing group every alert of which matches is marked silenced (and acknowledged, as Silence does), so that its card shows it.

func (*Bridge) Silences

func (b *Bridge) Silences(ctx context.Context) ([]alertmanager.Silence, error)

Silences lists the active and pending silences.

func (*Bridge) Snippets

func (b *Bridge) Snippets(secret, agent string) []Snippet

Snippets are the ready-made ways to connect an agent with a token: Claude Code, Codex, curl, and the SSH configuration when the agent has a key and the channel is on.

func (*Bridge) Summarize

func (b *Bridge) Summarize() Summary

Summarize returns the summary.

func (*Bridge) T

func (b *Bridge) T(format string, args ...any) string

T translates a message into the language Beacon speaks in the chat.

func (*Bridge) TestHook

func (b *Bridge) TestHook(ctx context.Context, who Actor, name string) (HookTest, error)

TestHook calls the hook name once, at once, and says how it went. A webhook gets a signed payload whose event is test, about no alert, which a receiver answers without waking anyone (beacon-oncall answers 200 and runs nothing). A GitHub hook's token is checked by reading its workflow, which starts no run. The call is not retried, and the audit log records it.

func (*Bridge) Tick

func (b *Bridge) Tick(ctx context.Context)

Tick runs timed escalation and upkeep, including receipt polling and retaining incident history.

func (*Bridge) Timeline

func (b *Bridge) Timeline(ctx context.Context, id, before string) (Timeline, error)

Timeline returns the alert group id's timeline, over the window of its evidence.

func (*Bridge) TimelineFor

func (b *Bridge) TimelineFor(ctx context.Context, p store.Principal, id, before string) (Timeline, error)

TimelineFor applies the authenticated principal's machine and session scopes to related sessions.

func (*Bridge) Tokens

func (b *Bridge) Tokens(who Actor) ([]TokenListView, error)

Tokens lists the tokens who may see, the newest first: an administrator every token; a person their agents'; an agent its own; a token of its own itself.

func (*Bridge) TransitionOf

func (b *Bridge) TransitionOf(g GroupView) Transition

TransitionOf is the transition a firing group would make now, for reminders.

func (*Bridge) UpdateAgent

func (b *Bridge) UpdateAgent(ctx context.Context, who Actor, name string, up AgentUpdate) (AgentView, error)

UpdateAgent sets what an agent may do and the machines it reaches, for its owner or an admin. The preset may not exceed the owner's role. Custom scopes follow checkCustom: a person or a legacy token with accounts:write, or the command line, never an agent, and never beyond the owner's role or the caller's own scopes. A change that would give the agent a scope it did not want, or a machine it did not reach, must stay within what the caller holds. Narrowing keeps working. A refusal changes nothing and is not audited. The command line is exempt.

func (*Bridge) UpdateConfig

func (b *Bridge) UpdateConfig(rt RuntimeDeps)

UpdateConfig atomically swaps runtime settings and notification senders without dropping active groups.

func (*Bridge) UpdateProfile

func (b *Bridge) UpdateProfile(_ context.Context, who Actor, displayName string) (UserView, error)

UpdateProfile updates the signed-in person's own display name.

func (*Bridge) UpdateUser

func (b *Bridge) UpdateUser(ctx context.Context, who Actor, username string, ch UserChange) (UserView, error)

UpdateUser changes someone's role, display name or contact, or disables or enables them. A lowered role or a disabled account limits their sessions and agents at once, and withdraws the links they made; Beacon always keeps an enabled owner. The caller must hold every scope of the account's role, and of the role it is given, and reach what those reach (withinRole). A raised role or an enabled account is written with its audit entry, or not at all (ErrUnrecorded); an account that changed meanwhile is refused, to be looked at again.

func (*Bridge) UpdateUserGroup

func (b *Bridge) UpdateUserGroup(ctx context.Context, who Actor, name string, ch GroupChange) (store.UserGroup, error)

UpdateUserGroup changes a group's description or its members as a whole.

func (*Bridge) User

func (b *Bridge) User(who Actor, username string) (UserView, error)

User returns one account; for an admin, or the person themself.

func (*Bridge) UserGroup

func (b *Bridge) UserGroup(name string) (store.UserGroup, error)

UserGroup returns one group (store.ErrNotFound when there is none).

func (*Bridge) UserGroups

func (b *Bridge) UserGroups() []store.UserGroup

UserGroups lists the groups.

func (*Bridge) UserGroupsOf

func (b *Bridge) UserGroupsOf(username string) []string

UserGroupsOf names the groups username is in.

func (*Bridge) UserSessions

func (b *Bridge) UserSessions(who Actor, username string) ([]SignInSessionView, error)

UserSessions lists a person's console sessions, for an administrator.

func (*Bridge) UserViewOf

func (b *Bridge) UserViewOf(a store.Account) UserView

UserViewOf is an account as the API shows it.

func (*Bridge) Users

func (b *Bridge) Users(who Actor) ([]UserView, []LinkView, error)

Users lists the accounts and the pending invitations; for an admin only.

func (*Bridge) Watchdog

func (b *Bridge) Watchdog()

Watchdog records that the rules pipeline delivered its Watchdog alert.

func (*Bridge) Whoami

func (b *Bridge) Whoami(p store.Principal, via string) (TokenView, error)

Whoami describes the caller's credential, so that an agent can learn who it is to Beacon, what it may do and when its credential expires.

func (*Bridge) WithdrawInvitation

func (b *Bridge) WithdrawInvitation(ctx context.Context, who Actor, id string) error

WithdrawInvitation deletes a pending invitation.

func (b *Bridge) WithdrawLink(ctx context.Context, who Actor, id string) (LinkView, error)

WithdrawLink deletes a pending invitation or password reset link, by its ID (LinkView.ID), for an admin. Withdrawing only takes access away, so any admin may.

func (b *Bridge) WithdrawResetLinks(ctx context.Context, who Actor, username string) (int, error)

WithdrawResetLinks withdraws the pending password reset links for a person, and reports how many there were. Withdrawing only takes access away, so any administrator may.

type ChangeList

type ChangeList struct {
	Changes   []store.Change `json:"changes"`
	Untrusted Untrusted      `json:"untrusted"`
}

ChangeList is change events as REST and MCP list them, with the fields that hold the senders' text.

type ChangeQuery

type ChangeQuery struct {
	Service, Machine, Source, Since string
	Limit                           int
}

ChangeQuery asks for change events. Since is how far back, as a duration (24h by default; 7d works too) or an RFC 3339 time.

type ChangeView

type ChangeView struct {
	store.Change
	Related string `json:"related,omitempty"` // service or machine
	Phase   string `json:"phase"`             // before, during or after
}

ChangeView is a change event in the window; Related says whether it is about the group's service or one of its machines, Phase whether it came before the group started, while it fired or after.

type DeliveryAttempt

type DeliveryAttempt struct {
	AlertID, Episode, Result string
	At, DeviceAcknowledgedAt time.Time
	Destination              DeliveryDestination
}

DeliveryAttempt links a recent provider response to its incident.

type DeliveryDestination

type DeliveryDestination int

DeliveryDestination describes whether a historical outcome matches the current configuration.

const (
	DeliveryUnverified DeliveryDestination = iota
	DeliveryPrevious
	DeliveryCurrent
)

type DeliveryRoute

type DeliveryRoute struct {
	Channel string          `json:"channel"`
	Initial string          `json:"initial,omitempty"` // primary or fallback
	After   config.Duration `json:"after,omitempty"`   // escalation for an unacknowledged alert
}

DeliveryRoute is when a provider is called for a critical alert.

type DeliverySetup

type DeliverySetup struct {
	CriticalToPeople    bool            `json:"critical_to_people"`
	FeishuApp           bool            `json:"feishu_app"`
	GroupBot            bool            `json:"group_bot"`
	Pushover            bool            `json:"pushover"`
	Bark                bool            `json:"bark"`
	NotificationWebhook bool            `json:"notification_webhook,omitempty"`
	Slack               bool            `json:"slack,omitempty"`
	CriticalChat        string          `json:"critical_chat"`
	CriticalPhone       []string        `json:"critical_phone_escalation,omitempty"`
	CriticalRoutes      []DeliveryRoute `json:"critical_routes,omitempty"`
}

DeliverySetup describes configuration, independently of Watchdog and of any delivery attempt.

type Deps

type Deps struct {
	Config              *config.Config
	Store               *store.Store
	AM                  Silencer
	Feishu              feishu.API
	Pushover            Pusher
	Bark                Barker
	Bot                 Poster
	NotificationWebhook WebhookSender
	Slack               WebhookSender
	VM                  Querier
	Catalog             func() *catalog.Catalog
	MonitorMachine      func(scope targets.OutageScope, started time.Time) (store.MonitorMachine, bool)
	Metrics             *metrics.Metrics
	Log                 *slog.Logger
	Now                 func() time.Time
	// WSReady reports whether Feishu's long connection is up; nil when callbacks come over HTTP.
	WSReady func() bool
	// ProbeNow is the board of requests to probe on demand (probenow.go); nil without a gateway.
	ProbeNow *probenow.Board
	// Pages builds the signed links to the pages people open from the chat (pages.go); nil: no links.
	Pages *link.Pages
	// ShellCommands reads, from a finished session's transcript, the commands run at an interactive
	// shell's prompt with their exit statuses; nil without the SSH channel.
	ShellCommands func(sessionID string) []ShellCommand
	// SSHConfig is the ssh configuration (ssh_config blocks and the known_hosts line) for the principal with
	// this key (store.Principal.Key) and optional machine; nil without the SSH channel.
	SSHConfig func(key, machine string) string
	// Recheck closes what is open on the SSH channel for whoever may no longer reach it, after a
	// credential, an agent or an account changed (sshgate.Gate.Recheck); nil without the channel.
	Recheck func() int
}

Deps are the bridge's collaborators. Notification providers and VM may be nil.

type DesignatedMachine

type DesignatedMachine struct {
	Name    string `json:"name"`
	Service string `json:"service"`
}

DesignatedMachine names an enrolled machine that was designated for the service when the alert opened and is within the reader's machine access.

type Done

type Done struct {
	Ack      *store.Ack        `json:"ack,omitempty"`
	Silences []SilenceView     `json:"silences"`
	Notes    []store.Note      `json:"notes"`
	Agents   []store.AgentCall `json:"agents"`
	Buzzed   *time.Time        `json:"buzzed_at,omitempty"`
	Pushed   *time.Time        `json:"pushover_at,omitempty"`
	Machines []string          `json:"machines"`
	Sessions []SessionView     `json:"sessions"`
}

Done is what was done about the group. Machines are those its labels name and those the catalogue names for its heartbeats, whose sessions in the window (from before the group started) are listed with the sessions of the agents that acknowledged it or left notes.

type DrillHookCheck

type DrillHookCheck struct {
	SignedWebhook bool   `json:"signed_webhook"`
	MatchesDrill  bool   `json:"matches_drill"`
	DrillOnly     bool   `json:"drill_only"`
	CriticalChat  string `json:"critical_chat"`
}

DrillHookCheck describes the loaded firing configuration. It makes no call to either receiver.

type EnrolledNode

type EnrolledNode struct {
	Secret string      `json:"secret"`
	Token  store.Token `json:"token"`
}

EnrolledNode is the new gateway token issued for a probe location, host, heartbeat sender or rule engine.

type Event

type Event struct {
	At      time.Time                `json:"at"`
	Kind    string                   `json:"kind"`
	By      string                   `json:"by,omitempty"`   // a person, a token, a hook, a change's source
	Via     string                   `json:"via,omitempty"`  // how: feishu, pushover, api, mcp, ssh; the channel people were told on
	Text    string                   `json:"text,omitempty"` // a note, a comment, a change's summary, a command, why a call failed, a heartbeat's description
	Type    string                   `json:"type,omitempty"` // a change's kind, a session's kind, a hook's kind
	From    string                   `json:"from,omitempty"` // an acknowledgement that took the alert over: whose it replaced
	Machine string                   `json:"machine,omitempty"`
	Service string                   `json:"service,omitempty"`
	ID      string                   `json:"id,omitempty"` // the session (of a command too), change, silence or hook delivery; the heartbeat's name
	Until   *time.Time               `json:"until,omitempty"`
	Event   string                   `json:"event,omitempty"`  // notification or agent call phase, or emergency cancellation
	Result  string                   `json:"result,omitempty"` // provider result or reported execution phase
	Exit    *int                     `json:"exit,omitempty"`   // a session, command or programme exit status
	URL     string                   `json:"url,omitempty"`
	Related string                   `json:"related,omitempty"` // why a change or session is listed: service, machine or agent
	Phase   string                   `json:"phase,omitempty"`   // before, during or after
	Probes  []store.ProbeObservation `json:"probes,omitempty"`  // on-demand observations, including missing results
}

Event is one entry of a timeline. Kind is started, notified, buzzed, pushover, notification, acknowledged, note, silenced, silence_ended, agent, agent_run, change, session, command (one run at a shell's prompt), heartbeat (its last success), probe_now or resolved; the other fields say what each needs. URL is a change's link, or the signed link to a session's page, where people replay it. Phase, on changes, sessions, commands and heartbeats, says whether the event came before the group started, while it fired or after it resolved.

type Evidence

type Evidence struct {
	Alert              AlertBrief          `json:"alert"`
	Window             Window              `json:"window"`
	Untrusted          Untrusted           `json:"untrusted"`
	Probes             ProbeEvidence       `json:"probes"`
	Heartbeats         []HeartbeatView     `json:"heartbeats,omitempty"`
	DesignatedMachines []DesignatedMachine `json:"designated_machines,omitempty"`
	Related            []RelatedAlert      `json:"related"`
	Changes            []ChangeView        `json:"changes"` // related ones first, then the newest
	Done               Done                `json:"done"`
	Links              AlertLinks          `json:"links"`
	// LinkedMachines are named by an explicit machine label or a catalogue heartbeat. The console
	// uses these for navigation, independently of the broader correlations in Done.
	LinkedMachines  []string               `json:"-"`
	MonitorMachines []store.MonitorMachine `json:"-"`
}

Evidence is what an agent needs to judge an alert group. Heartbeats are there when its labels name a heartbeat (HeartbeatStale, HeartbeatMissing).

type FiringCall

type FiringCall struct {
	Delivery string    `json:"delivery"`
	At       time.Time `json:"at"`
	Status   string    `json:"status"` // pending, ok or failed
	Recent   bool      `json:"recent"`
}

FiringCall is, in a resolved payload, the hook's call that woke the agent when the group fired: its delivery, when it was made and how it went. Recent says it was made less than recentFiring before the group resolved, so the run it started may still be going, writing its notes.

type GrantView

type GrantView struct {
	ID     string `json:"id"`
	Client string `json:"client"`
	Scope  string `json:"scope"`
	Preset string `json:"preset"` // what the person allowed it, within what the agent may do
	MachineAccessView
	Created  time.Time `json:"created"`
	LastUsed time.Time `json:"last_used,omitzero"`
	Expires  time.Time `json:"expires"`
}

GrantView is one of an agent's OAuth grants.

type GroupChange

type GroupChange struct {
	Description *string   `json:"description"`
	Members     *[]string `json:"members"`
}

GroupChange is what a change to a group sets; nil leaves it.

type GroupView

type GroupView struct {
	ID          string            `json:"id"`
	Status      string            `json:"status"`
	Severity    string            `json:"severity"`
	Title       string            `json:"title"`
	Description string            `json:"description,omitempty"`
	Service     string            `json:"service,omitempty"`
	Labels      map[string]string `json:"labels"`
	Alerts      int               `json:"alerts"`
	StartsAt    time.Time         `json:"starts_at"`
	ResolvedAt  *time.Time        `json:"resolved_at,omitempty"`
	Channel     string            `json:"channel"`
	Ack         *store.Ack        `json:"ack,omitempty"`
	AckVersion  string            `json:"ack_version"`       // the acknowledgement as read, for AckOptions.Expected
	Episode     string            `json:"episode,omitempty"` // the current incident within the group
	Silence     *store.Silence    `json:"silence,omitempty"`
	Buzzed      *time.Time        `json:"buzzed_at,omitempty"`
	Pushed      *time.Time        `json:"pushover_at,omitempty"`
	Runbook     string            `json:"runbook,omitempty"`
	Dashboard   string            `json:"dashboard,omitempty"`
	Notes       []store.Note      `json:"notes,omitempty"`
	Agents      []store.AgentCall `json:"agents,omitempty"` // the hooks called to wake agents, and how that went
	Page        string            `json:"page,omitempty"`   // the signed link to the alert's page, for people

	PushoverCancellation string `json:"pushover_cancellation,omitempty"`
}

GroupView is an alert group as the API shows it.

type HeartbeatView

type HeartbeatView struct {
	Name        string     `json:"name"`
	Description string     `json:"description,omitempty"`
	MaxAge      string     `json:"max_age,omitempty"` // as the catalogue writes it: 26h
	Severity    string     `json:"severity,omitempty"`
	Machine     string     `json:"machine,omitempty"`
	Enrolled    *bool      `json:"enrolled,omitempty"`
	LastSuccess *time.Time `json:"last_success,omitempty"`
	Hint        string     `json:"hint,omitempty"`
	Error       string     `json:"error,omitempty"`
}

HeartbeatView is a heartbeat an alert is about: its entry in the catalogue, whether the SSH channel has the machine it names (Enrolled, when it names one), and its last success at the end of the window. Hint says how to reach the machine. Error says what could not be found out.

type HookPayload

type HookPayload struct {
	Delivery   string      `json:"delivery"`
	Event      string      `json:"event"` // firing or resolved
	At         time.Time   `json:"at"`
	Hook       string      `json:"hook"`
	Alert      AlertBrief  `json:"alert"`
	Links      AlertLinks  `json:"links"`
	FiringCall *FiringCall `json:"firing_call,omitempty"`
	Hint       string      `json:"hint"`
	Untrusted  Untrusted   `json:"untrusted"`
}

HookPayload is what a webhook receives. Delivery stays the same when a call is retried, and At is when the event happened, so a receiver can refuse a delivery it has seen or one that is too old. A resolved payload has the FiringCall that woke the agent for this episode.

type HookTest

type HookTest struct {
	Hook       string `json:"hook"`
	Kind       string `json:"kind"`
	OK         bool   `json:"ok"`
	Status     int    `json:"status,omitempty"`
	Error      string `json:"error,omitempty"`
	Delivery   string `json:"delivery,omitempty"` // a webhook's test delivery
	DurationMS int64  `json:"duration_ms"`
}

HookTest is how a test call of a hook went. Status is the receiver's HTTP status (0 without an answer); Error says why it failed, without an address or a secret.

type LatencySeries

type LatencySeries struct {
	Location string       `json:"location"`
	Points   [][2]float64 `json:"points"` // [unix seconds, milliseconds]
}

LatencySeries is one location's response times, in milliseconds.

type LinkView

type LinkView struct {
	ID        string    `json:"id"`
	Kind      string    `json:"kind"`
	Role      string    `json:"role,omitempty"`
	Note      string    `json:"note,omitempty"`
	User      string    `json:"user,omitempty"`
	URL       string    `json:"url,omitempty"`
	Created   time.Time `json:"created"`
	CreatedBy string    `json:"created_by,omitempty"`
	Expires   time.Time `json:"expires"`
}

LinkView is a one-time link: an invitation, the setup link or a password reset. URL, with the code, is shown only when the link is made.

type MachineAccessView

type MachineAccessView struct {
	Access   string               `json:"machine_access"`
	Machines []string             `json:"machines,omitempty"`
	Until    map[string]time.Time `json:"machine_until,omitempty"`
	Summary  string               `json:"machine_summary"`
}

MachineAccessView is a machine access as the API shows it: Access is all, named or none; Machines the machines named (with all: the critical machines it also reaches); Until when the access to a named machine ends; Summary the same in a sentence.

func AccessView

AccessView shows a.

func (MachineAccessView) MachineAccess

func (v MachineAccessView) MachineAccess() store.MachineAccess

MachineAccess is the access the view shows.

type MaintenanceInput

type MaintenanceInput struct {
	Services    []string  `json:"services"`
	StartsAt    time.Time `json:"starts_at,omitzero"`
	EndsAt      time.Time `json:"ends_at,omitzero"`
	Title       string    `json:"title"`
	Description string    `json:"description,omitempty"`
	// Schedule makes it last until ended (manual) or recur (interval, weekly, monthly, cron) between StartsAt
	// and EndsAt (a year when left out); nil or once is the single window.
	Schedule *store.MaintenanceSchedule `json:"schedule,omitempty"`
}

MaintenanceInput is a maintenance window to plan. A start in the past, or none, is now: a window cannot cover what already happened.

type OutcomePage

type OutcomePage struct {
	Outcomes  []store.IncidentOutcome `json:"outcomes"`
	Before    string                  `json:"before,omitempty"`
	Untrusted Untrusted               `json:"untrusted"`
}

OutcomePage is the contract shared by the console, REST and MCP. Before is the next page's cursor.

type OutcomeQuery

type OutcomeQuery struct {
	Group, Before, Severity, Since, Origin, Evidence string
	Limit                                            int
}

OutcomeQuery filters retained incidents before applying the result limit and cursor.

type OutcomeResult

type OutcomeResult struct {
	Outcome   store.IncidentOutcome `json:"outcome"`
	Untrusted Untrusted             `json:"untrusted"`
}

type Poster

type Poster interface {
	Send(ctx context.Context, text string) error
}

Poster posts plain text to the alert chat.

type ProbeEvidence

type ProbeEvidence struct {
	Services  []string      `json:"services"`
	Locations int           `json:"locations"` // locations with results
	Failing   []string      `json:"failing"`   // locations failing at the end of the window
	Results   []ProbeResult `json:"results"`   // failing first
	Truncated bool          `json:"truncated,omitempty"`
	Queries   []string      `json:"queries,omitempty"`
	Error     string        `json:"error,omitempty"` // why the probes could not be read, or not all of them
}

ProbeEvidence is what the probes of the group's services saw, one result per location, target and module. Queries are the PromQL used, for a closer look through the gateway (metrics:read).

type ProbeNow

type ProbeNow struct {
	ID        string           `json:"id"`
	Episode   string           `json:"episode,omitempty"` // the incident selected for the check
	Targets   []ProbeTarget    `json:"targets"`
	Locations []string         `json:"locations"` // expected to answer
	Results   []ProbeNowResult `json:"results"`
	Missing   []string         `json:"missing"`  // locations with at least one missing result
	Complete  bool             `json:"complete"` // every expected result arrived
	Summary   string           `json:"summary"`
	Untrusted Untrusted        `json:"untrusted"`
}

ProbeNow is the answer: what was probed, each location's result (failing first), the locations that did not answer in time, and a one-line summary.

type ProbeNowInput

type ProbeNowInput struct {
	AlertID string
	Target  string
	Module  string
	Service string
	Wait    int
	Episode *string // when set, only verify this alert episode
}

ProbeNowInput is what to probe: one of AlertID (the targets of the group's alerts), Target (with an optional Module) or Service; and how many seconds to wait for the locations (0: the default).

type ProbeNowResult

type ProbeNowResult struct {
	Location        string     `json:"location"`
	Instance        string     `json:"instance"`
	Module          string     `json:"module"`
	Service         string     `json:"service,omitempty"`
	OK              bool       `json:"ok"`
	Reason          string     `json:"reason,omitempty"`
	DurationSeconds float64    `json:"duration_seconds"`
	HTTPStatus      int        `json:"http_status,omitempty"`
	Attempts        int        `json:"attempts,omitempty"`
	CertExpires     *time.Time `json:"cert_expires,omitempty"`
	ProbedAt        time.Time  `json:"probed_at"`
}

ProbeNowResult is one location's answer for one target: the fields the evidence shows, fresh. ProbedAt is when the answer reached Beacon.

type ProbeResult

type ProbeResult struct {
	Location            string         `json:"location"`
	Service             string         `json:"service,omitempty"` // when the group has several
	Instance            string         `json:"instance"`
	Module              string         `json:"module,omitempty"`
	OK                  bool           `json:"ok"`
	Stale               bool           `json:"stale,omitempty"` // no confirmed result in the last three minutes
	FailingSince        *time.Time     `json:"failing_since,omitempty"`
	FailingBeforeWindow bool           `json:"failing_before_window,omitempty"`
	RecoveredAt         *time.Time     `json:"recovered_at,omitempty"`
	Reason              string         `json:"reason,omitempty"` // probe_failure_info{reason}, while failing
	Reasons             map[string]int `json:"reasons,omitempty"`
	DurationSeconds     *float64       `json:"duration_seconds,omitempty"`
	HTTPStatus          int            `json:"http_status,omitempty"`
	Attempts            int            `json:"attempts,omitempty"` // beacon_probe_attempts
	CertExpires         *time.Time     `json:"cert_expires,omitempty"`
	LastSeen            time.Time      `json:"last_seen,omitzero"` // the stored sample time, when available
}

ProbeResult is one probe's state at the end of the window and its story in it. FailingSince is when the current failure began (FailingBeforeWindow: before the window); RecoveredAt is when a probe that failed in the window came back. Reasons counts the failed checks in the window by reason.

type ProbeTarget

type ProbeTarget struct {
	Instance  string   `json:"instance"`
	Module    string   `json:"module"`
	Service   string   `json:"service,omitempty"`
	Locations []string `json:"locations"`
}

ProbeTarget is one target of a request and the locations expected to probe it.

type Pusher

type Pusher interface {
	Send(ctx context.Context, m notify.Emergency) (string, error)
	Receipt(ctx context.Context, receipt string) (notify.Receipt, error)
	Cancel(ctx context.Context, receipt string) error
}

Pusher is Pushover's emergency priority.

type Querier

type Querier interface {
	Query(ctx context.Context, query string) ([]vm.Sample, error)
}

Querier evaluates instant queries (for the per-location matrix on cards).

type RangeQuerier

type RangeQuerier interface {
	QueryAt(ctx context.Context, query string, at time.Time) ([]vm.Sample, error)
	QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) ([]vm.Series, error)
}

RangeQuerier is what the evidence needs of VictoriaMetrics besides the card's instant queries; *vm.Client has it.

type RelatedAlert

type RelatedAlert struct {
	ID       string    `json:"id"`
	Title    string    `json:"title"`
	Severity string    `json:"severity"`
	Service  string    `json:"service,omitempty"`
	StartsAt time.Time `json:"starts_at"`
	Acked    bool      `json:"acknowledged"`
	Why      string    `json:"why"` // failure_domain=<value>, or service
}

RelatedAlert is another firing alert group in the same failure domain, or of the same service.

type Renewed

type Renewed struct {
	Token         TokenView `json:"token"`
	Secret        string    `json:"secret"`
	OldValidUntil time.Time `json:"old_secret_valid_until"`
}

Renewed is the answer to a renewal: the new secret, shown once, and when the old one stops working.

type RuntimeDeps

type RuntimeDeps struct {
	Config              *config.Config
	Lang                i18n.Lang
	Feishu              feishu.API
	Pushover            Pusher
	Bark                Barker
	Bot                 Poster
	NotificationWebhook WebhookSender
	Slack               WebhookSender
	VM                  Querier
	WSReady             func() bool
}

RuntimeDeps holds the mutable collaborators swapped atomically by UpdateConfig.

type SSHKeyView

type SSHKeyView struct {
	Key         string    `json:"key"`
	Fingerprint string    `json:"fingerprint"`
	Comment     string    `json:"comment,omitempty"`
	Added       time.Time `json:"added,omitzero"`
	Via         string    `json:"via,omitempty"` // the agent's own credential that added it (token:NAME, grant:ID); the key goes with it
}

SSHKeyView is a key for the SSH channel.

type SessionView

type SessionView struct {
	ID            string         `json:"id"`
	Agent         string         `json:"agent"`
	Via           string         `json:"via"`
	Machine       string         `json:"machine"`
	Kind          string         `json:"kind"`
	Command       string         `json:"command,omitempty"`
	Started       time.Time      `json:"started"`
	Ended         *time.Time     `json:"ended,omitempty"`
	Exit          *int           `json:"exit,omitempty"`
	Commands      int            `json:"commands,omitempty"` // commands run at an interactive shell's prompt
	Related       string         `json:"related"`            // machine or agent
	Phase         string         `json:"phase"`              // before, during or after
	ShellCommands []ShellCommand `json:"shell_commands,omitempty"`
	Page          string         `json:"page,omitempty"`
}

SessionView is a session on one of the group's machines, or by an agent that acted on the group. Page opens its replay in the console. Phase says whether it began before the group started (a possible cause), while it fired or after it resolved. A shell's ShellCommands are the last commands run at its prompt, with their exit statuses, from its transcript (Commands counts them all; get_session has the rest and their output).

type ShareTarget

type ShareTarget struct {
	Kind, ID, Title string
	// contains filtered or unexported fields
}

ShareTarget is the record whose outstanding signed links an owner can manage.

type SharedLink struct {
	URL       string    `json:"url"`
	ExpiresAt time.Time `json:"expires_at"`
}

SharedLink is shown to the caller that explicitly requests the current link.

type ShellCommand

type ShellCommand struct {
	Command string    `json:"command"`
	Exit    *int      `json:"exit,omitempty"`
	Started time.Time `json:"started"`
}

ShellCommand is a command run at an interactive shell's prompt, as the session's transcript has it.

type SignInSessionView

type SignInSessionView struct {
	ID        string    `json:"id"`
	Kind      string    `json:"kind"` // console or extension
	Name      string    `json:"name,omitempty"`
	Current   bool      `json:"current"`
	Address   string    `json:"address,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
	Method    string    `json:"method,omitempty"`
	Created   time.Time `json:"created"`
	LastSeen  time.Time `json:"last_seen,omitzero"`
	Expires   time.Time `json:"expires"`
}

SignInSessionView is a console sign-in, or a browser extension's device credential (Kind extension, with the Name the extension gave), as its person and the administrators see it: never its secret.

func SignInSessionViews

func SignInSessionViews(list []store.ConsoleSession, current string) []SignInSessionView

SignInSessionViews lists the person's console sessions; current is the hash of the caller's own, if any.

type SilenceView

type SilenceView struct {
	ID       string    `json:"id"`
	By       string    `json:"by"`
	Comment  string    `json:"comment,omitempty"`
	StartsAt time.Time `json:"starts_at,omitzero"`
	EndsAt   time.Time `json:"ends_at"`
}

SilenceView is a silence covering the group in the window.

type Silencer

type Silencer interface {
	CreateSilence(ctx context.Context, labels map[string]string, start, end time.Time, createdBy, comment string) (string, error)
	ExpireSilence(ctx context.Context, id string) error
	Silences(ctx context.Context) ([]alertmanager.Silence, error)
}

Silencer is what the bridge needs from the router: creating, ending and listing silences.

type Snippet

type Snippet struct {
	Key   string `json:"key"`   // claude-code, codex, curl, ssh
	Title string `json:"title"` // what it is for, in English
	Text  string `json:"text"`
}

Snippet is a ready-made way to connect an agent: a command or a configuration block.

type Summary

type Summary struct {
	Ready        bool           `json:"ready"`
	NotReady     []string       `json:"not_ready,omitempty"`
	Firing       map[string]int `json:"firing"`
	Acknowledged int            `json:"acknowledged"`
	FeishuCalls  int64          `json:"feishu_api_calls_this_month"`
	FeishuBudget int            `json:"feishu_api_budget"`
	Delivery     DeliverySetup  `json:"delivery"`
}

Summary is the bridge's state at a glance.

type Timeline

type Timeline struct {
	Alert      AlertBrief      `json:"alert"`
	Window     Window          `json:"window"`
	Untrusted  Untrusted       `json:"untrusted"`
	Heartbeats []HeartbeatView `json:"heartbeats,omitempty"`
	Events     []Event         `json:"events"`
}

Timeline is an alert group's story in time order: when it started and how people were told, what people and agents did, which agents were woken, and the changes and sessions on its machines around it, from before it started. Heartbeats are there when its labels name a heartbeat, as in the evidence.

type TokenListView

type TokenListView struct {
	Name               string    `json:"name"`
	Kind               string    `json:"kind"`
	Agent              string    `json:"agent,omitempty"`
	Owner              string    `json:"owner,omitempty"`
	Subject            string    `json:"subject,omitempty"`
	Scopes             []string  `json:"scopes"`
	Legacy             bool      `json:"legacy,omitempty"` // from before agents: an owner may make it an agent's
	*MachineAccessView           // a token of its own that reaches machines; an agent's reach is its agent's
	CreatedBy          string    `json:"created_by,omitempty"`
	Created            time.Time `json:"created"`
	Expires            time.Time `json:"expires"`
	Lifetime           string    `json:"lifetime"`
	Renewed            time.Time `json:"renewed,omitzero"`
	Expired            bool      `json:"expired"`
	Current            bool      `json:"current"`
	Revocable          bool      `json:"revocable"`
}

TokenListView is a token as a list shows it: never the secret or its hash. Kind is agent (an agent's credential; what it may do follows the agent), machine (an enrolled probe's, host's, heartbeat's or another machine's), or standalone (a token of its own, made on the host). Scopes are a token of its own's. Current is the caller's own; Revocable says whether the caller may delete it here.

type TokenView

type TokenView struct {
	Name         string   `json:"name"`
	Actor        string   `json:"actor"`
	User         string   `json:"user,omitempty"`
	Agent        string   `json:"agent,omitempty"`
	Preset       string   `json:"preset,omitempty"`
	Credential   string   `json:"credential"`
	Client       string   `json:"client,omitempty"`
	Scopes       []string `json:"scopes"`
	Subject      string   `json:"subject,omitempty"`
	MachineScope string   `json:"machine_scope"` // all, listed or none; the operation still needs its scope
	MachineAccessView
	SSHKeys []string  `json:"ssh_keys,omitempty"` // fingerprints of the keys it signs in with
	Created time.Time `json:"created,omitzero"`
	Expires time.Time `json:"expires"`
	// Lifetime is what the token was created with, as `token create -expires` takes it (365d, 12h); a
	// renewal makes it expire this long from then.
	Lifetime string    `json:"lifetime"`
	Renewed  time.Time `json:"renewed,omitzero"`
	// Renewable is false for an enrolled machine's token, which enroll -rotate replaces, and for an OAuth
	// access token. RenewableAt is when it may next renew itself (at most once a day).
	Renewable   bool      `json:"renewable"`
	RenewableAt time.Time `json:"renewable_at,omitzero"`
	Via         string    `json:"via"` // how the caller reached Beacon: api or mcp
}

TokenView is the caller's credential as its holder sees it: never the secret or its hash. Actor is how the audit log names the caller; User and Agent say whose it is (an agent's, owned by a person), Preset what the agent was given, and Scopes what it may do now (the preset within its owner's role). Credential is token, or oauth for an access token a person allowed an OAuth client (Client) to hold.

type Transition

type Transition struct {
	Event      string    `json:"event"` // firing or resolved
	Group      string    `json:"group"`
	Episode    string    `json:"episode"`
	Severity   string    `json:"severity"`
	Title      string    `json:"title"`
	Service    string    `json:"service,omitempty"`
	Monitor    string    `json:"monitor,omitempty"`
	Reason     string    `json:"reason,omitempty"`
	Locations  string    `json:"locations,omitempty"` // the probe locations failing, by id, comma-separated
	URL        string    `json:"url,omitempty"`
	StartsAt   time.Time `json:"starts_at"`
	ResolvedAt time.Time `json:"resolved_at,omitzero"`
}

Transition is a new firing episode of an alert group, or its recovery, as the notification channels (package channels) are told of it: what to say and where it leads. Its text is made from labels, so it is cleaned.

type Untrusted

type Untrusted struct {
	Fields []string `json:"fields"`
	Note   string   `json:"note"`
}

Untrusted names the fields of an answer that hold text from outside Beacon.

type UserChange

type UserChange struct {
	Role         *string `json:"role,omitempty"`
	Disabled     *bool   `json:"disabled,omitempty"`
	DisplayName  *string `json:"display_name,omitempty"`
	FeishuOpenID *string `json:"feishu_open_id,omitempty"`
}

UserChange changes an account; nil fields stay.

type UserView

type UserView struct {
	Username     string    `json:"username"`
	DisplayName  string    `json:"display_name"`
	Role         string    `json:"role"`
	FeishuOpenID string    `json:"feishu_open_id,omitempty"`
	Created      time.Time `json:"created"`
	CreatedBy    string    `json:"created_by,omitempty"`
	LastSignIn   time.Time `json:"last_sign_in,omitzero"`
	Disabled     bool      `json:"disabled"`
	TwoFactor    bool      `json:"two_factor"` // signs in with a code from an authenticator app too
	Agents       []string  `json:"agents,omitempty"`
	// The person's own machine access: every machine for an owner; every machine that is not critical,
	// and the critical machines named on the account, for anyone else.
	MachineAccessView
}

UserView is an account as the API shows it: never its password's hash.

type WebhookSender

type WebhookSender interface {
	Send(context.Context, []byte) error
}

WebhookSender submits a signed human notification to the configured receiver.

type Window

type Window struct {
	From time.Time `json:"from"`
	To   time.Time `json:"to"`
}

Window is the time an answer covers.

Jump to

Keyboard shortcuts

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