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

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:
Ilia Denisov
2026-06-27 11:37:31 +02:00
parent 13c22734ee
commit 65c194264c
43 changed files with 1175 additions and 50 deletions
+55 -9
View File
@@ -32,6 +32,7 @@ import {
telegramCloudGet,
telegramCloudSet,
} from './telegram';
import { onVKPath, insideVK, vkInit, vkLaunchParams, vkUserName } from './vk';
import { CLOUD_PREFS_KEY, decodeClientPrefs, encodeClientPrefs } from './cloudprefs';
import { parseStartParam } from './deeplink';
import { clearSession, loadPrefs, loadSession, saveSession, savePrefs } from './session';
@@ -664,6 +665,17 @@ export async function bootstrap(): Promise<void> {
return;
}
// VK Mini App launch: signal readiness to the VK client (which dismisses its loading cover), then
// authenticate from the signed launch parameters in the URL — the display name comes from
// VKWebAppGetUserInfo, since VK omits it from the signed params. The /vk/ entry opened outside VK
// (no signed params — e.g. a developer hitting the URL directly) falls through to the web flow.
if (onVKPath() && insideVK()) {
await vkInit();
await bootVK();
app.ready = true;
return;
}
const saved = await loadSession();
if (saved) {
await adoptSession(saved);
@@ -674,10 +686,10 @@ export async function bootstrap(): Promise<void> {
app.ready = true;
}
// Inside a Mini App the only identity is the Telegram session, so a failed launch must never fall
// back to the web login screen. A transient backend outage (a deploy rolling over) is retried a
// few times in silence; only then does the boot-error screen surface, from which Retry re-runs the
// same path (retryTelegramBoot).
// Inside a Mini App the only identity is the platform session (Telegram or VK), so a failed launch
// must never fall back to the web login screen. A transient backend outage (a deploy rolling over)
// is retried a few times in silence; only then does the boot-error screen surface, from which Retry
// re-runs the same path (retryMiniAppBoot).
const TELEGRAM_BOOT_RETRIES = 2;
const TELEGRAM_BOOT_RETRY_MS = 1200;
@@ -714,14 +726,48 @@ async function bootTelegram(launch: TelegramLaunch): Promise<void> {
}
/**
* retryTelegramBoot re-attempts the Mini App launch from the boot-error screen's Retry button. It
* clears the error and shows the loading state again, then runs the same retrying boot; on success
* the app renders normally, otherwise the boot-error screen returns.
* bootVK authenticates a VK Mini App launch from the signed launch parameters in the URL, seeding a
* brand-new account's display name from VKWebAppGetUserInfo. Like bootTelegram it retries a few
* times on a transient failure before raising the boot-error screen, and a blocked account is
* terminal. This MVP carries no VK deep-link routing.
*/
export async function retryTelegramBoot(): Promise<void> {
async function bootVK(): Promise<void> {
const params = vkLaunchParams();
const displayName = await vkUserName();
for (let attempt = 0; ; attempt++) {
try {
await adoptSession(await gateway.authVK(params, displayName));
app.bootError = false;
return;
} catch (err) {
if (err instanceof GatewayError && err.code === 'account_blocked') {
await enterBlocked();
return;
}
if (attempt >= TELEGRAM_BOOT_RETRIES) {
app.bootError = true;
return;
}
await delay(TELEGRAM_BOOT_RETRY_MS);
}
}
}
/**
* retryMiniAppBoot re-attempts a Mini App launch from the boot-error screen's Retry button — the VK
* boot on the /vk/ entry, the Telegram boot otherwise. It clears the error and shows the loading
* state again, then runs the same retrying boot; on success the app renders normally, otherwise the
* boot-error screen returns.
*/
export async function retryMiniAppBoot(): Promise<void> {
app.bootError = false;
app.ready = false;
await bootTelegram(telegramLaunch());
if (onVKPath()) {
await vkInit();
await bootVK();
} else {
await bootTelegram(telegramLaunch());
}
app.ready = true;
}
+4
View File
@@ -58,6 +58,10 @@ export type Unsubscribe = () => void;
export interface GatewayClient {
// --- auth (unauthenticated) ---
authTelegram(initData: string): Promise<Session>;
/** Authenticate a VK Mini App launch: params is the signed vk_* launch query string (the gateway
* verifies its sign); displayName is the client-read VKWebAppGetUserInfo name (an unsigned,
* cosmetic seed for a brand-new account). */
authVK(params: string, displayName: string): Promise<Session>;
authGuest(locale?: string): Promise<Session>;
authEmailRequest(email: string): Promise<void>;
authEmailLogin(email: string, code: string): Promise<Session>;
+8
View File
@@ -30,6 +30,7 @@ import {
encodeTarget,
encodeTelegramLogin,
encodeUpdateProfile,
encodeVKLogin,
} from './codec';
describe('codec', () => {
@@ -94,6 +95,13 @@ describe('codec', () => {
);
expect(email.email()).toBe('a@example.com');
expect(email.browserTz()).toBe('+00:00');
const vk = fb.VKLoginRequest.getRootAsVKLoginRequest(
new ByteBuffer(encodeVKLogin('vk_user_id=494075&vk_ts=1&sign=abc', '+03:00', 'Иван Петров')),
);
expect(vk.params()).toBe('vk_user_id=494075&vk_ts=1&sign=abc');
expect(vk.browserTz()).toBe('+03:00');
expect(vk.displayName()).toBe('Иван Петров');
});
it('round-trips a feedback submit and decodes state + unread', () => {
+12
View File
@@ -189,6 +189,18 @@ export function encodeTelegramLogin(initData: string, browserTz: string): Uint8A
return finish(b, fb.TelegramLoginRequest.endTelegramLoginRequest(b));
}
export function encodeVKLogin(params: string, browserTz: string, displayName: string): Uint8Array {
const b = new Builder(512);
const p = b.createString(params);
const tz = b.createString(browserTz);
const dn = b.createString(displayName);
fb.VKLoginRequest.startVKLoginRequest(b);
fb.VKLoginRequest.addParams(b, p);
fb.VKLoginRequest.addBrowserTz(b, tz);
fb.VKLoginRequest.addDisplayName(b, dn);
return finish(b, fb.VKLoginRequest.endVKLoginRequest(b));
}
export function encodeGuestLogin(locale: string, browserTz: string): Uint8Array {
const b = new Builder(64);
const l = b.createString(locale);
+3
View File
@@ -142,6 +142,9 @@ export class MockGateway implements GatewayClient {
if (initData.includes('bootfail')) throw new GatewayError('unavailable');
return { ...SESSION, isGuest: false };
}
async authVK(): Promise<Session> {
return { ...SESSION, isGuest: false };
}
async authGuest(): Promise<Session> {
return { ...SESSION };
}
+3
View File
@@ -65,6 +65,9 @@ export function createTransport(baseUrl: string): GatewayClient {
async authTelegram(initData) {
return codec.decodeSession(await exec('auth.telegram', codec.encodeTelegramLogin(initData, browserOffset())));
},
async authVK(params, displayName) {
return codec.decodeSession(await exec('auth.vk', codec.encodeVKLogin(params, browserOffset(), displayName)));
},
async authGuest(locale) {
return codec.decodeSession(await exec('auth.guest', codec.encodeGuestLogin(locale ?? '', browserOffset())));
},
+31
View File
@@ -0,0 +1,31 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { insideVK, onVKPath, vkLaunchParams } from './vk';
describe('vk launch detection', () => {
afterEach(() => vi.unstubAllGlobals());
it('is not inside VK and not on the VK path without a location (node / SSR)', () => {
expect(onVKPath()).toBe(false);
expect(insideVK()).toBe(false);
expect(vkLaunchParams()).toBe('');
});
it('detects the dedicated /vk/ entry path', () => {
vi.stubGlobal('location', { pathname: '/vk/', search: '' });
expect(onVKPath()).toBe(true);
vi.stubGlobal('location', { pathname: '/app/', search: '' });
expect(onVKPath()).toBe(false);
});
it('returns the signed launch query only when a sign is present', () => {
vi.stubGlobal('location', { pathname: '/vk/', search: '?vk_user_id=1&vk_ts=2&sign=abc' });
expect(vkLaunchParams()).toBe('vk_user_id=1&vk_ts=2&sign=abc');
expect(insideVK()).toBe(true);
});
it('treats a URL carrying no sign as not a VK launch', () => {
vi.stubGlobal('location', { pathname: '/vk/', search: '?utm_source=catalog' });
expect(vkLaunchParams()).toBe('');
expect(insideVK()).toBe(false);
});
});
+66
View File
@@ -0,0 +1,66 @@
// VK Mini App SDK access via @vkontakte/vk-bridge. The bridge is imported lazily inside the
// functions that need it — not at module top level — because the SDK reads browser globals on
// import: the lazy import keeps the pure URL helpers below importable in the node test environment,
// and code-splits the bridge into a chunk loaded only on the /vk/ entry. This wraps the subset the
// app uses: launch detection, the signed launch parameters (for auth.vk) and the user's display name
// (VKWebAppGetUserInfo, since VK omits it from the signed launch params). Every helper is safe to
// call outside VK.
async function bridge() {
return (await import('@vkontakte/vk-bridge')).default;
}
/**
* onVKPath reports whether the app is served under the dedicated VK entry path (/vk/).
*/
export function onVKPath(): boolean {
if (typeof location === 'undefined') return false;
return location.pathname.startsWith('/vk/');
}
/**
* vkLaunchParams returns the raw signed VK launch query string (the vk_* parameters plus sign) from
* the page URL — the exact form the gateway verifies — or '' when the URL carries no signed launch
* (an ordinary browser tab, or the /vk/ path opened directly).
*/
export function vkLaunchParams(): string {
if (typeof location === 'undefined') return '';
const query = location.search.replace(/^\?/, '');
return new URLSearchParams(query).has('sign') ? query : '';
}
/**
* insideVK reports whether the app launched as a VK Mini App — the URL carries signed launch
* parameters (an ordinary browser tab has none).
*/
export function insideVK(): boolean {
return vkLaunchParams() !== '';
}
/**
* vkInit signals to the VK client that the Mini App has loaded (VKWebAppInit), dismissing VK's own
* loading cover. Best-effort: it resolves even if the bridge is unavailable (outside VK), so the
* caller can await it unconditionally.
*/
export async function vkInit(): Promise<void> {
try {
await (await bridge()).send('VKWebAppInit', {});
} catch {
// Outside VK there is no client to receive it; the launch continues regardless.
}
}
/**
* vkUserName fetches the launching user's display name via VKWebAppGetUserInfo, since VK omits it
* from the signed launch params. Returns '' on any failure or outside VK, so the backend falls back
* to a generated placeholder. The value is a cosmetic seed only — being unsigned, the gateway never
* trusts it for identity.
*/
export async function vkUserName(): Promise<string> {
try {
const u = await (await bridge()).send('VKWebAppGetUserInfo', {});
return [u.first_name, u.last_name].filter(Boolean).join(' ').trim();
} catch {
return '';
}
}