From 4a8b0ac80625e28d01144ac51c8b7cc0870535c7 Mon Sep 17 00:00:00 2001 From: devilreef Date: Wed, 29 Apr 2026 12:14:18 +0600 Subject: [PATCH] feat: add tma authorization middleware --- src/middleware/auth.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/middleware/auth.ts diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts new file mode 100644 index 0000000..3cf0918 --- /dev/null +++ b/src/middleware/auth.ts @@ -0,0 +1,28 @@ +import { createMiddleware } from 'hono/factory' +import { InitDataError, validateInitData } from '@/lib/initdata.js' +import { config } from '@/shared/config.js' + +export interface AuthEnv { + Variables: { userId: bigint } +} + +export const authMiddleware = createMiddleware(async (c, next) => { + const header = c.req.header('Authorization') ?? '' + const idx = header.indexOf(' ') + const scheme = idx === -1 ? '' : header.slice(0, idx) + const raw = idx === -1 ? '' : header.slice(idx + 1) + if (scheme !== 'tma' || !raw) + return c.json({ error: 'missing-tma-authorization' }, 401) + + try { + const { userId } = validateInitData(raw, config.botToken, config.authDateMaxAgeSeconds) + c.set('userId', userId) + } + catch (e) { + if (e instanceof InitDataError) + return c.json({ error: e.code }, 401) + throw e + } + + await next() +})