feat: add tma authorization middleware

This commit is contained in:
devilreef 2026-04-29 12:14:18 +06:00
parent 22eb41b0bc
commit 4a8b0ac806
Signed by: devilreef
SSH key fingerprint: SHA256:UZisRr4iuXx+IhkbZnR655L2RWAT6o2rgbGv5F/6m3Y

28
src/middleware/auth.ts Normal file
View file

@ -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<AuthEnv>(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()
})