Stage 9: Telegram integration (connector side-service, Mini App, out-of-app push)
Tests · Go / test (push) Successful in 7s
Tests · Integration / integration (push) Successful in 12s
Tests · Go / test (pull_request) Successful in 6s
Tests · Integration / integration (pull_request) Successful in 11s
Tests · UI / test (pull_request) Successful in 19s
Tests · Go / test (push) Successful in 7s
Tests · Integration / integration (push) Successful in 12s
Tests · Go / test (pull_request) Successful in 6s
Tests · Integration / integration (pull_request) Successful in 11s
Tests · UI / test (pull_request) Successful in 19s
New platform/telegram connector (own container, bot token only there): - go-telegram/bot long-poll loop: /start deep-links + Mini App launch button. - gRPC API pkg/proto/telegram/v1 (Telegram service): ValidateInitData, Notify (renders a localized message + deep-link button), SendToUser/SendToGameChannel (admin, wired in Stage 10). Generic methods are platform-agnostic (external_id). - Bot API base override for Telegram's test environment; Dockerfile + compose (VPN sidecar, no public ingress); README. Gateway: - initData validation relocated from the gateway into the connector; the gateway calls ValidateInitData over gRPC (GATEWAY_CONNECTOR_ADDR), drops the bot token, and deletes internal/auth. - Out-of-app push: runPushPump routes events whose recipient has no live in-app stream to connector.Notify, gated by /internal/push-target + the in-app-only flag (race-free de-dup); HasSubscribers added to the push hub. Backend: - Migration 00007 accounts.notifications_in_app_only (default true) + jetgen. - ProvisionTelegram seeds a new account's language/display name from the launch fields; IdentityExternalID reverse lookup; /internal/push-target handler. UI: - Telegram Mini App launch: detect initData, apply themeParams, authTelegram, route the deep-link start_param (g/i/f); /telegram/ guard redirects outside Telegram. Vite relative base + telegram-web-app.js. In-app-only profile toggle; share-to-Telegram link for a friend code. Vitest + Playwright coverage. Wire/docs/CI: fbs Profile/UpdateProfileRequest gain notifications_in_app_only (Go + TS); go.work uses ./platform/telegram; go-unit.yaml covers it; PLAN, ARCHITECTURE, FUNCTIONAL (+ru), UI_DESIGN, READMEs updated.
This commit is contained in:
+6
-1
@@ -19,7 +19,7 @@ internal/config/ # GATEWAY_* env config
|
||||
internal/backendclient/ # typed REST client (+ X-User-ID) and push gRPC client
|
||||
internal/session/ # in-memory session cache (LRU/TTL, backend fallback)
|
||||
internal/ratelimit/ # token-bucket limiter (golang.org/x/time/rate)
|
||||
internal/auth/ # Telegram initData HMAC validator (seam + fixtures)
|
||||
internal/connector/ # gRPC client to the Telegram connector (initData validate, out-of-app push) + routing
|
||||
internal/push/ # live-event fan-out hub (per-user client streams)
|
||||
internal/transcode/ # FlatBuffers<->REST bridge + message_type registry
|
||||
internal/connectsrv/ # the Connect Gateway service over h2c
|
||||
@@ -39,6 +39,11 @@ operations are unauthenticated and return the minted token. A unary domain
|
||||
outcome rides back in `ExecuteResponse.result_code` (HTTP 200); only edge
|
||||
failures become Connect error codes.
|
||||
|
||||
`auth.telegram` validates the Mini App `initData` by calling the **Telegram connector**
|
||||
(`GATEWAY_CONNECTOR_ADDR`), which holds the bot token; the gateway also routes
|
||||
out-of-app push to that connector for recipients with no live in-app stream
|
||||
(ARCHITECTURE.md §10). When `GATEWAY_CONNECTOR_ADDR` is unset, both are disabled.
|
||||
|
||||
The Stage 6 message-type slice: `auth.telegram`, `auth.guest`,
|
||||
`auth.email.request`, `auth.email.login`, `profile.get`, `game.submit_play`,
|
||||
`game.state`, `lobby.enqueue`, `lobby.poll`, `chat.post`; live events
|
||||
|
||||
+43
-10
@@ -18,9 +18,9 @@ import (
|
||||
"go.uber.org/zap"
|
||||
|
||||
"scrabble/gateway/internal/admin"
|
||||
"scrabble/gateway/internal/auth"
|
||||
"scrabble/gateway/internal/backendclient"
|
||||
"scrabble/gateway/internal/config"
|
||||
"scrabble/gateway/internal/connector"
|
||||
"scrabble/gateway/internal/connectsrv"
|
||||
"scrabble/gateway/internal/push"
|
||||
"scrabble/gateway/internal/ratelimit"
|
||||
@@ -73,14 +73,20 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
limiter := ratelimit.New()
|
||||
hub := push.NewHub(0)
|
||||
|
||||
var tg auth.TelegramValidator
|
||||
if cfg.TelegramBotToken != "" {
|
||||
tg = auth.NewHMACValidator(cfg.TelegramBotToken)
|
||||
var conn *connector.Client
|
||||
var validator transcode.TelegramValidator
|
||||
if cfg.ConnectorAddr != "" {
|
||||
conn, err = connector.New(cfg.ConnectorAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
validator = conn
|
||||
} else {
|
||||
logger.Warn("telegram auth disabled (GATEWAY_TELEGRAM_BOT_TOKEN unset)")
|
||||
logger.Warn("telegram disabled (GATEWAY_CONNECTOR_ADDR unset)")
|
||||
}
|
||||
|
||||
registry := transcode.NewRegistry(backend, tg)
|
||||
registry := transcode.NewRegistry(backend, validator)
|
||||
edge := connectsrv.NewServer(connectsrv.Deps{
|
||||
Registry: registry,
|
||||
Sessions: sessions,
|
||||
@@ -91,8 +97,9 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
Logger: logger,
|
||||
})
|
||||
|
||||
// Bridge the backend push stream into the fan-out hub.
|
||||
go runPushPump(ctx, backend, hub, logger)
|
||||
// Bridge the backend push stream into the fan-out hub (and the out-of-app
|
||||
// channel via the connector).
|
||||
go runPushPump(ctx, backend, hub, conn, logger)
|
||||
|
||||
public := &http.Server{Addr: cfg.HTTPAddr, Handler: edge.HTTPHandler()}
|
||||
servers := []*namedServer{{name: "public", srv: public}}
|
||||
@@ -153,8 +160,10 @@ func runServers(ctx context.Context, cancel context.CancelFunc, servers []*named
|
||||
}
|
||||
|
||||
// runPushPump keeps a backend push subscription open, forwarding every event to
|
||||
// the hub and re-subscribing after the stream ends, until the context is done.
|
||||
func runPushPump(ctx context.Context, backend *backendclient.Client, hub *push.Hub, logger *zap.Logger) {
|
||||
// the hub and re-subscribing after the stream ends, until the context is done. For
|
||||
// the out-of-app push kinds it also routes events whose recipient has no live
|
||||
// in-app stream to the platform connector (a nil connector disables that channel).
|
||||
func runPushPump(ctx context.Context, backend *backendclient.Client, hub *push.Hub, conn *connector.Client, logger *zap.Logger) {
|
||||
for ctx.Err() == nil {
|
||||
stream, err := backend.SubscribePush(ctx, gatewayID)
|
||||
if err != nil {
|
||||
@@ -178,6 +187,12 @@ func runPushPump(ctx context.Context, backend *backendclient.Client, hub *push.H
|
||||
Payload: ev.GetPayload(),
|
||||
EventID: ev.GetEventId(),
|
||||
})
|
||||
// Out-of-app fallback: when the recipient has no live in-app stream,
|
||||
// deliver the event over the platform push channel. Done in a goroutine
|
||||
// so a slow connector never stalls the in-app firehose.
|
||||
if conn != nil && connector.OutOfAppKind(ev.GetKind()) && !hub.HasSubscribers(ev.GetUserId()) {
|
||||
go deliverOutOfApp(ctx, backend, conn, ev.GetUserId(), ev.GetKind(), ev.GetPayload(), logger)
|
||||
}
|
||||
}
|
||||
if !sleep(ctx, pushReconnectDelay) {
|
||||
return
|
||||
@@ -185,6 +200,24 @@ func runPushPump(ctx context.Context, backend *backendclient.Client, hub *push.H
|
||||
}
|
||||
}
|
||||
|
||||
// deliverOutOfApp resolves the recipient's push target and, when they have a
|
||||
// Telegram identity and have not confined notifications to the app, asks the
|
||||
// connector to deliver the event. It is best-effort: every failure is logged and
|
||||
// dropped (the in-app stream remains the primary channel).
|
||||
func deliverOutOfApp(ctx context.Context, backend *backendclient.Client, conn *connector.Client, userID, kind string, payload []byte, logger *zap.Logger) {
|
||||
target, err := backend.PushTarget(ctx, userID)
|
||||
if err != nil {
|
||||
logger.Warn("push target lookup failed", zap.String("user_id", userID), zap.Error(err))
|
||||
return
|
||||
}
|
||||
if !connector.DeliverToTarget(target.ExternalID, target.NotificationsInAppOnly) {
|
||||
return
|
||||
}
|
||||
if _, err := conn.Notify(ctx, target.ExternalID, kind, payload, target.Language); err != nil {
|
||||
logger.Warn("out-of-app notify failed", zap.String("kind", kind), zap.Error(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 {
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
// Package auth holds the gateway's credential validators. The only non-trivial
|
||||
// one is the Telegram Web App initData HMAC check; guest and email logins carry
|
||||
// no gateway-side secret and are validated by the backend. The validator is an
|
||||
// interface so handlers test against fixtures without a bot token.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrInvalidInitData is returned when initData fails HMAC validation, is missing
|
||||
// the hash, is malformed, or is older than the freshness window.
|
||||
var ErrInvalidInitData = errors.New("auth: invalid telegram init data")
|
||||
|
||||
// defaultMaxAge bounds how old a validated initData payload may be.
|
||||
const defaultMaxAge = 24 * time.Hour
|
||||
|
||||
// TelegramUser is the identity extracted from a validated initData payload. ID
|
||||
// is the platform user id used as the identity's external_id.
|
||||
type TelegramUser struct {
|
||||
ID string
|
||||
Username string
|
||||
FirstName string
|
||||
}
|
||||
|
||||
// TelegramValidator validates Telegram Web App launch data and returns the
|
||||
// authenticated user.
|
||||
type TelegramValidator interface {
|
||||
Validate(initData string) (TelegramUser, error)
|
||||
}
|
||||
|
||||
// HMACValidator validates initData against a bot token per Telegram's documented
|
||||
// algorithm: the data-check string is HMAC-SHA256'd under a secret derived from
|
||||
// the bot token, and the result is compared with the supplied hash.
|
||||
type HMACValidator struct {
|
||||
botToken string
|
||||
maxAge time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewHMACValidator constructs a validator for botToken.
|
||||
func NewHMACValidator(botToken string) *HMACValidator {
|
||||
return &HMACValidator{botToken: botToken, maxAge: defaultMaxAge, now: time.Now}
|
||||
}
|
||||
|
||||
// Validate parses and verifies initData, returning the authenticated user.
|
||||
func (v *HMACValidator) Validate(initData string) (TelegramUser, error) {
|
||||
values, err := url.ParseQuery(initData)
|
||||
if err != nil {
|
||||
return TelegramUser{}, ErrInvalidInitData
|
||||
}
|
||||
hash := values.Get("hash")
|
||||
if hash == "" {
|
||||
return TelegramUser{}, ErrInvalidInitData
|
||||
}
|
||||
values.Del("hash")
|
||||
|
||||
if !v.checkSignature(values, hash) {
|
||||
return TelegramUser{}, ErrInvalidInitData
|
||||
}
|
||||
if err := v.checkFreshness(values.Get("auth_date")); err != nil {
|
||||
return TelegramUser{}, err
|
||||
}
|
||||
return parseUser(values.Get("user"))
|
||||
}
|
||||
|
||||
// checkSignature recomputes the HMAC over the sorted data-check string and
|
||||
// compares it with hash in constant time.
|
||||
func (v *HMACValidator) checkSignature(values url.Values, hash string) bool {
|
||||
keys := make([]string, 0, len(values))
|
||||
for k := range values {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
lines := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
lines = append(lines, k+"="+values.Get(k))
|
||||
}
|
||||
dataCheck := strings.Join(lines, "\n")
|
||||
|
||||
secret := hmacSHA256([]byte("WebAppData"), []byte(v.botToken))
|
||||
want := hmacSHA256(secret, []byte(dataCheck))
|
||||
got, err := hex.DecodeString(hash)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return hmac.Equal(want, got)
|
||||
}
|
||||
|
||||
// checkFreshness rejects an auth_date older than the validator's window.
|
||||
func (v *HMACValidator) checkFreshness(authDate string) error {
|
||||
if authDate == "" {
|
||||
return ErrInvalidInitData
|
||||
}
|
||||
secs, err := strconv.ParseInt(authDate, 10, 64)
|
||||
if err != nil {
|
||||
return ErrInvalidInitData
|
||||
}
|
||||
if v.now().Sub(time.Unix(secs, 0)) > v.maxAge {
|
||||
return ErrInvalidInitData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseUser extracts the user id and names from the user JSON field.
|
||||
func parseUser(userJSON string) (TelegramUser, error) {
|
||||
if userJSON == "" {
|
||||
return TelegramUser{}, ErrInvalidInitData
|
||||
}
|
||||
var u struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
FirstName string `json:"first_name"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(userJSON), &u); err != nil || u.ID == 0 {
|
||||
return TelegramUser{}, ErrInvalidInitData
|
||||
}
|
||||
return TelegramUser{
|
||||
ID: strconv.FormatInt(u.ID, 10),
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// hmacSHA256 returns HMAC-SHA256(message) under key.
|
||||
func hmacSHA256(key, message []byte) []byte {
|
||||
h := hmac.New(sha256.New, key)
|
||||
h.Write(message)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"scrabble/gateway/internal/auth"
|
||||
)
|
||||
|
||||
// signedInitData builds a valid Telegram initData query string for botToken,
|
||||
// computing the hash exactly as Telegram does.
|
||||
func signedInitData(botToken string, fields map[string]string) string {
|
||||
keys := make([]string, 0, len(fields))
|
||||
for k := range fields {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
lines := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
lines = append(lines, k+"="+fields[k])
|
||||
}
|
||||
secretMAC := hmac.New(sha256.New, []byte("WebAppData"))
|
||||
secretMAC.Write([]byte(botToken))
|
||||
secret := secretMAC.Sum(nil)
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
mac.Write([]byte(strings.Join(lines, "\n")))
|
||||
hash := hex.EncodeToString(mac.Sum(nil))
|
||||
|
||||
v := url.Values{}
|
||||
for k, val := range fields {
|
||||
v.Set(k, val)
|
||||
}
|
||||
v.Set("hash", hash)
|
||||
return v.Encode()
|
||||
}
|
||||
|
||||
func TestValidateAcceptsGenuineInitData(t *testing.T) {
|
||||
const token = "test-bot-token"
|
||||
fields := map[string]string{
|
||||
"auth_date": strconv.FormatInt(time.Now().Unix(), 10),
|
||||
"query_id": "abc",
|
||||
"user": `{"id":42,"first_name":"Ann","username":"ann"}`,
|
||||
}
|
||||
u, err := auth.NewHMACValidator(token).Validate(signedInitData(token, fields))
|
||||
if err != nil {
|
||||
t.Fatalf("validate genuine: %v", err)
|
||||
}
|
||||
if u.ID != "42" || u.Username != "ann" {
|
||||
t.Fatalf("user = %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsTamperedHash(t *testing.T) {
|
||||
const token = "test-bot-token"
|
||||
fields := map[string]string{
|
||||
"auth_date": strconv.FormatInt(time.Now().Unix(), 10),
|
||||
"user": `{"id":42}`,
|
||||
}
|
||||
data := signedInitData(token, fields) + "0" // corrupt the trailing hash
|
||||
if _, err := auth.NewHMACValidator(token).Validate(data); err == nil {
|
||||
t.Fatal("expected rejection of tampered init data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsWrongToken(t *testing.T) {
|
||||
fields := map[string]string{
|
||||
"auth_date": strconv.FormatInt(time.Now().Unix(), 10),
|
||||
"user": `{"id":42}`,
|
||||
}
|
||||
data := signedInitData("real-token", fields)
|
||||
if _, err := auth.NewHMACValidator("other-token").Validate(data); err == nil {
|
||||
t.Fatal("expected rejection under a different bot token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsStaleInitData(t *testing.T) {
|
||||
const token = "test-bot-token"
|
||||
fields := map[string]string{
|
||||
"auth_date": strconv.FormatInt(time.Now().Add(-48*time.Hour).Unix(), 10),
|
||||
"user": `{"id":42}`,
|
||||
}
|
||||
if _, err := auth.NewHMACValidator(token).Validate(signedInitData(token, fields)); err == nil {
|
||||
t.Fatal("expected rejection of stale init data")
|
||||
}
|
||||
}
|
||||
@@ -20,16 +20,17 @@ type SessionResp struct {
|
||||
|
||||
// ProfileResp is an account's own profile.
|
||||
type ProfileResp struct {
|
||||
UserID string `json:"user_id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
AwayStart string `json:"away_start"`
|
||||
AwayEnd string `json:"away_end"`
|
||||
HintBalance int `json:"hint_balance"`
|
||||
BlockChat bool `json:"block_chat"`
|
||||
BlockFriendRequests bool `json:"block_friend_requests"`
|
||||
IsGuest bool `json:"is_guest"`
|
||||
UserID string `json:"user_id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
AwayStart string `json:"away_start"`
|
||||
AwayEnd string `json:"away_end"`
|
||||
HintBalance int `json:"hint_balance"`
|
||||
BlockChat bool `json:"block_chat"`
|
||||
BlockFriendRequests bool `json:"block_friend_requests"`
|
||||
IsGuest bool `json:"is_guest"`
|
||||
NotificationsInAppOnly bool `json:"notifications_in_app_only"`
|
||||
}
|
||||
|
||||
// TileJSON is one placed tile, used in both play requests and move responses.
|
||||
@@ -109,11 +110,35 @@ type ChatResp struct {
|
||||
CreatedAtUnix int64 `json:"created_at_unix"`
|
||||
}
|
||||
|
||||
// TelegramAuth provisions/finds the Telegram account and mints a session.
|
||||
func (c *Client) TelegramAuth(ctx context.Context, externalID string) (SessionResp, error) {
|
||||
// TelegramAuth provisions/finds the Telegram account and mints a session, seeding a
|
||||
// brand-new account's display name and language from the validated launch fields.
|
||||
func (c *Client) TelegramAuth(ctx context.Context, externalID, languageCode, username, firstName string) (SessionResp, error) {
|
||||
var out SessionResp
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/telegram", "", "",
|
||||
map[string]string{"external_id": externalID}, &out)
|
||||
map[string]string{
|
||||
"external_id": externalID,
|
||||
"language_code": languageCode,
|
||||
"username": username,
|
||||
"first_name": firstName,
|
||||
}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// PushTargetResp is a recipient's out-of-app push routing data: their Telegram
|
||||
// external_id (empty when they have no Telegram identity), preferred language, and
|
||||
// whether they confined notifications to the in-app stream.
|
||||
type PushTargetResp struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
Language string `json:"language"`
|
||||
NotificationsInAppOnly bool `json:"notifications_in_app_only"`
|
||||
}
|
||||
|
||||
// PushTarget resolves a user id to their out-of-app Telegram routing data (the
|
||||
// gateway uses it to decide whether to deliver an event over platform push).
|
||||
func (c *Client) PushTarget(ctx context.Context, userID string) (PushTargetResp, error) {
|
||||
var out PushTargetResp
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/internal/push-target", "", "",
|
||||
map[string]string{"user_id": userID}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
|
||||
@@ -215,13 +215,14 @@ func (c *Client) ListInvitations(ctx context.Context, userID string) (Invitation
|
||||
func (c *Client) UpdateProfile(ctx context.Context, userID string, p ProfileResp) (ProfileResp, error) {
|
||||
var out ProfileResp
|
||||
body := map[string]any{
|
||||
"display_name": p.DisplayName,
|
||||
"preferred_language": p.PreferredLanguage,
|
||||
"time_zone": p.TimeZone,
|
||||
"away_start": p.AwayStart,
|
||||
"away_end": p.AwayEnd,
|
||||
"block_chat": p.BlockChat,
|
||||
"block_friend_requests": p.BlockFriendRequests,
|
||||
"display_name": p.DisplayName,
|
||||
"preferred_language": p.PreferredLanguage,
|
||||
"time_zone": p.TimeZone,
|
||||
"away_start": p.AwayStart,
|
||||
"away_end": p.AwayEnd,
|
||||
"block_chat": p.BlockChat,
|
||||
"block_friend_requests": p.BlockFriendRequests,
|
||||
"notifications_in_app_only": p.NotificationsInAppOnly,
|
||||
}
|
||||
err := c.do(ctx, http.MethodPut, "/api/v1/user/profile", userID, "", body, &out)
|
||||
return out, err
|
||||
|
||||
@@ -28,9 +28,10 @@ type Config struct {
|
||||
// checks before proxying admin traffic to the backend. Empty disables admin.
|
||||
AdminUser string
|
||||
AdminPassword string
|
||||
// TelegramBotToken is the secret used to validate Telegram initData HMACs.
|
||||
// Empty disables the telegram auth path.
|
||||
TelegramBotToken string
|
||||
// ConnectorAddr is the gRPC address of the Telegram connector side-service. The
|
||||
// gateway calls it to validate Mini App initData and to deliver out-of-app push.
|
||||
// Empty disables the telegram auth path and the out-of-app push channel.
|
||||
ConnectorAddr string
|
||||
// SessionTTL bounds how long a resolved session stays cached; SessionCacheMax
|
||||
// caps the number of cached sessions.
|
||||
SessionTTL time.Duration
|
||||
@@ -83,16 +84,16 @@ func DefaultRateLimit() RateLimitConfig {
|
||||
func Load() (Config, error) {
|
||||
var err error
|
||||
c := Config{
|
||||
HTTPAddr: envOr("GATEWAY_HTTP_ADDR", defaultHTTPAddr),
|
||||
AdminAddr: envOr("GATEWAY_ADMIN_ADDR", defaultAdminAddr),
|
||||
LogLevel: envOr("GATEWAY_LOG_LEVEL", defaultLogLevel),
|
||||
BackendHTTPURL: envOr("GATEWAY_BACKEND_HTTP_URL", defaultBackendHTTPURL),
|
||||
BackendGRPCAddr: envOr("GATEWAY_BACKEND_GRPC_ADDR", defaultBackendGRPCAddr),
|
||||
AdminUser: os.Getenv("GATEWAY_ADMIN_USER"),
|
||||
AdminPassword: os.Getenv("GATEWAY_ADMIN_PASSWORD"),
|
||||
TelegramBotToken: os.Getenv("GATEWAY_TELEGRAM_BOT_TOKEN"),
|
||||
SessionCacheMax: defaultSessionCacheMax,
|
||||
RateLimit: DefaultRateLimit(),
|
||||
HTTPAddr: envOr("GATEWAY_HTTP_ADDR", defaultHTTPAddr),
|
||||
AdminAddr: envOr("GATEWAY_ADMIN_ADDR", defaultAdminAddr),
|
||||
LogLevel: envOr("GATEWAY_LOG_LEVEL", defaultLogLevel),
|
||||
BackendHTTPURL: envOr("GATEWAY_BACKEND_HTTP_URL", defaultBackendHTTPURL),
|
||||
BackendGRPCAddr: envOr("GATEWAY_BACKEND_GRPC_ADDR", defaultBackendGRPCAddr),
|
||||
AdminUser: os.Getenv("GATEWAY_ADMIN_USER"),
|
||||
AdminPassword: os.Getenv("GATEWAY_ADMIN_PASSWORD"),
|
||||
ConnectorAddr: os.Getenv("GATEWAY_CONNECTOR_ADDR"),
|
||||
SessionCacheMax: defaultSessionCacheMax,
|
||||
RateLimit: DefaultRateLimit(),
|
||||
}
|
||||
if c.BackendTimeout, err = envDuration("GATEWAY_BACKEND_TIMEOUT", defaultBackendTimeout); err != nil {
|
||||
return Config{}, err
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// Package connector is the gateway's gRPC client for the Telegram connector
|
||||
// side-service: it validates Mini App initData and delivers out-of-app push. The
|
||||
// connector lives on the trusted internal network, so the connection uses insecure
|
||||
// (plaintext) transport credentials (ARCHITECTURE.md §12).
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
)
|
||||
|
||||
// ErrInvalidInitData is returned by ValidateInitData when the connector rejects the
|
||||
// launch data (a gRPC InvalidArgument), letting the transcode layer surface a stable
|
||||
// result code.
|
||||
var ErrInvalidInitData = errors.New("connector: invalid telegram init data")
|
||||
|
||||
// User is a validated Mini App identity.
|
||||
type User struct {
|
||||
ExternalID string
|
||||
Username string
|
||||
FirstName string
|
||||
LanguageCode string
|
||||
}
|
||||
|
||||
// Client wraps the connector's Telegram gRPC service.
|
||||
type Client struct {
|
||||
conn *grpc.ClientConn
|
||||
c telegramv1.TelegramClient
|
||||
}
|
||||
|
||||
// New dials the connector gRPC endpoint.
|
||||
func New(addr string) (*Client, error) {
|
||||
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connector: dial %s: %w", addr, err)
|
||||
}
|
||||
return &Client{conn: conn, c: telegramv1.NewTelegramClient(conn)}, nil
|
||||
}
|
||||
|
||||
// Close releases the gRPC connection.
|
||||
func (c *Client) Close() error { return c.conn.Close() }
|
||||
|
||||
// ValidateInitData verifies Mini App launch data and returns the user identity,
|
||||
// mapping a connector InvalidArgument to ErrInvalidInitData.
|
||||
func (c *Client) ValidateInitData(ctx context.Context, initData string) (User, error) {
|
||||
resp, err := c.c.ValidateInitData(ctx, &telegramv1.ValidateInitDataRequest{InitData: initData})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.InvalidArgument {
|
||||
return User{}, ErrInvalidInitData
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
return User{
|
||||
ExternalID: resp.GetExternalId(),
|
||||
Username: resp.GetUsername(),
|
||||
FirstName: resp.GetFirstName(),
|
||||
LanguageCode: resp.GetLanguageCode(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Notify delivers an out-of-app notification for a push event; delivered reports
|
||||
// whether a message was actually sent.
|
||||
func (c *Client) Notify(ctx context.Context, externalID, kind string, payload []byte, language string) (bool, error) {
|
||||
resp, err := c.c.Notify(ctx, &telegramv1.NotifyRequest{
|
||||
ExternalId: externalID,
|
||||
Kind: kind,
|
||||
Payload: payload,
|
||||
Language: language,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return resp.GetDelivered(), nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package connector
|
||||
|
||||
// outOfAppKinds is the set of backend push kinds delivered out-of-app; the rest
|
||||
// stay in-app only (opponent_moved and chat_message are too noisy for a platform
|
||||
// notification).
|
||||
var outOfAppKinds = map[string]bool{
|
||||
"your_turn": true,
|
||||
"nudge": true,
|
||||
"match_found": true,
|
||||
"notify": true,
|
||||
}
|
||||
|
||||
// OutOfAppKind reports whether a push kind is eligible for out-of-app delivery.
|
||||
func OutOfAppKind(kind string) bool { return outOfAppKinds[kind] }
|
||||
|
||||
// DeliverToTarget reports whether a resolved push target should receive an
|
||||
// out-of-app message: it has a Telegram identity (externalID != "") and has not
|
||||
// confined notifications to the app (inAppOnly == false). Combined with the
|
||||
// caller's "recipient is offline" check, this is the dedup rule that keeps the
|
||||
// platform push free of duplicates with the in-app stream.
|
||||
func DeliverToTarget(externalID string, inAppOnly bool) bool {
|
||||
return externalID != "" && !inAppOnly
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package connector
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestOutOfAppKind(t *testing.T) {
|
||||
out := []string{"your_turn", "nudge", "match_found", "notify"}
|
||||
for _, k := range out {
|
||||
if !OutOfAppKind(k) {
|
||||
t.Errorf("OutOfAppKind(%q) = false, want true", k)
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"opponent_moved", "chat_message", "", "unknown"} {
|
||||
if OutOfAppKind(k) {
|
||||
t.Errorf("OutOfAppKind(%q) = true, want false", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverToTarget(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
externalID string
|
||||
inAppOnly bool
|
||||
want bool
|
||||
}{
|
||||
{"telegram + opted in", "12345", false, true},
|
||||
{"in-app only suppresses", "12345", true, false},
|
||||
{"no telegram identity", "", false, false},
|
||||
{"no identity and in-app only", "", true, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := DeliverToTarget(tc.externalID, tc.inAppOnly); got != tc.want {
|
||||
t.Errorf("DeliverToTarget(%q, %v) = %v, want %v", tc.externalID, tc.inAppOnly, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -86,3 +86,18 @@ func (h *Hub) SubscriberCount() int {
|
||||
defer h.mu.Unlock()
|
||||
return len(h.subs)
|
||||
}
|
||||
|
||||
// HasSubscribers reports whether any live client stream is registered for userID.
|
||||
// It gates out-of-app push: an online user is already reached in-app, so the
|
||||
// platform push (Telegram) is skipped for them — keeping the fallback channel free
|
||||
// of duplicates.
|
||||
func (h *Hub) HasSubscribers(userID string) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
for _, s := range h.subs {
|
||||
if s.userID == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -54,3 +54,21 @@ func TestHubUnsubscribeClosesChannel(t *testing.T) {
|
||||
}
|
||||
h.Publish(push.Event{UserID: "u"}) // must not panic
|
||||
}
|
||||
|
||||
func TestHubHasSubscribers(t *testing.T) {
|
||||
h := push.NewHub(2)
|
||||
if h.HasSubscribers("u") {
|
||||
t.Fatal("no subscribers yet")
|
||||
}
|
||||
_, cancel := h.Subscribe("u")
|
||||
if !h.HasSubscribers("u") {
|
||||
t.Error("u should be reported online after Subscribe")
|
||||
}
|
||||
if h.HasSubscribers("other") {
|
||||
t.Error("other has no subscription")
|
||||
}
|
||||
cancel()
|
||||
if h.HasSubscribers("u") {
|
||||
t.Error("u should be offline after unsubscribe")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ func encodeProfile(p backendclient.ProfileResp) []byte {
|
||||
fb.ProfileAddIsGuest(b, p.IsGuest)
|
||||
fb.ProfileAddAwayStart(b, awayStart)
|
||||
fb.ProfileAddAwayEnd(b, awayEnd)
|
||||
fb.ProfileAddNotificationsInAppOnly(b, p.NotificationsInAppOnly)
|
||||
b.Finish(fb.ProfileEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"scrabble/gateway/internal/auth"
|
||||
"scrabble/gateway/internal/backendclient"
|
||||
"scrabble/gateway/internal/connector"
|
||||
fb "scrabble/pkg/fbs/scrabblefb"
|
||||
)
|
||||
|
||||
@@ -63,10 +63,16 @@ type Registry struct {
|
||||
ops map[string]Op
|
||||
}
|
||||
|
||||
// TelegramValidator validates Mini App launch data via the connector side-service.
|
||||
// *connector.Client implements it; a nil value disables the telegram auth path.
|
||||
type TelegramValidator interface {
|
||||
ValidateInitData(ctx context.Context, initData string) (connector.User, error)
|
||||
}
|
||||
|
||||
// NewRegistry builds the slice's message-type catalog over the backend client.
|
||||
// The Telegram auth op is registered only when a validator is supplied (a bot
|
||||
// token is configured); otherwise auth.telegram is simply unknown.
|
||||
func NewRegistry(backend *backendclient.Client, tg auth.TelegramValidator) *Registry {
|
||||
// The Telegram auth op is registered only when a validator is supplied (the
|
||||
// connector is configured); otherwise auth.telegram is simply unknown.
|
||||
func NewRegistry(backend *backendclient.Client, tg TelegramValidator) *Registry {
|
||||
r := &Registry{ops: make(map[string]Op)}
|
||||
if tg != nil {
|
||||
r.ops[MsgAuthTelegram] = Op{Handler: authTelegramHandler(backend, tg)}
|
||||
@@ -109,20 +115,20 @@ func DomainCode(err error) (string, bool) {
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code, true
|
||||
}
|
||||
if errors.Is(err, auth.ErrInvalidInitData) {
|
||||
if errors.Is(err, connector.ErrInvalidInitData) {
|
||||
return "invalid_init_data", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func authTelegramHandler(backend *backendclient.Client, tg auth.TelegramValidator) Handler {
|
||||
func authTelegramHandler(backend *backendclient.Client, tg TelegramValidator) Handler {
|
||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||
in := fb.GetRootAsTelegramLoginRequest(req.Payload, 0)
|
||||
user, err := tg.Validate(string(in.InitData()))
|
||||
user, err := tg.ValidateInitData(ctx, string(in.InitData()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess, err := backend.TelegramAuth(ctx, user.ID)
|
||||
sess, err := backend.TelegramAuth(ctx, user.ExternalID, user.LanguageCode, user.Username, user.FirstName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -233,13 +233,14 @@ func profileUpdateHandler(backend *backendclient.Client) Handler {
|
||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||
in := fb.GetRootAsUpdateProfileRequest(req.Payload, 0)
|
||||
p := backendclient.ProfileResp{
|
||||
DisplayName: string(in.DisplayName()),
|
||||
PreferredLanguage: string(in.PreferredLanguage()),
|
||||
TimeZone: string(in.TimeZone()),
|
||||
AwayStart: string(in.AwayStart()),
|
||||
AwayEnd: string(in.AwayEnd()),
|
||||
BlockChat: in.BlockChat(),
|
||||
BlockFriendRequests: in.BlockFriendRequests(),
|
||||
DisplayName: string(in.DisplayName()),
|
||||
PreferredLanguage: string(in.PreferredLanguage()),
|
||||
TimeZone: string(in.TimeZone()),
|
||||
AwayStart: string(in.AwayStart()),
|
||||
AwayEnd: string(in.AwayEnd()),
|
||||
BlockChat: in.BlockChat(),
|
||||
BlockFriendRequests: in.BlockFriendRequests(),
|
||||
NotificationsInAppOnly: in.NotificationsInAppOnly(),
|
||||
}
|
||||
out, err := backend.UpdateProfile(ctx, req.UserID, p)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package transcode_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
@@ -202,11 +203,15 @@ func TestGcgRoundTrip(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestProfileUpdateRoundTripAway(t *testing.T) {
|
||||
var gotBody map[string]any
|
||||
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut || r.URL.Path != "/api/v1/user/profile" {
|
||||
t.Errorf("unexpected %s %q", r.Method, r.URL.Path)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"user_id":"u-1","display_name":"Kaya","preferred_language":"ru","time_zone":"Europe/Moscow","away_start":"00:00","away_end":"07:30"}`))
|
||||
_ = json.NewDecoder(r.Body).Decode(&gotBody)
|
||||
// Respond with notifications_in_app_only=false to exercise the encode path
|
||||
// carrying a non-default value back to the client.
|
||||
_, _ = w.Write([]byte(`{"user_id":"u-1","display_name":"Kaya","preferred_language":"ru","time_zone":"Europe/Moscow","away_start":"00:00","away_end":"07:30","notifications_in_app_only":false}`))
|
||||
})
|
||||
defer cleanup()
|
||||
|
||||
@@ -225,6 +230,7 @@ func TestProfileUpdateRoundTripAway(t *testing.T) {
|
||||
fb.UpdateProfileRequestAddTimeZone(b, tz)
|
||||
fb.UpdateProfileRequestAddAwayStart(b, as)
|
||||
fb.UpdateProfileRequestAddAwayEnd(b, ae)
|
||||
fb.UpdateProfileRequestAddNotificationsInAppOnly(b, true)
|
||||
b.Finish(fb.UpdateProfileRequestEnd(b))
|
||||
|
||||
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: b.FinishedBytes()})
|
||||
@@ -235,4 +241,12 @@ func TestProfileUpdateRoundTripAway(t *testing.T) {
|
||||
if string(p.AwayStart()) != "00:00" || string(p.AwayEnd()) != "07:30" || string(p.PreferredLanguage()) != "ru" {
|
||||
t.Fatalf("profile away round-trip wrong: start=%q end=%q lang=%q", p.AwayStart(), p.AwayEnd(), p.PreferredLanguage())
|
||||
}
|
||||
// The request's in-app-only flag (true) must reach the backend, and the backend's
|
||||
// value (false) must come back in the encoded Profile.
|
||||
if v, ok := gotBody["notifications_in_app_only"].(bool); !ok || v != true {
|
||||
t.Errorf("forwarded notifications_in_app_only = %v (ok=%v), want true", gotBody["notifications_in_app_only"], ok)
|
||||
}
|
||||
if p.NotificationsInAppOnly() {
|
||||
t.Error("response notifications_in_app_only = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package transcode_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
|
||||
"scrabble/gateway/internal/connector"
|
||||
"scrabble/gateway/internal/transcode"
|
||||
fb "scrabble/pkg/fbs/scrabblefb"
|
||||
)
|
||||
|
||||
// fakeValidator stands in for the connector's ValidateInitData RPC.
|
||||
type fakeValidator struct {
|
||||
user connector.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeValidator) ValidateInitData(context.Context, string) (connector.User, error) {
|
||||
return f.user, f.err
|
||||
}
|
||||
|
||||
func telegramLoginPayload(initData string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
off := b.CreateString(initData)
|
||||
fb.TelegramLoginRequestStart(b)
|
||||
fb.TelegramLoginRequestAddInitData(b, off)
|
||||
b.Finish(fb.TelegramLoginRequestEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
func TestTelegramAuthForwardsSeedFields(t *testing.T) {
|
||||
var gotBody map[string]string
|
||||
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/internal/sessions/telegram" {
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&gotBody)
|
||||
_, _ = w.Write([]byte(`{"token":"tok-tg","user_id":"u-tg","is_guest":false,"display_name":"Иван"}`))
|
||||
})
|
||||
defer cleanup()
|
||||
|
||||
v := fakeValidator{user: connector.User{ExternalID: "42", Username: "neo", FirstName: "Иван", LanguageCode: "ru"}}
|
||||
reg := transcode.NewRegistry(backend, v)
|
||||
op, ok := reg.Lookup(transcode.MsgAuthTelegram)
|
||||
if !ok {
|
||||
t.Fatal("auth.telegram not registered")
|
||||
}
|
||||
|
||||
payload, err := op.Handler(context.Background(), transcode.Request{Payload: telegramLoginPayload("init")})
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
sess := fb.GetRootAsSession(payload, 0)
|
||||
if string(sess.Token()) != "tok-tg" || string(sess.UserId()) != "u-tg" {
|
||||
t.Fatalf("session decoded wrong: token=%q user=%q", sess.Token(), sess.UserId())
|
||||
}
|
||||
// The validated launch fields are forwarded so the backend can seed a new account.
|
||||
if gotBody["external_id"] != "42" || gotBody["language_code"] != "ru" || gotBody["first_name"] != "Иван" {
|
||||
t.Errorf("forwarded body = %+v, want external_id=42 language_code=ru first_name=Иван", gotBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramAuthInvalidInitData(t *testing.T) {
|
||||
backend, cleanup := fakeBackend(t, func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("backend must not be called when initData is invalid")
|
||||
})
|
||||
defer cleanup()
|
||||
|
||||
reg := transcode.NewRegistry(backend, fakeValidator{err: connector.ErrInvalidInitData})
|
||||
op, _ := reg.Lookup(transcode.MsgAuthTelegram)
|
||||
|
||||
_, err := op.Handler(context.Background(), transcode.Request{Payload: telegramLoginPayload("bad")})
|
||||
if code, ok := transcode.DomainCode(err); !ok || code != "invalid_init_data" {
|
||||
t.Errorf("DomainCode = (%q, %v), want (invalid_init_data, true)", code, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramAuthDisabledWithoutConnector confirms a nil validator leaves
|
||||
// auth.telegram unregistered.
|
||||
func TestTelegramAuthDisabledWithoutConnector(t *testing.T) {
|
||||
backend, cleanup := fakeBackend(t, func(http.ResponseWriter, *http.Request) {})
|
||||
defer cleanup()
|
||||
reg := transcode.NewRegistry(backend, nil)
|
||||
if _, ok := reg.Lookup(transcode.MsgAuthTelegram); ok {
|
||||
t.Error("auth.telegram should be unregistered without a connector")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user