Documentation
¶
Overview ¶
Package telegram sends the panel's alerts to the admins who linked a Telegram chat, and serves the admin TelegramService that sets the bot up. One bot (the owner's), long polling only to hear "/start <code>" (the panel sits behind a decoy site and takes no inbound webhook), sendMessage for everything else.
What goes out is decided by the callers (cmd/mistgate wires them): health alert transitions, a new panel release, agents behind a release, a failed backup, an MCP plan waiting for the owner, an AWG kernel build that failed, and sign-in security events. This package owns the how: who receives it by role, never the same open alert twice, bursts coalesced into one message, retries with backoff and Telegram's retry_after, and a clean stop.
Index ¶
- Constants
- func ValidateUserBroadcast(text string, channels int) (trimmed, problem string)
- type ClientLogsNews
- type Config
- type L
- type ProposalNews
- type Service
- func (s *Service) AlertTransition(a store.HealthAlert, resolved bool)
- func (s *Service) ApplyUserNoticeChanges(ctx context.Context, kinds []store.UserNoticeChange, ...) error
- func (s *Service) AwgPrepareFailed(nodeID, code string, at int64)
- func (s *Service) BackupFailed(code string)
- func (s *Service) BackupOK()
- func (s *Service) BeginUserLink(ctx context.Context, user string) (link string, expires time.Time, err error)
- func (s *Service) CancelUserLink(ctx context.Context, user string) error
- func (s *Service) CheckUserBroadcast(ctx context.Context, b store.UserBroadcast) (UserBroadcastCheck, error)
- func (s *Service) ClearUserBot(ctx context.Context) (card UserBotStatus, dropped int, err error)
- func (s *Service) ClientLogs(n ClientLogsNews)
- func (s *Service) FlushNow(ctx context.Context)
- func (s *Service) FollowUpProblem(adminID, summary string)
- func (s *Service) Handler(opts ...connect.HandlerOption) (string, http.Handler)
- func (s *Service) MuteUserChat(ctx context.Context, user, chat string, muted bool) error
- func (s *Service) PlanWaiting(tool, tokenName string)
- func (s *Service) PollPendingLinkCode(ctx context.Context) error
- func (s *Service) PollPendingLinkCodes(ctx context.Context) error
- func (s *Service) PollPendingUserLink(ctx context.Context) error
- func (s *Service) ProduceUserIncidents(ctx context.Context) error
- func (s *Service) ProduceUserStatus(ctx context.Context) error
- func (s *Service) ProposalApplied(n ProposalNews)
- func (s *Service) ProposalFailed(n ProposalNews)
- func (s *Service) ProposalWaiting(n ProposalNews)
- func (s *Service) PurgeUserJournal(ctx context.Context) (more bool, err error)
- func (s *Service) RenderUserAppNotices(ctx context.Context) error
- func (s *Service) ResetUserNoticeKind(ctx context.Context, kind string) (store.UserNoticeKindView, error)
- func (s *Service) Run(ctx context.Context)
- func (s *Service) Security(e auth.Event)
- func (s *Service) SendUserBroadcast(ctx context.Context, b store.UserBroadcast) (id string, reach int, next time.Time, err error)
- func (s *Service) SendUserNotices(ctx context.Context) error
- func (s *Service) SetSources(src Sources)
- func (s *Service) SetUserBot(ctx context.Context, rawToken string) (card UserBotStatus, dropped int, err error)
- func (s *Service) SetUserChatLimit(ctx context.Context, user string, n int) error
- func (s *Service) SetUserNoticeKind(ctx context.Context, kind string, p store.UserNoticeKindPatch) (store.UserNoticeKindView, error)
- func (s *Service) SetUserNoticeOff(ctx context.Context, user string, kinds []string) ([]string, error)
- func (s *Service) TestUserBot(ctx context.Context) error
- func (s *Service) TestUserChat(ctx context.Context, user, chat string) error
- func (s *Service) UnlinkUserChat(ctx context.Context, user, chat string) error
- func (s *Service) UserBot(ctx context.Context) (UserBotStatus, error)
- func (s *Service) UserBroadcastSummary(ctx context.Context, id string) (store.UserBroadcastStatus, time.Time, error)
- func (s *Service) UserChats(ctx context.Context, user string) (UserChats, error)
- func (s *Service) UserDrafts(ctx context.Context) error
- func (s *Service) UserNoticeGlobalSettings(ctx context.Context) (map[string]string, error)
- func (s *Service) UserNoticeHistory(ctx context.Context, user, filter string, limit int, cursor, lang string) (items []UserNoticeHistoryItem, next string, notDelivered int, err error)
- func (s *Service) UserNoticeOff(ctx context.Context, user string) (off []string, stored string, err error)
- func (s *Service) UserNoticeSamples(ctx context.Context, lang string) ([]UserNoticeSampleText, error)
- func (s *Service) UserNoticeSettings(ctx context.Context) ([]store.UserNoticeKindView, error)
- func (s *Service) UserNotices(ctx context.Context, user, filter string, limit int, cursor string) (rows []store.UserNoticeLogEntry, next string, err error)
- func (s *Service) WatchTick(ctx context.Context, now time.Time)
- type Sources
- type UserBotStatus
- type UserBroadcastCheck
- type UserChatInfo
- type UserChats
- type UserNoticeHistoryItem
- type UserNoticeSampleText
Constants ¶
const UserBroadcastTextMax = 1000
UserBroadcastTextMax is the longest text, in characters: the contract with the app (spec 6a).
const (
UserJournalMinute = 23
)
The retention of the journal runs once an hour. The VPS loop keeps the time of its next run in itself; the edge tick calls it only in minute UserJournalMinute of the hour (as the health retention does in minute 17), so a tick of any other minute costs nothing, and a run is the read of the setting, one read of what is due (store.PurgeUserJournal) and the deletes when there is something. A second isolate in the same minute only deletes what is gone already.
Variables ¶
This section is empty.
Functions ¶
func ValidateUserBroadcast ¶
ValidateUserBroadcast trims the text and says what is wrong with it: "" for nothing, else empty, too_long or link. A link counts only when Telegram is among the channels asked for (0 asks for both).
Types ¶
type ClientLogsNews ¶
ClientLogsNews is the owner's news about the logs of a person's app (clientdebug.Notice, which the app wiring turns into this): the kind is "received" (the owner asked and they came), "unasked" (the person sent them on their own) or "declined" (the person refused the request). Only metadata: who, from which device, how many lines.
type Config ¶
type Config struct {
Store *store.Store
Vault *vault.Vault
// StepUp is auth.Service.RequireStepUp: setting the bot and linking a chat ask for it. Required.
StepUp func(context.Context) error
// AdminURL is the public address of the admin ("" = unknown: messages carry no link).
AdminURL string
Log *slog.Logger
// Edge is the Cloudflare edition: work is triggered by EdgeTick and bounded after-response tasks, not process loops.
Edge bool
// AfterResponse keeps short request producers alive until a post-response flush has finished. The runner is bounded by
// its caller; nil leaves delivery to the VPS background loop.
AfterResponse func(func())
// Test seams. The zero value is production.
APIBase string // https://api.telegram.org
UserAPIBase string // the same for the bot of the people; default APIBase
HTTPClient *http.Client // default: a client with no timeout of its own (every call has its context's)
Now func() time.Time
Window time.Duration // how long a burst is gathered into one message; default 30 s
PollTimeout int // getUpdates long-poll seconds; default 30
RetryBase time.Duration // first wait after a failed send, doubled each time; default 2 s
RetryMax int // sends tried before a message is dropped; default 6
WatchEvery time.Duration // release / agent check period; default 5 min
WatchFirst time.Duration // first check after Run starts; default 1 min
// UserBotTestEvery is the minimum interval between the owner's tests of the people's bot; default 10 s. It stays a Go default,
// not a setting: it only keeps a double click from sending two messages.
UserBotTestEvery time.Duration
// Wait replaces the timers in tests: it waits d, or until ctx ends (false) or wake fires (wake is nil where a bot
// change must not cut the wait short).
Wait func(ctx context.Context, d time.Duration, wake <-chan struct{}) bool
}
Config configures Service. Store and Vault are required.
type ProposalNews ¶
type ProposalNews struct {
ID, Kind string
NodeID string
// SubjectID is the inbound the proposal is about; its profile gives the name in the message.
SubjectID string
From, To string
// Code is the outcome code of a failed proposal.
Code string
}
ProposalNews is what a message about a proposal is made from. From and To are set only when the kind's values are public.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the Telegram module.
func New ¶
New builds the module. VPS starts Run; the edge invokes the bounded polling, watcher, and flush methods from EdgeTick.
func (*Service) AlertTransition ¶
func (s *Service) AlertTransition(a store.HealthAlert, resolved bool)
AlertTransition is health.Config.OnTransition: an alert opened (or re-opened) or ended. An alert already announced as open is not announced again; one that ended because a worse one replaced it, was accepted as normal or lost its node says nothing; one the admin muted ends and re-opens quietly.
func (*Service) ApplyUserNoticeChanges ¶
func (s *Service) ApplyUserNoticeChanges(ctx context.Context, kinds []store.UserNoticeChange, person *store.UserNoticeOffChange, settings ...store.UserNoticeSettingsChange) error
ApplyUserNoticeChanges carries out an approved plan: every change or none (plan_stale when a setting is no longer what the plan saw).
func (*Service) AwgPrepareFailed ¶
AwgPrepareFailed announces a failed build of the AmneziaWG kernel module on a node. at is the panel's time of the running-to-failed transition, which the fleet reports once per requested build: the same transition is told once, and a new build that fails again (even with the same code) is told again.
func (*Service) BackupFailed ¶
BackupFailed announces a failed backup once; the next one that works resolves it. The scheduler retries with a growing wait, and every retry that fails again would otherwise be a message.
func (*Service) BackupOK ¶
func (s *Service) BackupOK()
BackupOK resolves a failure that was announced.
func (*Service) BeginUserLink ¶
func (s *Service) BeginUserLink(ctx context.Context, user string) (link string, expires time.Time, err error)
BeginUserLink hands out the link of a person: the t.me address that holds a fresh one-time code, and when it runs out.
func (*Service) CancelUserLink ¶
CancelUserLink withdraws the pending code of a person.
func (*Service) CheckUserBroadcast ¶
func (s *Service) CheckUserBroadcast(ctx context.Context, b store.UserBroadcast) (UserBroadcastCheck, error)
CheckUserBroadcast counts the people a broadcast would reach, per channel, and names what is in the way. Numbers only: every admin and every token may ask.
func (*Service) ClearUserBot ¶
ClearUserBot switches the bot off and forgets every chat: the owner, after a step-up.
func (*Service) ClientLogs ¶
func (s *Service) ClientLogs(n ClientLogsNews)
ClientLogs tells the owner (only the owner: a person's logs are the owner's business) that the logs of a person's app came, on request or on the person's own, or that the person refused the request. The text has names and a count, never a word of the logs. How often a device sends on its own is bounded at the intake (once in ten minutes), so there is no throttle here.
func (*Service) FlushNow ¶ added in v0.1.50
FlushNow replaces the VPS burst window for bounded edge jobs and request producers.
func (*Service) FollowUpProblem ¶
FollowUpProblem tells an admin that a follow-up of their assistant found a problem: only that admin's chat, and only when the follow-up asked for Telegram (the person asked the assistant for it). The summary is the model's one line, scrubbed.
func (*Service) Handler ¶
Handler is the admin TelegramService (mounted behind the session like the others).
func (*Service) MuteUserChat ¶
MuteUserChat switches the announcements of one chat of a person.
func (*Service) PlanWaiting ¶
PlanWaiting announces an MCP plan that waits for the owner's approval: the owner only, with a link to the screen where the decision is made (never an approval from the chat).
func (*Service) PollPendingLinkCode ¶ added in v0.1.50
PollPendingLinkCode is one edge tick's bounded Telegram poll. It checks D1 before taking the cross-isolate lease, so the edge does not long-poll when there is no link code to hear.
func (*Service) PollPendingLinkCodes ¶
PollPendingLinkCodes is the edge tick's whole Telegram poll step: one read says whether an admin's or a person's link code waits, and only a bot with a code waiting is polled, each within its own time budget.
func (*Service) PollPendingUserLink ¶
PollPendingUserLink is a bounded poll of the people's bot on its own. It asks D1 for a waiting link code first, so with none the edge makes no call to Telegram, and holds the lease while it polls. The edge tick uses PollPendingLinkCodes, which does the one read for both bots.
func (*Service) ProduceUserIncidents ¶
ProduceUserIncidents is the edge tick's pass: with no person who can be told and nothing open or lately closed it is one read.
func (*Service) ProduceUserStatus ¶
ProduceUserStatus is the edge tick's pass: with no chat of a person it is one read; else the settings are read and one batch inserts what is missing. What does not fit in the page is made by the next tick.
func (*Service) ProposalApplied ¶
func (s *Service) ProposalApplied(n ProposalNews)
ProposalApplied announces a change the panel made itself.
func (*Service) ProposalFailed ¶
func (s *Service) ProposalFailed(n ProposalNews)
ProposalFailed announces a change that did not happen.
func (*Service) ProposalWaiting ¶
func (s *Service) ProposalWaiting(n ProposalNews)
ProposalWaiting announces a proposal that waits for the owner's decision: the owner only, with a link to the screen where it is decided (never an answer from the chat, so no buttons).
func (*Service) PurgeUserJournal ¶
PurgeUserJournal removes what the journal keeps past its retention (the setting "journal", 30 days unless the owner set it); more says a page limit stopped it.
func (*Service) RenderUserAppNotices ¶
RenderUserAppNotices is one pass: with nothing to render it is one read.
func (*Service) ResetUserNoticeKind ¶
func (s *Service) ResetUserNoticeKind(ctx context.Context, kind string) (store.UserNoticeKindView, error)
ResetUserNoticeKind returns one kind to the defaults of the code. The owner's.
func (*Service) Run ¶
Run starts the VPS polling, sending, and watcher loops until ctx ends, then briefly flushes queued messages. No goroutine outlives it; the edge runs bounded methods from EdgeTick instead.
func (*Service) Security ¶
Security is the auth event hook. It is called on its own goroutine and may block.
func (*Service) SendUserBroadcast ¶
func (s *Service) SendUserBroadcast(ctx context.Context, b store.UserBroadcast) (id string, reach int, next time.Time, err error)
SendUserBroadcast writes the broadcast, one notice for each person it reaches, in one batch. The owner's, or a token carrying out the approved plan of user_broadcast. It returns the id to follow it by, how many people it was written for and when the next broadcast is allowed. A problem of the check is a refusal of the same word (INVALID_ARGUMENT for the text and the audience, FAILED_PRECONDITION for nobody and too_soon), and nothing is written.
func (*Service) SendUserNotices ¶
SendUserNotices is the edge tick's pass: one read says whether anything is due (nothing due, no call to Telegram and no write), then a bounded batch is sent. What is left waits for the next tick.
func (*Service) SetSources ¶
SetSources connects the watcher to the update module (they are built after this one).
func (*Service) SetUserBot ¶
func (s *Service) SetUserBot(ctx context.Context, rawToken string) (card UserBotStatus, dropped int, err error)
SetUserBot sets the bot of the people: the owner, after a step-up. dropped is how many chats went with the old bot.
func (*Service) SetUserChatLimit ¶
SetUserChatLimit sets the chat limit of everybody (user "") or of one person, 1 to 10; 0 returns it to the default. The owner's.
func (*Service) SetUserNoticeKind ¶
func (s *Service) SetUserNoticeKind(ctx context.Context, kind string, p store.UserNoticeKindPatch) (store.UserNoticeKindView, error)
SetUserNoticeKind changes some fields of one kind and returns it as it is now. A value that makes no sense is an error, never ignored. The owner's.
func (*Service) SetUserNoticeOff ¶
func (s *Service) SetUserNoticeOff(ctx context.Context, user string, kinds []string) ([]string, error)
SetUserNoticeOff replaces the kinds switched off for one person; an empty list removes the setting. The owner's.
func (*Service) TestUserBot ¶
TestUserBot sends the test to the owner's admin-linked chat using the people's bot.
func (*Service) TestUserChat ¶
TestUserChat sends the fixed test message to one chat of a person at once, outside the outbox, in the language of the chat. It answers nil when Telegram took it. A chat that blocked the bot is forgotten, and the answer says so ("telegram_blocked"); a refused token is "telegram_unauthorized" and shows on the card of the bot; any other failure is "telegram_unreachable".
func (*Service) UnlinkUserChat ¶
UnlinkUserChat forgets one chat of a person.
func (*Service) UserBot ¶
func (s *Service) UserBot(ctx context.Context) (UserBotStatus, error)
UserBot is the card of the bot, for any signed-in admin.
func (*Service) UserBroadcastSummary ¶
func (s *Service) UserBroadcastSummary(ctx context.Context, id string) (store.UserBroadcastStatus, time.Time, error)
UserBroadcastSummary is how a broadcast fares (the last one when id is "") and when the next is allowed. Every admin and token.
func (*Service) UserDrafts ¶
UserDrafts is the edge tick's pass: with no draft waiting and no card open it is one read. While a card is open the queue of the owner's bot is read first, without waiting, and the presses in it are carried out before anything is burned or sent, so a press that came in time is not lost to the clock; the long poll of the tick stays last.
func (*Service) UserNoticeGlobalSettings ¶
UserNoticeGlobalSettings reads the effective settings and their stored values.
func (*Service) UserNoticeHistory ¶
func (s *Service) UserNoticeHistory(ctx context.Context, user, filter string, limit int, cursor, lang string) (items []UserNoticeHistoryItem, next string, notDelivered int, err error)
UserNoticeHistory is a page of one person's journal with the texts rendered the way the sender writes them, in lang (the panel's language when ""), and how many of the person's notices were never delivered. A signed-in admin of any role, never a token: the texts hold the owner's own words and node names, which a token (MCP, a script) must not read.
func (*Service) UserNoticeOff ¶
func (s *Service) UserNoticeOff(ctx context.Context, user string) (off []string, stored string, err error)
UserNoticeOff is the kinds switched off for one person alone, in the order of the table, and the setting as stored ("" for none).
func (*Service) UserNoticeSamples ¶
func (s *Service) UserNoticeSamples(ctx context.Context, lang string) ([]UserNoticeSampleText, error)
UserNoticeSamples renders what a person would read, for one language or, with lang "", for all five. It reads nothing from the store: the owner's days and percent are not in the samples yet (ponytail, user_samples.go).
func (*Service) UserNoticeSettings ¶
UserNoticeSettings is the table of the settings, 13 kinds in the order of the screen.
func (*Service) UserNotices ¶
func (s *Service) UserNotices(ctx context.Context, user, filter string, limit int, cursor string) (rows []store.UserNoticeLogEntry, next string, err error)
UserNotices is a page of the journal, newest first: of one person (user) or of everybody. filter is "" or "not_delivered". The cursor is the one the previous page returned; next is "" at the end.
type Sources ¶
type Sources struct {
// PanelRelease: the newest signed panel release that is newer than this build, if any.
PanelRelease func() (version string, available bool)
// OutdatedAgents: the version of the release the nodes are compared with and the names of the connected nodes behind it.
OutdatedAgents func(ctx context.Context) (version string, nodes []string)
}
Sources are what the periodic watcher asks other modules (wired after they exist; nil = not watched).
type UserBotStatus ¶
type UserBotStatus struct {
Configured bool
Username string
State string // "", "ok", "unauthorized", "unreachable", "conflict" or "same_as_owner"
LastSent time.Time
LastOK time.Time
Week store.UserNoticeCounts
People int // people with at least one chat
Chats int
ChatLimit int // of everybody
DefaultLimit int
}
UserBotStatus is the card of the bot of the people.
type UserBroadcastCheck ¶
type UserBroadcastCheck struct {
store.UserBroadcastReach
Problem string // "" or empty, too_long, link, audience_invalid, nobody, too_soon
Next time.Time // when the next broadcast is allowed; zero = now
}
UserBroadcastCheck is what a broadcast would do: the people it reaches and the first thing in its way.
type UserChatInfo ¶
UserChatInfo is one chat of a person, by its row id.
type UserChats ¶
type UserChats struct {
Chats []UserChatInfo
PendingExpires time.Time // zero: no code waits
Limit int // that applies to this person
LimitOverride int // the person's own, 0 = none
BotConfigured bool
}
UserChats is a person's chats and what the tab of the person needs next to them.
type UserNoticeHistoryItem ¶
type UserNoticeHistoryItem struct {
Notice store.UserNoticeLogEntry
Text string
Nodes []string
RestoredUnix int64
WantedChannels int
}
UserNoticeHistoryItem is a notice of one person's history as the owner's screen shows it: the notice, the text as it reads (or would read) in the language asked for, the names of the nodes of its incident and when they came back, what the owner asked a broadcast to reach.
type UserNoticeSampleText ¶
type UserNoticeSampleText struct{ Lang, Kind, Text string }
UserNoticeSampleText is one text of the preview: the kind (or variant), the language and the rendered text.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package usernotifyrpc is the UserNotifyService (proto/mistgate/usernotify/v1): the bot of the people and their Telegram chats, for the admin.
|
Package usernotifyrpc is the UserNotifyService (proto/mistgate/usernotify/v1): the bot of the people and their Telegram chats, for the admin. |