import { Hono, type Context } from 'hono' import type { AppEnv, Deps } from './context.ts' const WINDOW_MS = 60_000 const MAX_PER_WINDOW = 60 /** * Run a command with the channel's API key, for Stream Deck buttons and similar tools. * * GET /api/hooks/command?key=&command=!count deaths +1 * POST /api/hooks/command Authorization: Bearer {"command": "!count deaths +1"} * * The command runs as the broadcaster and the bot answers in chat as usual. * GET is allowed because Stream Deck's built-in Website action can only send GET requests. */ export function hookRoutes(deps: Deps) { const { store, manager } = deps const app = new Hono() const recent = new Map() const keyFrom = (c: Context) => { const auth = c.req.header('authorization')?.match(/^Bearer\s+(.+)$/i)?.[1] return (auth ?? c.req.header('x-api-key') ?? c.req.query('key') ?? '').trim() } const commandFrom = async (c: Context) => { const fromQuery = c.req.query('command') if (fromQuery !== undefined || c.req.method === 'GET') return fromQuery ?? '' const type = c.req.header('content-type') ?? '' if (type.includes('application/json')) { const body = (await c.req.json().catch(() => null)) as { command?: unknown } | null return typeof body?.command === 'string' ? body.command : '' } return c.req.text() } const limited = (channelId: string) => { const now = Date.now() const hits = (recent.get(channelId) ?? []).filter((t) => now - t < WINDOW_MS) if (hits.length >= MAX_PER_WINDOW) return true hits.push(now) recent.set(channelId, hits) return false } const run = async (c: Context) => { c.header('cache-control', 'no-store') const key = keyFrom(c) const channel = key ? store.channelForApiKey(key) : undefined if (!channel || channel.kind !== 'channel') return c.json({ error: 'Invalid API key.' }, 401) const command = (await commandFrom(c)).trim() if (!command) return c.json({ error: 'Add the command to run, e.g. ?command=!count deaths +1' }, 400) if (command.length > 500) return c.json({ error: 'Commands can be at most 500 characters.' }, 400) if (!channel.bot_joined) return c.json({ error: 'Superbot isn’t in your channel. Join it from the dashboard first.' }, 409) if (limited(channel.id)) return c.json({ error: 'Too many requests. Try again in a minute.' }, 429) const rt = manager.runtimeFor(channel.id) if (!rt) return c.json({ error: 'Channel not found.' }, 404) const { handled, steps } = await rt.runAsBroadcaster(command) if (!handled) return c.json({ ok: false, error: `No command matched “${command}”.`, steps }, 404) return c.json({ ok: true, steps }) } app.get('/command', run) app.post('/command', run) return app }