Developer docs

Telvoro Web Bridge Protocol v1 (normative)

On this page

The protocol between web content (a mini app, or an interactive HTML card in a message) and the host (a Telvoro client). A third-party Telvoro client can implement the host side from this document alone; content authors normally use the SDKs in sdk/js (@televo/webapp, @televo/card) instead of speaking it directly.

Security requirements for hosts (isolation, link policy, UI chrome) are in MINIAPPS.md; this document covers the wire protocol. “MUST”, “SHOULD” follow RFC 2119.

1. Messages

Every message is one JSON text (a UTF-8 string, not a structured-clone object), at most 65 536 bytes. Three shapes:

// request: content → host
{ "v": 1, "id": 7, "method": "openLink", "params": { "url": "https://example.com" }, "token": "…" }
// response: host → content (exactly one per request that has an id)
{ "v": 1, "id": 7, "result": { "opened": true } }
{ "v": 1, "id": 7, "error": { "code": "USER_DECLINED", "message": "…" } }
// event: host → content
{ "v": 1, "event": "themeChanged", "data": { "theme": { … } } }
FieldRules
vprotocol version selected in the handshake (§3); 1 for this spec
idinteger 1…2³⁰, unique per page load; optional — requests without id are fire-and-forget (no response)
methodone of §5 / §6; unknown → UNKNOWN_METHOD
paramsobject (default {}); validated against the method’s schema; unknown fields → INVALID_PARAMS
tokenchannel token from the init event, when the host provided one (§2.2)

Hosts MUST reject (no response) requests that fail authentication (§2), and answer every other request that has an id with result or error. Content MUST ignore responses for unknown ids and unknown events.

2. Transports and authentication

2.1 Channels per platform

Host platformcontent → hosthost → contentSender authentication
Browser (host page embeds content in an <iframe>)window.parent.postMessage(json, hostOrigin)iframe.contentWindow.postMessage(json, contentOrigin) (cards: "*", opaque origin)event.source === iframe.contentWindow and event.origin ∈ allowed origins (cards: "null")
iOS / macOS WKWebViewwindow.webkit.messageHandlers.televo.postMessage(json)evaluateJavaScript("window.TelevoBridge.receive(<json string literal>)") in the main frameWKScriptMessage.frameInfo.isMainFrame and securityOrigin ∈ allowed; or channel token
Android WebView (preferred)WebMessagePort delivered with the init event (§2.3)same portthe port is posted only to the main frame with targetOrigin = app origin
Android WebView (JS interface)window.televo.postMessage(json) (@JavascriptInterface with a single postMessage(String))evaluateJavascript(...) as abovechannel token (the interface is visible to all frames)
Windows WebView2window.chrome.webview.postMessage(json)PostWebMessageAsString(json)CoreWebView2.Source origin ∈ allowed (top-level only) or channel token

Content-side detection order (used by the SDKs): webkit.messageHandlers.televo → televo.postMessage (JS interface) → chrome.webview → parent (if window.parent !== window). Host → content via script evaluation always calls window.TelevoBridge.receive(jsonString); SDKs define it.

2.2 Channel token

When the platform cannot tell which frame sent a message (Android JS interface, webview_flutter channels), the host generates a 128-bit random token per page load and delivers it only to the main frame in the init event. Content echoes it in every request ("token"); requests with a missing or wrong token are dropped silently. Cross-origin sub-frames never see the token. Hosts compare tokens in constant time. The token is not a credential for anything else and is never sent to any server.

2.3 Handshake

  1. After every main-frame load the host sends the init event (main frame only; browser hosts: postMessage to the expected origin after the iframe load):
    { "v": 1, "event": "init", "data": {
        "protocol": { "min": 1, "max": 1 },
        "token": "q9V3…",            // optional, see §2.2
        "context": "webapp",          // or "card"
        "platform": "ios",            // ios | android | macos | windows | linux | web
        "methods": ["openLink", …],   // methods this host implements for this context
        "theme": { …ThemeParams },
        "viewport": { "height": 640, "stableHeight": 640, "expanded": true },
        "safeArea": { "top": 0, "bottom": 34, "left": 0, "right": 0 },
        "lang": "en",
        "port": true                  // Android: a MessagePort is attached to this message
    } }
    
    Browser content MUST remember the origin of this message and only accept later host messages from that origin and from window.parent.
  2. Content replies with handshake: { "method": "handshake", "params": { "versions": [1], "sdk": "@televo/[email protected]" } }.
  3. Host answers { "result": { "version": 1, "methods": [...] } } — the highest version in both ranges — or VERSION_UNSUPPORTED. Content uses version as v from then on.
  4. Requests sent before the handshake completes are queued by the SDKs.

Launch data (init_data, start_param, …) for mini apps is in the URL fragment, not in init (§7).

3. Versioning

Additive changes (new methods, events, optional params, result fields) do not change v; content uses methods from the handshake for feature detection. Breaking changes bump v; hosts SHOULD support the previous version for at least 12 months.

4. Errors

codeMeaning
INVALID_REQUESTnot JSON / bad envelope / too large (only sent when id is readable)
UNKNOWN_METHODmethod not in this context
INVALID_PARAMSschema violation; message names the field
UNSUPPORTEDdefined method the host doesn’t implement on this platform
VERSION_UNSUPPORTEDhandshake: no common version
RATE_LIMITED§8 limits; data.retryAfterMs may be present
BUSYa host dialog for this content is already open
NOT_ALLOWEDrejected by policy (e.g. javascript: URL, wrong context)
USER_DECLINEDthe user cancelled a confirmation
INTERNALhost-side failure

5. Mini app methods (context: "webapp")

Types: Color = "#RRGGBB"; strings are limited by the max shown.

MethodParamsResultNotes
handshakeversions: int[] (≤8), sdk?: string(64){version, methods}no token needed for browser hosts
ready—{}app finished first render; host hides its loader
expand—{}
close—{}host asks the user if closing confirmation is on
requestFullscreen / exitFullscreen—{isFullscreen}host chrome collapses to a pill, never disappears
setBackgroundColorcolor: Color{}
setClosingConfirmationenabled: bool{}
setMainButton / setSecondaryButtontext?: string(64), visible?, active?, progress?, color?: Color, textColor?: Color, position? (`leftrighttop
setBackButton / setSettingsButtonvisible: bool{}
openLinkurl: string(2048){opened: bool}https only (http with warning); always confirmed by the user; external browser
openInternalLinkurl: string(512){opened}televo:// routes user, chat, join, addstickers, app only
sendDatadata: string(4096){}needs a query_id; once per launch; confirmed; host then closes the app
showPopuptitle?: string(64), message: string(256), buttons?: [{id?: string(64), type?: default|ok|close|cancel|destructive, text?: string(64)}] (≤3){buttonId} ("" = dismissed)
requestWriteAccess—{status: "allowed"|"cancelled"}
requestContact—{status}allowed → the server shares the user’s phone with the bot
requestLocation—{status}allowed → the web view may use navigator.geolocation
downloadFileurl: string(2048) (https), fileName: string(255) (no path separators/control chars){downloaded: bool}confirmed
hapticFeedbacktype: impact|notification|selection, style?: light|medium|heavy|rigid|soft|error|success|warning{}

Not in v1 (no protocol support yet): cloud storage, QR scanner, biometrics, invoices, clipboard read, home-screen shortcuts. SDKs report them via isSupported() === false.

Mini app events

EventData
init§2.3
themeChanged{theme}
viewportChanged{height, stableHeight, expanded, isStateStable}
safeAreaChanged{top, bottom, left, right}
fullscreenChanged{isFullscreen}
mainButtonClicked / secondaryButtonClicked / backButtonClicked / settingsButtonClicked{}
activated / deactivated{} — app visible / hidden

6. HTML card methods (context: "card")

Cards run with no network access and an opaque origin (MINIAPPS.md §8).

MethodParamsResultNotes
handshakeas above
ready—{}
resizeheight: int 40…640{height}
callbackdata: string(4096){text?, alert?}becomes a bot CallbackQuery with from_html_card = true; the host shows the bot’s answer
openLinkurl: string(2048){opened}same policy as mini apps
openMiniAppshortName: [A-Za-z0-9_]{1,64}{}only the sending bot’s own apps
hapticFeedbackas above{}

Card events: init, themeChanged, stopped ({reason} — sent best-effort before teardown).

7. Launch data (init_data)

Mini app URL fragment: #tvWebAppData=<urlencoded init_data>&tvWebAppVersion=1&tvWebAppPlatform=<p>&tvWebAppThemeParams=<urlencoded JSON>.

init_data is a URL-encoded query string with fields query_id, user (JSON), receiver (JSON), chat (JSON), chat_type, chat_instance, start_param, auth_date, expires_at (unix seconds), hash, signature.

HMAC (bot token, Telegram-compatible): data_check_string = all fields except hash, as key=value (decoded values), sorted by key, joined with \n. secret_key = HMAC_SHA256(key="WebAppData", msg=bot_token); valid iff hex(HMAC_SHA256(key=secret_key, msg=data_check_string)) == hash.

Ed25519 (no bot token needed): check = "<bot_id>:WebAppData\n" + <data_check_string without hash and signature>; valid iff Ed25519-verify(televo_public_key, check, base64url-decode(signature)). The key set is served at GET /.well-known/televo-webapp-key as {"ed25519": "<active key, base64url>", "kid": "<active kid>", "keys": [{"kid", "alg", "key", "status", "expires_at"}]}; verify with the key whose kid equals the kid field of init_data (retired keys stay listed 24 h after rotation). kid is an ordinary field covered by both signatures. Exact rules and a shared test vector: MINIAPPS.md §1.1; the server (server/internal/webapp/vector_test.go) and @televo/validate both reproduce it.

Both: reject if auth_date is older than your limit (recommended ≤ 3600 s) or expires_at is in the past. Validators: sdk/js/packages/validate (Node), and below.

Go
func ValidateHMAC(initData, botToken string, maxAge time.Duration) (url.Values, error) {
	v, err := url.ParseQuery(initData)
	if err != nil { return nil, err }
	hash := v.Get("hash")
	keys := make([]string, 0, len(v))
	for k := range v { if k != "hash" { keys = append(keys, k) } }
	sort.Strings(keys)
	lines := make([]string, len(keys))
	for i, k := range keys { lines[i] = k + "=" + v.Get(k) }
	sk := hmac.New(sha256.New, []byte("WebAppData")); sk.Write([]byte(botToken))
	m := hmac.New(sha256.New, sk.Sum(nil)); m.Write([]byte(strings.Join(lines, "\n")))
	want, _ := hex.DecodeString(hash)
	if !hmac.Equal(m.Sum(nil), want) { return nil, errors.New("bad hash") }
	ts, _ := strconv.ParseInt(v.Get("auth_date"), 10, 64)
	if time.Since(time.Unix(ts, 0)) > maxAge { return nil, errors.New("expired") }
	return v, nil
}

func ValidateEd25519(initData string, botID int64, pub ed25519.PublicKey, maxAge time.Duration) (url.Values, error) {
	v, err := url.ParseQuery(initData)
	if err != nil { return nil, err }
	sig, err := base64.RawURLEncoding.DecodeString(v.Get("signature"))
	if err != nil { return nil, err }
	keys := []string{}
	for k := range v { if k != "hash" && k != "signature" { keys = append(keys, k) } }
	sort.Strings(keys)
	lines := make([]string, len(keys))
	for i, k := range keys { lines[i] = k + "=" + v.Get(k) }
	msg := fmt.Sprintf("%d:WebAppData\n%s", botID, strings.Join(lines, "\n"))
	if !ed25519.Verify(pub, []byte(msg), sig) { return nil, errors.New("bad signature") }
	ts, _ := strconv.ParseInt(v.Get("auth_date"), 10, 64)
	if time.Since(time.Unix(ts, 0)) > maxAge { return nil, errors.New("expired") }
	return v, nil
}
Python (stdlib + PyNaCl for Ed25519)
import hashlib, hmac, time, base64
from urllib.parse import parse_qsl

def _dcs(fields, exclude):
    return "\n".join(f"{k}={v}" for k, v in sorted(fields.items()) if k not in exclude)

def validate_hmac(init_data: str, bot_token: str, max_age: int = 3600) -> dict:
    f = dict(parse_qsl(init_data, keep_blank_values=True, strict_parsing=True))
    secret = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
    calc = hmac.new(secret, _dcs(f, {"hash"}).encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc, f.get("hash", "")):
        raise ValueError("bad hash")
    if time.time() - int(f.get("auth_date", 0)) > max_age:
        raise ValueError("expired")
    return f

def validate_ed25519(init_data: str, bot_id: int, public_key: bytes, max_age: int = 3600) -> dict:
    from nacl.signing import VerifyKey
    f = dict(parse_qsl(init_data, keep_blank_values=True, strict_parsing=True))
    sig = base64.urlsafe_b64decode(f["signature"] + "=" * (-len(f["signature"]) % 4))
    msg = f"{bot_id}:WebAppData\n" + _dcs(f, {"hash", "signature"})
    VerifyKey(public_key).verify(msg.encode(), sig)  # raises BadSignatureError
    if time.time() - int(f.get("auth_date", 0)) > max_age:
        raise ValueError("expired")
    return f

8. Rate limits (host-enforced, per content instance)

WhatLimitError
all requests200 / sRATE_LIMITED
dialogs (showPopup, request*, downloadFile)1 open at a time; 3 / minBUSY / RATE_LIMITED
openLink, openInternalLink, openMiniApp3 / min, not while a dialog is openRATE_LIMITED / BUSY
hapticFeedback20 / sRATE_LIMITED
sendDataonce per launchNOT_ALLOWED
card callback1 / s and 30 / minRATE_LIMITED

9. Conformance checklist (hosts)

  • init only to the main frame, after every main-frame load, with a fresh token
  • Sender authentication per §2.1; unauthenticated → silently dropped
  • Every id gets exactly one response; JSON text only; ≤ 64 KiB
  • Strict schema validation; unknown fields rejected
  • URL policy, confirmations, header chrome per MINIAPPS.md §3–4
  • Limits per §8
  • Cards: subset of §6 only, sandbox + CSP per MINIAPPS.md §8

Generated from docs/WEBAPP_BRIDGE.md in the Telvoro repository. Wire names such as televo.v1 are unchanged.