feat(payments): trusted platform signal on the session
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m42s

Record the execution platform (kind vk|telegram|direct + device subtype
ios|android|web) on each session, captured at creation and carried
gateway->backend as a trusted X-Platform header, so the upcoming
store-compliance gate has an unforgeable execution context.

- backend.sessions gains nullable platform_kind/platform_subtype columns
  (migration 00011, CHECK-constrained, jet regenerated); session.Platform
  captures them at mint, resolve returns them, middleware exposes platform(c).
  kind is derived from the establish endpoint, never a client field; the
  account-merge session mint inherits the caller's platform.
- gateway derives the platform (VK subtype from the signed vk_platform via
  vkauth, Telegram/direct best-effort from the client) and injects X-Platform
  on every authenticated backend call through the request context.
- ui submits a best-effort device subtype on the telegram/guest/email login
  requests (new FBS subtype field); VK is server-derived from the signed params.
- an unattributed session is untrusted (view-only); VK/TG self-heal on the next
  cold-start re-mint, direct/email on re-login.

Signal plumbing only, no user-visible change; X-Platform is inert until the
gate consumes it.
This commit is contained in:
Ilia Denisov
2026-07-08 03:31:51 +02:00
parent 07815c5a30
commit 92633f935e
39 changed files with 970 additions and 221 deletions
+18 -3
View File
@@ -130,8 +130,8 @@ dropped). Horizontal scaling is explicit future work.
solver version, so it cannot drift from the running backend. The **move journal, history
and GCG are unaffected** (they stay decoded concrete characters, §9.1).
- **gateway ↔ backend (sync)**: plain HTTP REST/JSON. The gateway injects
`X-User-ID` for authenticated requests; `backend` never re-derives identity
from the body. Because every sync call targets the one backend host, the
`X-User-ID` (and the session's trusted `X-Platform`, §3) for authenticated
requests; `backend` never re-derives identity or platform from the body. Because every sync call targets the one backend host, the
gateway's REST client widens its keep-alive pool well past the stdlib default
of 2 idle connections per host; otherwise the per-request connection churn
exhausts ephemeral ports and burns gateway CPU under load (see
@@ -199,6 +199,21 @@ arrive from a platform rather than completing a mandatory registration).
until explicitly revoked (`status``revoked`). A revoke can target one token or,
on an account merge (§4), **every** session of the retired account
(`RevokeAllForAccount`, which also evicts them from the warm cache).
- **Trusted execution platform.** Each session also records a `platform` — a `kind`
(`vk`/`telegram`/`direct`) plus a device `subtype` (`ios`/`android`/`web`) — captured
at creation, so a store-compliance gate has an unforgeable execution context
(`docs/PAYMENTS.md` §8). `kind` is derived server-side from the validated establish
path (the VK launch, the Telegram initData, or a web-native session), **never a client
field**; the `subtype` is trusted only for VK (it rides inside the signed `vk_platform`
parameter) and is client-reported best-effort for telegram/direct. VK and Telegram
re-mint (and so re-validate and re-capture) on every cold start; a direct session
captures it once. The gateway injects the resolved platform as **`X-Platform`**
(`<kind>/<subtype>`) alongside `X-User-ID`, sourced from the session and never the
request body; an absent or unrecorded platform — a session predating the feature, or
one the gateway could not attribute — is **untrusted**, treated as view-only (no
spends). Consistent with the revoke-only model, platform freshness carries no separate
TTL; a stale untrusted session recovers on its next VK/TG cold-start re-mint, or (for a
reused direct/email session) on re-login.
- **Guest** = ephemeral web session (no platform, no email). A guest is backed by
a durable `accounts` row flagged `is_guest` and carrying **no identity** — the
row is a technical necessity (the `sessions` and `game_players` foreign keys
@@ -1150,7 +1165,7 @@ link — misses the event; while an add-email confirmation is pending the client
| Public rate limiting / anti-abuse | gateway (per-IP public/email/admin classes, per-user authenticated class; a request body cap of `GATEWAY_MAX_BODY_BYTES`; rejections are metered, summarised to the backend and surfaced in the admin console with a conservative reversible auto-flag — §11). In prod a **temporary IP ban** (`GATEWAY_ABUSE_BAN_ENABLED`) blocks an IP that sustains rejections or trips a **honeypot** decoy path / **honeytoken**, refused with 429 before any work; operators lift bans from the console. Off in the shared-NAT test contour, where the client IP is not real (§11) |
| Telegram initData validation (bot-token HMAC) | the Telegram **validator**; the gateway delegates it over gRPC, so the bot token (the HMAC secret) lives only in the validator and the bot, never in the gateway. The validator also **rejects a bot principal** (the signed `is_bot` flag) before any account is provisioned |
| Session minting; email-code / guest validation | gateway (with backend) |
| Session → `user_id` resolution, `X-User-ID` injection | gateway |
| Session → `user_id` + trusted platform resolution, `X-User-ID` / `X-Platform` injection | gateway (platform sourced from the session, never the request body — §3) |
| Authorisation, ownership, state transitions | backend (`X-User-ID` is the sole identity input) |
| Manual account block (suspension) | backend: a per-request gate refuses a blocked account on every `/api/v1/user/*` route except the block-status probe with **403 `account_blocked`**; the operator blocks/unblocks from the admin console (§11) |
| User feedback gate | backend rejects a guest or a `feedback_banned` account from submitting; the **gateway** also rejects a guest's `feedback.submit` (the `Op.NonGuest` flag + `is_guest` from session resolve) with **`guest_forbidden`** before any backend call; attachments are served `nosniff` with a download disposition for non-images (§15) |
+16 -13
View File
@@ -180,20 +180,23 @@ an archive, so history/receipts/tax are independent of later catalog edits.
The gate (§4) needs a **trusted, unforgeable** platform context on the server. The client is
never the source of truth.
- The platform is a **property of the session**, re-confirmed by a fresh signature on **every
cold start** — VK launch-params `sign` / TG `initData` (validator already exists at
`platform/telegram/internal/initdata`). VK/TG wrappers resend the signature on every open,
so this is not a one-time login.
- `direct` is established by the fact of a web/native session's creation (no external
signer, and none needed — reaching vk/tg segments in a direct context still requires a
real attachment, §6).
- The platform is a **property of the session**, captured when the session is created. VK and
Telegram wrappers re-mint (and so re-validate the launch signature — VK launch-params `sign`
/ Telegram `initData`) on **every cold start**, so their platform is re-confirmed each launch;
a `direct` session captures it once, established by the fact of a web/native session's creation
(no external signer, and none needed — reaching vk/tg segments in a direct context still
requires a real attachment, §6).
- The platform carries **kind** (`vk`/`telegram`/`direct`) **plus subtype**
(`ios`/`android`/`web`) — the subtype is mandatory (VK iOS is frozen).
- The gateway resolves the session and passes `platform` to the backend (alongside the
existing `X-User-ID`).
- **Fail-closed:** an untrusted/unconfirmed platform (a VK/TG session without a valid
cold-start signature; an old session with no recorded platform) denies spends/purchases
and applying any foreign origin — view only.
(`ios`/`android`/`web`). `kind` is always trusted — the server derives it from the validated
launch, never a client field. The **subtype is trusted only for VK**: it rides inside the
signed launch parameters, which is what makes the **VK iOS freeze** enforceable; for Telegram
and direct the subtype is client-reported and best-effort, so the gate never keys off it.
- The gateway resolves the session and passes `platform` to the backend (alongside the existing
`X-User-ID`), sourced from the session — never the client request body.
- **Fail-closed:** an untrusted platform — a session with no recorded platform, one predating
this feature or one the gateway could not attribute — denies spends/purchases and applying any
foreign origin (view only). A VK/TG session recovers on its next cold-start re-mint; a reused
direct/email session on re-login.
## 9. Payment intake
+17 -14
View File
@@ -180,20 +180,23 @@ durable).
Гейту (§4) нужен **доверенный, неподделываемый** контекст платформы на сервере. Клиент —
никогда не источник правды.
- Платформа — **свойство сессии**, переподтверждается свежей подписью на **каждом холодном
старте** — VK launch-params `sign` / TG `initData` (валидатор уже есть в
`platform/telegram/internal/initdata`). Обёртки VK/TG шлют подпись при каждом открытии,
так что это не одноразовый вход.
- `direct` устанавливается самим фактом создания веб/native-сессии (внешней подписи нет и
не нужно — доступ к vk/tg-сегментам в direct-контексте всё равно требует реальной
привязки, §6).
- Платформа несёт **kind** (`vk`/`telegram`/`direct`) **плюс подтип**
(`ios`/`android`/`web`) — подтип обязателен (VK iOS заморожен).
- Гейтвей резолвит сессию и передаёт `platform` в бэкенд (рядом с существующим
`X-User-ID`).
- **Fail-closed:** недоверенная/неподтверждённая платформа (VK/TG-сессия без валидной
подписи на холодном старте; старая сессия без записанной платформы) запрещает
траты/покупки и применение любого чужого origin — только просмотр.
- Платформа — **свойство сессии**, фиксируется при создании сессии. Обёртки VK и Telegram
пересоздают сессию (и потому заново проверяют подпись запуска — VK launch-params `sign` /
Telegram `initData`) на **каждом холодном старте**, поэтому их платформа переподтверждается
при каждом запуске; `direct`-сессия фиксирует платформу один раз, самим фактом создания
веб/native-сессии (внешней подписи нет и не нужно — доступ к vk/tg-сегментам в direct-контексте
всё равно требует реальной привязки, §6).
- Платформа несёт **kind** (`vk`/`telegram`/`direct`) **плюс подтип** (`ios`/`android`/`web`).
`kind` доверенный всегда — сервер выводит его из проверенного запуска, не из клиентского поля.
**Подтип доверенный только у VK**: он лежит внутри подписанных параметров запуска, что и делает
**заморозку VK iOS** выполнимой; у Telegram и direct подтип сообщает клиент, он best-effort, и
гейт на него не опирается.
- Гейтвей резолвит сессию и передаёт `platform` в бэкенд (рядом с существующим `X-User-ID`),
беря его из сессии — не из тела клиентского запроса.
- **Fail-closed:** недоверенная платформа — сессия без записанной платформы, созданная до этой
функции или которую гейтвей не смог атрибутировать — запрещает траты/покупки и применение
любого чужого origin (только просмотр). VK/TG-сессия восстанавливается на следующем холодном
старте (пересоздание), переиспользуемая direct/email-сессия — при повторном входе.
## 9. Приём платежей