138 Commits

  • fix(widgets): send updateMessageWidgetData without a pts filler
    updateMessageWidgetData carries its own pts and pts_count, so a widget
    data patch needs no filler to keep the pts contiguous:
    
    - message_widget_data leaves LacksWirePts, so neither the private patch
      response nor its outbox delivery appends an empty updateDeleteMessages;
    - the channel patch no longer appends an empty
      updateDeleteChannelMessages.
    
    td drops updateMessageWidgetData for profiles 225-232. Those sessions see
    the pts gap and recover it through updates.getDifference
    (updates.getChannelDifference for channels), whose state covers the pts.
    TestLayer233WidgetDataOutboxCarriesNoPtsFiller pins the outbox projection,
    and the channel patch test now expects only the widget update.
    
    Also fix the docs that #173 left stale: docs/bot-widgets.md no longer says
    the shared definition keeps the HTML (it keeps the Payload) and describes
    the gap recovery, AGENTS.md names td v1.9.0, and two widget.go comments
    drop the removed HTML field.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • fix(widgets): address the approve-with-follow-ups review
    - A shared widget's initial public data now lives in its definition only
      (PublicDataSet is unset for shared sends), so editWidgetData is visible on the
      original message, not just copies.
    - A clear (public_data="") is pushed with the public_data flag set:
      updateMessageWidgetData (private + channel) and messageMediaWidget now set
      flags.0 whenever PublicDataSet is true, so live clients learn about the clear
      without polling.
    - The private editMessageWidgetData response now carries users/chats.
    - The inline widget-data edit passes the clock EditDate (memory store no longer
      stamps the event with the send date).
    - lockChannelMessageMedia re-checks deleted, so a delete that commits before the
      lock is not overwritten and gets no widget-data event.
    - Removed dead BotWidget fields (HTML, CreatedAt, UpdatedAt) and the duplicate
      html column write.
    - Docs: shared-widget public-data rule and the pushed clear.
  • fix(widgets): fail closed on a widget-id owner conflict; more tests/docs
    Second block-3 pass (Other issues):
    - A preassigned widget id is reusable only by the same bot: CreateWidget and the
      committed-send definition insert now check the existing row's owner and return
      ErrWidgetNotFound on a conflict instead of silently linking (CreateBotWidgetIfAbsent
      is :execrows to detect the no-op). Tests for postgres/memory.
    - Added tests: domain ApplyWidgetDataPatch presence/clear, and the
      getWidgetPublicData precedence/clear rule.
    - Docs: disclose the uploadMedia row-on-send, memory-store and transcription
      document limits.
  • fix(widgets): address the block-3 review (authz, pts, routing, patch, transcription)
    Blocking issues:
    1. Authorization: a widget-data patch is now allowed only for the bot that sent
       the message (or its via bot), enforced in the RPC and in both private and
       channel stores (no admin/recipient fallback). Negative tests added.
    2. Pts gap on 225-232: updateMessageWidgetData/channel_widget_data are dropped by
       td for older profiles, so UpdateEventMessageWidgetData now uses the aux-pts
       bookkeeping and the private response / channel fanout carry an empty
       updateDeleteMessages/updateDeleteChannelMessages filler with the same pts.
    3. Channel patch hardening: lock the message row (FOR UPDATE) before the
       read-modify-write so concurrent patches cannot lose a field; store a compact
       event (id + widget media); stamp it with the patch time (not the send date);
       do not queue a Bot API edited_channel_post for a data-only patch. Channel
       widget-data events now also respect pre-history-hidden and privacy-bot filters.
    4. Query routing: a forwarded/shared widget the owner bot did not send is
       answered as updateBotWidgetCopyQuery (never the querier's chat); a private
       chat_instance hashes the querier, not the partner; a shared-owner lookup error
       fails closed instead of reassigning the widget to another bot.
    5. editInlineBotMessageWidgetData reuses the in-place widget-data patch for
       private and channel inline messages (no edit marker, invert_media preserved,
       not-modified reported).
    6. transcribeAudioFile bounds the summed stored part size (via
       FilesService.UploadedFileSize) instead of assuming 512 KiB parts.
    7. Per-message public data records explicit presence (PublicDataSet), so
       editWidgetData is visible and public_data="" can be cleared.
    
    Also: docs, dead-code removal (MessageWidget.IsZero, BackgroundQuery,
    pendingAnswer.userID), and gofmt for messages_transcription_test.go.
  • fix(widgets): create shared widget rows in the committed send path
    Resolving inputMediaWidget no longer inserts a bot_widgets row: it assigns the
    random widget id and owner bot id on the media snapshot, and the definition is
    persisted inside the message send transaction. That removes the orphan rows left
    by uploadMedia, setInlineBotResults before its query check and sends that fail
    later.
    
    - domain: MessageWidget.OwnerBotID carries the owner bot so the row can be
      created without the requesting user; domain.RandomWidgetID is the shared
      random-id helper.
    - rpc: domainWidgetFromInline/domainWidgetFromID set the id + owner bot and stop
      calling WidgetStore.CreateWidget.
    - store/postgres: ensureSharedWidgetDefinitionTx inserts the definition inside the
      private and channel send transactions (no-op for non-shared media, idempotent
      on an existing id); CreateWidget honors a preassigned id.
    - Tests: resolving no longer creates a row; a committed private send does
      (postgres integration); the round-trip/inline tests persist the definition
      explicitly to emulate the commit.
  • feat(widgets): patch-only channel widget-data edit (block 8 channels)
    Complete block 8 for channels, mirroring the WebPageResolve channel mode.
    
    - domain: ChannelUpdateWidgetData event type ('channel_widget_data').
    - store/postgres + store/memory EditChannelMessage: when WidgetData is set,
      decode the target media, patch the widget's public/chat data in place, rewrite
      only the media jsonb (body/entities/edit_date untouched, so the message is not
      marked edited), reserve channel pts, append a channel_widget_data durable event
      and fan it out over the channel pts stream. Unchanged data returns
      ErrMessageNotModified.
    - rpc: tgChannelUpdate projects ChannelUpdateWidgetData to the schema-native
      updateMessageWidgetData (peer = the channel, msg_id, pts, public/chat data);
      onMessagesEditMessageWidgetData now routes channel messages through the patch
      request instead of a full edit, mapping ErrMessageNotModified to
      WIDGET_DATA_NOT_MODIFIED.
    - migration 20261106030000 adds 'channel_widget_data' to the
      channel_update_events allowlist (down rewrites retained rows to noop first).
    - tests: memory channel patch test, postgres integration test, and an rpc-level
      channel patch test asserting the updateMessageWidgetData projection.
    - docs: drop the "channel still uses the full edit path" limit.
  • docs(widgets): record the Layer 233 widget surface
    Documents docs/bot-widgets.md: media (message + inline), public/chat data, the
    durable updateMessageWidgetData event, the bot query round trip, transcription
    files, and the deliberate limits (process-local query registry, unmodelled
    channel forum sidebar, no TON widget signing).
  • admin(review console): fix "Load older" order and the re-review follow-ups
    Maintainer repair for the #167 re-review of 25d9375f.
    
    Blocking: "Load older messages" prepended the older page to a newest-first
    list that MessagePreview reverses, so it showed under the newest message.
    It is appended now.
    
    Live media:
    - LiveMedia probes each candidate key with a one-byte read and returns
      ErrLiveMediaTooLarge for an object over 16 MiB before reading it. The
      admin API maps it to 413 and the panel answers 413 with a plain-text
      reason and the same nosniff / CSP sandbox headers.
    - Responses are Cache-Control: no-store again, at both layers.
    - parseMedia reads the top-level kind and the id of the right object, so
      documents get their download link. Number literals are quoted before
      JSON.parse, so 64-bit ids never become JS numbers.
    - Tests: LiveMedia over the real files service on LocalFS (sniffing,
      allowlist, key checks, the cap and the probe), /v1/media and panel proxy
      headers, a messages.read gate test for /api/live/*, and a DSN-gated
      dialog paging test with tied and zero dates.
    
    Messenger:
    - The dialog cursor is keyed on before_peer_id, since top_message_date is
      0 for dialogs created by a scheduled message, a TTL or a chat theme.
    - The dialog list has its own stale-response guard for owner switches and
      "Load more chats".
    - Bubbles show the box id that "Delete selected" takes.
    - Detail pages preview the 50 messages ending at the opened one and keep
      it in view.
    - ?focus=env jumps once, so Status can be opened afterwards.
    - The shell title and the lit tab use the longest matching tab path, so
      group pages say Groups and detail routes light their tab; /premium is
      an alias of the Premium tab.
    - The remaining hardcoded strings go through i18n (en, zh, ru).
    
    Docs: /api/live/* rows document the cursor, has_more, media types, status
    codes, headers and messages.read; "Adding a page" says the shell renders
    the tab bar, and the generator now fails on a <SectionTabs> in a page.
    AGENTS.md, .env.example and comments use the current section names.
    web/dist is rebuilt.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • fix(giftfetch): read the 2FA password without a flag, echo or trimming
    The QR login now finishes two-step verification without exposing or
    changing the password:
    
    - Drop the -password flag. Arguments are visible to other users through
      ps and stay in shell history.
    - Read TG_PASSWORD, matching TG_API_ID and TG_API_HASH. Otherwise prompt
      without echo on a terminal (golang.org/x/term v0.46.0, which needs the
      x/sys v0.48.0 already required), or read the first line of piped
      stdin. The generic PASSWORD and TG_2FA_PASSWORD fallbacks are gone.
    - Use the password exactly as given. A cloud password may start or end
      with spaces; only a piped line's terminator is removed.
    - Match SESSION_PASSWORD_NEEDED with tgerr.Is alone. It already sees
      through the error qrlogin wraps.
    - docs/giftfetch.md describes the 2FA step instead of saying the QR
      route needs no password.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Translate Chinese/Russian comments, logs and diagnostics to English
    Translate all natural-language comments, log/diagnostic messages, SQL comments and config/doc prose from Chinese (and Russian) to English across the codebase (~840 files). Rebased on upstream main; upstream's newly added files are translated too.
    
    Locale resources and functional non-English data are left intact: language packs, admin/grammystore i18n bundles, localized docs, the officialBrandRE regex, seeded Russian premium-bot text, user-facing Russian bot strings and asserted Unicode test fixtures. A new internal/translation guard test fails if CJK/Cyrillic reappears in source outside that allowlist.
    
    No code, identifiers, struct tags or behavior changed (verified with an AST-level comment/string audit). go build ./..., go vet ./... and the guard pass.
  • feat(bots): BotFather shows the server's public Bot API URL
    TELESRV_BOT_API_PUBLIC_URL names the client-reachable Bot API base URL.
    When set, the /newbot and /token replies add "Bot API on this server:
    <url>/bot<token>/<method>", so bot owners on a private server know where
    to point their library instead of api.telegram.org. Empty keeps the replies
    as they are.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • feat(stickerfetch): export reactions, featured sets and thumbs
    - New specs: reactions (telegram_reactions_export layout read by
      seedReactions), featured_emoji / featured_stickers, id:<id>:<access_hash>,
      dice:<emoji>, animated_emoji, animated_emoji_animations,
      emoji_generic_animations.
    - Export document thumbs: inline sizes as hex, PhotoSize renditions as
      <doc_id>_thumb<N>_PhotoSize_type<t>.jpg. Android renders .tgs stickers and
      custom emoji only with thumbs, and emoji avatars are drawn from them.
    - Set thumbs and thumb_document_id in set_info.json.
    - -timeout flag (default 12m) for long featured exports.
    - TG_API_ID / TG_API_HASH override the built-in TDesktop credentials in
      stickerfetch and giftfetch (API_ID_PUBLISHED_FLOOD).
    - Downloaded files are 0644 so a server running as another uid can read a
      mounted seed directory; existing complete files are not re-downloaded.
    - Tests: golden reactions export in cmd/stickerfetch/testdata, imported by
      SeedMedia in internal/app/files to pin the format on both sides.
    - docs/stickerfetch.md, linked from docs/local-setup.md.
  • docs: document differences from official Telegram and the new options
    Public-only documentation for the issue fixes synced from telesrv:
    
    - docs/telegram-differences.md lists the deliberate differences from
      official Telegram reported in #140 (basic groups, long text, near
      schedule dates, privacy defaults, send rate, pts bookkeeping, push,
      Bot API, withdrawal URLs), each checked against the current code.
    - README: -NoPull/--no-pull for locally built stacks (#136), the
      plain-HTTP LAN withdrawal note (#135), OwpenGram host:port onboarding
      via /owpengram/server-info (#138), and a link to the new page.
    
    Refs #140
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • feat(botapi): add sendChatAction, editMessageCaption, editMessageReplyMarkup (#137)
    Sync private telesrv a0e217b6, the first tier of the #137 coverage map:
    
    - sendChatAction: transient typing-style status like messages.setTyping;
      a private chat needs an existing user, a channel/supergroup an active
      bot membership.
    - editMessageCaption: replaces the caption of a photo/document message;
      a text message returns MESSAGE_HAS_NO_CAPTION instead of having its
      text rewritten.
    - editMessageReplyMarkup: changes only the inline keyboard (omitted
      removes it).
    
    Both edits use the existing durable private/channel edit paths, so pts,
    outbox and fanout match editMessageText. inline_message_id and
    business_connection_id are refused for now. The public edit request has
    no PreserveText (a private message-workflow field), so the public
    gateway re-sends the stored text and entities it reads just before a
    keyboard-only edit; every other file is byte-identical to the private
    commit. The Bot API docs list the new methods.
    
    Refs #137
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • feat(server): serve /owpengram/server-info on the MTProto port (#138)
    Sync private telesrv 165c3c3c. OwpenGram-family clients fill in "Add
    server" from host:port by fetching
    http://<host>:<mtproto port>/owpengram/server-info (and
    /owpengram/server-icon); the same-port HTTP side only knew /apiws*, so
    users had to paste the RSA PEM by hand.
    
    internal/serverinfo serves the PKCS#1 RSA public key, home DC and the
    Server identity name/description/has_icon as JSON, plus the icon bytes,
    with an explicit Content-Length. Everything exposed is public.
    mtprotoedge only gains a SamePortHTTP routing hook for non-WebSocket
    paths. Reachable while TELESRV_WEBSOCKET_ENABLE is on (the default).
    cmd/telesrv/main.go, cmd/telesrv-admin/serversettings.go and the public
    configuration docs keep their existing public differences and received
    only the private hunks/row.
    
    Refs #138
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Merge pull request #151 from shuzq-sh/pr/resale-flat-floor
    fix(star-gifts): use a flat resale price floor instead of the cheapest listing
  • fix(star-gifts): advertise the flat resale floor and pin it in tests
    Maintainer follow-up for the flat resale floor.
    
    - help.getAppConfig advertises stars_stargift_resale_amount_min with
      domain.MinStarGiftResaleStars, so the client's price field and the
      server agree (default config hash 36 -> 37; the TDesktop fallback
      config gets the same key, hash 21 -> 22).
    - TestStarGiftResaleFloorIgnoresTrollListingsPostgres pinned the old
      market floor ("undercut below the real floor" refused) and was not in
      the CI PostgreSQL list. It now pins the new rules: a seller may lower
      their price below the cheapest listing, one Star below the flat minimum
      is refused without changing the listing, the minimum itself is
      accepted, and the troll-proof display floor follows.
    - docs/collectible-gifts.md describes the resale price rules.
    
    Refs: #151
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • fix(star-gifts): refuse upgrades of deleted gifts and align withdrawal docs
    A deleted gift keeps its row, and a user message ref still resolves to it
    by owner and msg_id. The paid upgrade path checked only Converted and
    UniqueGiftID, so an upgrade of a deleted, upgradable gift ran until the
    upgrade_msg_id write found no aggregate row and failed with an internal
    error. The transaction rolled back, but the client got INTERNAL instead
    of STARGIFT_INVALID.
    
    The upgrade form now refuses a deleted gift before issuing a payment
    form, and the upgrade transaction re-checks the lifecycle under the row
    lock. TestStarGiftDeleteBlocksLaterUpgradePostgres pins that no Stars
    are charged and nothing is minted.
    
    docs/collectible-gifts.md described tmp_password as unsupported; main
    issues account.getTmpPassword grants and serves exact Layer 225-231 via
    payments.getStarGiftWithdrawalUrlLegacy with SRP.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • fix(star-gifts): refresh collections and narrow deleteStarGift eligibility
    deleteStarGift removed collection memberships with a bare DELETE, without the
    owner collection advisory lock and without refreshing star_gift_collections.hash,
    so payments.getStarGiftCollections(hash) kept answering NotModified for a
    collection whose membership had changed. The delete now takes the same lock as
    every other terminal transition and goes through removeSavedGiftFromCollections.
    
    The delete is irreversible, so eligibility now matches TDLib's deleteGift
    preconditions: only a plain gift with no Stars attached. Refused: an upgraded
    collectible, a limited-edition or auction release, a gift with a conversion
    value and a gift carrying the sender's prepaid upgrade Stars. A delivered gift
    is never refunded in this tree (refunds settle at the invoice layer before
    delivery), so there is no refunded state to check. Channel gifts stay refused:
    deleting one needs a channel-ownership check that does not exist yet.
    
    The migration CHECK now enforces unique_gift_id IS NULL for the deleted state,
    and the comments that still described the first commit's semantics (burning the
    collectible, refusing listed/offered gifts) are aligned with the code.
  • fix(star-gifts): payments.deleteStarGift only deletes plain received gifts
    A gift that was upgraded into a collectible (NFT) is refused with
    STARGIFT_INVALID: destroying a collectible is a different operation with its
    own financial rules, so this method must never burn one. The store no longer
    touches unique_star_gifts and the listing/offer/withdrawal guards are gone
    with it.
    
    The delete itself is unchanged: the saved gift row survives for the audit
    trail, the gift moves to lifecycle_status='deleted', it leaves every
    collection and disappears from the profile projections.
    
    Covered by TestStarGiftDeleteRefusesUpgradedGiftPostgres, which upgrades a
    gift and asserts the delete is refused and the gift stays active.
  • feat(star-gifts): implement payments.deleteStarGift (Layer 232)
    Layer 232 added payments.deleteStarGift#3cdaf8aa stargift:InputSavedStarGift
    = Bool. The owner removes a received gift from the profile.
    
    The saved gift row survives: upgrade commands, offers and transfers reference
    it, so the delete is a lifecycle transition. The new 'deleted' state lives in
    migration 20261017010003_star_gift_deleted_state; read paths only project
    lifecycle_status='active', so the gift leaves the profile, the account rating
    signal and the saved-gift lists at once. A gift that was upgraded into a
    collectible also burns that collectible, so it can neither be listed nor
    exported afterwards, and it is dropped from every collection.
    
    Refused states (STARGIFT_INVALID): converted, exported, burned, already
    deleted, listed for resale, under a pending purchase offer or under a pending
    withdrawal request. Only the caller may delete their own gift; channel gifts
    are a channel asset (STARGIFT_OWNER_INVALID) and bots are refused
    (BOT_METHOD_INVALID).
  • fix(channels): keep bot invite lookups strict and bots out of broadcasts
    Maintainer reconciliation for #133 (and the #132 Bot API docs).
    
    - A failed bot lookup in the chat_invite filter now aborts the invite
      before any membership write; previously the bot was silently evaluated
      as a human target and reported as privacy-restricted.
    - With bots no longer filtered by chat_invite privacy, inviteToChannel
      could write a bot as a plain member of a broadcast channel. Bots join
      channels only as admins (channels.editAdmin), so inviting one into a
      broadcast now returns USER_BOT before privacy evaluation or any write,
      as TDesktop expects locally and DrKLO consumes.
    - docs/bot-api: setWebhook/deleteWebhook wait up to 20s for an
      in-flight delivery and return 409 only if it is still running.
    
    Refs: #133, #132
    Source: telesrv ee17fb72286257df02a55314e49c25327ddafab7
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • fix(auth): reject invalid confirm-phone identity after policy changes
    A short identity accepted under the lenient phone policy becomes invalid when
    strict validation is enabled. Comparing two empty normalization results let
    invalid input resend or consume the same user's scoped confirmation code.
    Reject invalid input before comparison and keep the original code untouched.
    
    Add normalization, reserved-system-login and policy-switch regressions.
    Clarify the lenient length/unknown-code rules, virtual +888 exception and the
    effect of switching existing deployments to strict validation.
    
    Origin: gramsrv#128
    Origin-Head: 2799e7d24c
    Origin-Merge: 43346f1996
    
    Canonical: telesrv 22a2fc0813cefc1b8bf6f9bb668bd984db0160ea
  • feat(auth): add a phone-number format policy
    TELESRV_CHECK_NUMBER_FORMAT selects the login identity format gate.
    
    The default lenient policy keeps the structural country-code gate and adds a
    fallback for numbers the numbering plan cannot describe, so short and
    unassigned international ranges such as "+7 123" or "+1488" are usable
    login identities. A national number that omits its country calling code
    (a leading trunk zero) stays refused, and the stored identity is canonical
    on every later normalization pass.
    
    The strict policy additionally requires the number to sit in an assigned
    range of a real country calling code, so short and unassigned ranges are
    rejected.
    
    The reserved service number +42777 stays resolvable under both policies so
    auth recognizes it as a system account; SendCode, SignIn and SignUp refuse
    it before any code is issued.
    
    The policy is installed in both the server and the admin process before
    stores and RPC services are constructed, so a number written from the panel
    is judged by the same rules.
  • feat(admin): fold the star giveaway into the Stars & Premium page
    Giveaway was a tab of its own holding one field and one button, which is
    not a job a tab bar should carry. The button now sits at the bottom of the
    Stars & Premium page, next to the per-user grants it belongs with, inside
    a frame with a warned border: it is the only write on the page that
    touches every account at once, and it keeps the same reason -> dry run ->
    confirm flow as every other write.
    
    Commerce drops to three tabs -- Stars & Premium, Prices, Stars balances --
    and the last one is renamed, because "Stars" and "Stars & Premium" in the
    same tab bar read as the same thing. The old /star-issue URL is an alias
    of the Stars & Premium tab, so a bookmark opens the same place and the
    sidebar row stays lit.
    
    The doc generator now prints the alias paths instead of "the bare alias",
    which was written for /messages and said nothing about /star-issue.
  • feat(admin): move gift granting into the Gifts section
    The "Give Gifts" tab lived under Commerce next to prices and stars, which
    made granting a gift look like a monetization action. It belongs with the
    gift catalog and the auctions, so the tab moves to the Gifts section and
    its label is spelled out ("Выдача подарков") instead of repeating the
    section name.
    
    The tab keeps its route and its gifts.read right, so no permission or
    bookmark changes; the page's tab bar now renders the Gifts section.
  • fix(profiles): preserve About privacy and author descriptions
    Hide the complete About projection when privacy disallows it. Return raw
    text to profile/channel editors, and keep author input unchanged on saves.
    Accept export and spaced keys in advisory configuration drift checks, and
    remove the unimplemented signup auto-join setting from the template.
    
    Follow-up to gramsrv#126.
    Canonical-Commit: 823084f5da40b9b410d13eecbc13ffbd4867840e
    Origin-Head: 1336bf6881
    Origin-Merge: 2705f82f07
  • fix(wallet): enforce authorization, custody and response boundaries
    Authenticate existing-balance reads, preserve transaction pagination, return boxed TON Connect event IDs, and propagate missing dependency and provisioning failures. Distinguish import/create replay, clear obsolete custody keys, validate persisted keys on startup, and keep only the written hex key format.
    
    Require explicit wallet activation and avoid advertising unimplemented chain transfers, top-up or gasless capabilities. Preserve immutable gift issuer snapshots, add deterministic PostgreSQL aggregate fixtures, and avoid guessing operator state during a data-only rollback.
    
    Follow-up to #120, #121, #122, #123, #124 and #125. Existing public Stars APIs, catalog prices, packaging and contribution history are preserved.
    
    Validated full Linux Go tests, vet, command builds, module verification, focused PostgreSQL aggregate/upgrade/replay tests, and public privacy/path gates. The partial wallet remains disabled by default; no chain operations or deployment acceptance is claimed.
    
    Co-authored-by: roon9e <roon9e@users.noreply.github.com>
    Co-authored-by: clockerka <clockerka@gmail.com>
  • docs(admin): generate the panel's route and permission tables
    The route and permission tables in docs/admin-panel-api.{en,ru}.md had
    drifted a long way out of date and nothing noticed: permissions.tsx
    exported a dozen section rights the tables never mentioned, the SPA table
    listed routes that no longer existed, and several pages and their rights
    were missing entirely. They are generated from nav.ts, permissions.tsx and
    security.go now, so editing the source and rerunning is the only way they
    move -- and CI runs --check so they cannot rot unnoticed again.
    
    The generator also documents what the panel does now, since the rules it
    follows were only ever in the diff: the sidebar, the tab bars and the
    route table are three views of one declaration in nav.ts, a sibling page
    is a tab rather than a second sidebar row, a right outside
    assignablePermissions() cannot be granted to a named operator, and the
    //go:embed web/dist bundle has to be rebuilt and committed or a src change
    does not ship. AGENTS.md and both API docs carry that, plus a section on
    adding a page in the order that avoids repeating this drift.
    
    docs/giftfetch.md is new, and local-setup.md points at it. Official
    Star-gifts are only reachable with an authorized user session, which is the
    part that actually stops people: the fetch is written up around the QR
    login, the snapshot layout, the validation it performs, and the fact that
    a .session file is a live account credential and belongs outside the
    repository.
    
    One fix to the generator itself. It read nav.ts's tab arrays with a
    non-greedy (?P<tabs>.*?)\]\s*\}, which stops at the first ] followed by a
    } -- the closing bracket of a tab's own aliases: [...] -- so the messages
    section parsed to zero tabs and dropped out of the table with no error
    where all the others were fine. The tabs array is now read by bracket
    matching, and a section that parses to zero tabs raises instead of
    vanishing, because a silently missing section is exactly the failure this
    commit exists to stop.
  • fix(donations): do not take custody of anything until an operator asks
    Crypto donations was on by default on every deployment, and "works out of the
    box" was doing a lot of work in docs/donations.md. Two things happened to any
    server that never wanted the feature:
    
    1. cmd/telesrv called EnsureWallet on first boot whenever the store had no
       wallet row, so a fresh install silently generated a real custodial BIP39
       mnemonic, wrote data/donation_wallet.key, and logged a warning about backing
       it up. The feature could not even run -- no usable chain -- but the custody
       was already created.
    
    2. The seed migration enabled ganache (http://127.0.0.1:7545) and sepolia.
       main.go already skipped a chain with an empty rpc_url, so sepolia was merely
       cosmetic; ganache had a URL, was therefore watchable, and was therefore
       dialled on every boot of every server. There is no Ganache node outside a
       developer's laptop, so each boot logged
    
           donations.ganache  ERROR  donation watcher stopped  dial ganache:
           connection refused
    
       forever, for a feature nobody had turned on -- and an ERROR in a log is what
       an operator pages on.
    
    Now there is a master switch, TELESRV_DONATIONS_ENABLED, default false. Off
    means no wallet, no key file, no chain contacted. The service object is still
    constructed and still handed to the bot and the admin service when it is on,
    and both already treat it as optional -- bots.Service answers /deposit from a
    nil source and admin.Service refuses the chain edit -- so the Donations page
    still renders read-only rather than erroring.
    
    Enabling the switch does not enable any chain. A watcher starts only for a row
    that is enabled *and* carries an RPC URL, which is what domain.DonationChain.
    Watchable already expressed; main.go was simply not applying it before dialling.
    Migration 20261017010000 clears the two seeded rows, and only rows still
    holding the seeded placeholder endpoint, so a deployment with a real endpoint
    already configured is not switched off by the migration.
    
    A watcher that stops is a configuration problem -- an unreachable or
    misconfigured endpoint the operator has to look at -- so it logs a Warn with
    the chain named rather than an unparameterised ERROR. An enabled chain with no
    endpoint now says so once, also at Warn, instead of being skipped silently.
    
    Verified with go build ./..., go vet, and go test over ./internal/config,
    ./internal/admin and ./internal/domain.
    
    Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
  • fix(business): reconcile avatar security and merged data migrations
    Follow up #114, #115, #117 and #119 after canonical integration. Remove
    missing-photo-ID lookup that could reveal a private channel avatar without
    valid membership or access hash. Preserve decoded flags, reject invalid photo
    DCs and retain empty-byte thumbnail writes.
    
    Append a higher-version, idempotent BotFather menu repair so already-upgraded
    databases receive /deletebot; preserve published migrations. Add PostgreSQL
    regressions for menu idempotency, rating boundaries and community avatar writes.
    Clarify that the 100-level ceiling is local policy and rebuild the Admin bundle.
    Store the donation wallet key in the existing persistent server-state volume to
    allow hardened read-only containers to start and restart.
    
    Canonical-Source: c34bc5848602e870b0c2dde6b8d81ecc471c1c85
    Origins: #114, #115, #117, #119
    Validation: full Go tests, vet, command builds, module verification, targeted
    race tests, fresh/populated PostgreSQL upgrades and repeat startup, Admin build,
    normal Docker builds and isolated bridge-network Compose health/STUN/restart.
    Public privacy/path scans passed. No live-client or production acceptance claim.
  • fix(rating): keep admin tone steps proportional; correct level-range docs
    The admin badge tone steps moved from 10/50 and 5/50 of the ladder to
    50/100 and 20/100, which made 'good' 6.25x more expensive in score terms
    instead of preserving the old share of the scale. Levels 20 and 10 on the
    new curve sit on exactly the old score thresholds (10k and 2.5k), so both
    the visible distribution and the tone semantics survive the ladder change.
    
    Docs: levels start at 0 (any score below 25), and a remapped score lands on
    level 2n or 2n+1 -- only the threshold itself maps exactly onto 2n. The
    'official clients render at most 100' bound is observed client behaviour,
    not a schema constant (TL says level:int), and is now labelled as such.
  • fix(rating): run the account level ladder to 100 instead of 50
    The local composite rating capped at MaxAccountRatingLevel = 50 with a
    quadratic threshold of 100 * n^2, so the top rung already cost 250k score
    while a twentieth level cost 40k. Almost every real account scores in the
    low thousands (the activity component is capped at 5k), so the ladder
    collapsed into levels 1..5 with a handful of whale accounts pinned to the
    ceiling.
    
    Raise the ceiling to 100, the highest level official clients render for
    stars_rating, and halve the quadratic unit to 25. The top rung still costs
    the same 250k score, so the change doubles the resolution of the scale
    instead of pushing stored scores out of reach: a score that was level n is
    now level 2n, and the population spreads across the whole ladder.
    
    Migration 20261013010000 re-derives level, current_level_stars and
    next_level_stars from the stored score so profiles and the level-keyed
    leaderboard are correct on startup instead of drifting until the next
    recompute cycle reaches each row. Down is a documented no-op: the curve
    cannot be inverted losslessly, and the read model is rebuilt from live
    signals anyway.
    
    Add a domain test that pins the 100-level ladder, the 250k ceiling, the
    strictly increasing thresholds and the exact-threshold behaviour the
    progress bar depends on. Update the memory store expectations, rescale the
    admin badge tone steps to the new ladder, and document the scale in the
    configuration references.
    
    Validation: full go tests over ./internal/... and ./cmd/..., go vet, gofmt
    and tsc --noEmit for the admin UI. The SQL re-derivation was cross-checked
    against domain.AccountRatingLevelForStars over every score from 0 to 300000
    plus 1e9 and -7 with zero mismatches, and the migration chain applies from
    scratch to head 20261013010000.
  • fix(business): reconcile main migrations and lifecycle regressions
    Restore migration uniqueness, invoice transaction boundaries, gift wallet
    spending and market suspension, profile pagination, ordinary crafting,
    channel history guards and stable long-message replay. Bound shared audio
    transcription jobs and verify canonical successful donation transfers before
    credit. Rebuild Admin assets from current source and remove obsolete ignored
    wallet RPC tests for unavailable protocol methods.
    
    Canonical-Source: telesrv 3a84827a7870cc79b2c66d50e3605b21996c04a9
    Reviewed-Public-Head: 4e244d238f
    
    Validation: full Go tests and vet; fresh PostgreSQL gift/invoice suites;
    transaction failure and concurrent replay; transcription/donation race tests;
    Admin TypeScript/Vite build; public path and secret scans. Live client,
    blockchain and external-provider acceptance remain deployment gates.
    
    Preserve the original contributor commits and independent repository history.
    
    Co-authored-by: SandyTAP <Zankin12@Yandex.ru>
    Co-authored-by: roonge <44918054+roon9e@users.noreply.github.com>
    Co-authored-by: RickPrime <exdpollo52@gmail.com>
    Co-authored-by: clockerka <clockerka@gmail.com>
  • add
  • add
  • fix(stargifts): forbid converting gifts sent by bots
    Bot API sendGift spends the bot's Stars wallet (bot_stars_balances), so
    crediting the recipient on conversion would let any gift cash the bot's
    spend out into a personal balance. Zero convert_stars at purchase for
    BuyerIsBot, refuse conversion server-side (backstop is the sender's
    users.is_bot flag, independent of data state) and migrate already-sent,
    unconverted bot gifts to convert_stars = 0. Human buyers keep the
    catalog convert price.