feat(bots): AI-answer settings + claim-winnings UI for existing bots

Two gaps found while answering "where can I change the API key for
existing users from a webhook":

1. The AI-answer API key ("let BotFights answer for me") could only
   ever be set at the exact moment of bot creation on JoinBoutPage,
   because that's the only place the bot's own secret is ever in the
   browser's hands (Authorization: Bot <id>:<secret> was the sole auth
   path for POST/GET/DELETE /api/bots/ai-config). An existing bot's
   owner had no way back in to add, change, or remove their key later.

   Fixed: new owner-scoped routes at /api/bots/:name/ai-config
   (GET/POST/DELETE), authorized via verifyBotOwner (nostr JWT OR the
   bot's own secret — see bot-auth.ts), reusing the same underlying
   ai-bot-config storage. Wired into BotProfilePage's existing
   owner-only settings area, mirroring the webhook-management section's
   UX pattern (collapsed toggle, provider picker, masked key input,
   configured/remove state).

2. Investigating the payout side of the same question ("can we confirm
   the fighter wins all the cashu sats into their node wallet
   automatically") surfaced that GET /winnings/:botId and POST
   /claim/:paymentId existed on the backend but had NO frontend caller
   anywhere — a Cashu payout (the common case: winner has no NWC/
   Lightning-address wallet linked) minted a token that was completely
   invisible in the UI.

   Added a "claim your winnings" section to BotProfilePage, shown
   proactively (not behind a toggle — it's the owner's own money):
   lists unclaimed payouts with a CLAIM button, reveals the bearer
   token once claimed with a copy-to-clipboard action and guidance to
   paste it into any Cashu wallet (there's no "auto-deposit" for a
   bearer token the way NWC allows for Lightning — no destination
   address to push to).

Route-shadowing note: /:name/ai-config is a different segment count
than the existing bare /ai-config and /:name routes, so it can't
collide with either (unlike the /poll vs /:id and /ai-config vs /:name
bugs fixed earlier this session) — confirmed via the full route table.

13 new/updated tests in ai-config.test.ts (owner-JWT auth, wrong-owner
403, bot-secret still works via verifyBotOwner, no-auth 401). Full
server suite: 815/816 passing (only the same pre-existing CPU-load-
sensitive constant-time-comparison flake, confirmed unrelated and
passing in isolation). tsc --noEmit clean (server + frontend).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-07-31 14:54:40 -04:00
co-authored by Claude
parent c162d5ebe9
commit 41f1b93e9e
3 changed files with 378 additions and 1 deletions
+67
View File
@@ -2,11 +2,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
// Mock DB: authenticateBot looks up a bot by id via db.select(...).from(...).where(...).limit(...)
const TEST_PUBKEY = 'b'.repeat(64)
const mockBotRow = {
id: 'bot_test123',
name: 'testbot',
secretHash: 'aa'.repeat(32), // placeholder; overridden per-test via crypto mock below
webhookUrl: 'http://poll.local/',
publicKey: TEST_PUBKEY,
}
vi.mock('../db/index.js', () => ({
@@ -52,11 +54,13 @@ const REAL_SECRET = 'test-bot-secret-1234567890'
mockBotRow.secretHash = createHash('sha256').update(REAL_SECRET).digest('hex')
const { botsRouter } = await import('./bots.js')
const { createJwt } = await import('../middleware/jwt.js')
const app = new Hono()
app.route('/api/bots', botsRouter)
const AUTH = { Authorization: `Bot ${mockBotRow.id}:${REAL_SECRET}` }
const OWNER_JWT_AUTH = { Authorization: `Bearer ${createJwt(TEST_PUBKEY)}` }
beforeEach(() => { store.clear() })
@@ -131,3 +135,66 @@ describe('bots ai-config routes', () => {
expect(res.status).toBe(401)
})
})
// --- Existing-bot owner settings page: /api/bots/:name/ai-config ---
// These exist because the routes above require the bot's own secret, which
// is only ever available at the exact moment of creation (JoinBoutPage) —
// there was previously no way to add/change/remove an AI key for a bot
// after that moment, even for its nostr-logged-in owner.
describe('bots :name/ai-config routes (existing-bot owner settings)', () => {
it('GET /api/bots/:name/ai-config with a valid owner JWT returns configured status', async () => {
const res = await app.request('/api/bots/testbot/ai-config', { headers: OWNER_JWT_AUTH })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ configured: false, provider: null })
})
it('POST /api/bots/:name/ai-config with a valid owner JWT sets the config', async () => {
const res = await app.request('/api/bots/testbot/ai-config', {
method: 'POST',
headers: { ...OWNER_JWT_AUTH, 'Content-Type': 'application/json' },
body: JSON.stringify({ provider: 'anthropic', apiKey: 'sk-ant-fake-key-value' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ configured: true, provider: 'anthropic' })
// Same underlying storage as the bot-secret path — visible either way.
const check = await app.request('/api/bots/ai-config', { headers: AUTH })
expect(await check.json()).toEqual({ configured: true, provider: 'anthropic' })
})
it('DELETE /api/bots/:name/ai-config with a valid owner JWT removes the config', async () => {
await app.request('/api/bots/testbot/ai-config', {
method: 'POST',
headers: { ...OWNER_JWT_AUTH, 'Content-Type': 'application/json' },
body: JSON.stringify({ provider: 'openai', apiKey: 'sk-openai-fake-key-value' }),
})
const del = await app.request('/api/bots/testbot/ai-config', { method: 'DELETE', headers: OWNER_JWT_AUTH })
expect(del.status).toBe(200)
const check = await app.request('/api/bots/testbot/ai-config', { headers: OWNER_JWT_AUTH })
expect(await check.json()).toEqual({ configured: false, provider: null })
})
it('rejects a JWT for a DIFFERENT pubkey than the bot owner (403)', async () => {
const wrongOwnerJwt = { Authorization: `Bearer ${createJwt('c'.repeat(64))}` }
const res = await app.request('/api/bots/testbot/ai-config', {
method: 'POST',
headers: { ...wrongOwnerJwt, 'Content-Type': 'application/json' },
body: JSON.stringify({ provider: 'anthropic', apiKey: 'sk-ant-fake-key-value' }),
})
expect(res.status).toBe(403)
})
it('rejects requests with no auth at all (401)', async () => {
const res = await app.request('/api/bots/testbot/ai-config')
expect(res.status).toBe(401)
})
it('also accepts the bot\'s own secret (Authorization: Bot id:secret) via verifyBotOwner', async () => {
const res = await app.request('/api/bots/testbot/ai-config', {
method: 'POST',
headers: { ...AUTH, 'Content-Type': 'application/json' },
body: JSON.stringify({ provider: 'openai', apiKey: 'sk-openai-fake-key-value' }),
})
expect(res.status).toBe(200)
})
})
+72 -1
View File
@@ -9,7 +9,7 @@ import { isAllowedWebhookUrl } from '../engine/orchestrator.js'
import { testWebhook } from '../engine/webhook-test.js'
import { rateLimit } from '../middleware/rate-limit.js'
import { botNameSchema, httpUrlSchema } from '../lib/validators.js'
import { authenticateBot } from '../middleware/bot-auth.js'
import { authenticateBot, verifyBotOwner } from '../middleware/bot-auth.js'
import { setAiBotConfig, getAiBotConfig, deleteAiBotConfig, type LlmProvider } from '../engine/ai-bot-config.js'
export const botsRouter = new Hono()
@@ -193,6 +193,77 @@ botsRouter.delete('/ai-config', async (c) => {
return c.json({ configured: false })
})
// --- Same feature, for an EXISTING bot's owner settings page ---
// The routes above require the bot's own secret (Authorization: Bot
// <id>:<secret>), which only the JoinBoutPage bot-creation flow has in hand
// at the moment of creation — it's never persisted anywhere the browser can
// re-fetch it. Before this, there was no way for an existing bot's owner to
// add, change, or remove their AI key later; they'd have to still be on the
// exact creation tab. These are owner-scoped by :name + nostr JWT
// (verifyBotOwner also accepts the bot's own secret, so an AI agent that
// happens to hold both could use either path — no harm either way).
//
// MUST be registered before GET /:name below for the same reason as
// /ai-config above (Hono resolves same-segment-count routes in registration
// order) — but :name/ai-config is a DIFFERENT segment count than :name, so
// it can't actually collide with it; kept adjacent for readability, not
// because ordering is load-bearing here.
botsRouter.get('/:name/ai-config', async (c) => {
const name = c.req.param('name')
const rows = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase()))
.limit(1)
if (rows.length === 0) return c.json({ error: 'Bot not found.' }, 404)
const ownerCheck = await verifyBotOwner(c, rows[0].id)
if (ownerCheck !== true) return ownerCheck
const config = getAiBotConfig(rows[0].id)
return c.json({ configured: !!config, provider: config?.provider ?? null })
})
botsRouter.post('/:name/ai-config', rateLimit(60_000, 10), async (c) => {
const name = c.req.param('name')
const rows = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase()))
.limit(1)
if (rows.length === 0) return c.json({ error: 'Bot not found.' }, 404)
const ownerCheck = await verifyBotOwner(c, rows[0].id)
if (ownerCheck !== true) return ownerCheck
const body = await c.req.json().catch(() => ({})) as { provider?: string; apiKey?: string }
const provider = body.provider
const apiKey = body.apiKey?.trim()
if (!provider || !AI_PROVIDERS.includes(provider as LlmProvider)) {
return c.json({ error: `provider must be one of: ${AI_PROVIDERS.join(', ')}` }, 400)
}
if (!apiKey || apiKey.length < 8 || apiKey.length > 512) {
return c.json({ error: 'apiKey is required (8-512 chars).' }, 400)
}
setAiBotConfig(rows[0].id, { provider: provider as LlmProvider, apiKey })
return c.json({ configured: true, provider })
})
botsRouter.delete('/:name/ai-config', async (c) => {
const name = c.req.param('name')
const rows = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase()))
.limit(1)
if (rows.length === 0) return c.json({ error: 'Bot not found.' }, 404)
const ownerCheck = await verifyBotOwner(c, rows[0].id)
if (ownerCheck !== true) return ownerCheck
deleteAiBotConfig(rows[0].id)
return c.json({ configured: false })
})
// Get single bot profile
botsRouter.get('/:name', async (c) => {
const name = c.req.param('name')