feat(telegram): split connector into home validator + remote bot
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Failing after 2m6s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Failing after 2m6s
Move all Telegram egress off the main host. The single connector held the bot token, long-polled Telegram and answered the gateway/backend over the trusted internal network, so the whole component (including login validation) shared fate with its VPN sidecar. Split it into two binaries that share the token: - cmd/validator (home, no VPN): Mini App initData + Login Widget HMAC only, never calls the Bot API. The gateway dials it for Telegram auth, so game login is now independent of Telegram reachability. - cmd/bot (remote): Bot API long-poll + sendMessage, the only component reaching Telegram. It holds no inbound port — it dials the gateway over a new reverse mTLS bot-link (pkg/proto/botlink/v1) and executes the send commands the gateway pushes. The gateway funnels sends to the bot-link: out-of-app push is fire-and-forget (at-most-once, dropped if no bot is connected); the backend admin broadcasts reach a gateway-served relay that forwards them and awaits the bot's ack (SendToUser/SendToGameChannel contract preserved). mTLS (pkg/mtls) is the one inter-service link that leaves the trusted segment; validator<->gateway and the relay stay plaintext internal. The bot is Telegram-rate-limited. One bot now; the gateway bot registry, an owns_updates flag and per-command ids leave seams for N later. Webhook rejected (one URL per token, adds inbound + a static address). The unified test contour runs the split (the bot keeps its VPN sidecar and dials the gateway by its internal name; bot-link certs from deploy/gen-certs.sh, generated in CI). The prod wiring — the bot on a separate host (no VPN), the gateway bot-link port published, PROD_ certs with scheduled rotation, an SSH deploy of both hosts together — is the deferred final stage (PRERELEASE.md TX, Stage 18). Docs: ARCHITECTURE, PRERELEASE (phase TX), platform/telegram + gateway + backend + deploy READMEs, FUNCTIONAL(+ru), CLAUDE.md, .env.example.
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
# Telegram connector image.
|
||||
# Telegram platform images: the home validator (HMAC of Mini App / Login Widget
|
||||
# data, no Bot API, no VPN) and the remote bot (Bot API long-poll + sendMessage,
|
||||
# dialing the gateway over the reverse mTLS bot-link). One build stage compiles both
|
||||
# binaries; the `validator` and `bot` targets each ship one on distroless nonroot.
|
||||
#
|
||||
# The connector imports only the shared scrabble/pkg module, so the build drops the
|
||||
# The platform imports only the shared scrabble/pkg module, so the build drops the
|
||||
# other workspace modules (backend, gateway, loadtest), the loadtest-only
|
||||
# scrabble/gateway replace and the scrabble-solver replace from a copy of go.work: it
|
||||
# needs neither their sources nor the solver sibling checkout.
|
||||
# Build from the repository ROOT so go.work, pkg/ and platform/telegram/ are all in
|
||||
# the context (see deploy/docker-compose.yml, which sets context: ../../..).
|
||||
# the context (see deploy/docker-compose.yml, which sets context: ..).
|
||||
FROM golang:1.26.3-alpine AS build
|
||||
WORKDIR /src
|
||||
|
||||
@@ -13,11 +16,18 @@ COPY go.work go.work.sum ./
|
||||
COPY pkg ./pkg
|
||||
COPY platform/telegram ./platform/telegram
|
||||
|
||||
# Reduce the workspace to what the connector needs: only pkg + platform/telegram.
|
||||
# Reduce the workspace to what the platform needs: only pkg + platform/telegram.
|
||||
RUN go work edit -dropuse=./backend -dropuse=./gateway -dropuse=./loadtest -dropreplace=scrabble/gateway@v0.0.0 -dropreplace=scrabble-solver
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/telegram ./platform/telegram/cmd/telegram
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/validator ./platform/telegram/cmd/validator
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/bot ./platform/telegram/cmd/bot
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=build /out/telegram /usr/local/bin/telegram
|
||||
ENTRYPOINT ["/usr/local/bin/telegram"]
|
||||
# --- validator (home) --------------------------------------------------------
|
||||
FROM gcr.io/distroless/static-debian12:nonroot AS validator
|
||||
COPY --from=build /out/validator /usr/local/bin/validator
|
||||
ENTRYPOINT ["/usr/local/bin/validator"]
|
||||
|
||||
# --- bot (remote) ------------------------------------------------------------
|
||||
FROM gcr.io/distroless/static-debian12:nonroot AS bot
|
||||
COPY --from=build /out/bot /usr/local/bin/bot
|
||||
ENTRYPOINT ["/usr/local/bin/bot"]
|
||||
|
||||
+91
-65
@@ -1,59 +1,68 @@
|
||||
# scrabble/platform/telegram — Telegram connector
|
||||
# scrabble/platform/telegram — Telegram validator + bot
|
||||
|
||||
The Telegram platform side-service. It is the **only** component that holds the bot
|
||||
token: it runs a Bot API long-poll loop (Mini App launch + deep-links) and serves
|
||||
the connector gRPC API that the gateway and backend call over the trusted internal
|
||||
network. See [`docs/ARCHITECTURE.md`](../../docs/ARCHITECTURE.md) §1/§3/§10/§12.
|
||||
The Telegram platform side-service, split into **two binaries** that share the bot
|
||||
token, so Telegram egress lives off the main host while game login does not depend on
|
||||
it. See [`docs/ARCHITECTURE.md`](../../docs/ARCHITECTURE.md) §1/§3/§10/§12/§13.
|
||||
|
||||
## Single bot
|
||||
- **`cmd/validator`** (home) — verifies Mini App `initData` and Login Widget data by
|
||||
HMAC (the bot token is the secret) and **never calls the Bot API**. It serves the
|
||||
validation gRPC API the gateway calls during Telegram auth, on the trusted internal
|
||||
network with no VPN. Because it needs no Telegram reachability, **game login stays up
|
||||
even when the bot or the bot-link is down**.
|
||||
- **`cmd/bot`** (remote) — runs the Bot API long-poll (Mini App launch + `/start`
|
||||
deep-links) and `sendMessage`, the only component reaching the Telegram Bot API. It
|
||||
holds **no inbound port**: it dials the gateway over a reverse **mTLS bot-link** and
|
||||
executes the send commands the gateway pushes, so its egress can run on a host with
|
||||
native Telegram access (a VPN sidecar in the test contour, a separate host in prod).
|
||||
|
||||
The connector hosts **one unified bot** — one token plus one optional game channel,
|
||||
configured by `TELEGRAM_BOT_TOKEN` and `TELEGRAM_GAME_CHANNEL_ID`. `ValidateInitData`
|
||||
validates `initData` against that single token (it does not validate ⇒ invalid) and
|
||||
returns only the Telegram user identity — there is no per-bot service language and no
|
||||
supported-languages set. Every message the bot sends is rendered in the **recipient's
|
||||
interface language**: the user-facing `Notify` renders in the request's `language` (the
|
||||
recipient's interface language); the admin `SendToUser` / `SendToGameChannel` render in
|
||||
an **operator-chosen** `language`. No call routes between bots — there is only one.
|
||||
Both hold the same token. One bot owns the exclusive `getUpdates` long-poll
|
||||
(`TELEGRAM_OWNS_UPDATES`, exactly one per token, else Telegram returns 409); the
|
||||
design leaves seams (a gateway bot registry, the `owns_updates` flag, per-command ids)
|
||||
for running several bots later, not built yet.
|
||||
|
||||
## Responsibilities
|
||||
## Validator
|
||||
|
||||
- **Mini App auth.** `ValidateInitData` verifies Telegram Web App `initData` (HMAC
|
||||
under the bot token) and returns the user identity. The gateway calls it during
|
||||
the `auth.telegram` edge operation, then provisions the session through the
|
||||
backend internal API — so the bot token never leaves this process.
|
||||
- **Out-of-app push.** `Notify` renders a backend push event (your_turn, nudge,
|
||||
match_found, and the invitation / friend_request notify sub-kinds) into a
|
||||
localized message with a Mini App launch button and sends it through the **single
|
||||
bot**, rendered in the request's `language` (the recipient's interface language).
|
||||
The gateway calls it **only** for a recipient with no live in-app stream and the
|
||||
`notifications_in_app_only` flag off, so the platform push never duplicates in-app
|
||||
delivery.
|
||||
`ValidateInitData` validates `initData` against the token and returns only the
|
||||
Telegram user identity (no per-bot service language, no supported-languages set);
|
||||
`ValidateLoginWidget` verifies Telegram **Login Widget** web sign-in data — HMAC under
|
||||
`SHA-256(bot_token)`, distinct from initData (`internal/loginwidget`) — for attaching a
|
||||
Telegram identity to an account from a browser. Both map a rejection to gRPC
|
||||
`InvalidArgument`.
|
||||
|
||||
## Bot
|
||||
|
||||
- **Send commands.** The gateway pushes `Notify` (out-of-app push: your_turn,
|
||||
game_over, nudge, match_found, and the invitation / friend_request notify sub-kinds),
|
||||
`SendToUser` and `SendToGameChannel` (operator broadcasts) down the bot-link. The bot
|
||||
renders the message in the command's `language` (the recipient's interface language;
|
||||
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
||||
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
||||
false when the kind is not rendered out-of-app or the user never started the bot).
|
||||
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a Mini App
|
||||
launch button; a deep-link payload routes the launch to a game / invitation /
|
||||
friend code.
|
||||
- **Admin messaging.** `SendToUser` and `SendToGameChannel` send
|
||||
arbitrary text to one user or a game channel through the single bot, rendered in the
|
||||
`language` the operator chooses in the admin console.
|
||||
launch button; a deep-link payload routes the launch to a game / invitation / friend
|
||||
code. This is **self-contained** — the bot never calls back into the game, so `/start`
|
||||
onboarding works even when the game is down.
|
||||
- **Rate limiting.** Outbound sends are throttled (`TELEGRAM_SEND_RATE_PER_SECOND`,
|
||||
default 25) to respect the Bot API flood limits.
|
||||
|
||||
The generic methods (`Notify`, `SendToUser`, `SendToGameChannel`) address a
|
||||
recipient by the identity `external_id` (as in the backend `identities` table), so a
|
||||
future VK / MAX connector can implement the same service; only `ValidateInitData` is
|
||||
Telegram-specific.
|
||||
The send commands address a recipient by the identity `external_id` (as in the backend
|
||||
`identities` table), so a future VK / MAX bot reuses them; only the validator's initData
|
||||
parsing is Telegram-specific.
|
||||
|
||||
## gRPC API
|
||||
## gRPC contracts
|
||||
|
||||
`pkg/proto/telegram/v1`, service `Telegram`: `ValidateInitData`,
|
||||
`ValidateLoginWidget`, `Notify`, `SendToUser`, `SendToGameChannel`. Generated Go is
|
||||
committed under `pkg`. `ValidateLoginWidget` verifies Telegram **Login
|
||||
Widget** web sign-in data — HMAC under `SHA-256(bot_token)`, distinct from initData
|
||||
(`internal/loginwidget`) — for attaching a Telegram identity to an account from a
|
||||
browser.
|
||||
- `pkg/proto/telegram/v1`, service `Telegram` — served by the **validator**
|
||||
(`ValidateInitData`, `ValidateLoginWidget`). Its `Notify` / `SendToUser` /
|
||||
`SendToGameChannel` request shapes are reused as bot-link command payloads; the
|
||||
gateway also implements `SendToUser` / `SendToGameChannel` as the backend's admin
|
||||
relay.
|
||||
- `pkg/proto/botlink/v1`, service `BotLink` — the reverse bidi stream the **bot** dials
|
||||
on the gateway (`Hello` / `Command` / `Ack`). Generated Go is committed under `pkg`.
|
||||
|
||||
## Deep-link scheme
|
||||
|
||||
Shared verbatim with the UI (`ui/src/lib/deeplink.ts`). A Mini App start parameter
|
||||
is a one-character kind prefix plus a value:
|
||||
Shared verbatim with the UI (`ui/src/lib/deeplink.ts`). A Mini App start parameter is a
|
||||
one-character kind prefix plus a value:
|
||||
|
||||
| Parameter | Destination |
|
||||
| --- | --- |
|
||||
@@ -67,40 +76,57 @@ The bot turns a `/start <payload>` or a notification target into a launch-button
|
||||
|
||||
## Configuration
|
||||
|
||||
Shared:
|
||||
|
||||
| Env var | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `TELEGRAM_BOT_TOKEN` | — (required) | The bot's API token + initData HMAC secret |
|
||||
| `TELEGRAM_GAME_CHANNEL_ID` | — | The bot's game channel chat id for `SendToGameChannel` |
|
||||
| `TELEGRAM_MINIAPP_URL` | — (required) | Mini App HTTPS origin (BotFather-registered) |
|
||||
| `TELEGRAM_GRPC_ADDR` | `:9091` | connector gRPC listen address |
|
||||
| `TELEGRAM_API_BASE_URL` | `https://api.telegram.org` | Bot API host override (mock / self-hosted) |
|
||||
| `TELEGRAM_TEST_ENV` | `false` | route to the Bot API **test environment** (`/bot<token>/test/METHOD`) |
|
||||
| `TELEGRAM_BOT_TOKEN` | — (required) | the bot's API token + initData HMAC secret |
|
||||
| `TELEGRAM_LOG_LEVEL` | `info` | zap log level |
|
||||
| `TELEGRAM_SERVICE_NAME` | `scrabble-telegram` | OpenTelemetry `service.name` |
|
||||
| `TELEGRAM_SERVICE_NAME` | per binary | OpenTelemetry `service.name` (validator: `scrabble-telegram-validator`, bot: `scrabble-telegram-bot`) |
|
||||
| `TELEGRAM_OTEL_TRACES_EXPORTER` | `none` | `none`, `stdout` or `otlp` (gRPC; endpoint from `OTEL_EXPORTER_OTLP_*`) |
|
||||
| `TELEGRAM_OTEL_METRICS_EXPORTER` | `none` | `none`, `stdout` or `otlp` |
|
||||
|
||||
The **test environment** is selected by `TELEGRAM_TEST_ENV=true`, which suffixes the
|
||||
Bot API path with `/test` (the connector appends it to the token, since the client
|
||||
builds `<host>/bot<token>/<method>`).
|
||||
Validator (`cmd/validator`):
|
||||
|
||||
| Env var | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `TELEGRAM_VALIDATOR_GRPC_ADDR` | `:9091` | validator gRPC listen address (the gateway dials it) |
|
||||
|
||||
Bot (`cmd/bot`):
|
||||
|
||||
| Env var | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `TELEGRAM_MINIAPP_URL` | — (required) | Mini App HTTPS origin (BotFather-registered) |
|
||||
| `TELEGRAM_GATEWAY_ADDR` | — (required) | the gateway bot-link endpoint to dial |
|
||||
| `TELEGRAM_BOTLINK_SERVER_NAME` | — (required) | the gateway certificate's expected SNI / CN |
|
||||
| `TELEGRAM_BOTLINK_TLS_CERT` / `_KEY` / `_CA` | — (required) | the bot client cert, its key, and the CA that signs the gateway server cert |
|
||||
| `TELEGRAM_GAME_CHANNEL_ID` | — | the bot's game channel chat id for `SendToGameChannel` |
|
||||
| `TELEGRAM_OWNS_UPDATES` | `true` | run the exclusive `getUpdates` long-poll (one bot per token) |
|
||||
| `TELEGRAM_SEND_RATE_PER_SECOND` | `25` | outbound Bot API send cap (0 disables) |
|
||||
| `TELEGRAM_INSTANCE_ID` | hostname | bot identity reported to the gateway |
|
||||
| `TELEGRAM_BOTLINK_RECONNECT_DELAY` | `2s` | pause before re-dialing after the stream ends |
|
||||
| `TELEGRAM_API_BASE_URL` | `https://api.telegram.org` | Bot API host override (mock / self-hosted) |
|
||||
| `TELEGRAM_TEST_ENV` | `false` | route to the Bot API **test environment** (`/bot<token>/test/METHOD`) |
|
||||
|
||||
## Build, test, run
|
||||
|
||||
```sh
|
||||
go build ./platform/telegram/...
|
||||
go test ./platform/telegram/... # unit tests use an httptest fake Bot API
|
||||
go run ./platform/telegram/cmd/telegram # needs a real TELEGRAM_BOT_TOKEN
|
||||
go test ./platform/telegram/... # unit tests use an httptest fake Bot API + an in-process bot-link
|
||||
go run ./platform/telegram/cmd/validator # needs TELEGRAM_BOT_TOKEN
|
||||
go run ./platform/telegram/cmd/bot # needs the bot env above + mTLS cert files
|
||||
```
|
||||
|
||||
## Deploy
|
||||
|
||||
The connector runs in its **own container** with the bot token held only there and
|
||||
all egress through a VPN sidecar (`deploy/docker-compose.yml`, mirroring
|
||||
`../../15-puzzle`). It needs no public ingress — it long-polls Telegram and answers
|
||||
internal gRPC at `telegram:9091` on the shared `edge` network. The host reverse proxy
|
||||
routes public traffic to the **gateway** port only, which serves the Mini App under
|
||||
`/telegram/`. The full multi-service deploy is `deploy/docker-compose.yml`.
|
||||
`platform/telegram/Dockerfile` builds both binaries on distroless nonroot with two
|
||||
targets, `validator` and `bot`. In the test contour (`deploy/docker-compose.yml`) the
|
||||
**validator** runs on the internal network (no VPN); the **bot** keeps a VPN sidecar
|
||||
for Telegram egress and dials the gateway bot-link by its internal name. The bot-link
|
||||
mTLS material is generated by `deploy/gen-certs.sh`. In prod the bot runs on a separate
|
||||
host with native Telegram access and dials the gateway's published bot-link port with
|
||||
`PROD_` certificates (the deferred final stage — see `PRERELEASE.md`).
|
||||
|
||||
A real end-to-end Telegram smoke needs a BotFather bot, its token, a public HTTPS
|
||||
Mini App origin, and the connector container; the unit tests cover the wire format,
|
||||
templates, deep-links and the gRPC handlers without a live bot.
|
||||
A real end-to-end Telegram smoke needs a BotFather bot, its token, a public HTTPS Mini
|
||||
App origin, and the bot container; the unit tests cover the wire format, templates,
|
||||
deep-links, the validator handlers and the bot-link client/executor without a live bot.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Command bot is the remote-side Telegram bot. It runs the Bot API long-poll
|
||||
// (Mini App launch + /start deep-links) and dials the gateway over the reverse mTLS
|
||||
// bot-link to receive and execute send commands (out-of-app push and admin sends).
|
||||
// It holds the bot token and is the only component that reaches the Telegram Bot
|
||||
// API, so it runs on a host with native Telegram access (no VPN) and needs no
|
||||
// inbound port. See platform/telegram/README.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc/credentials"
|
||||
|
||||
"scrabble/pkg/mtls"
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
"scrabble/platform/telegram/internal/bot"
|
||||
"scrabble/platform/telegram/internal/botlink"
|
||||
"scrabble/platform/telegram/internal/config"
|
||||
)
|
||||
|
||||
// telemetryShutdownTimeout bounds the OpenTelemetry flush during process exit.
|
||||
const telemetryShutdownTimeout = 5 * time.Second
|
||||
|
||||
func main() {
|
||||
cfg, err := config.LoadBot()
|
||||
if err != nil {
|
||||
log.Fatalf("bot: load config: %v", err)
|
||||
}
|
||||
logger, err := newLogger(cfg.LogLevel)
|
||||
if err != nil {
|
||||
log.Fatalf("bot: build logger: %v", err)
|
||||
}
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
if err := run(ctx, cfg, logger); err != nil {
|
||||
logger.Fatal("bot: terminated", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// run wires the bot long-poll and the bot-link client and runs both until the
|
||||
// context is cancelled.
|
||||
func run(ctx context.Context, cfg config.BotConfig, logger *zap.Logger) error {
|
||||
tel, err := pkgtel.New(ctx, cfg.Telemetry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), telemetryShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := tel.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Warn("telemetry shutdown", zap.Error(err))
|
||||
}
|
||||
}()
|
||||
if err := tel.StartRuntimeMetrics(); err != nil {
|
||||
logger.Warn("telemetry: start runtime metrics", zap.Error(err))
|
||||
}
|
||||
|
||||
b, err := bot.New(bot.Config{
|
||||
Token: cfg.Token,
|
||||
APIBaseURL: cfg.APIBaseURL,
|
||||
TestEnv: cfg.TestEnv,
|
||||
MiniAppURL: cfg.MiniAppURL,
|
||||
SendRatePerSecond: cfg.SendRatePerSecond,
|
||||
}, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tlsCfg, err := mtls.ClientConfig(cfg.BotLink.CertFile, cfg.BotLink.KeyFile, cfg.BotLink.CAFile, cfg.BotLink.ServerName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exec := botlink.NewExecutor(b, cfg.GameChannelID, logger)
|
||||
client := botlink.NewClient(botlink.ClientConfig{
|
||||
GatewayAddr: cfg.BotLink.GatewayAddr,
|
||||
InstanceID: cfg.BotLink.InstanceID,
|
||||
OwnsUpdates: cfg.OwnsUpdates,
|
||||
Creds: credentials.NewTLS(tlsCfg),
|
||||
ReconnectDelay: cfg.BotLink.ReconnectDelay,
|
||||
}, exec, logger)
|
||||
|
||||
logger.Info("telegram bot starting",
|
||||
zap.String("gateway", cfg.BotLink.GatewayAddr),
|
||||
zap.String("miniapp_url", cfg.MiniAppURL),
|
||||
zap.Bool("owns_updates", cfg.OwnsUpdates),
|
||||
zap.Bool("test_env", cfg.TestEnv))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
// The long-poll holds the exclusive getUpdates lease (one bot per token); a bot
|
||||
// that does not own it only delivers sends over the bot-link.
|
||||
if cfg.OwnsUpdates {
|
||||
wg.Go(func() { b.Run(ctx) })
|
||||
}
|
||||
wg.Go(func() {
|
||||
if err := client.Run(ctx); err != nil && ctx.Err() == nil {
|
||||
logger.Error("bot-link client stopped", zap.Error(err))
|
||||
}
|
||||
})
|
||||
|
||||
<-ctx.Done()
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// newLogger builds a production JSON logger at the given level.
|
||||
func newLogger(level string) (*zap.Logger, error) {
|
||||
var lvl zap.AtomicLevel
|
||||
if err := lvl.UnmarshalText([]byte(level)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := zap.NewProductionConfig()
|
||||
cfg.Level = lvl
|
||||
return cfg.Build()
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// Command telegram is the Telegram platform side-service (the "connector"). It is
|
||||
// the only component holding the bot token: it runs the Bot API long-poll loop
|
||||
// (Mini App launch + /start deep-links) and serves the connector gRPC API
|
||||
// (pkg/proto/telegram/v1) that the gateway and backend call over the trusted
|
||||
// internal network. See platform/telegram/README.md.
|
||||
// Command validator is the home-side Telegram validator. It serves the validation
|
||||
// gRPC API (pkg/proto/telegram/v1 ValidateInitData/ValidateLoginWidget) the gateway
|
||||
// calls during Telegram auth. It holds the bot token only as the HMAC secret and
|
||||
// never reaches the Telegram Bot API, so it runs on the main host with no VPN and
|
||||
// no Telegram egress, and game login stays independent of the remote bot. See
|
||||
// platform/telegram/README.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -20,24 +21,23 @@ import (
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
"scrabble/platform/telegram/internal/bot"
|
||||
"scrabble/platform/telegram/internal/config"
|
||||
"scrabble/platform/telegram/internal/connector"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
"scrabble/platform/telegram/internal/validator"
|
||||
)
|
||||
|
||||
// telemetryShutdownTimeout bounds the OpenTelemetry flush during process exit.
|
||||
const telemetryShutdownTimeout = 5 * time.Second
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
cfg, err := config.LoadValidator()
|
||||
if err != nil {
|
||||
log.Fatalf("telegram: load config: %v", err)
|
||||
log.Fatalf("validator: load config: %v", err)
|
||||
}
|
||||
logger, err := newLogger(cfg.LogLevel)
|
||||
if err != nil {
|
||||
log.Fatalf("telegram: build logger: %v", err)
|
||||
log.Fatalf("validator: build logger: %v", err)
|
||||
}
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
@@ -45,13 +45,12 @@ func main() {
|
||||
defer stop()
|
||||
|
||||
if err := run(ctx, cfg, logger); err != nil {
|
||||
logger.Fatal("telegram: terminated", zap.Error(err))
|
||||
logger.Fatal("validator: terminated", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// run wires the bot and the gRPC server and serves both until the context is
|
||||
// cancelled.
|
||||
func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
// run wires the validator gRPC server and serves it until the context is cancelled.
|
||||
func run(ctx context.Context, cfg config.ValidatorConfig, logger *zap.Logger) error {
|
||||
tel, err := pkgtel.New(ctx, cfg.Telemetry)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -67,23 +66,7 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
logger.Warn("telemetry: start runtime metrics", zap.Error(err))
|
||||
}
|
||||
|
||||
// The single bot validates launch data and delivers push/admin messages.
|
||||
b, err := bot.New(bot.Config{
|
||||
Token: cfg.Token,
|
||||
APIBaseURL: cfg.APIBaseURL,
|
||||
TestEnv: cfg.TestEnv,
|
||||
MiniAppURL: cfg.MiniAppURL,
|
||||
}, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := connector.NewServer(connector.BotRuntime{
|
||||
Sender: b,
|
||||
ChannelID: cfg.GameChannelID,
|
||||
InitValidator: initdata.NewHMACValidator(cfg.Token),
|
||||
WidgetValidator: loginwidget.NewHMACValidator(cfg.Token),
|
||||
}, logger)
|
||||
|
||||
srv := validator.NewServer(initdata.NewHMACValidator(cfg.Token), loginwidget.NewHMACValidator(cfg.Token))
|
||||
grpcServer := grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler()))
|
||||
telegramv1.RegisterTelegramServer(grpcServer, srv)
|
||||
|
||||
@@ -92,18 +75,12 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// The long-poll loop and the gRPC server run together; cancelling the context
|
||||
// stops the bot loop and gracefully drains the gRPC server.
|
||||
go b.Run(ctx)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
grpcServer.GracefulStop()
|
||||
}()
|
||||
|
||||
logger.Info("telegram connector starting",
|
||||
zap.String("grpc_addr", cfg.GRPCAddr),
|
||||
zap.String("miniapp_url", cfg.MiniAppURL),
|
||||
zap.Bool("test_env", cfg.TestEnv))
|
||||
logger.Info("telegram validator starting", zap.String("grpc_addr", cfg.GRPCAddr))
|
||||
if err := grpcServer.Serve(lis); err != nil && !errors.Is(err, grpc.ErrServerStopped) {
|
||||
return err
|
||||
}
|
||||
@@ -7,6 +7,7 @@ require (
|
||||
github.com/google/flatbuffers v23.5.26+incompatible
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0
|
||||
go.uber.org/zap v1.27.1
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/grpc v1.80.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
scrabble/pkg v0.0.0
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
tgbot "github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// Config configures the bot wrapper.
|
||||
@@ -25,6 +26,10 @@ type Config struct {
|
||||
TestEnv bool
|
||||
// MiniAppURL is the base URL of the Mini App launch button.
|
||||
MiniAppURL string
|
||||
// SendRatePerSecond caps outbound sends (Notify and SendText) to respect the
|
||||
// Telegram Bot API flood limits; 0 disables the limiter. The burst equals the
|
||||
// per-second rate.
|
||||
SendRatePerSecond int
|
||||
}
|
||||
|
||||
// Bot wraps a Telegram Bot API client and the Mini App launch URL.
|
||||
@@ -32,6 +37,9 @@ type Bot struct {
|
||||
api *tgbot.Bot
|
||||
miniAppURL string
|
||||
log *zap.Logger
|
||||
// limiter throttles outbound sends to stay under the Bot API flood limits; nil
|
||||
// disables throttling.
|
||||
limiter *rate.Limiter
|
||||
}
|
||||
|
||||
// New builds the bot wrapper, registering the /start handler and a default handler
|
||||
@@ -42,6 +50,9 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log}
|
||||
if cfg.SendRatePerSecond > 0 {
|
||||
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
||||
}
|
||||
|
||||
opts := []tgbot.Option{
|
||||
tgbot.WithDefaultHandler(t.handleStart),
|
||||
@@ -85,6 +96,9 @@ func (t *Bot) Run(ctx context.Context) {
|
||||
// Notify sends a notification message with a Mini App launch button that opens the
|
||||
// app at startParam (empty opens the lobby).
|
||||
func (t *Bot) Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
if err := t.throttle(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{
|
||||
ChatID: chatID,
|
||||
Text: text,
|
||||
@@ -95,10 +109,22 @@ func (t *Bot) Notify(ctx context.Context, chatID int64, text, buttonText, startP
|
||||
|
||||
// SendText sends a plain text message with no markup (admin use).
|
||||
func (t *Bot) SendText(ctx context.Context, chatID int64, text string) error {
|
||||
if err := t.throttle(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{ChatID: chatID, Text: text})
|
||||
return err
|
||||
}
|
||||
|
||||
// throttle blocks until the rate limiter admits one send, or ctx is cancelled. It
|
||||
// is a no-op when no limiter is configured.
|
||||
func (t *Bot) throttle(ctx context.Context) error {
|
||||
if t.limiter == nil {
|
||||
return nil
|
||||
}
|
||||
return t.limiter.Wait(ctx)
|
||||
}
|
||||
|
||||
// handleStart replies to /start (with an optional deep-link payload) and to any
|
||||
// other message with a Mini App launch button.
|
||||
func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Update) {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// clientKeepaliveTime is how often the bot pings the gateway to hold the WAN
|
||||
// connection open (kept above the gateway's MinTime to avoid an enforcement ban).
|
||||
clientKeepaliveTime = 30 * time.Second
|
||||
// clientKeepaliveTimeout bounds the wait for a keepalive ping reply.
|
||||
clientKeepaliveTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// ClientConfig configures the bot's dial side of the reverse bot-link.
|
||||
type ClientConfig struct {
|
||||
// GatewayAddr is the gateway bot-link endpoint to dial.
|
||||
GatewayAddr string
|
||||
// InstanceID identifies this bot to the gateway.
|
||||
InstanceID string
|
||||
// OwnsUpdates reports whether this bot runs the exclusive getUpdates long-poll.
|
||||
OwnsUpdates bool
|
||||
// Creds is the transport credentials for the dial (mutual TLS in production,
|
||||
// built from pkg/mtls).
|
||||
Creds credentials.TransportCredentials
|
||||
// ReconnectDelay is the pause before re-dialing after the stream ends.
|
||||
ReconnectDelay time.Duration
|
||||
}
|
||||
|
||||
// Client maintains the long-lived bot-link to the gateway, executing the commands
|
||||
// it receives and re-dialing after any break.
|
||||
type Client struct {
|
||||
cfg ClientConfig
|
||||
exec *Executor
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewClient builds the bot-link client over the executor.
|
||||
func NewClient(cfg ClientConfig, exec *Executor, log *zap.Logger) *Client {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Client{cfg: cfg, exec: exec, log: log}
|
||||
}
|
||||
|
||||
// Run dials the gateway and keeps the bot-link open, re-dialing after each break,
|
||||
// until ctx is cancelled. The gRPC connection auto-reconnects the transport; this
|
||||
// loop re-opens the Link stream on top of it.
|
||||
func (c *Client) Run(ctx context.Context) error {
|
||||
conn, err := grpc.NewClient(c.cfg.GatewayAddr,
|
||||
grpc.WithTransportCredentials(c.cfg.Creds),
|
||||
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
|
||||
grpc.WithKeepaliveParams(keepalive.ClientParameters{
|
||||
Time: clientKeepaliveTime,
|
||||
Timeout: clientKeepaliveTimeout,
|
||||
PermitWithoutStream: true,
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
client := botlinkv1.NewBotLinkClient(conn)
|
||||
|
||||
for ctx.Err() == nil {
|
||||
if err := c.serve(ctx, client); err != nil && ctx.Err() == nil {
|
||||
c.log.Warn("bot-link stream ended", zap.Error(err))
|
||||
}
|
||||
if !sleep(ctx, c.cfg.ReconnectDelay) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// serve opens one Link stream, registers with a Hello, then executes commands and
|
||||
// replies with an Ack each until the stream ends.
|
||||
func (c *Client) serve(ctx context.Context, client botlinkv1.BotLinkClient) error {
|
||||
stream, err := client.Link(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.FromBot{Msg: &botlinkv1.FromBot_Hello{Hello: &botlinkv1.Hello{
|
||||
InstanceId: c.cfg.InstanceID,
|
||||
OwnsUpdates: c.cfg.OwnsUpdates,
|
||||
}}}); err != nil {
|
||||
return err
|
||||
}
|
||||
c.log.Info("bot-link connected", zap.String("gateway", c.cfg.GatewayAddr), zap.Bool("owns_updates", c.cfg.OwnsUpdates))
|
||||
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := msg.GetCommand()
|
||||
if cmd == nil {
|
||||
continue
|
||||
}
|
||||
delivered, herr := c.exec.Handle(ctx, cmd)
|
||||
ack := &botlinkv1.Ack{CommandId: cmd.GetCommandId(), Delivered: delivered}
|
||||
if herr != nil {
|
||||
ack.Error = herr.Error()
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.FromBot{Msg: &botlinkv1.FromBot_Ack{Ack: ack}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sleep waits for d or until ctx is cancelled, reporting whether it waited the full
|
||||
// duration.
|
||||
func sleep(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
)
|
||||
|
||||
// testLinkServer registers one bot, pushes a single Notify command, and records the
|
||||
// Ack the client returns.
|
||||
type testLinkServer struct {
|
||||
botlinkv1.UnimplementedBotLinkServer
|
||||
acks chan *botlinkv1.Ack
|
||||
}
|
||||
|
||||
func (s *testLinkServer) Link(stream grpc.BidiStreamingServer[botlinkv1.FromBot, botlinkv1.ToBot]) error {
|
||||
hello, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hello.GetHello() == nil {
|
||||
return fmt.Errorf("first message was not Hello")
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.ToBot{Command: &botlinkv1.Command{
|
||||
CommandId: "c1",
|
||||
Payload: &botlinkv1.Command_Notify{Notify: &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "your_turn",
|
||||
Payload: yourTurnPayload("7c9e6679-7425-40de-944b-e07fc1f90ae7"), Language: "en",
|
||||
}},
|
||||
}}); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ack := msg.GetAck(); ack != nil {
|
||||
s.acks <- ack
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientServesCommands verifies the bot client dials, registers, executes a
|
||||
// pushed command through the executor, and acks it.
|
||||
func TestClientServesCommands(t *testing.T) {
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
ts := &testLinkServer{acks: make(chan *botlinkv1.Ack, 1)}
|
||||
srv := grpc.NewServer()
|
||||
botlinkv1.RegisterBotLinkServer(srv, ts)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
sender := &fakeSender{}
|
||||
client := NewClient(ClientConfig{
|
||||
GatewayAddr: lis.Addr().String(),
|
||||
InstanceID: "test",
|
||||
Creds: insecure.NewCredentials(),
|
||||
ReconnectDelay: 50 * time.Millisecond,
|
||||
}, NewExecutor(sender, 0, nil), nil)
|
||||
|
||||
go func() { _ = client.Run(t.Context()) }()
|
||||
|
||||
select {
|
||||
case ack := <-ts.acks:
|
||||
if ack.GetCommandId() != "c1" || !ack.GetDelivered() {
|
||||
t.Errorf("ack = %+v, want command_id c1 delivered=true", ack)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("server received no ack")
|
||||
}
|
||||
// The channel receive above happens-after the client wrote the sender call.
|
||||
if len(sender.notify) != 1 || sender.notify[0].chatID != 12345 {
|
||||
t.Errorf("sender notify calls = %+v, want one call to chat 12345", sender.notify)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Package botlink is the bot side of the reverse Telegram channel: the bot dials
|
||||
// the gateway over mTLS (pkg/proto/botlink/v1), opens one long-lived Link stream,
|
||||
// and executes the send Commands the gateway pushes, replying with an Ack per
|
||||
// command. It keeps the Bot API token and egress on the remote bot host with no
|
||||
// inbound port. See docs/ARCHITECTURE.md.
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/render"
|
||||
)
|
||||
|
||||
// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
|
||||
type Sender interface {
|
||||
// Notify sends a notification with a Mini App launch button to chatID.
|
||||
Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
|
||||
// SendText sends a plain text message to chatID.
|
||||
SendText(ctx context.Context, chatID int64, text string) error
|
||||
}
|
||||
|
||||
// Executor turns a bot-link Command into a Bot API send. The delivered flag mirrors
|
||||
// the former connector semantics (false when the kind is not rendered out-of-app,
|
||||
// the user never started the bot, or no channel is configured); a returned error is
|
||||
// an unexpected or malformed failure carried back in the Ack error field, distinct
|
||||
// from a clean not-delivered.
|
||||
type Executor struct {
|
||||
sender Sender
|
||||
channelID int64
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewExecutor builds the executor over a bot sender and the optional game channel.
|
||||
func NewExecutor(sender Sender, channelID int64, log *zap.Logger) *Executor {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Executor{sender: sender, channelID: channelID, log: log}
|
||||
}
|
||||
|
||||
// Handle dispatches one command to the matching Bot API send.
|
||||
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, error) {
|
||||
switch p := cmd.GetPayload().(type) {
|
||||
case *botlinkv1.Command_Notify:
|
||||
return e.notify(ctx, p.Notify)
|
||||
case *botlinkv1.Command_SendToUser:
|
||||
return e.sendToUser(ctx, p.SendToUser)
|
||||
case *botlinkv1.Command_SendToChannel:
|
||||
return e.sendToChannel(ctx, p.SendToChannel)
|
||||
default:
|
||||
return false, fmt.Errorf("botlink: empty command")
|
||||
}
|
||||
}
|
||||
|
||||
// notify renders an out-of-app push and sends it with a Mini App launch button.
|
||||
func (e *Executor) notify(ctx context.Context, req *telegramv1.NotifyRequest) (bool, error) {
|
||||
msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := e.sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
|
||||
e.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// sendToUser sends an admin text message to one user.
|
||||
func (e *Executor) sendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (bool, error) {
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := e.sender.SendText(ctx, chat, req.GetText()); err != nil {
|
||||
e.log.Warn("send to user failed", zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// sendToChannel posts an admin text message to the bot's game channel.
|
||||
func (e *Executor) sendToChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (bool, error) {
|
||||
if e.channelID == 0 {
|
||||
return false, fmt.Errorf("botlink: game channel is not configured")
|
||||
}
|
||||
if err := e.sender.SendText(ctx, e.channelID, req.GetText()); err != nil {
|
||||
e.log.Warn("send to channel failed", zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// parseChatID converts a Telegram identity external_id into a numeric chat id.
|
||||
func parseChatID(externalID string) (int64, error) {
|
||||
id, err := strconv.ParseInt(externalID, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid external_id %q", externalID)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
|
||||
"scrabble/pkg/fbs/scrabblefb"
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
)
|
||||
|
||||
// fakeSender records the delivery calls the executor makes.
|
||||
type fakeSender struct {
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
err error
|
||||
}
|
||||
|
||||
type notifyCall struct {
|
||||
chatID int64
|
||||
text, buttonText, startParam string
|
||||
}
|
||||
type textCall struct {
|
||||
chatID int64
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeSender) SendText(_ context.Context, chatID int64, text string) error {
|
||||
f.text = append(f.text, textCall{chatID, text})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func yourTurnPayload(gameID string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
gid := b.CreateString(gameID)
|
||||
scrabblefb.YourTurnEventStart(b)
|
||||
scrabblefb.YourTurnEventAddGameId(b, gid)
|
||||
b.Finish(scrabblefb.YourTurnEventEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
func notifyCmd(externalID, kind string, payload []byte, language string) *botlinkv1.Command {
|
||||
return &botlinkv1.Command{Payload: &botlinkv1.Command_Notify{Notify: &telegramv1.NotifyRequest{
|
||||
ExternalId: externalID, Kind: kind, Payload: payload, Language: language,
|
||||
}}}
|
||||
}
|
||||
|
||||
func TestExecutorNotifyDelivers(t *testing.T) {
|
||||
const gameID = "7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "your_turn", yourTurnPayload(gameID), "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered {
|
||||
t.Fatal("expected delivered=true")
|
||||
}
|
||||
if len(sender.notify) != 1 {
|
||||
t.Fatalf("notify calls = %d, want 1", len(sender.notify))
|
||||
}
|
||||
if got := sender.notify[0]; got.chatID != 12345 || got.startParam != "g"+gameID {
|
||||
t.Errorf("notify call = %+v, want chatID 12345 startParam g%s", got, gameID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "opponent_moved", nil, "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if delivered {
|
||||
t.Error("expected delivered=false for an unrendered kind")
|
||||
}
|
||||
if len(sender.notify) != 0 {
|
||||
t.Errorf("sender called %d times, want 0", len(sender.notify))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorNotifyInvalidExternalID(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), notifyCmd("not-a-number", "your_turn", yourTurnPayload("g"), "en")); err == nil {
|
||||
t.Error("expected an error for a non-numeric external_id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorSendToUser(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToUser{SendToUser: &telegramv1.SendToUserRequest{ExternalId: "999", Text: "hi"}}}
|
||||
delivered, err := exec.Handle(context.Background(), cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered || len(sender.text) != 1 || sender.text[0].chatID != 999 || sender.text[0].text != "hi" {
|
||||
t.Errorf("send to user = %v / calls %+v", delivered, sender.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorSendToChannel(t *testing.T) {
|
||||
channelCmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToChannel{SendToChannel: &telegramv1.SendToGameChannelRequest{Text: "news"}}}
|
||||
|
||||
t.Run("unconfigured", func(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), channelCmd); err == nil {
|
||||
t.Error("expected an error when no channel is configured")
|
||||
}
|
||||
})
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 555, nil)
|
||||
delivered, err := exec.Handle(context.Background(), channelCmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered || len(sender.text) != 1 || sender.text[0].chatID != 555 {
|
||||
t.Errorf("send to channel: %+v", sender.text)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
// Package config loads the Telegram connector's environment configuration.
|
||||
// Package config loads the environment configuration for the two Telegram
|
||||
// platform binaries: the home validator (HMAC of Mini App / Login Widget data, no
|
||||
// Telegram egress) and the remote bot (Bot API long-poll + sendMessage, dialing
|
||||
// the gateway over the reverse mTLS bot-link). The bot token lives in both
|
||||
// processes — the validator needs it only as the HMAC secret (ARCHITECTURE.md §12).
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -6,73 +10,173 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
)
|
||||
|
||||
// Config is the Telegram connector's runtime configuration, read from the
|
||||
// environment. The bot token lives only in this process (ARCHITECTURE.md §12).
|
||||
type Config struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required). It both
|
||||
// authenticates the Bot API client and is the HMAC secret for Mini App initData
|
||||
// and Login Widget validation.
|
||||
// ValidatorConfig is the home validator's runtime configuration.
|
||||
type ValidatorConfig struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required). The
|
||||
// validator uses it only as the HMAC secret for Mini App initData and Login
|
||||
// Widget validation; it never calls the Bot API.
|
||||
Token string
|
||||
// GameChannelID is the chat id of the bot's game channel for SendToGameChannel
|
||||
// (TELEGRAM_GAME_CHANNEL_ID, optional; 0 disables channel posts).
|
||||
GameChannelID int64
|
||||
// GRPCAddr is the listen address of the connector gRPC server that gateway and
|
||||
// backend call (TELEGRAM_GRPC_ADDR, default :9091).
|
||||
// GRPCAddr is the listen address of the validator gRPC server the gateway calls
|
||||
// (TELEGRAM_VALIDATOR_GRPC_ADDR, default :9091).
|
||||
GRPCAddr string
|
||||
// MiniAppURL is the HTTPS origin of the Mini App registered with BotFather; it
|
||||
// is the base of every launch button, to which a deep-link adds a startapp
|
||||
// query parameter (TELEGRAM_MINIAPP_URL, required).
|
||||
MiniAppURL string
|
||||
// APIBaseURL overrides the Bot API host (TELEGRAM_API_BASE_URL, optional;
|
||||
// default https://api.telegram.org) — used for a local mock or a self-hosted
|
||||
// Bot API server.
|
||||
APIBaseURL string
|
||||
// TestEnv routes the Bot API client to Telegram's test environment
|
||||
// (.../bot<token>/test/METHOD) (TELEGRAM_TEST_ENV=true, default false).
|
||||
TestEnv bool
|
||||
// LogLevel is the zap log level (TELEGRAM_LOG_LEVEL, default info).
|
||||
LogLevel string
|
||||
// Telemetry configures the OpenTelemetry providers (shared bootstrap).
|
||||
Telemetry pkgtel.Config
|
||||
}
|
||||
|
||||
// Load reads the connector configuration from the environment, applying defaults
|
||||
// and validating the required fields.
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
GRPCAddr: envOr("TELEGRAM_GRPC_ADDR", ":9091"),
|
||||
MiniAppURL: os.Getenv("TELEGRAM_MINIAPP_URL"),
|
||||
APIBaseURL: os.Getenv("TELEGRAM_API_BASE_URL"),
|
||||
TestEnv: os.Getenv("TELEGRAM_TEST_ENV") == "true",
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
// BotConfig is the remote bot's runtime configuration.
|
||||
type BotConfig struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required).
|
||||
Token string
|
||||
// GameChannelID is the chat id of the bot's game channel for the admin channel
|
||||
// post (TELEGRAM_GAME_CHANNEL_ID, optional; 0 disables channel posts).
|
||||
GameChannelID int64
|
||||
// MiniAppURL is the HTTPS origin of the Mini App registered with BotFather; it is
|
||||
// the base of every launch button (TELEGRAM_MINIAPP_URL, required).
|
||||
MiniAppURL string
|
||||
// APIBaseURL overrides the Bot API host (TELEGRAM_API_BASE_URL, optional;
|
||||
// default https://api.telegram.org).
|
||||
APIBaseURL string
|
||||
// TestEnv routes the Bot API client to Telegram's test environment
|
||||
// (TELEGRAM_TEST_ENV=true, default false).
|
||||
TestEnv bool
|
||||
// OwnsUpdates reports whether this bot runs the exclusive getUpdates long-poll
|
||||
// (TELEGRAM_OWNS_UPDATES, default true). Exactly one bot per token must own it.
|
||||
OwnsUpdates bool
|
||||
// SendRatePerSecond caps outbound Bot API sends to respect Telegram flood limits
|
||||
// (TELEGRAM_SEND_RATE_PER_SECOND, default 25; 0 disables the limiter).
|
||||
SendRatePerSecond int
|
||||
// BotLink configures the reverse mTLS channel the bot dials.
|
||||
BotLink BotLinkClientConfig
|
||||
// LogLevel is the zap log level (TELEGRAM_LOG_LEVEL, default info).
|
||||
LogLevel string
|
||||
// Telemetry configures the OpenTelemetry providers (shared bootstrap).
|
||||
Telemetry pkgtel.Config
|
||||
}
|
||||
|
||||
// BotLinkClientConfig is the bot's dial side of the reverse bot-link.
|
||||
type BotLinkClientConfig struct {
|
||||
// GatewayAddr is the gateway bot-link endpoint to dial (TELEGRAM_GATEWAY_ADDR,
|
||||
// required), e.g. "gateway.example.com:9443".
|
||||
GatewayAddr string
|
||||
// ServerName is the gateway certificate's expected SNI / CN
|
||||
// (TELEGRAM_BOTLINK_SERVER_NAME, required).
|
||||
ServerName string
|
||||
// InstanceID identifies this bot to the gateway (TELEGRAM_INSTANCE_ID, default
|
||||
// the hostname).
|
||||
InstanceID string
|
||||
// CertFile, KeyFile and CAFile are the bot client certificate, its key and the
|
||||
// CA bundle that signs the gateway server certificate (required).
|
||||
CertFile string
|
||||
KeyFile string
|
||||
CAFile string
|
||||
// ReconnectDelay is the pause before re-dialing after the stream ends
|
||||
// (TELEGRAM_BOTLINK_RECONNECT_DELAY, default 2s).
|
||||
ReconnectDelay time.Duration
|
||||
}
|
||||
|
||||
const (
|
||||
defaultValidatorGRPCAddr = ":9091"
|
||||
defaultBotReconnectDelay = 2 * time.Second
|
||||
defaultSendRatePerSecond = 25
|
||||
)
|
||||
|
||||
// LoadValidator reads the validator configuration from the environment.
|
||||
func LoadValidator() (ValidatorConfig, error) {
|
||||
cfg := ValidatorConfig{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
GRPCAddr: envOr("TELEGRAM_VALIDATOR_GRPC_ADDR", defaultValidatorGRPCAddr),
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
}
|
||||
if v := strings.TrimSpace(os.Getenv("TELEGRAM_GAME_CHANNEL_ID")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_GAME_CHANNEL_ID %q: %w", v, err)
|
||||
}
|
||||
cfg.GameChannelID = id
|
||||
tel, err := loadTelemetry("scrabble-telegram-validator")
|
||||
if err != nil {
|
||||
return ValidatorConfig{}, err
|
||||
}
|
||||
tel := pkgtel.DefaultConfig("scrabble-telegram")
|
||||
cfg.Telemetry = tel
|
||||
if cfg.Token == "" {
|
||||
return ValidatorConfig{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadBot reads the bot configuration from the environment.
|
||||
func LoadBot() (BotConfig, error) {
|
||||
cfg := BotConfig{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
MiniAppURL: os.Getenv("TELEGRAM_MINIAPP_URL"),
|
||||
APIBaseURL: os.Getenv("TELEGRAM_API_BASE_URL"),
|
||||
TestEnv: os.Getenv("TELEGRAM_TEST_ENV") == "true",
|
||||
OwnsUpdates: os.Getenv("TELEGRAM_OWNS_UPDATES") != "false",
|
||||
SendRatePerSecond: defaultSendRatePerSecond,
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
BotLink: BotLinkClientConfig{
|
||||
GatewayAddr: os.Getenv("TELEGRAM_GATEWAY_ADDR"),
|
||||
ServerName: os.Getenv("TELEGRAM_BOTLINK_SERVER_NAME"),
|
||||
InstanceID: envOr("TELEGRAM_INSTANCE_ID", hostname()),
|
||||
CertFile: os.Getenv("TELEGRAM_BOTLINK_TLS_CERT"),
|
||||
KeyFile: os.Getenv("TELEGRAM_BOTLINK_TLS_KEY"),
|
||||
CAFile: os.Getenv("TELEGRAM_BOTLINK_TLS_CA"),
|
||||
},
|
||||
}
|
||||
var err error
|
||||
if cfg.GameChannelID, err = envInt64("TELEGRAM_GAME_CHANNEL_ID", 0); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
if cfg.SendRatePerSecond, err = envInt("TELEGRAM_SEND_RATE_PER_SECOND", defaultSendRatePerSecond); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
if cfg.BotLink.ReconnectDelay, err = envDuration("TELEGRAM_BOTLINK_RECONNECT_DELAY", defaultBotReconnectDelay); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
tel, err := loadTelemetry("scrabble-telegram-bot")
|
||||
if err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
cfg.Telemetry = tel
|
||||
|
||||
if cfg.Token == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
}
|
||||
if cfg.MiniAppURL == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_MINIAPP_URL is required")
|
||||
}
|
||||
if cfg.BotLink.GatewayAddr == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_GATEWAY_ADDR is required")
|
||||
}
|
||||
if cfg.BotLink.ServerName == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOTLINK_SERVER_NAME is required")
|
||||
}
|
||||
if cfg.BotLink.CertFile == "" || cfg.BotLink.KeyFile == "" || cfg.BotLink.CAFile == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOTLINK_TLS_CERT, _KEY and _CA are required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// loadTelemetry builds the shared OpenTelemetry config with the given default
|
||||
// service name, applying the TELEGRAM_* overrides and validating the result.
|
||||
func loadTelemetry(defaultService string) (pkgtel.Config, error) {
|
||||
tel := pkgtel.DefaultConfig(defaultService)
|
||||
tel.ServiceName = envOr("TELEGRAM_SERVICE_NAME", tel.ServiceName)
|
||||
tel.TracesExporter = envOr("TELEGRAM_OTEL_TRACES_EXPORTER", tel.TracesExporter)
|
||||
tel.MetricsExporter = envOr("TELEGRAM_OTEL_METRICS_EXPORTER", tel.MetricsExporter)
|
||||
cfg.Telemetry = tel
|
||||
if cfg.Token == "" {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
if err := tel.Validate(); err != nil {
|
||||
return pkgtel.Config{}, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
if cfg.MiniAppURL == "" {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_MINIAPP_URL is required")
|
||||
return tel, nil
|
||||
}
|
||||
|
||||
// hostname returns the machine hostname, or "telegram-bot" when it cannot be read.
|
||||
func hostname() string {
|
||||
if h, err := os.Hostname(); err == nil && h != "" {
|
||||
return h
|
||||
}
|
||||
if err := cfg.Telemetry.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
return "telegram-bot"
|
||||
}
|
||||
|
||||
// envOr returns the environment value for key, or def when it is unset or empty.
|
||||
@@ -82,3 +186,45 @@ func envOr(key, def string) string {
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// envInt parses the environment variable named key as an int, returning fallback
|
||||
// when unset and an error when set but malformed.
|
||||
func envInt(key string, fallback int) (int, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// envInt64 parses the environment variable named key as an int64, returning
|
||||
// fallback when unset and an error when set but malformed.
|
||||
func envInt64(key string, fallback int64) (int64, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// envDuration parses the environment variable named key as a Go duration,
|
||||
// returning fallback when unset and an error when set but malformed.
|
||||
func envDuration(key string, fallback time.Duration) (time.Duration, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
@@ -6,71 +6,110 @@ import (
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
)
|
||||
|
||||
// setRequired sets the required connector variables (the bot token + the Mini App
|
||||
// URL) so Load reaches the telemetry checks.
|
||||
func setRequired(t *testing.T) {
|
||||
// setBotRequired sets every required bot variable so LoadBot reaches the optional
|
||||
// parsing and telemetry checks.
|
||||
func setBotRequired(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "test-token")
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "bot-token")
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
t.Setenv("TELEGRAM_GATEWAY_ADDR", "gateway.example.org:9443")
|
||||
t.Setenv("TELEGRAM_BOTLINK_SERVER_NAME", "gateway.example.org")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_CERT", "/certs/bot.crt")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_KEY", "/certs/bot.key")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_CA", "/certs/ca.crt")
|
||||
}
|
||||
|
||||
// TestLoadBot verifies the bot parsing: the token is read and the game channel id is
|
||||
// parsed when present.
|
||||
func TestLoadBot(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "bot-token")
|
||||
t.Setenv("TELEGRAM_GAME_CHANNEL_ID", "-100111")
|
||||
c, err := Load()
|
||||
// TestLoadValidator verifies the validator reads the token, defaults its address
|
||||
// and names its telemetry service.
|
||||
func TestLoadValidator(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "secret")
|
||||
c, err := LoadValidator()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
t.Fatalf("LoadValidator: %v", err)
|
||||
}
|
||||
if c.Token != "secret" {
|
||||
t.Errorf("Token = %q, want secret", c.Token)
|
||||
}
|
||||
if c.GRPCAddr != defaultValidatorGRPCAddr {
|
||||
t.Errorf("GRPCAddr = %q, want %q", c.GRPCAddr, defaultValidatorGRPCAddr)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram-validator" {
|
||||
t.Errorf("ServiceName = %q, want scrabble-telegram-validator", c.Telemetry.ServiceName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadValidatorRequiresToken verifies the validator fails without a token.
|
||||
func TestLoadValidatorRequiresToken(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "")
|
||||
if _, err := LoadValidator(); err == nil {
|
||||
t.Fatal("LoadValidator: expected an error without a token, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadBot verifies the bot parses the token, channel id and owns_updates and
|
||||
// names its telemetry service.
|
||||
func TestLoadBot(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv("TELEGRAM_GAME_CHANNEL_ID", "-100111")
|
||||
c, err := LoadBot()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBot: %v", err)
|
||||
}
|
||||
if c.Token != "bot-token" || c.GameChannelID != -100111 {
|
||||
t.Errorf("config = token %q / channel %d, want bot-token / -100111", c.Token, c.GameChannelID)
|
||||
}
|
||||
if !c.OwnsUpdates {
|
||||
t.Error("OwnsUpdates = false, want true by default")
|
||||
}
|
||||
if c.SendRatePerSecond != defaultSendRatePerSecond {
|
||||
t.Errorf("SendRatePerSecond = %d, want %d", c.SendRatePerSecond, defaultSendRatePerSecond)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram-bot" {
|
||||
t.Errorf("ServiceName = %q, want scrabble-telegram-bot", c.Telemetry.ServiceName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadOptionalChannel verifies the game channel id defaults to 0 when unset.
|
||||
func TestLoadOptionalChannel(t *testing.T) {
|
||||
setRequired(t)
|
||||
c, err := Load()
|
||||
// TestLoadBotOwnsUpdatesOptOut verifies TELEGRAM_OWNS_UPDATES=false disables the
|
||||
// long-poll ownership.
|
||||
func TestLoadBotOwnsUpdatesOptOut(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv("TELEGRAM_OWNS_UPDATES", "false")
|
||||
c, err := LoadBot()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
t.Fatalf("LoadBot: %v", err)
|
||||
}
|
||||
if c.GameChannelID != 0 {
|
||||
t.Errorf("GameChannelID = %d, want 0", c.GameChannelID)
|
||||
if c.OwnsUpdates {
|
||||
t.Error("OwnsUpdates = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRequiresBot verifies Load fails when no bot token is configured.
|
||||
func TestLoadRequiresBot(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load: expected an error when no bot token is set, got nil")
|
||||
// TestLoadBotRequired verifies LoadBot fails when a required variable is missing.
|
||||
func TestLoadBotRequired(t *testing.T) {
|
||||
cases := []string{
|
||||
"TELEGRAM_BOT_TOKEN",
|
||||
"TELEGRAM_MINIAPP_URL",
|
||||
"TELEGRAM_GATEWAY_ADDR",
|
||||
"TELEGRAM_BOTLINK_SERVER_NAME",
|
||||
"TELEGRAM_BOTLINK_TLS_CERT",
|
||||
}
|
||||
for _, missing := range cases {
|
||||
t.Run(missing, func(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv(missing, "")
|
||||
if _, err := LoadBot(); err == nil {
|
||||
t.Fatalf("LoadBot: expected an error without %s, got nil", missing)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadTelemetryDefaults verifies the connector telemetry defaults: the
|
||||
// "scrabble-telegram" service name and both exporters off.
|
||||
func TestLoadTelemetryDefaults(t *testing.T) {
|
||||
setRequired(t)
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram" {
|
||||
t.Errorf("Telemetry.ServiceName = %q, want scrabble-telegram", c.Telemetry.ServiceName)
|
||||
}
|
||||
if c.Telemetry.TracesExporter != pkgtel.ExporterNone || c.Telemetry.MetricsExporter != pkgtel.ExporterNone {
|
||||
t.Errorf("exporters = %q/%q, want none/none", c.Telemetry.TracesExporter, c.Telemetry.MetricsExporter)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRejectsUnsupportedExporter verifies an exporter outside the supported
|
||||
// set fails validation.
|
||||
// TestLoadRejectsUnsupportedExporter verifies an exporter outside the supported set
|
||||
// fails validation (the validator path).
|
||||
func TestLoadRejectsUnsupportedExporter(t *testing.T) {
|
||||
setRequired(t)
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "secret")
|
||||
t.Setenv("TELEGRAM_OTEL_TRACES_EXPORTER", "jaeger")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load: expected an error for an unsupported exporter, got nil")
|
||||
if _, err := LoadValidator(); err == nil {
|
||||
t.Fatal("LoadValidator: expected an error for an unsupported exporter, got nil")
|
||||
}
|
||||
_ = pkgtel.ExporterNone
|
||||
}
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
// Package connector implements the Telegram gRPC service (pkg/proto/telegram/v1):
|
||||
// the gateway calls ValidateInitData (Mini App auth) and Notify (out-of-app push);
|
||||
// the admin surface calls SendToUser and SendToGameChannel. The generic
|
||||
// methods address a recipient by the identity external_id, so a future platform
|
||||
// connector can implement the same service.
|
||||
//
|
||||
// The connector hosts a single bot. ValidateInitData/ValidateLoginWidget verify
|
||||
// launch data against its token; Notify renders the message in the recipient's
|
||||
// interface language (the single bot needs no routing); the admin methods deliver
|
||||
// through that bot.
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
"scrabble/platform/telegram/internal/render"
|
||||
)
|
||||
|
||||
// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
|
||||
type Sender interface {
|
||||
// Notify sends a notification with a Mini App launch button to chatID.
|
||||
Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
|
||||
// SendText sends a plain text message to chatID.
|
||||
SendText(ctx context.Context, chatID int64, text string) error
|
||||
}
|
||||
|
||||
// BotRuntime is the configured bot: its sender, game channel id, and the two HMAC
|
||||
// validators bound to its token.
|
||||
type BotRuntime struct {
|
||||
// Sender delivers messages through the bot.
|
||||
Sender Sender
|
||||
// ChannelID is the bot's game channel (0 disables channel posts).
|
||||
ChannelID int64
|
||||
// InitValidator verifies Mini App initData signed by the bot's token.
|
||||
InitValidator initdata.Validator
|
||||
// WidgetValidator verifies Login Widget data signed by the bot's token.
|
||||
WidgetValidator loginwidget.Validator
|
||||
}
|
||||
|
||||
// Server implements telegramv1.TelegramServer over the single configured bot.
|
||||
type Server struct {
|
||||
telegramv1.UnimplementedTelegramServer
|
||||
bot BotRuntime
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewServer builds the gRPC service from the configured bot.
|
||||
func NewServer(bot BotRuntime, log *zap.Logger) *Server {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Server{bot: bot, log: log}
|
||||
}
|
||||
|
||||
// ValidateInitData verifies Mini App launch data against the bot's token and returns
|
||||
// the user identity.
|
||||
func (s *Server) ValidateInitData(ctx context.Context, req *telegramv1.ValidateInitDataRequest) (*telegramv1.ValidateInitDataResponse, error) {
|
||||
u, err := s.bot.InitValidator.Validate(req.GetInitData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateInitDataResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LanguageCode: u.LanguageCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateLoginWidget verifies Login Widget authorization data against the bot's
|
||||
// token and returns the user identity, for attaching a Telegram identity to an
|
||||
// existing account.
|
||||
func (s *Server) ValidateLoginWidget(ctx context.Context, req *telegramv1.ValidateLoginWidgetRequest) (*telegramv1.ValidateLoginWidgetResponse, error) {
|
||||
u, err := s.bot.WidgetValidator.Validate(req.GetData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateLoginWidgetResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Notify renders and delivers an out-of-app notification through the bot. The message
|
||||
// is rendered in the recipient's interface language (req language). It reports
|
||||
// delivered=false (without an error) when the kind is not pushed out-of-app or the
|
||||
// bot could not deliver (e.g. the user never started it), so the gateway treats a
|
||||
// fallback miss as best-effort.
|
||||
func (s *Server) Notify(ctx context.Context, req *telegramv1.NotifyRequest) (*telegramv1.NotifyResponse, error) {
|
||||
msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
|
||||
if !ok {
|
||||
return &telegramv1.NotifyResponse{Delivered: false}, nil
|
||||
}
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if err := s.bot.Sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
|
||||
s.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
|
||||
return &telegramv1.NotifyResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.NotifyResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// SendToUser sends an arbitrary admin message to one user through the bot.
|
||||
func (s *Server) SendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (*telegramv1.SendResponse, error) {
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if err := s.bot.Sender.SendText(ctx, chat, req.GetText()); err != nil {
|
||||
s.log.Warn("send to user failed", zap.Error(err))
|
||||
return &telegramv1.SendResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.SendResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// SendToGameChannel posts an arbitrary admin message to the bot's game channel.
|
||||
func (s *Server) SendToGameChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (*telegramv1.SendResponse, error) {
|
||||
if s.bot.ChannelID == 0 {
|
||||
return nil, status.Error(codes.FailedPrecondition, "game channel is not configured")
|
||||
}
|
||||
if err := s.bot.Sender.SendText(ctx, s.bot.ChannelID, req.GetText()); err != nil {
|
||||
s.log.Warn("send to channel failed", zap.Error(err))
|
||||
return &telegramv1.SendResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.SendResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// parseChatID converts a Telegram identity external_id into a numeric chat id.
|
||||
func parseChatID(externalID string) (int64, error) {
|
||||
id, err := strconv.ParseInt(externalID, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid external_id %q", externalID)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"scrabble/pkg/fbs/scrabblefb"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// stubValidator returns a fixed user / error from Validate.
|
||||
type stubValidator struct {
|
||||
user initdata.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubValidator) Validate(string) (initdata.User, error) { return s.user, s.err }
|
||||
|
||||
// stubWidgetValidator returns a fixed user / error from the Login Widget Validate.
|
||||
type stubWidgetValidator struct {
|
||||
user loginwidget.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubWidgetValidator) Validate(string) (loginwidget.User, error) { return s.user, s.err }
|
||||
|
||||
// fakeSender records the delivery calls the server makes.
|
||||
type fakeSender struct {
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
err error
|
||||
}
|
||||
|
||||
type notifyCall struct {
|
||||
chatID int64
|
||||
text, buttonText, startParam string
|
||||
}
|
||||
type textCall struct {
|
||||
chatID int64
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeSender) SendText(_ context.Context, chatID int64, text string) error {
|
||||
f.text = append(f.text, textCall{chatID, text})
|
||||
return f.err
|
||||
}
|
||||
|
||||
// botRT assembles the bot runtime for a test.
|
||||
func botRT(sender Sender, channelID int64, iv initdata.Validator, wv loginwidget.Validator) BotRuntime {
|
||||
return BotRuntime{Sender: sender, ChannelID: channelID, InitValidator: iv, WidgetValidator: wv}
|
||||
}
|
||||
|
||||
func yourTurnPayload(gameID string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
gid := b.CreateString(gameID)
|
||||
scrabblefb.YourTurnEventStart(b)
|
||||
scrabblefb.YourTurnEventAddGameId(b, gid)
|
||||
b.Finish(scrabblefb.YourTurnEventEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
func TestValidateInitData(t *testing.T) {
|
||||
want := initdata.User{ExternalID: "42", Username: "neo", FirstName: "Thomas", LanguageCode: "en-GB"}
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{user: want}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{InitData: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" || resp.GetLanguageCode() != "en-GB" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(botRT(&fakeSender{}, 0, stubValidator{err: initdata.ErrInvalidInitData}, stubWidgetValidator{}), nil)
|
||||
if _, err := bad.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLoginWidget(t *testing.T) {
|
||||
want := loginwidget.User{ExternalID: "42", Username: "neo", FirstName: "Thomas"}
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{user: want}), nil)
|
||||
resp, err := srv.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{Data: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{err: loginwidget.ErrInvalidLoginWidget}), nil)
|
||||
if _, err := bad.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyDelivers(t *testing.T) {
|
||||
const gameID = "7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "your_turn", Payload: yourTurnPayload(gameID), Language: "en",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("notify: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() {
|
||||
t.Fatal("expected delivered=true")
|
||||
}
|
||||
if len(sender.notify) != 1 {
|
||||
t.Fatalf("notify calls = %d, want 1", len(sender.notify))
|
||||
}
|
||||
if got := sender.notify[0]; got.chatID != 12345 || got.startParam != "g"+gameID {
|
||||
t.Errorf("notify call = %+v, want chatID 12345 startParam g%s", got, gameID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "opponent_moved", Language: "en",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("notify: %v", err)
|
||||
}
|
||||
if resp.GetDelivered() {
|
||||
t.Error("expected delivered=false for an unrendered kind")
|
||||
}
|
||||
if len(sender.notify) != 0 {
|
||||
t.Errorf("sender called %d times, want 0", len(sender.notify))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyInvalidExternalID(t *testing.T) {
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
_, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "not-a-number", Kind: "your_turn", Payload: yourTurnPayload("g"), Language: "en",
|
||||
})
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendToUser(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.SendToUser(context.Background(), &telegramv1.SendToUserRequest{ExternalId: "999", Text: "hi"})
|
||||
if err != nil {
|
||||
t.Fatalf("send to user: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() || len(sender.text) != 1 || sender.text[0].chatID != 999 || sender.text[0].text != "hi" {
|
||||
t.Errorf("send to user = %v / calls %+v", resp.GetDelivered(), sender.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendToGameChannel(t *testing.T) {
|
||||
t.Run("unconfigured", func(t *testing.T) {
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
_, err := srv.SendToGameChannel(context.Background(), &telegramv1.SendToGameChannelRequest{Text: "x"})
|
||||
if status.Code(err) != codes.FailedPrecondition {
|
||||
t.Errorf("err code = %v, want FailedPrecondition", status.Code(err))
|
||||
}
|
||||
})
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 555, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.SendToGameChannel(context.Background(), &telegramv1.SendToGameChannelRequest{Text: "news"})
|
||||
if err != nil {
|
||||
t.Fatalf("send to channel: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() || len(sender.text) != 1 || sender.text[0].chatID != 555 {
|
||||
t.Errorf("send to channel: %+v", sender.text)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package validator implements the home-side Telegram validator gRPC service: it
|
||||
// verifies Mini App initData and Login Widget data with the bot token's HMAC and
|
||||
// never calls the Bot API. The gateway calls it during the auth.telegram and
|
||||
// link.telegram edge operations. It holds the token only as the HMAC secret, so it
|
||||
// can run on the main host with no VPN and no Telegram egress (ARCHITECTURE.md §12).
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// Server implements the validation subset of telegramv1.TelegramServer; the
|
||||
// delivery methods (Notify, SendToUser, SendToGameChannel) are intentionally
|
||||
// unimplemented here — those run on the remote bot over the bot-link.
|
||||
type Server struct {
|
||||
telegramv1.UnimplementedTelegramServer
|
||||
initValidator initdata.Validator
|
||||
widgetValidator loginwidget.Validator
|
||||
}
|
||||
|
||||
// NewServer builds the validator from the two HMAC validators bound to the token.
|
||||
func NewServer(iv initdata.Validator, wv loginwidget.Validator) *Server {
|
||||
return &Server{initValidator: iv, widgetValidator: wv}
|
||||
}
|
||||
|
||||
// ValidateInitData verifies Mini App launch data against the bot's token and
|
||||
// returns the user identity.
|
||||
func (s *Server) ValidateInitData(_ context.Context, req *telegramv1.ValidateInitDataRequest) (*telegramv1.ValidateInitDataResponse, error) {
|
||||
u, err := s.initValidator.Validate(req.GetInitData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateInitDataResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LanguageCode: u.LanguageCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateLoginWidget verifies Login Widget authorization data against the bot's
|
||||
// token and returns the user identity, for attaching a Telegram identity to an
|
||||
// existing account.
|
||||
func (s *Server) ValidateLoginWidget(_ context.Context, req *telegramv1.ValidateLoginWidgetRequest) (*telegramv1.ValidateLoginWidgetResponse, error) {
|
||||
u, err := s.widgetValidator.Validate(req.GetData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateLoginWidgetResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// stubValidator returns a fixed user / error from Validate.
|
||||
type stubValidator struct {
|
||||
user initdata.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubValidator) Validate(string) (initdata.User, error) { return s.user, s.err }
|
||||
|
||||
// stubWidgetValidator returns a fixed user / error from the Login Widget Validate.
|
||||
type stubWidgetValidator struct {
|
||||
user loginwidget.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubWidgetValidator) Validate(string) (loginwidget.User, error) { return s.user, s.err }
|
||||
|
||||
func TestValidateInitData(t *testing.T) {
|
||||
want := initdata.User{ExternalID: "42", Username: "neo", FirstName: "Thomas", LanguageCode: "en-GB"}
|
||||
srv := NewServer(stubValidator{user: want}, stubWidgetValidator{})
|
||||
resp, err := srv.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{InitData: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" || resp.GetLanguageCode() != "en-GB" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(stubValidator{err: initdata.ErrInvalidInitData}, stubWidgetValidator{})
|
||||
if _, err := bad.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLoginWidget(t *testing.T) {
|
||||
want := loginwidget.User{ExternalID: "42", Username: "neo", FirstName: "Thomas"}
|
||||
srv := NewServer(stubValidator{}, stubWidgetValidator{user: want})
|
||||
resp, err := srv.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{Data: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(stubValidator{}, stubWidgetValidator{err: loginwidget.ErrInvalidLoginWidget})
|
||||
if _, err := bad.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user