Merge pull request 'feat(offer): live catalog price list in the public offer (render sidecar)' (#244) from feature/offer-pricing-live into development
CI / changes (push) Successful in 2s
CI / unit (push) Successful in 12s
CI / integration (push) Successful in 19s
CI / ui (push) Successful in 1m11s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m48s

This commit was merged in pull request #244.
This commit is contained in:
2026-07-11 09:51:48 +00:00
32 changed files with 720 additions and 95 deletions
+12 -7
View File
@@ -510,15 +510,20 @@ jobs:
- name: Probe the /offer/ public offer page is served - name: Probe the /offer/ public offer page is served
run: | run: |
set -u set -u
# /offer/ is a static page baked into the landing image (rendered from # /offer/ is rendered by the render sidecar: it splices the live catalog price list
# ui/legal/offer_ru.md). If the landing Caddyfile stops routing it, the request # (fetched from the backend's internal endpoint) into the committed ui/legal/offer_ru.md.
# silently falls through to the landing shell (also 200) — so assert offer-specific # If the @offer caddy route is missing, the request falls to the landing shell (also 200),
# content, never just the status. # and if the backend fetch fails the sidecar returns 502 — so assert offer-specific content
# (the seller INN, §11) AND that the pricing marker was substituted (proves the fetch +
# splice ran), never just the status. Data-independent: an empty catalog still substitutes
# the marker with nothing, so "pricing_template" must be absent either way.
out="$(docker run --rm --network edge alpine:3.20 wget -q -O - http://scrabble/offer/ 2>&1 || true)" out="$(docker run --rm --network edge alpine:3.20 wget -q -O - http://scrabble/offer/ 2>&1 || true)"
if echo "$out" | grep -q "290210610742"; then if echo "$out" | grep -q "290210610742" && ! echo "$out" | grep -q "pricing_template"; then
echo "ok: /offer/ serves the public offer page" echo "ok: /offer/ serves the rendered offer with the price list spliced in"
else else
echo "FAIL: /offer/ did not serve the offer page (fell through to the landing shell?)" echo "FAIL: /offer/ did not serve the rendered offer (route fell through, or the price splice failed)"
docker logs --tail 50 scrabble-renderer || true
docker logs --tail 50 scrabble-backend || true
docker logs --tail 50 scrabble-landing || true docker logs --tail 50 scrabble-landing || true
exit 1 exit 1
fi fi
+7
View File
@@ -283,6 +283,13 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
} }
logger.Info("payments domain ready") logger.Info("payments domain ready")
// Warm the public-offer price list cache so /offer/ serves the current catalog from the first
// request; it is reprojected lazily thereafter on any catalog edit. Non-fatal — a transient
// failure here only defers the projection to the first read.
if _, err := paymentsSvc.OfferPricing(ctx); err != nil {
logger.Warn("offer pricing warm failed; will project on first request", zap.Error(err))
}
// Wire the payments surface into the domains that consume it: the online-game hint wallet // Wire the payments surface into the domains that consume it: the online-game hint wallet
// and the account-merge wallet fold. Done after the reachability check so a broken payments // and the account-merge wallet fold. Done after the reachability check so a broken payments
// schema fails boot before anything depends on it. // schema fails boot before anything depends on it.
@@ -4,6 +4,7 @@ package inttest
import ( import (
"context" "context"
"strings"
"testing" "testing"
"github.com/google/uuid" "github.com/google/uuid"
@@ -111,3 +112,44 @@ func TestPaymentsCatalogExcludesDeactivated(t *testing.T) {
t.Error("deactivated product must not appear in the storefront") t.Error("deactivated product must not appear in the storefront")
} }
} }
// TestOfferPricingReflectsCatalogEdits verifies the public-offer price list (§4.4) is projected from
// the live catalog and its cache is invalidated on a catalog mutation: a newly created pack appears
// with its per-rail prices, and archiving it through the service drops it from the next read.
func TestOfferPricingReflectsCatalogEdits(t *testing.T) {
svc := newPaymentsService()
ctx := context.Background()
title := "OfferTest " + uuid.NewString()
id, err := svc.CreateProduct(ctx, payments.ProductInput{
Title: title,
Atoms: []payments.AtomLine{{Atom: "chips", Quantity: 50}},
Prices: []payments.PriceLine{
{Method: "direct", Currency: payments.CurrencyRUB, Amount: 20000},
{Method: "vk", Currency: payments.CurrencyVote, Amount: 30},
{Method: "telegram", Currency: payments.CurrencyStar, Amount: 100},
},
}, true)
if err != nil {
t.Fatalf("create pack: %v", err)
}
md, err := svc.OfferPricing(ctx)
if err != nil {
t.Fatalf("offer pricing: %v", err)
}
if row := "| " + title + " | 200.00 | 30 | 100 |"; !strings.Contains(md, row) {
t.Fatalf("offer pricing missing the new pack row %q\n%s", row, md)
}
// Archiving through the service marks the cache stale; the next read must reproject without it.
if err := svc.SetProductActive(ctx, id, false); err != nil {
t.Fatalf("archive: %v", err)
}
md, err = svc.OfferPricing(ctx)
if err != nil {
t.Fatalf("offer pricing after archive: %v", err)
}
if strings.Contains(md, title) {
t.Errorf("archived pack must drop from the offer pricing:\n%s", md)
}
}
+20 -4
View File
@@ -153,7 +153,11 @@ func (s *Service) CreateProduct(ctx context.Context, in ProductInput, active boo
if err := validateProduct(in, active); err != nil { if err := validateProduct(in, active); err != nil {
return uuid.Nil, err return uuid.Nil, err
} }
return s.store.createProduct(ctx, in, active, s.clock()) id, err := s.store.createProduct(ctx, in, active, s.clock())
if err == nil {
s.markOfferStale()
}
return id, err
} }
// UpdateProduct validates and replaces a product's title, atoms and prices. An active product must // UpdateProduct validates and replaces a product's title, atoms and prices. An active product must
@@ -166,7 +170,11 @@ func (s *Service) UpdateProduct(ctx context.Context, id uuid.UUID, in ProductInp
if err := validateProduct(in, active); err != nil { if err := validateProduct(in, active); err != nil {
return err return err
} }
return s.store.updateProduct(ctx, id, in, s.clock()) if err := s.store.updateProduct(ctx, id, in, s.clock()); err != nil {
return err
}
s.markOfferStale()
return nil
} }
// SetProductActive archives (active=false) or unarchives a product. Unarchiving revalidates the // SetProductActive archives (active=false) or unarchives a product. Unarchiving revalidates the
@@ -181,11 +189,19 @@ func (s *Service) SetProductActive(ctx context.Context, id uuid.UUID, active boo
return err return err
} }
} }
return s.store.setProductActive(ctx, id, active, s.clock()) if err := s.store.setProductActive(ctx, id, active, s.clock()); err != nil {
return err
}
s.markOfferStale()
return nil
} }
// DeleteProduct hard-deletes a product only when it has never been transacted (no order or ledger // DeleteProduct hard-deletes a product only when it has never been transacted (no order or ledger
// row references it); otherwise it returns ErrProductTransacted and the caller archives instead. // row references it); otherwise it returns ErrProductTransacted and the caller archives instead.
func (s *Service) DeleteProduct(ctx context.Context, id uuid.UUID) error { func (s *Service) DeleteProduct(ctx context.Context, id uuid.UUID) error {
return s.store.deleteProduct(ctx, id) if err := s.store.deleteProduct(ctx, id); err != nil {
return err
}
s.markOfferStale()
return nil
} }
+212
View File
@@ -0,0 +1,212 @@
package payments
import (
"cmp"
"context"
"fmt"
"math"
"slices"
"strings"
)
// pricingMarker is the token the owner-edited offer markdown (ui/legal/offer_ru.md, §4.4) carries
// where the price list belongs. The render sidecar replaces it with the markdown [Service.OfferPricing]
// returns before rendering the /offer/ page; the backend only produces the tables, never the marker.
const pricingMarker = "<#pricing_template#>"
// OfferPricing returns the public-offer price list (§4.4) as two markdown tables projected from the
// active catalog: first the chip packs (funding chips with money, priced per rail — roubles / VK
// votes / Telegram Stars), then the chip-priced values (what a player exchanges chips for). The
// result is cached in memory and reprojected only after a catalog mutation (see [Service.markOfferStale]),
// so a steady-state read issues no query — only the first read after an edit reprojects. The render
// sidecar fetches it and splices it into the offer markdown at the pricing marker.
func (s *Service) OfferPricing(ctx context.Context) (string, error) {
s.offerMu.Lock()
defer s.offerMu.Unlock()
if s.offerFresh {
return s.offerMD, nil
}
md, err := s.buildOfferPricing(ctx)
if err != nil {
return "", err
}
s.offerMD = md
s.offerFresh = true
return md, nil
}
// markOfferStale marks the cached offer price list for reprojection on the next [Service.OfferPricing]
// read. Every catalog mutation calls it; it takes no I/O, so it never fails the mutation that triggers it.
func (s *Service) markOfferStale() {
s.offerMu.Lock()
s.offerFresh = false
s.offerMu.Unlock()
}
// buildOfferPricing loads the active catalog and projects it into the offer tables.
func (s *Service) buildOfferPricing(ctx context.Context) (string, error) {
entries, err := s.store.loadCatalog(ctx)
if err != nil {
return "", err
}
return projectOfferPricing(entries), nil
}
// projectOfferPricing renders the active catalog into the two offer tables. A chip pack (it carries
// the chips atom) lists its per-rail money price; a value (no chips atom) lists its uniform chip
// price. Packs are ordered by ascending rouble price; values are grouped by what they grant (hints
// only, then no-ads only, then no-ads + hints, then tournament — see [offerValueGroup]) and, within
// each group, ordered by ascending chip price. Price columns are right-aligned. An empty section is
// omitted. Amounts are rendered through [Money] so no floating point ever reaches the page (roubles
// show kopecks as "200.00", whole-unit rails as integers); a missing rail price shows an em dash.
func projectOfferPricing(entries []catalogEntry) string {
var packs, values []catalogEntry
for _, e := range entries {
if isPackEntry(e) {
packs = append(packs, e)
} else {
values = append(values, e)
}
}
// Packs: ascending by the rouble price (the offer's base currency); a pack with no rouble price
// sorts last. Values: by group, then ascending chip price. Stable, so the catalog order breaks ties.
slices.SortStableFunc(packs, func(a, b catalogEntry) int {
return cmp.Compare(offerSortAmount(a, string(SourceDirect), CurrencyRUB), offerSortAmount(b, string(SourceDirect), CurrencyRUB))
})
slices.SortStableFunc(values, func(a, b catalogEntry) int {
if d := cmp.Compare(offerValueGroup(a), offerValueGroup(b)); d != 0 {
return d
}
return cmp.Compare(offerSortAmount(a, "", CurrencyChip), offerSortAmount(b, "", CurrencyChip))
})
var b strings.Builder
if len(packs) > 0 {
b.WriteString("Приобретение внутриигровой валюты «Фишка»:\n\n")
b.WriteString("| Наименование | Рубли | Голоса в VK | Stars в Telegram |\n")
b.WriteString("| --- | ---: | ---: | ---: |\n")
for _, e := range packs {
fmt.Fprintf(&b, "| %s | %s | %s | %s |\n",
offerCell(e.title),
offerPrice(e, string(SourceDirect), CurrencyRUB),
offerPrice(e, string(SourceVK), CurrencyVote),
offerPrice(e, string(SourceTelegram), CurrencyStar),
)
}
}
if len(values) > 0 {
if len(packs) > 0 {
b.WriteString("\n")
}
b.WriteString("Использование внутриигровой валюты «Фишка»:\n\n")
b.WriteString("| Наименование | «Фишки» |\n")
b.WriteString("| --- | ---: |\n")
for _, e := range values {
fmt.Fprintf(&b, "| %s | %s |\n", offerCell(e.title), offerPrice(e, "", CurrencyChip))
}
}
return strings.TrimRight(b.String(), "\n")
}
// offerValueGroup ranks a chip-priced value into the offer's usage groups, in listing order: hints
// only (0), no-ads only (1), no-ads + hints (2), then anything carrying the tournament atom (3).
// Tournament products are not sellable yet (validateProduct forbids an active one), so group 3 is
// empty today; the rank reserves their place for when the tournament economy lands. A value with no
// recognised benefit atom sorts after the known groups (defensive — the catalog shape forbids it).
func offerValueGroup(e catalogEntry) int {
hasHints, hasNoAds, hasTournament := false, false, false
for _, a := range e.atoms {
switch a.atomType {
case "hints":
hasHints = true
case "noads_days":
hasNoAds = true
case "tournament":
hasTournament = true
}
}
switch {
case hasTournament:
return 3
case hasHints && hasNoAds:
return 2
case hasNoAds:
return 1
case hasHints:
return 0
default:
return 4
}
}
// offerSortAmount returns the entry's price in the given method and currency for ordering, or
// math.MaxInt64 when it carries no such price, so a misconfigured row sorts last rather than leading.
func offerSortAmount(e catalogEntry, method string, cur Currency) int64 {
if amt, ok := offerAmount(e, method, cur); ok {
return amt
}
return math.MaxInt64
}
// isPackEntry reports whether the catalog entry is a chip pack — it carries the chips atom (funds
// chips with money) rather than being a chip-priced value.
func isPackEntry(e catalogEntry) bool {
for _, a := range e.atoms {
if a.atomType == atomChips {
return true
}
}
return false
}
// offerPrice formats the entry's price for the given payment method and currency as a major-unit
// string, or an em dash when the entry carries no such price.
func offerPrice(e catalogEntry, method string, cur Currency) string {
amt, ok := offerAmount(e, method, cur)
if !ok {
return "—"
}
m, err := MoneyFromMinor(amt, cur)
if err != nil {
return "—"
}
return m.Major()
}
// offerAmount returns the raw minor-unit amount of the entry's price for the payment method and
// currency, and whether such a price exists.
func offerAmount(e catalogEntry, method string, cur Currency) (int64, bool) {
for _, pr := range e.prices {
if pr.method == method && pr.currency == cur {
return pr.amount, true
}
}
return 0, false
}
// offerCellReplacer neutralises every metacharacter of an admin-entered title so it renders as
// literal text in the public offer. The title is operator input (the /_gm catalog editor) that flows
// into a markdown table cell and then through marked into the /offer/ HTML, which is deliberately not
// sanitised — so escaping here is the trust boundary. It covers HTML (no tag or entity reaches the
// page), the markdown table pipe and the row newline, and the link brackets (a title must never
// become a "javascript:" link). marked passes the entities through unchanged, so the reader sees the
// exact title. NewReplacer scans once and never re-scans its own output, so "&" → "&amp;" does not
// double-escape the entities the other rules emit.
var offerCellReplacer = strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
`"`, "&quot;",
"'", "&#39;",
"|", `\|`,
"[", `\[`,
"]", `\]`,
"\n", " ",
)
// offerCell escapes an admin-entered title for safe, literal rendering in a markdown table cell of
// the public offer (see [offerCellReplacer]).
func offerCell(s string) string {
return offerCellReplacer.Replace(s)
}
+137
View File
@@ -0,0 +1,137 @@
package payments
import (
"strings"
"testing"
"github.com/google/uuid"
)
// TestProjectOfferPricing checks the happy path: a chip pack priced on every rail and a chip-priced
// value render into the two tables, pack table first, money formatted through Money.
func TestProjectOfferPricing(t *testing.T) {
entries := []catalogEntry{
{
id: uuid.New(),
title: "50 «Фишек»",
atoms: []atomQty{{atomType: atomChips, quantity: 50}},
prices: []priceRow{
{method: string(SourceDirect), currency: CurrencyRUB, amount: 20000},
{method: string(SourceVK), currency: CurrencyVote, amount: 30},
{method: string(SourceTelegram), currency: CurrencyStar, amount: 100},
},
},
{
id: uuid.New(),
title: "200 подсказок",
atoms: []atomQty{{atomType: "hints", quantity: 200}},
prices: []priceRow{{method: "", currency: CurrencyChip, amount: 50}},
},
}
md := projectOfferPricing(entries)
for _, want := range []string{
"| Наименование | Рубли | Голоса в VK | Stars в Telegram |",
"| --- | ---: | ---: | ---: |", // price columns right-aligned
"| 50 «Фишек» | 200.00 | 30 | 100 |",
"| Наименование | «Фишки» |",
"| --- | ---: |",
"| 200 подсказок | 50 |",
} {
if !strings.Contains(md, want) {
t.Errorf("projection missing %q\n---\n%s", want, md)
}
}
if strings.Index(md, "Приобретение") > strings.Index(md, "Использование") {
t.Errorf("the pack table must precede the values table:\n%s", md)
}
}
// TestProjectOfferPricingOrdering checks packs sort by ascending rouble price, and values sort by
// group (hints only → no-ads only → no-ads + hints) then ascending chip price within a group.
func TestProjectOfferPricingOrdering(t *testing.T) {
pack := func(title string, rub int64) catalogEntry {
return catalogEntry{
id: uuid.New(),
title: title,
atoms: []atomQty{{atomType: atomChips, quantity: 1}},
prices: []priceRow{{method: string(SourceDirect), currency: CurrencyRUB, amount: rub}},
}
}
value := func(title string, chips int64, atoms ...string) catalogEntry {
e := catalogEntry{id: uuid.New(), title: title, prices: []priceRow{{method: "", currency: CurrencyChip, amount: chips}}}
for _, a := range atoms {
e.atoms = append(e.atoms, atomQty{atomType: a, quantity: 1})
}
return e
}
// Deliberately out of order on input.
entries := []catalogEntry{
pack("packDear", 30000),
pack("packCheap", 10000),
value("bundle", 500, "hints", "noads_days"),
value("adsOnly", 150, "noads_days"),
value("hintsBig", 200, "hints"),
value("hintsSmall", 50, "hints"),
}
md := projectOfferPricing(entries)
order := []string{"packCheap", "packDear", "hintsSmall", "hintsBig", "adsOnly", "bundle"}
last := -1
for _, title := range order {
i := strings.Index(md, "| "+title+" |")
if i < 0 {
t.Fatalf("row %q missing:\n%s", title, md)
}
if i < last {
t.Errorf("row %q out of order (want sequence %v):\n%s", title, order, md)
}
last = i
}
}
// TestProjectOfferPricingMissingRailAndEscaping checks a pack missing a rail shows an em dash and a
// title carrying a pipe is escaped so the table layout survives.
func TestProjectOfferPricingMissingRailAndEscaping(t *testing.T) {
entries := []catalogEntry{{
id: uuid.New(),
title: "Bonus | pack",
atoms: []atomQty{{atomType: atomChips, quantity: 10}},
// A roubles price only — no VK, no Telegram.
prices: []priceRow{{method: string(SourceDirect), currency: CurrencyRUB, amount: 9900}},
}}
md := projectOfferPricing(entries)
if want := `| Bonus \| pack | 99.00 | — | — |`; !strings.Contains(md, want) {
t.Errorf("want row %q in:\n%s", want, md)
}
}
// TestProjectOfferPricingEscapesHTMLAndLinks checks an admin title carrying HTML or a markdown link
// is neutralised so it cannot inject markup into the public offer: the tag becomes entities and the
// link brackets are escaped (so no "javascript:" anchor forms). The raw metacharacters must not
// survive into the projected markdown.
func TestProjectOfferPricingEscapesHTMLAndLinks(t *testing.T) {
entries := []catalogEntry{{
id: uuid.New(),
title: `<script>alert(1)</script> [x](javascript:alert(2)) & "q"`,
atoms: []atomQty{{atomType: "hints", quantity: 1}},
prices: []priceRow{{method: "", currency: CurrencyChip, amount: 5}},
}}
md := projectOfferPricing(entries)
for _, bad := range []string{"<script>", "</script>", "[x]", `& "q"`} {
if strings.Contains(md, bad) {
t.Errorf("unescaped %q survived into the projection:\n%s", bad, md)
}
}
for _, want := range []string{"&lt;script&gt;", `\[x\]`, "&amp;", "&quot;q&quot;"} {
if !strings.Contains(md, want) {
t.Errorf("want escaped %q in:\n%s", want, md)
}
}
}
// TestProjectOfferPricingEmpty checks an empty catalog projects to the empty string (no stray table
// headers), so the offer's pricing marker is replaced with nothing.
func TestProjectOfferPricingEmpty(t *testing.T) {
if got := projectOfferPricing(nil); got != "" {
t.Errorf("empty catalog must project to empty string, got %q", got)
}
}
+8
View File
@@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"sync"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
@@ -19,6 +20,13 @@ import (
type Service struct { type Service struct {
store *Store store *Store
clock func() time.Time clock func() time.Time
// offerMu guards the cached public-offer price list (§4.4). offerMD holds the projected
// markdown tables and offerFresh whether they are current; a catalog mutation clears offerFresh
// (markOfferStale) and the next OfferPricing read reprojects, so a served render issues no query.
offerMu sync.Mutex
offerMD string
offerFresh bool
} }
// NewService constructs a Service over store with a wall-clock time source. // NewService constructs a Service over store with a wall-clock time source.
+3
View File
@@ -74,6 +74,9 @@ func (s *Server) registerRoutes() {
u.POST("/wallet/buy", s.handleWalletBuy) u.POST("/wallet/buy", s.handleWalletBuy)
// A rewarded-video credit (VK ads): client-attested + a config daily cap. // A rewarded-video credit (VK ads): client-attested + a config daily cap.
u.POST("/wallet/reward", s.handleWalletReward) u.POST("/wallet/reward", s.handleWalletReward)
// The public-offer price list (§4.4) as markdown, for the render sidecar that serves the
// /offer/ page. Internal (off the edge allow-list); called by the renderer, not the gateway.
s.internal.GET("/offer/pricing", s.handleOfferPricing)
} }
if s.payments != nil { if s.payments != nil {
// The money order endpoint dispatches by rail (direct → Robokassa, vk → VK); an // The money order endpoint dispatches by rail (direct → Robokassa, vk → VK); an
@@ -112,6 +112,22 @@ func (s *Server) handleWalletCatalog(c *gin.Context) {
c.JSON(http.StatusOK, catalogDTOFrom(view)) c.JSON(http.StatusOK, catalogDTOFrom(view))
} }
// handleOfferPricing serves the public-offer price list (§4.4) as markdown — the two catalog tables
// projected from the active products. The render sidecar fetches it and splices it into the offer
// markdown before rendering the /offer/ page. Internal, non-public: the /api/v1/internal group is
// off the edge allow-list, and the value is served from the payments cache (no per-request query in
// the steady state). Called by the renderer, not the gateway.
func (s *Server) handleOfferPricing(c *gin.Context) {
md, err := s.payments.OfferPricing(c.Request.Context())
if err != nil {
s.log.Error("offer pricing projection failed", zap.Error(err))
c.String(http.StatusInternalServerError, "offer pricing unavailable")
return
}
c.Header("Content-Type", "text/markdown; charset=utf-8")
c.String(http.StatusOK, md)
}
// handleWallet returns the caller's wallet — the segments and benefits visible in the current // handleWallet returns the caller's wallet — the segments and benefits visible in the current
// trusted execution context, plus the rewarded-video payout available here (0 outside VK or when // trusted execution context, plus the rewarded-video payout available here (0 outside VK or when
// unconfigured), which gates the client's "watch for chips" button. // unconfigured), which gates the client's "watch for chips" button.
+9
View File
@@ -107,6 +107,15 @@
} }
} }
# The public offer page is rendered by the render sidecar: it splices the live catalog price
# list (backend, internal) into the committed ui/legal/offer_ru.md and returns the HTML. Only
# /offer/ is exposed here — the sidecar's /render stays off this allow-list, internal-only. Kept
# disjoint from the landing/app paths so the catch-all below never shadows it.
@offer path /offer /offer/*
handle @offer {
reverse_proxy renderer:8090
}
# Everything else — the public landing at / and any stray path — is static. # Everything else — the public landing at / and any stray path — is static.
handle { handle {
reverse_proxy landing:80 reverse_proxy landing:80
+3
View File
@@ -84,6 +84,9 @@ services:
logging: *default-logging logging: *default-logging
environment: environment:
RENDERER_PORT: "8090" RENDERER_PORT: "8090"
# The offer page (GET /offer/) fetches the live catalog price list from the backend's internal
# endpoint and splices it into the committed offer markdown. Backend down ⇒ /offer/ returns 502.
RENDERER_BACKEND_URL: http://backend:8080
healthcheck: healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8090/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8090/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 10s interval: 10s
+3 -12
View File
@@ -18,18 +18,9 @@
@shell not path /assets/* @shell not path /assets/*
header @shell Cache-Control "no-cache" header @shell Cache-Control "no-cache"
# The static public offer page, rendered from ui/legal/offer_ru.md at build # The public offer page (/offer/) is no longer served here: the contour caddy routes it to the
# time into dist/offer/index.html (vite emit-offer plugin). Served with its own # render sidecar, which splices the live catalog price list into ui/legal/offer_ru.md. This
# index so /offer/ resolves to /srv/offer/index.html rather than falling to the # container never sees /offer/, so it carries no offer assets (the vite emit-offer plugin is gone).
# landing shell below (whose index is landing.html). A bare /offer redirects in.
handle /offer {
redir * /offer/ permanent
}
handle /offer/* {
file_server {
index index.html
}
}
# An unknown path falls back to the landing shell (the gateway's old "/" # An unknown path falls back to the landing shell (the gateway's old "/"
# behaviour); "/" itself resolves through the index below. # behaviour); "/" itself resolves through the index below.
+20 -3
View File
@@ -909,6 +909,22 @@ finished journal on each GET. The only degraded platform is a legacy Telegram cl
predating `downloadFile`, where the GCG falls back to the old clipboard copy and the predating `downloadFile`, where the GCG falls back to the old clipboard copy and the
image option is not offered. image option is not offered.
The same sidecar also serves the **public offer page** at `/offer/` — the one edge-exposed
route on it (caddy routes `/offer/` here; its `/render` stays internal). It reuses the shared
`ui/src/lib/offer.ts` renderer (again one renderer, no drift) over the owner-edited
`ui/legal/offer_ru.md`, baked into the image, splicing in the **live price list** (§4.4): it
fetches the two catalog tables as markdown from the backend's internal
`/api/v1/internal/offer/pricing` at the `<#pricing_template#>` marker, then renders the page. The
backend projects the tables from the active catalog through `payments.Money` (no float reaches the
page) and caches them in memory — built at boot, reprojected on any catalog edit — so a served
render issues no query in the steady state and the page always reflects the current catalog without
a redeploy. A backend outage degrades `/offer/` to a 502 rather than a stale price list. Packs are
ordered by ascending rouble price; values are grouped by what they grant — hints only, then no-ads
only, then no-ads + hints, then (reserved, empty today) products carrying the **tournament** atom,
which becomes a fourth group once the tournament economy makes them sellable — and ordered by
ascending chip price within each group. Product titles are admin input, so the projection escapes
them (HTML entities + markdown metacharacters) before they reach the un-sanitised renderer.
The alphabet-on-the-wire transport does **not** touch this invariant: the live edge The alphabet-on-the-wire transport does **not** touch this invariant: the live edge
exchanges alphabet indices, but the persisted journal (and everything derived from it — exchanges alphabet indices, but the persisted journal (and everything derived from it —
replay, history, GCG) keeps the decoded concrete letters described above, so an archived replay, history, GCG) keeps the decoded concrete letters described above, so an archived
@@ -1349,9 +1365,10 @@ in-process (the distroless image has no `/etc/mime.types`). Hash-named `/assets/
in-compose **caddy** is the contour's edge: it owns a single `/_gm` Basic-Auth and in-compose **caddy** is the contour's edge: it owns a single `/_gm` Basic-Auth and
routes `/_gm/grafana/*` to **Grafana** (anonymous-admin, so the one shared login gates routes `/_gm/grafana/*` to **Grafana** (anonymous-admin, so the one shared login gates
it with no per-user Grafana accounts) and the rest of `/_gm/*` to the backend-rendered it with no per-user Grafana accounts) and the rest of `/_gm/*` to the backend-rendered
**admin console**; `/app/`, `/telegram/`, `/vk/` and the Connect path go to the gateway; the **admin console**; `/app/`, `/telegram/`, `/vk/` and the Connect path go to the gateway; `/offer/`
catch-all — notably the landing at `/`, plus the static public offer at `/offer/` (the public offer, rendered by the `renderer` sidecar with the live catalog price list spliced in)
(rendered from `ui/legal/offer_ru.md` at build time) — goes to the landing container. The goes to the render sidecar; and the catch-all — notably the landing at `/` — goes to the landing
container. The
**Telegram validator** runs as a separate container with **no public ingress**, **Telegram validator** runs as a separate container with **no public ingress**,
answering only internal gRPC (HMAC, no Telegram egress). The **Telegram bot** holds answering only internal gRPC (HMAC, no Telegram egress). The **Telegram bot** holds
no inbound port either: it dials the gateway's **bot-link** (mTLS) and egresses to no inbound port either: it dials the gateway's **bot-link** (mTLS) and egresses to
+5 -1
View File
@@ -30,7 +30,11 @@ render with arbitrary languages, so detection would make the indexed content
nondeterministic); a saved 🌐 choice still wins. The page carries a static Russian SEO head nondeterministic); a saved 🌐 choice still wins. The page carries a static Russian SEO head
(title/description, the Open Graph card Telegram/VK link previews use, a canonical link (title/description, the Open Graph card Telegram/VK link previews use, a canonical link
pinned to the production origin, JSON-LD, the favicon set and `robots.txt`), while the SPA pinned to the production origin, JSON-LD, the favicon set and `robots.txt`), while the SPA
shell is `noindex` — the landing is the only indexable page. shell is `noindex` — the landing is the only indexable page. The footer links to the **public
offer** (`/offer/`) and, beside it, **feedback** — the Telegram bot the offer names as the seller's
contact. The offer page (the legal document a purchase accepts) is rendered on demand from
`ui/legal/offer_ru.md` with its **price list** (§4.4) generated from the live product catalog, so
the published prices always match what is currently on sale — no redeploy to update them.
On the plain web the client is an **installable PWA**: a logged-out player sees an install On the plain web the client is an **installable PWA**: a logged-out player sees an install
call-to-action under the login form (and at the bottom of Settings) that installs the app to the call-to-action under the login form (and at the bottom of Settings) that installs the app to the
+6 -1
View File
@@ -32,7 +32,12 @@ top-1 подсказку, безлимитную проверку слова с
главнее. Страница несёт статическую русскую SEO-«шапку» (title/description, карточка главнее. Страница несёт статическую русскую SEO-«шапку» (title/description, карточка
Open Graph, которую используют превью ссылок в Telegram/VK, канонический адрес Open Graph, которую используют превью ссылок в Telegram/VK, канонический адрес
продакшен-домена, JSON-LD, набор favicon и `robots.txt`), а оболочка SPA помечена продакшен-домена, JSON-LD, набор favicon и `robots.txt`), а оболочка SPA помечена
`noindex` — индексируется только посадочная страница. `noindex` — индексируется только посадочная страница. В подвале — ссылки на **публичную
оферту** (`/offer/`) и рядом на **обратную связь** (тот самый Telegram-бот, который оферта
указывает как контакт Продавца). Страница оферты (юридический документ, который принимается при
покупке) рендерится по запросу из `ui/legal/offer_ru.md`, а её **перечень стоимости** (§4.4)
формируется из живого каталога товаров, поэтому опубликованные цены всегда совпадают с тем, что
сейчас в продаже — без передеплоя.
В обычном вебе клиент — **устанавливаемое PWA**: незалогиненный игрок видит призыв к установке В обычном вебе клиент — **устанавливаемое PWA**: незалогиненный игрок видит призыв к установке
под формой входа (и внизу «Настроек»), который в один тап ставит приложение на рабочий стол под формой входа (и внизу «Настроек»), который в один тап ставит приложение на рабочий стол
+4 -1
View File
@@ -23,7 +23,10 @@ ENV APP_VERSION=${VERSION}
WORKDIR /app WORKDIR /app
COPY --from=build /src/renderer/node_modules ./node_modules COPY --from=build /src/renderer/node_modules ./node_modules
COPY --from=build /src/renderer/dist ./dist COPY --from=build /src/renderer/dist ./dist
COPY renderer/src/server.mjs renderer/src/render.mjs ./src/ COPY renderer/src/server.mjs renderer/src/render.mjs renderer/src/offer.mjs ./src/
# The public-offer prose (GET /offer/): the owner-edited markdown, read once at boot. The dynamic
# price list is fetched from the backend at request time and spliced in.
COPY ui/legal/offer_ru.md ./legal/offer_ru.md
USER node USER node
EXPOSE 8090 EXPOSE 8090
CMD ["node", "src/server.mjs"] CMD ["node", "src/server.mjs"]
+22 -12
View File
@@ -1,10 +1,10 @@
# renderer — the finished-game image-render sidecar # renderer — the render sidecar (finished-game image + public offer page)
An internal-only Node service that rasterizes the finished-game export PNG. It runs the An internal Node service that runs shared `ui/src/lib` renderers server-side — bundled verbatim at
**same** `ui/src/lib/gameimage.ts` the web project unit-tests — bundled verbatim at image image build time (`src/entry.ts` → esbuild → `dist/gameimage.mjs`) so there is one renderer and no
build time (`src/entry.ts` → esbuild → `dist/gameimage.mjs`) — on drift from the browser. It serves two surfaces: the finished-game export **PNG** (on
[skia-canvas](https://github.com/samizdatco/skia-canvas), so the server render is [skia-canvas](https://github.com/samizdatco/skia-canvas), pixel-identical to the design the owner
pixel-identical to the design the owner signed off in the browser. signed off) and the public **offer page**.
## Interface ## Interface
@@ -12,20 +12,30 @@ pixel-identical to the design the owner signed off in the browser.
`image/png`. `game`/`moves` are the ui-model shapes (`GameView` / `MoveRecord[]`); `image/png`. `game`/`moves` are the ui-model shapes (`GameView` / `MoveRecord[]`);
`alphabet` is the per-variant `(index, letter, value)` table tile values are drawn `alphabet` is the per-variant `(index, letter, value)` table tile values are drawn
from; `labels` localizes the non-play moves (pass/exchange/resign/timeout); from; `labels` localizes the non-play moves (pass/exchange/resign/timeout);
`hostname` + `dateLocale` feed the footer. `hostname` + `dateLocale` feed the footer. Internal-only.
- `GET /offer/` — the public offer page as `text/html`: the owner-edited `ui/legal/offer_ru.md`
(baked into the image, read at boot) with the live catalog **price list** (§4.4) fetched as
markdown from the backend's internal `/api/v1/internal/offer/pricing` (`RENDERER_BACKEND_URL`)
and spliced in at the `<#pricing_template#>` marker, then rendered by the shared
`ui/src/lib/offer.ts`. `GET /offer` → 301 `/offer/`. **The only edge-exposed route** — caddy
routes `/offer/` here; a backend outage yields a 502, never a stale price list.
- `GET /healthz` — liveness (the compose healthcheck the backend's `depends_on` gates on). - `GET /healthz` — liveness (the compose healthcheck the backend's `depends_on` gates on).
The service draws and nothing else: authentication, the participant check and the signed The service renders and nothing else: for the PNG, authentication, the participant check and the
public download URL all live in the backend (`backend/internal/server/export.go`); the signed public download URL all live in the backend (`backend/internal/server/export.go`), the path
network path is client → gateway `/dl/*` → backend → this sidecar. being client → gateway `/dl/*` → backend → this sidecar; for the offer, the catalog projection and
its cache live in the backend (`backend/internal/payments/offer.go`) and no user input reaches the
page.
## Development ## Development
```sh ```sh
pnpm install # skia-canvas + esbuild MUST stay approved in pnpm-workspace.yaml pnpm install # skia-canvas + esbuild MUST stay approved in pnpm-workspace.yaml
# (allowBuilds) or the native binary is silently never fetched # (allowBuilds) or the native binary is silently never fetched
pnpm test # bundles, then node --test against testdata/request.json pnpm test # bundles, then node --test (PNG smoke + offer splice)
node src/server.mjs # local run on :8090 (RENDERER_PORT overrides) # local run on :8090 (RENDERER_PORT overrides). For /offer/, point at the offer source and a
# reachable backend (else the boot read / the price fetch fail):
RENDERER_OFFER_MD=../ui/legal/offer_ru.md RENDERER_BACKEND_URL=http://localhost:8080 node src/server.mjs
``` ```
The runtime image (`renderer/Dockerfile`, `node:22-slim`) bakes in Liberation Sans (the The runtime image (`renderer/Dockerfile`, `node:22-slim`) bakes in Liberation Sans (the
+4
View File
@@ -9,5 +9,9 @@ await build({
format: 'esm', format: 'esm',
platform: 'node', platform: 'node',
outfile: 'dist/gameimage.mjs', outfile: 'dist/gameimage.mjs',
// The shared ui/src/lib modules are copied without their node_modules, so a bare npm import they
// make (offer.ts → 'marked', the offer renderer's markdown parser) is not resolvable from the ui
// tree. NODE_PATH-style fallback to the renderer's own node_modules, where marked is a dependency.
nodePaths: ['node_modules'],
logLevel: 'info', logLevel: 'info',
}); });
+1
View File
@@ -9,6 +9,7 @@
"test": "pnpm run bundle && node --test test/*.test.mjs" "test": "pnpm run bundle && node --test test/*.test.mjs"
}, },
"dependencies": { "dependencies": {
"marked": "^18.0.5",
"skia-canvas": "^3.0.6" "skia-canvas": "^3.0.6"
}, },
"devDependencies": { "devDependencies": {
+10
View File
@@ -8,6 +8,9 @@ importers:
.: .:
dependencies: dependencies:
marked:
specifier: ^18.0.5
version: 18.0.6
skia-canvas: skia-canvas:
specifier: ^3.0.6 specifier: ^3.0.6
version: 3.0.8 version: 3.0.8
@@ -209,6 +212,11 @@ packages:
resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
engines: {node: '>= 14'} engines: {node: '>= 14'}
marked@18.0.6:
resolution: {integrity: sha512-MrV5puXBfuiy6wl6DLaq3BtIJQAJToAd5zt/ZKhRfGRAuFPALE7/4Y7jnxRQoEgK/pBgurGqLyAuRgZ2xOjr6w==}
engines: {node: '>= 20'}
hasBin: true
ms@2.1.3: ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -347,6 +355,8 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
marked@18.0.6: {}
ms@2.1.3: {} ms@2.1.3: {}
parenthesis@3.1.8: {} parenthesis@3.1.8: {}
+7 -4
View File
@@ -1,6 +1,9 @@
// The esbuild bundle entry: re-exports the SHARED game-image renderer from ui/src/lib — // The esbuild bundle entry: re-exports the SHARED ui/src/lib modules — the exact modules the
// the exact module the browser build unit-tests — plus the alphabet cache seeder the // browser build unit-tests — so the sidecar runs them on the server. Bundled by `pnpm run bundle`
// server fills from the backend-supplied per-variant table. Bundled by `pnpm run bundle` // into dist/gameimage.mjs (type erasure only; the ui project type-checks the source):
// into dist/gameimage.mjs (type erasure only; the ui project type-checks the source). // - drawGameImage + setAlphabet: the finished-game PNG export (POST /render).
// - renderOfferHtml: the public-offer page (GET /offer/) — the same renderer the landing build
// used to invoke, now server-side so the live catalog price list can be spliced in.
export { drawGameImage, type RenderOptions } from '../../ui/src/lib/gameimage'; export { drawGameImage, type RenderOptions } from '../../ui/src/lib/gameimage';
export { setAlphabet } from '../../ui/src/lib/alphabet'; export { setAlphabet } from '../../ui/src/lib/alphabet';
export { renderOfferHtml } from '../../ui/src/lib/offer';
+17
View File
@@ -0,0 +1,17 @@
// The public-offer page renderer: splices the live catalog price list into the owner-edited offer
// markdown and renders it with the SAME renderOfferHtml the landing build used to invoke (bundled
// from ui/src/lib/offer). Kept out of server.mjs so the substitution is unit-testable without HTTP.
import { renderOfferHtml } from '../dist/gameimage.mjs';
// pricingMarker is the token ui/legal/offer_ru.md carries at §4.4 where the price list belongs. It
// mirrors the backend marker (backend/internal/payments/offer.go) and is replaced with the fetched
// tables before rendering.
export const pricingMarker = '<#pricing_template#>';
// renderOffer returns the standalone /offer/ HTML: the offer markdown with the pricing marker
// replaced by pricingTables (the two markdown tables the backend projects from the active catalog),
// rendered to a self-contained document. The replacement is literal (a function replacer) so a "$"
// in a product title is never read as a replacement pattern; a missing marker leaves the text as is.
export function renderOffer(offerMarkdown, pricingTables) {
return renderOfferHtml(offerMarkdown.replace(pricingMarker, () => pricingTables));
}
+43 -8
View File
@@ -1,20 +1,43 @@
// The render sidecar: a minimal internal HTTP service the backend calls to rasterize the // The render sidecar: a minimal internal HTTP service on skia-canvas and the shared ui/src/lib
// finished-game export image. It runs the same drawGameImage the browser build ships // renderers (bundled from ui/src/lib at image build time). It serves two surfaces:
// (bundled from ui/src/lib at image build time) on skia-canvas, with system fonts from
// the image (Liberation Sans + Noto Color Emoji via fontconfig).
// //
// POST /render {game, moves, alphabet, labels, dateLocale, hostname, scale?} → image/png // POST /render {game, moves, alphabet, labels, dateLocale, hostname, scale?} → image/png
// GET /offer/ → text/html (the public offer page: ui/legal/offer_ru.md with the live catalog
// price list spliced in — the only edge-exposed route; caddy routes /offer/ here)
// GET /offer → 301 /offer/
// GET /healthz → 200 // GET /healthz → 200
// //
// The service is internal-only (docker network `internal`); authentication, participant // /render is internal-only (the backend calls it; authentication, participant checks and the signed
// checks and the signed public URL all live in the backend — this process only draws. // public URL live in the backend). /offer/ is reachable from the edge but read-only and unprivileged
// — it fetches the price list from the backend's internal endpoint and renders the committed offer
// markdown; no user input reaches it.
import { createServer } from 'node:http'; import { createServer } from 'node:http';
import { readFileSync } from 'node:fs';
import { renderRequest } from './render.mjs'; import { renderRequest } from './render.mjs';
import { renderOffer } from './offer.mjs';
const PORT = Number(process.env.RENDERER_PORT || 8090); const PORT = Number(process.env.RENDERER_PORT || 8090);
// A render request is a finished game's journal — generously capped. // A render request is a finished game's journal — generously capped.
const MAX_BODY = 2 * 1024 * 1024; const MAX_BODY = 2 * 1024 * 1024;
// The offer prose is baked into the image (renderer/Dockerfile) and read once at boot; only the
// price list is dynamic (fetched per request). The backend endpoint is internal (off the edge
// allow-list) and serves the tables from its in-memory cache. RENDERER_OFFER_MD overrides the baked
// path for a local run (point it at ../ui/legal/offer_ru.md).
const OFFER_MD = readFileSync(process.env.RENDERER_OFFER_MD || new URL('../legal/offer_ru.md', import.meta.url), 'utf8');
const OFFER_PRICING_URL =
(process.env.RENDERER_BACKEND_URL || 'http://backend:8080') + '/api/v1/internal/offer/pricing';
// fetchOfferPricing returns the two catalog price tables as markdown from the backend, or throws a
// 502 (upstream error) / 504 (timeout) so the offer never renders with a broken price list.
async function fetchOfferPricing() {
const resp = await fetch(OFFER_PRICING_URL, { signal: AbortSignal.timeout(5000) });
if (!resp.ok) {
throw Object.assign(new Error(`offer pricing upstream ${resp.status}`), { status: 502 });
}
return resp.text();
}
function readBody(req) { function readBody(req) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const chunks = []; const chunks = [];
@@ -35,11 +58,23 @@ function readBody(req) {
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
try { try {
if (req.method === 'GET' && req.url === '/healthz') { const path = (req.url || '').split('?')[0];
if (req.method === 'GET' && path === '/healthz') {
res.writeHead(200, { 'content-type': 'text/plain' }).end('ok'); res.writeHead(200, { 'content-type': 'text/plain' }).end('ok');
return; return;
} }
if (req.method === 'POST' && req.url === '/render') { if (req.method === 'GET' && path === '/offer') {
res.writeHead(301, { location: '/offer/' }).end();
return;
}
if (req.method === 'GET' && path === '/offer/') {
const html = renderOffer(OFFER_MD, await fetchOfferPricing());
res
.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' })
.end(html);
return;
}
if (req.method === 'POST' && path === '/render') {
const png = await renderRequest(JSON.parse(await readBody(req))); const png = await renderRequest(JSON.parse(await readBody(req)));
res.writeHead(200, { 'content-type': 'image/png', 'content-length': png.length }).end(png); res.writeHead(200, { 'content-type': 'image/png', 'content-length': png.length }).end(png);
return; return;
+29
View File
@@ -0,0 +1,29 @@
// Unit test for the public-offer page assembly: renderOffer splices the backend's price-list
// markdown into the offer at the pricing marker and renders it with the shared renderOfferHtml
// (bundled from ui/src/lib/offer). The prose rendering itself is unit-tested in ui/ (offer.test.ts);
// here we assert the substitution and that the tables reach the rendered HTML.
import test from 'node:test';
import assert from 'node:assert/strict';
import { renderOffer, pricingMarker } from '../src/offer.mjs';
const tables =
'| Наименование | Рубли | Голоса в VK | Stars в Telegram |\n' +
'| --- | --- | --- | --- |\n' +
'| 50 «Фишек» | 200.00 | 30 | 100 |';
test('splices the price list into the offer and renders the tables to HTML', () => {
const md = `# Публичная оферта\n\n**4.4.** Стоимость Товаров:\n\n${pricingMarker}\n`;
const html = renderOffer(md, tables);
// The marker is gone and the projected table reached the document as a real HTML table.
assert.ok(!html.includes(pricingMarker), 'pricing marker must be substituted');
assert.ok(html.includes('<table>'), 'the price list must render as an HTML table');
assert.ok(html.includes('<td>200.00</td>'), 'a rouble price cell must be present');
assert.ok(html.includes('50 «Фишек»'), 'the product title must be present');
// The offer chrome from the shared renderer is intact.
assert.ok(html.includes('<!doctype html>'));
});
test('a "$" in a title is substituted literally, not as a replacement pattern', () => {
const html = renderOffer(`x ${pricingMarker} y`, '| $5 pack | 1 |');
assert.ok(html.includes('$5 pack'), 'a "$" in the tables must survive substitution');
});
+8 -3
View File
@@ -59,13 +59,18 @@ test('the landing shows a web-version entry linking /app/, with a caption', asyn
await expect(page.getByText('Веб-версия')).toBeVisible(); await expect(page.getByText('Веб-версия')).toBeVisible();
}); });
// The footer carries a public-offer link to the static /offer/ page (rendered from // The footer carries the public-offer link (/offer/ — the legal document a purchase accepts,
// ui/legal/offer_ru.md at build; the legal document a purchase accepts). // rendered by the render sidecar) and, beside it, the feedback link to the Telegram bot the offer
test('the landing footer links to the public offer at /offer/', async ({ page }) => { // lists as the seller's contact.
test('the landing footer links to the public offer and the feedback bot', async ({ page }) => {
await page.goto('/landing.html'); await page.goto('/landing.html');
await expect(page.getByText(/Играй в «Эрудита»/)).toBeVisible(); // Russian by default await expect(page.getByText(/Играй в «Эрудита»/)).toBeVisible(); // Russian by default
const offer = page.getByRole('link', { name: 'Публичная оферта' }); const offer = page.getByRole('link', { name: 'Публичная оферта' });
await expect(offer).toBeVisible(); await expect(offer).toBeVisible();
expect(await offer.getAttribute('href')).toBe('/offer/'); expect(await offer.getAttribute('href')).toBe('/offer/');
const feedback = page.getByRole('link', { name: 'Обратная связь' });
await expect(feedback).toBeVisible();
expect(await feedback.getAttribute('href')).toBe('https://t.me/Erudit_GameBot');
}); });
+16 -6
View File
@@ -20,6 +20,8 @@
**Сайт Продавца в сети «Интернет»** — совокупность программ для электронных вычислительных машин и иной информации, содержащейся в информационной системе, доступ к которой обеспечивается посредством сети «Интернет» по доменному имени и сетевому адресу: `erudit-game.ru`. **Сайт Продавца в сети «Интернет»** — совокупность программ для электронных вычислительных машин и иной информации, содержащейся в информационной системе, доступ к которой обеспечивается посредством сети «Интернет» по доменному имени и сетевому адресу: `erudit-game.ru`.
**Приложение Продавца** - предоставляемое Продавцом для загрузки из сети «Интернет», добровольно загружаемое Покупателем и исполняемое на электронной вычислительной машине (устройстве) Покупателя программное обеспечение, предоставляющее игровые или иные функции и позволяющее Покупателю взимодействовать с Продавцом путём осуществления сделок купли-продажи внутригровых ценностей. Приложение может распространяться в форматах, но не ограничиваясь, такими как: веб-приложение на Сайте Продавца, мини-приложение в экосистеме VK, мини-приложение в экосистеме Telegram, Android-приложение в экосистеме Google Play, Android-приложение в экосистеме RuStore, iOS-приложение в экосистеме Apple App Store и дугих форматах распространения.
**Стороны Договора (Стороны)** — Продавец и Покупатель. **Стороны Договора (Стороны)** — Продавец и Покупатель.
**Товар** — товаром по договору купли-продажи могут быть любые вещи с соблюдением правил, предусмотренных статьей 129 Гражданского кодекса РФ. **Товар** — товаром по договору купли-продажи могут быть любые вещи с соблюдением правил, предусмотренных статьей 129 Гражданского кодекса РФ.
@@ -28,13 +30,13 @@
**2.1.** По настоящему Договору Продавец обязуется передать вещь (Товар) в собственность Покупателя, а Покупатель обязуется принять Товар и уплатить за него определенную денежную сумму. **2.1.** По настоящему Договору Продавец обязуется передать вещь (Товар) в собственность Покупателя, а Покупатель обязуется принять Товар и уплатить за него определенную денежную сумму.
**2.2.** Наименование, количество, а также ассортимент Товара, его стоимость, порядок доставки и иные условия определяются на основании сведений Продавца при оформлении заявки Покупателем, либо устанавливаются на сайте Продавца в сети «Интернет» `erudit-game.ru`. **2.2.** Наименование, количество, а также ассортимент Товара, его стоимость, порядок доставки и иные условия определяются на основании сведений Продавца при оформлении заявки Покупателем, либо устанавливаются на Сайте Продавца в сети «Интернет», либо в Приложении Продавца.
**2.3.** Акцепт настоящей Оферты выражается в совершении конклюдентных действий, в частности: **2.3.** Акцепт настоящей Оферты выражается в совершении конклюдентных действий, в частности:
- действиях, связанных с регистрацией учетной записи на Сайте Продавца в сети «Интернет» при наличии необходимости регистрации учетной записи; - действиях, связанных с регистрацией учетной записи на Сайте Продавца в сети «Интернет» либо в Приложении Продавца при наличии необходимости регистрации учетной записи;
- путем составления и заполнения заявки на оформление заказа Товара; - путем составления и заполнения заявки на оформление заказа Товара;
- путем сообщения требуемых для заключения Договора сведений по телефону, электронной почте, указанными на сайте Продавца в сети «Интернет», в том числе, при обратном звонке Продавца по заявке Покупателя; - путем сообщения требуемых для заключения Договора сведений по телефону, электронной почте, указанными на Сайте Продавца в сети «Интернет» либо в Приложении Продавца, в том числе, при обратном звонке Продавца по заявке Покупателя;
- оплаты Товара Покупателем. - оплаты Товара Покупателем.
Данный перечень не является исчерпывающим, могут быть и другие действия, которые ясно выражают намерение лица принять предложение контрагента. Данный перечень не является исчерпывающим, могут быть и другие действия, которые ясно выражают намерение лица принять предложение контрагента.
@@ -76,10 +78,16 @@
## 4. Цена и порядок расчетов ## 4. Цена и порядок расчетов
**4.1.** Стоимость, а также порядок оплаты Товара определяется на основании сведений Продавца при оформлении заявки Покупателем, либо устанавливаются на сайте Продавца в сети «Интернет»: `erudit-game.ru`. **4.1.** Стоимость, а также порядок оплаты Товара определяется на основании сведений Продавца при оформлении заявки Покупателем, либо устанавливаются на Сайте Продавца в сети «Интернет» а так же в Приложении Продавца.
**4.2.** Все расчеты по Договору производятся в безналичном порядке. **4.2.** Все расчеты по Договору производятся в безналичном порядке.
**4.3.** Порядок расчётов. Приобретаемым Товаром является внутриигровая валюта «Фишка» — условная учётная единица, используемая исключительно в пределах Сайта Продавца либо в Приложения Продавца. «Фишки» предоставляют Покупателю возможность получения внутриигровых благ и дополнительных функций, включая, но не ограничиваясь: отказ от показа рекламы, приобретение подсказок в игре и иные внутриигровые возможности. «Фишка» не является электронным средством платежа либо денежным средством, не подлежит обмену на денежные средства и не может быть использована за пределами Сайта Продавца либо Приложения Продавца. «Фишки» зачисляются на внутриигровой счёт Покупателя единовременно после поступления оплаты; дальнейшее их использование для получения внутриигровых благ осуществляется Покупателем самостоятельно в рамках используемого Сайта Продавца либо Приложения Продавца.
**4.4.** Стоимость Товаров:
<#pricing_template#>
## 5. Обмен и возврат Товара ## 5. Обмен и возврат Товара
**5.1.** Покупатель вправе осуществить возврат (обмен) Продавцу Товара, приобретенный дистанционным способом, за исключением перечня товаров, не подлежащих обмену и возврату согласно действующему законодательству Российской Федерации. Условия, сроки и порядок возврата Товара надлежащего и ненадлежащего качества установлены в соответствии с Гражданским кодексом РФ, Закона РФ от 07.02.1992 N 2300-1 «О защите прав потребителей», Правил, утвержденных Постановлением Правительства РФ от 31.12.2020 N 2463. **5.1.** Покупатель вправе осуществить возврат (обмен) Продавцу Товара, приобретенный дистанционным способом, за исключением перечня товаров, не подлежащих обмену и возврату согласно действующему законодательству Российской Федерации. Условия, сроки и порядок возврата Товара надлежащего и ненадлежащего качества установлены в соответствии с Гражданским кодексом РФ, Закона РФ от 07.02.1992 N 2300-1 «О защите прав потребителей», Правил, утвержденных Постановлением Правительства РФ от 31.12.2020 N 2463.
@@ -120,7 +128,7 @@
**9.3.** Договор вступает в силу с момента Акцепта условий настоящей Оферты Покупателем и действует до полного исполнения Сторонами обязательств по Договору. **9.3.** Договор вступает в силу с момента Акцепта условий настоящей Оферты Покупателем и действует до полного исполнения Сторонами обязательств по Договору.
**9.4.** Изменения, внесенные Продавцом в Договор и опубликованные на сайте в форме актуализированной Оферты, считаются принятыми Покупателем в полном объеме. **9.4.** Изменения, внесенные Продавцом в Договор и опубликованные на Сайте Продавца в форме актуализированной Оферты, считаются принятыми Покупателем в полном объеме при оплате Товаров.
## 10. Дополнительные условия ## 10. Дополнительные условия
@@ -138,8 +146,10 @@
**10.5.** Бездействие одной из Сторон в случае нарушения условий настоящей Оферты не лишает права заинтересованной Стороны осуществлять защиту своих интересов позднее, а также не означает отказа от своих прав в случае совершения одной из Сторон подобных либо сходных нарушений в будущем. **10.5.** Бездействие одной из Сторон в случае нарушения условий настоящей Оферты не лишает права заинтересованной Стороны осуществлять защиту своих интересов позднее, а также не означает отказа от своих прав в случае совершения одной из Сторон подобных либо сходных нарушений в будущем.
**10.6.** Если на Сайте Продавца в сети «Интернет» есть ссылки на другие веб-сайты и материалы третьих лиц, такие ссылки размещены исключительно в целях информирования, и Продавец не имеет контроля в отношении содержания таких сайтов или материалов. Продавец не несет ответственность за любые убытки или ущерб, которые могут возникнуть в результате использования таких ссылок. **10.6.** Если на Сайте Продавца в сети «Интернет» либо в Приложении Продавца есть ссылки на другие веб-сайты и материалы третьих лиц, такие ссылки размещены исключительно в целях информирования, и Продавец не имеет контроля в отношении содержания таких сайтов или материалов. Продавец не несет ответственность за любые убытки или ущерб, которые могут возникнуть в результате использования таких ссылок.
## 11. Реквизиты Продавца ## 11. Реквизиты Продавца
Денисов Илья Аркадьевич, ИНН 290210610742. Денисов Илья Аркадьевич, ИНН 290210610742.
Обратная связь в Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot).
+14
View File
@@ -125,7 +125,13 @@
</section> </section>
<footer class="ft"> <footer class="ft">
<span class="legal">
<a class="offer" href="/offer/">{t('landing.offer')}</a> <a class="offer" href="/offer/">{t('landing.offer')}</a>
<span class="sep" aria-hidden="true">|</span>
<!-- The feedback bot: the same Telegram contact the offer lists (section 11 «Реквизиты»);
external, opens in a new tab. -->
<a class="offer" href="https://t.me/Erudit_GameBot" target="_blank" rel="noopener noreferrer">{t('landing.feedback')}</a>
</span>
<span>{t('about.version', { v: __APP_VERSION__ })}</span> <span>{t('about.version', { v: __APP_VERSION__ })}</span>
</footer> </footer>
</main> </main>
@@ -287,6 +293,14 @@
color: var(--text-muted); color: var(--text-muted);
font-size: 0.8rem; font-size: 0.8rem;
} }
.ft .legal {
display: flex;
align-items: center;
gap: 8px;
}
.ft .sep {
color: var(--text-muted);
}
.ft .offer { .ft .offer {
color: inherit; color: inherit;
} }
+1
View File
@@ -285,6 +285,7 @@ export const en = {
'landing.captionVK': 'VK', 'landing.captionVK': 'VK',
'landing.captionWeb': 'Web', 'landing.captionWeb': 'Web',
'landing.offer': 'Public offer', 'landing.offer': 'Public offer',
'landing.feedback': 'Feedback',
'install.title': 'Install the app', 'install.title': 'Install the app',
'install.subtitle': 'Put the app icon on your desktop (home screen) to open the game in one tap.', 'install.subtitle': 'Put the app icon on your desktop (home screen) to open the game in one tap.',
+1
View File
@@ -285,6 +285,7 @@ export const ru: Record<MessageKey, string> = {
'landing.captionVK': 'VK', 'landing.captionVK': 'VK',
'landing.captionWeb': 'Веб-версия', 'landing.captionWeb': 'Веб-версия',
'landing.offer': 'Публичная оферта', 'landing.offer': 'Публичная оферта',
'landing.feedback': 'Обратная связь',
'install.title': 'Установить приложение', 'install.title': 'Установить приложение',
'install.subtitle': 'Поместите иконку приложения на рабочий стол (домашний экран), чтобы открывать игру одним нажатием.', 'install.subtitle': 'Поместите иконку приложения на рабочий стол (домашний экран), чтобы открывать игру одним нажатием.',
+2 -2
View File
@@ -10,8 +10,8 @@ describe('renderOfferHtml', () => {
// The markdown heading is rendered, not left as literal source. // The markdown heading is rendered, not left as literal source.
expect(html).toContain('<h1>Публичная оферта</h1>'); expect(html).toContain('<h1>Публичная оферта</h1>');
expect(html).not.toContain('# Публичная оферта'); expect(html).not.toContain('# Публичная оферта');
// A back link to the landing root is always present. // No in-page navigation: the standalone offer carries no "back" link.
expect(html).toContain('href="/"'); expect(html).not.toContain('class="back"');
}); });
it('renders headings, bold clause numbers and lists', () => { it('renders headings, bold clause numbers and lists', () => {
+37 -12
View File
@@ -2,13 +2,15 @@ import { marked } from 'marked';
/** /**
* renderOfferHtml renders the public-offer markdown source into a standalone, * renderOfferHtml renders the public-offer markdown source into a standalone,
* self-contained HTML document served statically at `/offer/`. The build emits * self-contained HTML document served at `/offer/`. It runs server-side in the
* the result as `dist/offer/index.html` (see the `emit-offer` plugin in * render sidecar (`renderer/src/offer.mjs`), which reads the owner-edited
* `vite.config.ts`), which the landing container serves. * `ui/legal/offer_ru.md`, splices the live catalog price list into it and calls
* this function — one renderer shared with the browser build, kept unit-tested
* here (`offer.test.ts`).
* *
* The input `markdown` is trusted repository content (the owner-edited * The input `markdown` is trusted repository content plus the backend's own
* `ui/legal/offer_ru.md`), not user input, so the rendered HTML is deliberately * catalog projection, not user input, so the rendered HTML is deliberately not
* not sanitised. The page carries its own minimal light/dark styling so it needs * sanitised. The page carries its own minimal light/dark styling so it needs
* neither the app bundle nor `app.css`. * neither the app bundle nor `app.css`.
*/ */
export function renderOfferHtml(markdown: string): string { export function renderOfferHtml(markdown: string): string {
@@ -29,6 +31,7 @@ export function renderOfferHtml(markdown: string): string {
--text: #1a1c20; --text: #1a1c20;
--accent: #2563eb; --accent: #2563eb;
--rule: #e5e7eb; --rule: #e5e7eb;
--cell-border: #d1d5db;
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { :root {
@@ -36,6 +39,9 @@ export function renderOfferHtml(markdown: string): string {
--text: #e7e9ee; --text: #e7e9ee;
--accent: #6ea8fe; --accent: #6ea8fe;
--rule: #242832; --rule: #242832;
/* A muted grey — the section rules (--rule) vanish on the dark background, so table cells
get a slightly firmer border to stay legible without being loud. */
--cell-border: #3a4250;
} }
} }
* { * {
@@ -55,11 +61,6 @@ export function renderOfferHtml(markdown: string): string {
a { a {
color: var(--accent); color: var(--accent);
} }
.back {
display: inline-block;
margin-bottom: 20px;
text-decoration: none;
}
h1 { h1 {
font-size: 1.6rem; font-size: 1.6rem;
text-align: center; text-align: center;
@@ -80,11 +81,35 @@ export function renderOfferHtml(markdown: string): string {
li { li {
margin: 0.25em 0; margin: 0.25em 0;
} }
/* The price tables (§4.4) span the full content width. */
table {
width: 100%;
border-collapse: collapse;
margin: 0.75em 0 1.25em;
font-size: 0.95rem;
}
th,
td {
border: 1px solid var(--cell-border);
padding: 6px 10px;
}
/* The product-name column shrinks to its content and never wraps; the price columns share the
rest of the width (width:1% is the shrink-to-fit idiom paired with the table's width:100%). */
th:first-child,
td:first-child {
width: 1%;
white-space: nowrap;
}
/* Right-aligned price columns. marked emits the alignment from the "---:" separator; this rule
keeps it applied whether that surfaces as an align attribute or an inline style. */
th[align='right'],
td[align='right'] {
text-align: right;
}
</style> </style>
</head> </head>
<body> <body>
<main> <main>
<a class="back" href="/">← На главную</a>
${body} ${body}
</main> </main>
</body> </body>
-18
View File
@@ -3,7 +3,6 @@ import { resolve } from 'node:path';
import { defineConfig, type Plugin } from 'vite'; import { defineConfig, type Plugin } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte'; import { svelte } from '@sveltejs/vite-plugin-svelte';
import { VitePWA } from 'vite-plugin-pwa'; import { VitePWA } from 'vite-plugin-pwa';
import { renderOfferHtml } from './src/lib/offer';
/** /**
* injectBootVersion stamps the app version into index.html's boot-capability guard, replacing its * injectBootVersion stamps the app version into index.html's boot-capability guard, replacing its
@@ -39,22 +38,6 @@ function emitPolyfills(): Plugin {
}; };
} }
/**
* emitOffer renders the public offer markdown (legal/offer_ru.md) to a standalone
* static page and emits it as dist/offer/index.html, which the landing container
* serves at /offer/ (deploy/landing/Caddyfile). The markdown is the owner-editable
* source of truth, so the page is regenerated from it on every build.
*/
function emitOffer(): Plugin {
return {
name: 'emit-offer',
generateBundle() {
const md = readFileSync(resolve(import.meta.dirname, 'legal/offer_ru.md'), 'utf8');
this.emitFile({ type: 'asset', fileName: 'offer/index.html', source: renderOfferHtml(md) });
},
};
}
// The edge Connect service is scrabble.edge.v1.Gateway; the gateway serves it over // The edge Connect service is scrabble.edge.v1.Gateway; the gateway serves it over
// h2c on :8081 by default. In dev we proxy the RPC path so the browser (which can // h2c on :8081 by default. In dev we proxy the RPC path so the browser (which can
// not speak h2c directly) talks to the dev server on the same origin. In `mock` // not speak h2c directly) talks to the dev server on the same origin. In `mock`
@@ -77,7 +60,6 @@ export default defineConfig(({ mode }) => ({
plugins: [ plugins: [
svelte(), svelte(),
emitPolyfills(), emitPolyfills(),
emitOffer(),
injectBootVersion(), injectBootVersion(),
// App-shell precache for the offline mode: a custom (injectManifest) service worker precaches // App-shell precache for the offline mode: a custom (injectManifest) service worker precaches
// index.html + the hashed assets so the installed web PWA cold-launches with no network. It // index.html + the hashed assets so the installed web PWA cold-launches with no network. It