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": { … } } }
| Field | Rules |
|---|---|
v | protocol version selected in the handshake (§3); 1 for this spec |
id | integer 1…2³⁰, unique per page load; optional — requests without id are fire-and-forget (no response) |
method | one of §5 / §6; unknown → UNKNOWN_METHOD |
params | object (default {}); validated against the method’s schema; unknown fields → INVALID_PARAMS |
token | channel 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 platform | content → host | host → content | Sender 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 WKWebView | window.webkit.messageHandlers.televo.postMessage(json) | evaluateJavaScript("window.TelevoBridge.receive(<json string literal>)") in the main frame | WKScriptMessage.frameInfo.isMainFrame and securityOrigin ∈ allowed; or channel token |
Android WebView (preferred) | WebMessagePort delivered with the init event (§2.3) | same port | the 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 above | channel token (the interface is visible to all frames) |
| Windows WebView2 | window.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
- After every main-frame load the host sends the
initevent (main frame only; browser hosts:postMessageto the expected origin after the iframeload):
Browser content MUST remember the{ "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 } }originof this message and only accept later host messages from that origin and fromwindow.parent. - Content replies with
handshake:{ "method": "handshake", "params": { "versions": [1], "sdk": "@televo/[email protected]" } }. - Host answers
{ "result": { "version": 1, "methods": [...] } }— the highest version in both ranges — orVERSION_UNSUPPORTED. Content usesversionasvfrom then on. - 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
code | Meaning |
|---|---|
INVALID_REQUEST | not JSON / bad envelope / too large (only sent when id is readable) |
UNKNOWN_METHOD | method not in this context |
INVALID_PARAMS | schema violation; message names the field |
UNSUPPORTED | defined method the host doesn’t implement on this platform |
VERSION_UNSUPPORTED | handshake: no common version |
RATE_LIMITED | §8 limits; data.retryAfterMs may be present |
BUSY | a host dialog for this content is already open |
NOT_ALLOWED | rejected by policy (e.g. javascript: URL, wrong context) |
USER_DECLINED | the user cancelled a confirmation |
INTERNAL | host-side failure |
5. Mini app methods (context: "webapp")
Types: Color = "#RRGGBB"; strings are limited by the max shown.
| Method | Params | Result | Notes |
|---|---|---|---|
handshake | versions: 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 |
setBackgroundColor | color: Color | {} | |
setClosingConfirmation | enabled: bool | {} | |
setMainButton / setSecondaryButton | text?: string(64), visible?, active?, progress?, color?: Color, textColor?: Color, position? (`left | right | top |
setBackButton / setSettingsButton | visible: bool | {} | |
openLink | url: string(2048) | {opened: bool} | https only (http with warning); always confirmed by the user; external browser |
openInternalLink | url: string(512) | {opened} | televo:// routes user, chat, join, addstickers, app only |
sendData | data: string(4096) | {} | needs a query_id; once per launch; confirmed; host then closes the app |
showPopup | title?: 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 |
downloadFile | url: string(2048) (https), fileName: string(255) (no path separators/control chars) | {downloaded: bool} | confirmed |
hapticFeedback | type: 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
| Event | Data |
|---|---|
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).
| Method | Params | Result | Notes |
|---|---|---|---|
handshake | as above | ||
ready | — | {} | |
resize | height: int 40…640 | {height} | |
callback | data: string(4096) | {text?, alert?} | becomes a bot CallbackQuery with from_html_card = true; the host shows the bot’s answer |
openLink | url: string(2048) | {opened} | same policy as mini apps |
openMiniApp | shortName: [A-Za-z0-9_]{1,64} | {} | only the sending bot’s own apps |
hapticFeedback | as 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)
| What | Limit | Error |
|---|---|---|
| all requests | 200 / s | RATE_LIMITED |
dialogs (showPopup, request*, downloadFile) | 1 open at a time; 3 / min | BUSY / RATE_LIMITED |
openLink, openInternalLink, openMiniApp | 3 / min, not while a dialog is open | RATE_LIMITED / BUSY |
hapticFeedback | 20 / s | RATE_LIMITED |
sendData | once per launch | NOT_ALLOWED |
card callback | 1 / s and 30 / min | RATE_LIMITED |
9. Conformance checklist (hosts)
-
initonly to the main frame, after every main-frame load, with a fresh token - Sender authentication per §2.1; unauthenticated → silently dropped
- Every
idgets 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.