Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about docs, how to validate WebApp.initDataUnsafe ? #21

Open
painkkiller opened this issue Sep 8, 2024 · 4 comments
Open

Question about docs, how to validate WebApp.initDataUnsafe ? #21

painkkiller opened this issue Sep 8, 2024 · 4 comments

Comments

@painkkiller
Copy link

painkkiller commented Sep 8, 2024

I am using @twa-dev/sdk and when my TWA application starts I am getting WebApp.initDataUnsafe. I need to validate it according the docs. And I use code from the docs.
The main problem that my hashes never equal. In my WebApp.initDataUnsafe there is object user, and looks that it ignored during this check, it included in the checkstring as user=>[object Object] and probably thats the cause of the problem. But removing it doesn't solve the issue. So it needs to clarify the format of the object required for valudation.

@MKRhere
Copy link
Member

MKRhere commented Sep 8, 2024

@painkkiller
Copy link
Author

Have you checked this yet?

https://github.com/feathers-studio/telegraf-docs/tree/master/examples/mini-apps#validating-initdata

I've provided the link to this document in my question

@MKRhere
Copy link
Member

MKRhere commented Sep 8, 2024

Ah, you're right. Let me fix that. Give me a few minutes.

@painkkiller
Copy link
Author

painkkiller commented Sep 9, 2024

This code works for me (it correctly handles user object in WebApp.initDataUnsafe)

  app.post('/api/validate', function (req, res) {

        const hash = req.body.hash;

        delete req.body.hash;

        const dataCheckString = Object.entries(req.body).sort().map(([k, v]) => {
            if (typeof v === "object" && v !== null) {
                v = JSON.stringify(v);
            }
            
            return `${k}=${v}`;
        }).join("\n");

        const secret = createHmac("sha256", "WebAppData").update(process.env.BOT_TOKEN ?? "");
        const _hash = createHmac("sha256", secret.digest()).update(dataCheckString).digest("hex");

        console.log('|', dataCheckString, '|', hash, _hash);
    
        if (hash === _hash) {
            return res.json(req.body);
        }

	    return res.status(401).json({});
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants