Files
scrabble-game/ui/src/lib/client.ts
T
Ilia Denisov 2c465c01d2
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m4s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m39s
feat(account): VK ID web login to link a VK identity from a browser
A browser has no signed VK Mini App launch params, so linking VK on the web uses
VK ID's raw OAuth 2.1 flow (PKCE, no @vkid/sdk): the SPA redirects to VK's hosted
login and returns with an authorization code, which the gateway exchanges
server-side (confidential, under the VK "Web" app's protected key) for the trusted
vk user id — then the existing link/merge machinery attaches or merges it.

- fbs LinkVKRequest{code, device_id, code_verifier}; codec + TS bindings.
- backend link.Service ConfirmVK/MergeVK/attachVK (KindVK, mirror Telegram),
  handleLinkVK[Merge], routes /user/link/vk[/merge], backendclient LinkVK[Merge].
- gateway internal/vkid confidential code exchange (id.vk.com/oauth2/auth);
  transcode link.vk.confirm/merge (registered only when configured) + config
  GATEWAY_VK_ID_{APP_ID,CLIENT_SECRET,REDIRECT_URL} + main wiring.
- UI lib/vkid (PKCE authorize redirect + callback), Profile "Link VK" control,
  boot callback handling; a merge re-authorizes for a fresh code (VK codes are
  single-use). Web-only (a redirect strands a Mini App webview).
- Deploy: VITE_VK_APP_ID + VITE_VK_ID_REDIRECT_URL build args + gateway env,
  ci.yaml/prod-deploy TEST_/PROD_ vars, compose/Dockerfile/.env.example/README.
- Tests: vkid exchange unit (string/number user_id, id_token fallback, errors),
  transcode link.vk, backend ConfirmVK/MergeVK inttest, codec encodeLinkVK.
- Docs: ARCHITECTURE §4, FUNCTIONAL(+ru), gateway README.
2026-07-03 17:59:33 +02:00

206 lines
9.5 KiB
TypeScript

// GatewayClient — the typed facade the screens call. Both the real Connect/
// FlatBuffers transport and the in-memory mock implement it. Domain failures (the
// gateway's result_code) and edge failures (Connect error codes) are normalised
// into a thrown GatewayError carrying a stable `code` the UI maps to an i18n
// message.
import type {
AccountRef,
BlockList,
BlockStatus,
ChatMessage,
EvalResult,
FeedbackState,
FriendCode,
GameList,
GameView,
ExportUrl,
GcgExport,
History,
HintResult,
Invitation,
InvitationSettings,
ConfirmLinkResult,
LinkResult,
MatchResult,
MoveResult,
OutgoingList,
Profile,
ProfileUpdate,
PushEvent,
Session,
StateView,
Stats,
Tile,
Variant,
WordCheckResult,
} from './model';
/** GatewayError carries a stable code (the gateway result_code, or an edge code). */
export class GatewayError extends Error {
readonly code: string;
constructor(code: string, message?: string) {
super(message ?? code);
this.name = 'GatewayError';
this.code = code;
}
}
/** A tile the player is submitting (rack/blank already resolved to a letter). */
export interface PlacedTile {
row: number;
col: number;
letter: string;
blank: boolean;
}
/** Unsubscribe handle for the live stream. */
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, language: string): Promise<void>;
authEmailLogin(email: string, code: string): Promise<Session>;
/** Confirm a one-tap email deeplink token: a login returns a session to adopt; a
* link returns a status ('confirmed' | 'merge_required'). */
confirmEmailLink(token: string): Promise<ConfirmLinkResult>;
// --- profile / lists ---
profileGet(): Promise<Profile>;
/** The caller's current manual block. Exempt from the backend's suspension gate, so a blocked
* client can still fetch it to render the blocked screen. */
blockStatus(): Promise<BlockStatus>;
gamesList(): Promise<GameList>;
// --- lobby ---
/** Start a quick game: human auto-match, or an honest-AI game against a robot when vsAi. */
lobbyEnqueue(variant: Variant, multipleWords: boolean, vsAi: boolean): Promise<MatchResult>;
lobbyPoll(): Promise<MatchResult>;
/** Leave the auto-match pool (idempotent); a cancelled quick-match must not stay queued. */
lobbyCancel(): Promise<void>;
// --- game ---
// The play loop exchanges alphabet indices, so submit/evaluate/exchange/
// check-word take the game's variant (to map letters<->indices via the cached alphabet
// table), and gameState's includeAlphabet asks the server to embed that table.
gameState(gameId: string, includeAlphabet: boolean): Promise<StateView>;
gameHistory(gameId: string): Promise<History>;
submitPlay(gameId: string, tiles: PlacedTile[], variant: Variant): Promise<MoveResult>;
pass(gameId: string): Promise<MoveResult>;
exchange(gameId: string, tiles: string[], variant: Variant): Promise<MoveResult>;
resign(gameId: string): Promise<MoveResult>;
hint(gameId: string): Promise<HintResult>;
evaluate(gameId: string, tiles: PlacedTile[], variant: Variant, signal?: AbortSignal): Promise<EvalResult>;
checkWord(gameId: string, word: string, variant: Variant): Promise<WordCheckResult>;
complaint(gameId: string, word: string, note: string): Promise<void>;
/** Hide a finished game from the caller's own lobby list; per-account, irreversible. */
hideGame(gameId: string): Promise<void>;
// --- dictionary (local move preview) ---
/** Fetch the raw serialized dictionary blob for a (variant, version) pair. Session-gated;
* lets the client validate and score a move locally instead of a network round trip.
* opts.signal aborts a stalled download; opts.reload bypasses the browser HTTP cache (the
* debug reset, for testing a cold load). */
fetchDict(variant: Variant, version: string, opts?: { signal?: AbortSignal; reload?: boolean }): Promise<ArrayBuffer>;
/** Post the client's local move-preview adoption telemetry — a small batch of counter deltas,
* session-gated and fire-and-forget (never on the gameplay path). */
reportLocalEval(counts: Record<string, number>): Promise<void>;
// --- draft ---
/** The player's server-persisted client-side composition (rack order + board tiles), so a
* reload or a second device resumes the same arrangement. The JSON is opaque to the
* gateway; the client owns the {rack_order, board_tiles} shape. */
draftGet(gameId: string): Promise<string>;
draftSave(gameId: string, json: string): Promise<void>;
// --- chat ---
chatPost(gameId: string, body: string): Promise<ChatMessage>;
chatList(gameId: string): Promise<ChatMessage[]>;
nudge(gameId: string): Promise<ChatMessage>;
/** Acknowledge the caller has read the game's chat (sent when they open the move history
* or chat), so the backend clears their unread bits and records the read latency. */
markChatRead(gameId: string): Promise<void>;
// --- feedback ---
/** feedbackSubmit sends a feedback message with an optional single attachment. */
feedbackSubmit(body: string, attachment: Uint8Array | null, attachmentName: string, channel: string): Promise<void>;
/** feedbackGet returns the feedback screen state and marks any pending reply delivered. */
feedbackGet(): Promise<FeedbackState>;
/** feedbackUnread reports whether an operator reply awaits delivery (the badge). */
feedbackUnread(): Promise<boolean>;
// --- friends ---
friendsList(): Promise<AccountRef[]>;
friendsIncoming(): Promise<AccountRef[]>;
/** Addressees the caller has already requested (pending or declined; cannot re-request),
* plus the per-game disguised-robot requests that keep the in-game 🤝 disabled by seat. */
friendsOutgoing(): Promise<OutgoingList>;
/** Send a friend request. A non-empty gameId marks an in-game request, so a disguised-robot
* opponent is recorded as a per-game request rather than against the shared robot account. */
friendRequest(accountId: string, gameId?: string): Promise<void>;
friendRespond(requesterId: string, accept: boolean): Promise<void>;
friendCancel(accountId: string): Promise<void>;
unfriend(accountId: string): Promise<void>;
friendCodeIssue(): Promise<FriendCode>;
friendCodeRedeem(code: string): Promise<AccountRef>;
// --- blocks ---
blocksList(): Promise<BlockList>;
block(accountId: string, gameId?: string): Promise<void>;
unblock(accountId: string): Promise<void>;
// --- invitations ---
invitationsList(): Promise<Invitation[]>;
invitationCreate(inviteeIds: string[], settings: InvitationSettings): Promise<Invitation>;
invitationAccept(invitationId: string): Promise<Invitation>;
invitationDecline(invitationId: string): Promise<Invitation>;
invitationCancel(invitationId: string): Promise<void>;
// --- profile / stats / history ---
profileUpdate(p: ProfileUpdate): Promise<Profile>;
statsGet(): Promise<Stats>;
exportGcg(gameId: string): Promise<GcgExport>;
/** Mints a signed download URL for a finished game's artifact. dateLocale and the
* localized non-play labels (pass/exchange/resign/timeout, in that order) ride the
* URL so the server-rendered image matches the player's presentation. */
exportUrl(gameId: string, kind: 'png' | 'gcg', dateLocale: string, actionLabels: string[], timeZone: string): Promise<ExportUrl>;
// --- account linking & merge ---
linkEmailRequest(email: string): Promise<void>;
linkEmailConfirm(email: string, code: string): Promise<LinkResult>;
linkEmailMerge(email: string, code: string): Promise<LinkResult>;
linkTelegram(data: string): Promise<LinkResult>;
linkTelegramMerge(data: string): Promise<LinkResult>;
/** Link a VK identity from the web: the args are the PKCE outputs of the VK ID
* authorization callback, exchanged for the trusted vk id on the gateway. */
linkVK(code: string, deviceId: string, codeVerifier: string): Promise<LinkResult>;
linkVKMerge(code: string, deviceId: string, codeVerifier: string): Promise<LinkResult>;
/** Detach a platform identity (kind 'telegram' | 'vk') from the account; email is never
* unlinked. Returns the refreshed link result (status 'unlinked'). */
linkUnlink(kind: string): Promise<LinkResult>;
/** Change the account's confirmed email: mail a code to the new address, then confirm
* to atomically switch (status 'changed'). A new address owned by another account is
* refused without disclosure. */
changeEmailRequest(email: string): Promise<void>;
changeEmailConfirm(email: string, code: string): Promise<LinkResult>;
/** Start account deletion; the backend mails a code (method 'email') or asks for the
* typed phrase (method 'phrase'). */
deleteRequest(): Promise<{ method: 'email' | 'phrase' }>;
/** Confirm and perform account deletion with the mailed code or the typed phrase. */
deleteConfirm(code: string, phrase: string): Promise<void>;
// --- live stream ---
subscribe(onEvent: (e: PushEvent) => void, onError?: (err: unknown) => void): Unsubscribe;
/** Set or clear the bearer token used for authenticated calls and the stream. */
setToken(token: string | null): void;
}
export type { GameView, Tile };