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:
@@ -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