server

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package server owns the single plaintext HTTP listener that fronts the bot: the Telegram webhook, the Mini App (static assets + JSON API) and the internal Gotenberg callback. It deliberately knows nothing about the handlers it serves, so packages that implement them can depend on this one without creating an import cycle. Business handlers are injected through Config by the composition root (cmd/server).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthorized reports initData that is missing, malformed, or not
	// signed by the configured bot. It is deliberately coarse for clients:
	// they must not learn which individual check failed.
	ErrUnauthorized = errors.New("init data is not authorized")

	// ErrExpired reports correctly signed initData whose auth_date is older
	// than the permitted ttl. Callers still answer 401, but may distinguish
	// it from ErrUnauthorized when logging or when asking the client to
	// reopen the Mini App.
	ErrExpired = errors.New("init data has expired")
)

Functions

func NewAPI

func NewAPI(cfg APIConfig) http.Handler

NewAPI builds the Mini App API: the read endpoints, the keyword/alarm writes, the optional conversion route, /api/me and the administrator surface.

Every route sits behind two gates: initData proves who the caller is, and requireAllowed decides whether the access policy serves them. The admin routes add requireAdmin on top. Mount the result at "/api/" — it expects the full, unstripped request path.

func NewConvertHandler

func NewConvertHandler(cfg ConvertConfig) http.Handler

NewConvertHandler builds the POST /api/convert handler.

The returned handler is NOT wrapped in NewInitDataMiddleware: the route owner must mount it behind that middleware (and behind a POST-only pattern), exactly like the read API. It reads the authenticated user from the request context with UserFromContext, so serving it without the middleware answers 401 instead of trusting an unauthenticated caller.

func NewInitDataMiddleware

func NewInitDataMiddleware(botToken string, ttl time.Duration) func(http.Handler) http.Handler

NewInitDataMiddleware returns middleware that authenticates every request below /api/* and injects the resulting InitDataUser into the request context. The middleware holds no mutable state, so one instance can wrap the whole API subtree safely.

A missing or invalid header produces 401 with the shared error envelope. Expiry is also a 401 for the client, but the server log records the reason. The raw header value, the bot token and the signature are never logged: the header is a bearer credential and a log sink is often less protected than the request channel.

func NewStaticHandler

func NewStaticHandler() http.Handler

NewStaticHandler returns the handler for the Mini App static assets.

Path convention: newRouter mounts it with mux.Handle(appPrefix, handler), and net/http passes the full request path to a subtree handler, so the handler always receives "/app/..." — including the prefix — and strips it here. It is not wrapped in http.StripPrefix on purpose: keeping the prefix visible makes the routing table and this handler agree on one string (appPrefix) instead of relying on a wrapper that is easy to drop.

func WriteError

func WriteError(w http.ResponseWriter, status int, code string)

WriteError answers with the standard Mini App error envelope, for example WriteError(w, http.StatusUnauthorized, "unauthorized") writes exactly {"error":{"code":"unauthorized"}}.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as a JSON response with the given status. The body is marshalled before the status is committed, so an encoding failure still yields a well-formed JSON 500 instead of a truncated success response.

It deliberately does not append a trailing newline: handlers compare and tests assert on the exact body, and the error envelope is a fixed string.

Types

type APIConfig

type APIConfig struct {
	// BotToken authenticates every initData signature. An empty token makes
	// the middleware fail closed, which is what a deployment that lost this
	// setting must do instead of trusting a publicly known HMAC key.
	BotToken string

	// BotUsername is embedded in t.me deep links. Empty means "links are not
	// available": the endpoints then serve "" and the client hides the action
	// instead of producing "https://t.me/?start=...".
	BotUsername string

	// InitDataTTL bounds how old initData may be. A non-positive value means
	// one hour, matching NewInitDataMiddleware.
	InitDataTTL time.Duration

	// Conversion starts a PDF/PNG conversion for the authenticated user. It is
	// optional: a deployment without Gotenberg leaves /api/convert unregistered,
	// so the client gets the same JSON 404 as for any other absent endpoint.
	Conversion ConversionStarter

	// AllowedHost is the only notice host the conversion endpoint accepts. It
	// comes from SERVER_URL, so a crafted request cannot turn the bot into a
	// screenshot service for arbitrary pages.
	AllowedHost string

	// Status supplies the deployment facts the admin status screen shows
	// (webhook state, recently rejected accounts). It is optional: without it
	// the screen reports those fields as unavailable instead of inventing them.
	Status AdminStatusProvider
}

APIConfig configures the Mini App API: the read endpoints, the keyword/alarm writes, the optional conversion endpoint and the administrator surface.

type AdminStatus

type AdminStatus struct {
	// Webhook is nil when webhook mode is not configured.
	Webhook *WebhookStatus
	// RecentDenied lists recently rejected accounts. Callers may return nil.
	RecentDenied []DeniedUser
}

AdminStatus is one snapshot of the optional deployment facts.

type AdminStatusProvider

type AdminStatusProvider interface {
	SystemStatus(ctx context.Context) AdminStatus
}

AdminStatusProvider supplies the deployment facts the status screen cannot read from the database. It is implemented by the handler layer (which knows the webhook state) and injected through APIConfig.Status; nil means the deployment has nothing extra to report.

type Config

type Config struct {
	// Addr is the plaintext listen address, for example ":8080".
	Addr string
	// TelegramWebhook receives updates pushed by Telegram.
	TelegramWebhook http.HandlerFunc
	// PDFCallback receives Gotenberg's conversion result at POST /pdf/{id}.
	PDFCallback http.HandlerFunc
	// Static serves the Mini App assets below /app/.
	Static http.Handler
	// API serves the Mini App JSON endpoints below /api/.
	API http.Handler
	// Logger is optional. When nil request logging is skipped entirely, so
	// tests and embedders do not have to construct a logger first.
	Logger *utils.Logger
}

Config describes the capabilities the unified server exposes. Every handler is optional: a nil handler means "this deployment does not provide that capability" and its routes are not registered at all, so callers receive a plain 404 instead of a half-working endpoint.

type ConversionLimiter

type ConversionLimiter interface {
	Allow(key string) bool
}

ConversionLimiter reports whether key still has budget in the current rate window. It is the subset of *Limiter this endpoint uses, so the endpoint does not depend on the limiter's storage or its window bookkeeping.

type ConversionStarter

type ConversionStarter interface {
	StartConversion(ctx context.Context, chatID int64, noticeURL string, kind model.FileType, replyMessageID int) (string, error)
}

ConversionStarter submits one asynchronous conversion and returns the request id the Gotenberg callback will present. It is implemented by *handler.BotContext.StartConversion.

type ConvertConfig

type ConvertConfig struct {
	// Starter performs the conversion. It is required.
	Starter ConversionStarter
	// AllowedHost is the notice host conversions may target, normally
	// config.ServiceConfig.MessageServerUrl. An empty value rejects every
	// request: the allow-list must never fail open.
	AllowedHost string
	// Limiter enforces the per-user budget. A nil limiter skips the check;
	// that is only acceptable for tests or before the composition root wires
	// the real limiter, and production always passes one.
	Limiter ConversionLimiter
	// Now is the clock behind the dedupe deadline. Tests pin it; production
	// leaves it nil so time.Now is used.
	Now func() time.Time
}

ConvertConfig configures POST /api/convert.

type DeniedUser

type DeniedUser struct {
	UserID   int64
	Username string
	Name     string
	At       time.Time
}

DeniedUser is one account rejected by the access policy.

type InitDataUser

type InitDataUser struct {
	ID           int64
	Username     string
	FirstName    string
	LastName     string
	LanguageCode string
}

InitDataUser is the authenticated identity derived from initData. Only stable identity fields are exposed; the full Telegram user object carries more (photo_url, is_premium, ...) and none of it is needed to scope data.

func UserFromContext

func UserFromContext(ctx context.Context) (InitDataUser, bool)

UserFromContext returns the identity injected by NewInitDataMiddleware. The boolean is false when the request did not pass the middleware (or when a different, unrelated context is inspected), which lets handlers answer 401 instead of silently operating on a zero-valued id.

func ValidateInitData

func ValidateInitData(botToken, rawInitData string, now time.Time, ttl time.Duration) (InitDataUser, error)

ValidateInitData verifies rawInitData exactly as Telegram documents it:

secret             = HMAC_SHA256(key="WebAppData", msg=botToken)
data_check_string  = all fields except "hash", sorted by key,
                     joined as "key=value" with "\n"
expected_hash      = hex(HMAC_SHA256(key=secret, msg=data_check_string))

The raw string is already URL-encoded, so it is parsed with url.ParseQuery and the decoded values are signed over; that is what the official examples do, and any other choice makes genuine clients fail for values containing reserved characters (the user JSON always does).

now is injected instead of reading the clock so callers and tests can pin time. A non-positive ttl falls back to defaultInitDataTTL (one hour).

All failures are reported as ErrUnauthorized or ErrExpired. The wrapping is intentionally absent: callers match with errors.Is, and a richer error text would give an unauthenticated client a useful oracle.

type Limiter

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

Limiter is a per-key sliding-window rate limiter: a key may perform at most limit actions in any trailing window of the configured duration.

A sliding window is used instead of a fixed bucket because it cannot be gamed at a boundary: a fixed window would let a client spend its whole allowance at the end of one window and again at the start of the next, doubling the burst the write endpoints are protected against.

Expired state is dropped lazily from Allow, at most once per window. A background ticker with Stop() was deliberately not used: NewAPI has no lifecycle hook to stop such a goroutine, so every discarded handler (tests, future embedders) would leak one. A lazy sweep has the same bounded memory behaviour without owning a resource.

Limiter is safe for concurrent use.

func NewLimiter

func NewLimiter(limit int, window time.Duration) *Limiter

NewLimiter returns a limiter allowing limit actions per key in any trailing window. A non-positive limit or window cannot express a policy, so such a limiter rejects every action (fail closed) rather than silently disabling the protection.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) bool

Allow reports whether key may act now, and records the action when it may.

The window is half-open: an action taken exactly window ago has expired, so a client that waited a full window is allowed again immediately.

type Server

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

Server is the unified HTTP server. New builds it, Start binds and serves it, Shutdown drains it.

func New

func New(cfg Config) *Server

New builds the server and its routing table. Listening is deferred to Start so that a bind failure is reported synchronously to the caller: the plan (§4.1) requires the process to fail fast rather than serve a partial surface that Caddy would happily route traffic to.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the address the server is actually listening on. It is useful when Config.Addr requested port 0, which is how tests and sandboxed runs avoid colliding with an already running instance.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully drains in-flight requests and closes the listener. It is safe even when Start never ran: http.Server.Shutdown on a non-serving server is a no-op, and the bot's stop path must not depend on whether the listener came up.

func (*Server) Start

func (s *Server) Start() error

Start binds Addr and then serves in the background. Bind errors (port in use, malformed address) are returned immediately. Errors observed later by Serve are not returned: shutdown is signalled through Shutdown, where http.ErrServerClosed is the expected outcome rather than a failure.

type WebhookStatus

type WebhookStatus struct {
	URL       string
	LastError string
	Pending   int
}

WebhookStatus describes the Telegram webhook, when one is configured.

Jump to

Keyboard shortcuts

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