feat(vk): embed the game as a VK Mini App
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 14s
CI / ui (pull_request) Successful in 1m0s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m19s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 14s
CI / ui (pull_request) Successful in 1m0s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m19s
Mirror the Telegram Mini App wrapper for VK: the SPA loads at a new /vk/ entry, authenticates from VK's signed launch parameters, and provisions a 'vk' platform identity — the minimum to run the game in VK test mode. - Gateway verifies the launch signature in-process (internal/vkauth: HMAC-SHA256 over the sorted vk_* params under GATEWAY_VK_APP_SECRET, base64url) — a pure offline check, no side-service. New auth.vk op (gated on the secret), backendclient.VKAuth, /vk/ SPA mount. - Backend: KindVK + ProvisionVK/vkSeed, /sessions/vk handler, identity kind widened to include 'vk' (migration 00005, expand-contract). - UI: src/lib/vk.ts (VK Bridge, lazy-imported), bootVK + the /vk/ boot dispatch, encodeVKLogin + authVK across transport/client/mock. VK omits the name from the signed params, so the client reads it via VKWebAppGetUserInfo as an unsigned display seed. - Deploy: /vk in the edge Caddyfile, GATEWAY_VK_APP_SECRET wired through compose + .env.example + CI (TEST_) + prod-deploy (PROD_). - Admin console: surface the VK user id (link to the VK profile) next to the Telegram id on the user card. - Docs: ARCHITECTURE §12/§13, FUNCTIONAL (+ _ru), gateway README; VK integration reference under .claude/. Signature algorithm verified against dev.vk.com plus independent Node/Python references and a %2C edge-case vector.
This commit is contained in:
@@ -22,12 +22,13 @@ import (
|
||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||
)
|
||||
|
||||
// Identity kinds recognised by the backend. Email is modelled as an identity
|
||||
// alongside platform identities; its confirmed flag is driven by the email
|
||||
// confirm-code flow. Robot is a synthetic kind: each pooled
|
||||
// robot opponent is a durable account bound to one robot identity.
|
||||
// Identity kinds recognised by the backend. Telegram and VK are platform identities,
|
||||
// auto-confirmed on first contact. Email is modelled as an identity alongside them; its
|
||||
// confirmed flag is driven by the email confirm-code flow. Robot is a synthetic kind:
|
||||
// each pooled robot opponent is a durable account bound to one robot identity.
|
||||
const (
|
||||
KindTelegram = "telegram"
|
||||
KindVK = "vk"
|
||||
KindEmail = "email"
|
||||
KindRobot = "robot"
|
||||
)
|
||||
@@ -185,6 +186,28 @@ func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode,
|
||||
return acc, created, err
|
||||
}
|
||||
|
||||
// ProvisionVK provisions (or finds) the account bound to a VK identity, reporting
|
||||
// whether this call created it (first contact). On first contact only, it seeds the new
|
||||
// account's preferred language from the VK languageCode (vk_language, when it maps to a
|
||||
// supported language) and its display name sanitized from displayName — the name read
|
||||
// client-side via VKWebAppGetUserInfo, since VK omits it from the signed launch params —
|
||||
// falling back to a generated placeholder when it yields no letters; an already-existing
|
||||
// account is returned unchanged, so a later profile edit is never overwritten.
|
||||
func (s *Store) ProvisionVK(ctx context.Context, externalID, languageCode, displayName, browserTZ string) (Account, bool, error) {
|
||||
// Pre-check whether the identity already exists so the caller can act on first
|
||||
// contact (mirrors ProvisionTelegram); a create race only mis-reports created for
|
||||
// that one call.
|
||||
_, err := s.findByIdentity(ctx, KindVK, externalID)
|
||||
created := errors.Is(err, ErrNotFound)
|
||||
if err != nil && !created {
|
||||
return Account{}, false, err
|
||||
}
|
||||
seed := vkSeed(languageCode, displayName)
|
||||
seed.timeZone = seedZone(browserTZ)
|
||||
acc, err := s.provision(ctx, KindVK, externalID, seed)
|
||||
return acc, created, err
|
||||
}
|
||||
|
||||
// provision finds the account for (kind, externalID) or creates it with seed,
|
||||
// collapsing a concurrent-create race on the identity unique constraint into a
|
||||
// re-read of the winner's account.
|
||||
@@ -258,6 +281,24 @@ func telegramSeed(languageCode, username, firstName string) provisionSeed {
|
||||
return seed
|
||||
}
|
||||
|
||||
// vkSeed derives the create-time seed from VK launch fields: a supported preferred
|
||||
// language from languageCode (vk_language, normally a 2-letter code) and a display name
|
||||
// from displayName (sanitized to the editable format), falling back to a generated
|
||||
// placeholder in the seeded language when the name yields no usable letters. Unlike
|
||||
// telegramSeed there is no @username fallback — VK provides only the name.
|
||||
func vkSeed(languageCode, displayName string) provisionSeed {
|
||||
var seed provisionSeed
|
||||
if lang, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(languageCode)), "-"); lang == "en" || lang == "ru" {
|
||||
seed.preferredLanguage = lang
|
||||
}
|
||||
name := sanitizeDisplayName(displayName)
|
||||
if name == "" {
|
||||
name = placeholderDisplayName(seed.preferredLanguage)
|
||||
}
|
||||
seed.displayName = name
|
||||
return seed
|
||||
}
|
||||
|
||||
// GetByID loads the account identified by id, or ErrNotFound when it is absent.
|
||||
func (s *Store) GetByID(ctx context.Context, id uuid.UUID) (Account, error) {
|
||||
stmt := postgres.SELECT(table.Accounts.AllColumns).
|
||||
@@ -421,7 +462,7 @@ func (s *Store) create(ctx context.Context, kind, externalID string, seed provis
|
||||
table.Identities.Kind,
|
||||
table.Identities.ExternalID,
|
||||
table.Identities.Confirmed,
|
||||
).VALUES(identityID, accountID, kind, externalID, kind == KindTelegram)
|
||||
).VALUES(identityID, accountID, kind, externalID, kind == KindTelegram || kind == KindVK)
|
||||
if _, err := insertIdentity.ExecContext(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -75,3 +75,55 @@ func TestTelegramSeedTruncatesLongName(t *testing.T) {
|
||||
t.Errorf("display name rune count = %d, want %d", n, maxDisplayName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVKSeed covers the pure mapping from VK launch fields to the create-time account
|
||||
// seed: supported-language detection from vk_language (bare and region-tagged) and the
|
||||
// display name sanitized from the client-supplied name. Unlike Telegram there is no
|
||||
// @username fallback — VK provides only the name.
|
||||
func TestVKSeed(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
languageCode, displayName string
|
||||
wantLang, wantName string
|
||||
}{
|
||||
"ru bare": {"ru", "Иван", "ru", "Иван"},
|
||||
"en region-tagged": {"en-US", "John", "en", "John"},
|
||||
"full name kept": {"ru", "Иван Петров", "ru", "Иван Петров"},
|
||||
"unknown language": {"uk", "Тарас", "", "Тарас"},
|
||||
"empty language": {"", "Neo", "", "Neo"},
|
||||
"trimmed": {" RU ", " Anna ", "ru", "Anna"},
|
||||
"emoji stripped": {"en", "🎮Kaya🎮", "en", "Kaya"},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got := vkSeed(tc.languageCode, tc.displayName)
|
||||
if got.preferredLanguage != tc.wantLang {
|
||||
t.Errorf("preferredLanguage = %q, want %q", got.preferredLanguage, tc.wantLang)
|
||||
}
|
||||
if got.displayName != tc.wantName {
|
||||
t.Errorf("displayName = %q, want %q", got.displayName, tc.wantName)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVKSeedPlaceholder checks a VK name with no usable letters falls back to a
|
||||
// generated placeholder in the seeded language ("Player-NNNNN" / "Игрок-NNNNN").
|
||||
func TestVKSeedPlaceholder(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
languageCode, displayName string
|
||||
wantRe string
|
||||
}{
|
||||
"en empty": {"en", "", `^Player-\d{5}$`},
|
||||
"ru empty": {"ru", "", `^Игрок-\d{5}$`},
|
||||
"default en": {"uk", "", `^Player-\d{5}$`},
|
||||
"name garbage": {"ru", "123!@#", `^Игрок-\d{5}$`},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got := vkSeed(tc.languageCode, tc.displayName).displayName
|
||||
if !regexp.MustCompile(tc.wantRe).MatchString(got) {
|
||||
t.Errorf("displayName = %q, want match %s", got, tc.wantRe)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ func TestRendererRendersEveryPage(t *testing.T) {
|
||||
{"dashboard", DashboardView{Accounts: 3, Variants: []VariantVersions{{Variant: "scrabble_en", Latest: "v1", Versions: []string{"v1"}}}}, "Dashboard"},
|
||||
{"users", UsersView{Items: []UserRow{{ID: "a1", DisplayName: "Kaya", FlaggedHighRate: true}}, Pager: NewPager(1, 50, 1)}, "high-rate"},
|
||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", HasStats: true, Stats: StatsRow{Wins: 2}, TelegramID: "123", ConnectorEnabled: true}, "Send Telegram message"},
|
||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", VKID: "494075"}, "vk.com/id494075"},
|
||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", FlaggedHighRateAt: "2026-06-10 12:00"}, "Clear high-rate flag"},
|
||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", Roles: []string{"feedback_banned"}, KnownRoles: []string{"feedback_banned"}}, "feedback_banned"},
|
||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya",
|
||||
|
||||
@@ -142,6 +142,11 @@
|
||||
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
{{if .VKID}}
|
||||
<section class="panel"><h2>VK</h2>
|
||||
<p>VK ID: <code>{{.VKID}}</code> · <a href="https://vk.com/id{{.VKID}}" target="_blank" rel="noopener">open profile</a></p>
|
||||
</section>
|
||||
{{end}}
|
||||
<section class="panel"><h2>Games</h2>
|
||||
<table class="list">
|
||||
<thead><tr><th>Game</th><th>Variant</th><th>Status</th><th class="num">Players</th><th>Updated</th></tr></thead>
|
||||
|
||||
@@ -156,13 +156,17 @@ type UserDetailView struct {
|
||||
HintBalance int
|
||||
// HintGrantMax is the per-grant cap the operator's "add hints" form enforces (it mirrors the
|
||||
// server's maxHintGrant), passed through so the policy value lives in one place.
|
||||
HintGrantMax int
|
||||
CreatedAt string
|
||||
HasStats bool
|
||||
Stats StatsRow
|
||||
Identities []IdentityRow
|
||||
Games []GameRow
|
||||
HintGrantMax int
|
||||
CreatedAt string
|
||||
HasStats bool
|
||||
Stats StatsRow
|
||||
Identities []IdentityRow
|
||||
Games []GameRow
|
||||
// TelegramID and VKID are the account's platform external ids (empty when absent).
|
||||
// TelegramID gates the "Send Telegram message" operator action; VKID surfaces the VK
|
||||
// user id with a link to the VK profile (there is no VK messaging to drive).
|
||||
TelegramID string
|
||||
VKID string
|
||||
ConnectorEnabled bool
|
||||
// MoveChart is the pre-rendered inline SVG of the account's per-move-number think
|
||||
// time (min/mean/max), empty when the account has no timed move.
|
||||
|
||||
@@ -154,6 +154,53 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestProvisionVKSeedsNewAccountOnly checks VK first contact seeds the new account's
|
||||
// language, display name and time zone from the launch fields / detected offset, records
|
||||
// the vk identity as confirmed (a platform identity), and never overwrites an existing
|
||||
// account on a later launch. It also exercises the widened identities.kind CHECK — a
|
||||
// 'vk' row must insert.
|
||||
func TestProvisionVKSeedsNewAccountOnly(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
ext := "vk-" + uuid.NewString()
|
||||
|
||||
acc, created, err := store.ProvisionVK(ctx, ext, "ru", "Иван Петров", "+03:00")
|
||||
if err != nil {
|
||||
t.Fatalf("provision vk: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Error("created = false on first contact, want true")
|
||||
}
|
||||
if acc.PreferredLanguage != "ru" {
|
||||
t.Errorf("PreferredLanguage = %q, want ru", acc.PreferredLanguage)
|
||||
}
|
||||
if acc.DisplayName != "Иван Петров" {
|
||||
t.Errorf("DisplayName = %q, want Иван Петров", acc.DisplayName)
|
||||
}
|
||||
if acc.TimeZone != "+03:00" {
|
||||
t.Errorf("TimeZone = %q, want the seeded +03:00", acc.TimeZone)
|
||||
}
|
||||
// A VK identity is a platform identity: confirmed on insert.
|
||||
if !identityConfirmed(t, account.KindVK, ext) {
|
||||
t.Error("vk identity must be confirmed")
|
||||
}
|
||||
|
||||
// A later launch with different fields returns the same account, unchanged.
|
||||
again, created, err := store.ProvisionVK(ctx, ext, "en", "Other Name", "+09:00")
|
||||
if err != nil {
|
||||
t.Fatalf("re-provision vk: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Error("created = true on a repeat launch, want false")
|
||||
}
|
||||
if again.ID != acc.ID {
|
||||
t.Errorf("re-provision id = %s, want %s", again.ID, acc.ID)
|
||||
}
|
||||
if again.PreferredLanguage != "ru" || again.DisplayName != "Иван Петров" || again.TimeZone != "+03:00" {
|
||||
t.Errorf("existing account overwritten: lang=%q name=%q tz=%q", again.PreferredLanguage, again.DisplayName, again.TimeZone)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProvisionSeedsTimeZone checks the create-time time-zone seed across paths: a
|
||||
// valid detected offset is stored verbatim (even "+00:00", which is deliberately
|
||||
// distinct from the unset "UTC" default), a guest is seeded the same way, and a
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Admit the 'vk' platform identity (VK Mini App users) into the identities.kind check
|
||||
-- constraint, alongside telegram/email/robot. Expand-contract: widening the allowed set
|
||||
-- is backward-compatible, so a backend image rollback stays DB-safe — the older code
|
||||
-- simply never writes a 'vk' row. The table shape is unchanged (only the CHECK), so the
|
||||
-- generated go-jet model is not regenerated.
|
||||
|
||||
-- +goose Up
|
||||
ALTER TABLE backend.identities DROP CONSTRAINT identities_kind_chk;
|
||||
ALTER TABLE backend.identities ADD CONSTRAINT identities_kind_chk CHECK ((kind = ANY (ARRAY['telegram'::text, 'vk'::text, 'email'::text, 'robot'::text])));
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE backend.identities DROP CONSTRAINT identities_kind_chk;
|
||||
ALTER TABLE backend.identities ADD CONSTRAINT identities_kind_chk CHECK ((kind = ANY (ARRAY['telegram'::text, 'email'::text, 'robot'::text])));
|
||||
@@ -27,6 +27,7 @@ func (s *Server) registerRoutes() {
|
||||
if s.sessions != nil && s.accounts != nil {
|
||||
in := s.internal
|
||||
in.POST("/sessions/telegram", s.handleTelegramAuth)
|
||||
in.POST("/sessions/vk", s.handleVKAuth)
|
||||
in.POST("/sessions/guest", s.handleGuestAuth)
|
||||
in.POST("/sessions/email/request", s.handleEmailRequest)
|
||||
in.POST("/sessions/email/login", s.handleEmailLogin)
|
||||
|
||||
@@ -362,6 +362,9 @@ func (s *Server) consoleUserDetail(c *gin.Context) {
|
||||
if tg, err := s.accounts.IdentityExternalID(ctx, id, account.KindTelegram); err == nil {
|
||||
view.TelegramID = tg
|
||||
}
|
||||
if vk, err := s.accounts.IdentityExternalID(ctx, id, account.KindVK); err == nil {
|
||||
view.VKID = vk
|
||||
}
|
||||
if games, err := s.games.ListForAccount(ctx, id); err == nil {
|
||||
for _, g := range games {
|
||||
view.Games = append(view.Games, gameRow(g))
|
||||
|
||||
@@ -65,6 +65,37 @@ func (s *Server) handleTelegramAuth(c *gin.Context) {
|
||||
s.mintSession(c, acc)
|
||||
}
|
||||
|
||||
// vkAuthRequest carries the identity the gateway extracted from verified VK launch
|
||||
// params. LanguageCode (vk_language) and DisplayName (read client-side via
|
||||
// VKWebAppGetUserInfo, since VK omits the name from the signed params) seed a brand-new
|
||||
// account's language and display name; BrowserTZ (the client's detected "±HH:MM" UTC
|
||||
// offset) seeds its time zone. All seeds apply on first contact only.
|
||||
type vkAuthRequest struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
LanguageCode string `json:"language_code"`
|
||||
DisplayName string `json:"display_name"`
|
||||
BrowserTZ string `json:"browser_tz"`
|
||||
}
|
||||
|
||||
// handleVKAuth provisions (or finds) the account bound to a VK identity and mints a
|
||||
// session for it, seeding a new account's language and display name from the supplied VK
|
||||
// fields (first contact only). Unlike Telegram there is no moderated-chat re-evaluation
|
||||
// or deep-link variant seed: a fresh VK account has no Telegram chat eligibility and the
|
||||
// MVP carries no launch deep link.
|
||||
func (s *Server) handleVKAuth(c *gin.Context) {
|
||||
var req vkAuthRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.ExternalID == "" {
|
||||
abortBadRequest(c, "external_id is required")
|
||||
return
|
||||
}
|
||||
acc, _, err := s.accounts.ProvisionVK(c.Request.Context(), req.ExternalID, req.LanguageCode, req.DisplayName, req.BrowserTZ)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
s.mintSession(c, acc)
|
||||
}
|
||||
|
||||
// pushTargetRequest asks for a user's out-of-app push routing data by account id.
|
||||
type pushTargetRequest struct {
|
||||
UserID string `json:"user_id"`
|
||||
|
||||
Reference in New Issue
Block a user