Skip to content

Add accessor for raw initData string #146

@RAprogramm

Description

@RAprogramm

Problem

The SDK provides init_sdk() to parse and validate initData, but does not expose a way to retrieve the raw initData string after initialization. This forces developers to manually access window.Telegram.WebApp.initData using JavaScript reflection.

Current Workaround

fn raw_init_data() -> Result<String, JsValue> {
    let win = window().ok_or_else(|| JsValue::from_str("no window"))?;
    let tg = Reflect::get(&win, &JsValue::from_str("Telegram"))?;
    let webapp = Reflect::get(&tg, &JsValue::from_str("WebApp"))?;
    Reflect::get(&webapp, &JsValue::from_str("initData"))?
        .as_string()
        .ok_or_else(|| JsValue::from_str("initData is not a string"))
}

This is verbose, error-prone, and duplicates environment detection logic.

Use Case

Backend authentication requires sending the raw initData string:

// Need raw initData for server-side validation
let raw = raw_init_data()?;
login_telegram(api_url, &raw).await?;

The server validates the signature using the raw string, so parsed data is insufficient.

Proposed Solution

Add a method to retrieve raw initData from initialized context:

impl TelegramWebApp {
    /// Get the raw initData string from Telegram WebApp.
    ///
    /// Returns the URL-encoded initData as provided by Telegram,
    /// suitable for server-side signature validation.
    ///
    /// # Errors
    ///
    /// Returns `Err` if:
    /// - SDK has not been initialized
    /// - initData is not available
    /// - initData is not a string
    pub fn raw_init_data() -> Result<String, JsValue> {
        let instance = Self::instance()
            .ok_or_else(|| JsValue::from_str("SDK not initialized"))?;
        
        // Access via js-sys bindings
        Reflect::get(instance.inner(), &JsValue::from_str("initData"))?
            .as_string()
            .ok_or_else(|| JsValue::from_str("initData is not a string"))
    }
}

Alternatively, store the raw initData during init_sdk() and provide accessor:

pub fn get_raw_init_data() -> Option<String> {
    CONTEXT.with(|ctx| {
        ctx.borrow().as_ref().map(|c| c.raw_init_data.clone())
    })
}

Benefits

  1. Eliminates boilerplate in consuming applications
  2. Centralizes environment access logic
  3. Makes authentication flows cleaner
  4. Prevents errors from incorrect Reflect usage
  5. Maintains single source of truth for WebApp access

Related

This complements issue about environment detection API, as both aim to reduce manual JavaScript interop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions