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() +})