feat: comedy overhaul start, profile page, bot setup docs, auth improvements

Rewrites announcer commentary (HYPE_LINES, DEEP_INTROS, ROUND_HYPE) with
modern edgy humor. Adds BOT_SETUP.md, bot SDK, customization engine,
profile page character display, persistent auth, rate limit tweaks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-03-07 08:52:24 +00:00
co-authored by Claude Opus 4.6
parent 4a35e1e0b5
commit 559782c8ce
15 changed files with 1086 additions and 58 deletions
+1
View File
@@ -75,6 +75,7 @@ const migrations = [
`ALTER TABLE bots ADD COLUMN last_fight_at TEXT`,
`ALTER TABLE bots ADD COLUMN consecutive_errors INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE bots ADD COLUMN last_error_at TEXT`,
`ALTER TABLE bots ADD COLUMN customization TEXT`,
]
for (const sql of migrations) {
+1
View File
@@ -19,6 +19,7 @@ export const bots = sqliteTable('bots', {
lastFightAt: text('last_fight_at'),
consecutiveErrors: integer('consecutive_errors').notNull().default(0),
lastErrorAt: text('last_error_at'),
customization: text('customization'),
createdAt: text('created_at').notNull(),
})
+113
View File
@@ -0,0 +1,113 @@
// Bot customization validation
// All values are validated against whitelists to prevent code injection
const VALID_ARCHETYPES = new Set([
'standard', 'lobster', 'sheep', 'cyborg', 'blob', 'tank', 'dog', 'cat',
'cactus', 'pizza', 'mushroom', 'shark', 'penguin', 'octopus', 'skeleton',
'ghost', 'alien', 'dinosaur', 'pirate', 'ninja', 'cowboy', 'wizard',
'bee', 'frog', 'snail', 'robot', 'android', 'drone', 'toaster', 'tv_head',
'calculator', 'satellite', 'mech', 'led_cube', 'circuit', 'antenna_bot',
'microwave', 'cyberdog', 'robocat', 'ufo_bot', 'minotaur', 'unicorn',
'phoenix', 'dragon', 'mermaid', 'griffin', 'cyclops', 'gargoyle', 'golem',
'vampire', 'werewolf', 'zombie', 'witch', 'demon', 'chef', 'firefighter',
'astronaut', 'clown', 'detective', 'nurse', 'lumberjack', 'scientist',
'wrestler', 'boxer', 'gladiator', 'samurai', 'viking', 'knight',
'elephant', 'giraffe', 'hippo', 'lion', 'monkey', 'parrot', 'raccoon',
'snake', 'turtle', 'whale', 'crocodile', 'flamingo', 'hedgehog', 'panda',
'hamster', 'sock_puppet', 'traffic_cone', 'toilet_man', 'potato',
'cloud_man', 'rock_man', 'balloon_man', 'trash_can', 'rubber_duck',
'snowman', 'scarecrow', 'jack_o_lantern', 'garden_gnome', 'lamp_post',
'broom_man',
])
const HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/
const HSL_COLOR_RE = /^hsl\(\d{1,3},\s?\d{1,3}%,\s?\d{1,3}%\)$/
export interface BotCustomization {
archetype?: string
primaryColor?: string
secondaryColor?: string
forceVisor?: boolean
forceMohawk?: boolean
forceHorns?: boolean
}
function isValidColor(c: string): boolean {
return HEX_COLOR_RE.test(c) || HSL_COLOR_RE.test(c)
}
function hexToHsl(hex: string): string {
const r = parseInt(hex.slice(1, 3), 16) / 255
const g = parseInt(hex.slice(3, 5), 16) / 255
const b = parseInt(hex.slice(5, 7), 16) / 255
const max = Math.max(r, g, b), min = Math.min(r, g, b)
const l = (max + min) / 2
if (max === min) return `hsl(0, 0%, ${Math.round(l * 100)}%)`
const d = max - min
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
let h = 0
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
else if (max === g) h = ((b - r) / d + 2) / 6
else h = ((r - g) / d + 4) / 6
return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`
}
export function validateCustomization(raw: unknown): { valid: true; data: BotCustomization } | { valid: false; error: string } {
if (raw == null) return { valid: true, data: {} }
if (typeof raw !== 'object' || Array.isArray(raw)) {
return { valid: false, error: 'Customization must be an object.' }
}
const obj = raw as Record<string, unknown>
const result: BotCustomization = {}
if (obj.archetype !== undefined) {
if (typeof obj.archetype !== 'string' || !VALID_ARCHETYPES.has(obj.archetype)) {
return { valid: false, error: `Invalid archetype. Must be one of: ${[...VALID_ARCHETYPES].slice(0, 10).join(', ')}...` }
}
result.archetype = obj.archetype
}
if (obj.primaryColor !== undefined) {
if (typeof obj.primaryColor !== 'string' || !isValidColor(obj.primaryColor)) {
return { valid: false, error: 'primaryColor must be a valid hex (#RRGGBB) or hsl color.' }
}
result.primaryColor = HEX_COLOR_RE.test(obj.primaryColor) ? hexToHsl(obj.primaryColor) : obj.primaryColor
}
if (obj.secondaryColor !== undefined) {
if (typeof obj.secondaryColor !== 'string' || !isValidColor(obj.secondaryColor)) {
return { valid: false, error: 'secondaryColor must be a valid hex (#RRGGBB) or hsl color.' }
}
result.secondaryColor = HEX_COLOR_RE.test(obj.secondaryColor) ? hexToHsl(obj.secondaryColor) : obj.secondaryColor
}
if (obj.forceVisor !== undefined) {
if (typeof obj.forceVisor !== 'boolean') return { valid: false, error: 'forceVisor must be a boolean.' }
result.forceVisor = obj.forceVisor
}
if (obj.forceMohawk !== undefined) {
if (typeof obj.forceMohawk !== 'boolean') return { valid: false, error: 'forceMohawk must be a boolean.' }
result.forceMohawk = obj.forceMohawk
}
if (obj.forceHorns !== undefined) {
if (typeof obj.forceHorns !== 'boolean') return { valid: false, error: 'forceHorns must be a boolean.' }
result.forceHorns = obj.forceHorns
}
// Reject any unexpected keys
const allowedKeys = new Set(['archetype', 'primaryColor', 'secondaryColor', 'forceVisor', 'forceMohawk', 'forceHorns'])
for (const key of Object.keys(obj)) {
if (!allowedKeys.has(key)) {
return { valid: false, error: `Unknown customization key: ${key}` }
}
}
return { valid: true, data: result }
}
export function getArchetypeList(): string[] {
return [...VALID_ARCHETYPES].sort()
}
+6
View File
@@ -1,5 +1,7 @@
import type { Context, Next } from 'hono'
const isDev = process.env.NODE_ENV !== 'production'
const hitCounts = new Map<string, { count: number; resetAt: number }>()
// Cleanup stale entries every 5 minutes
@@ -12,6 +14,8 @@ setInterval(() => {
export function rateLimit(windowMs: number, maxHits: number) {
return async (c: Context, next: Next) => {
if (isDev) return next()
const key = c.req.header('x-forwarded-for') || c.req.header('cf-connecting-ip') || 'unknown'
const now = Date.now()
const entry = hitCounts.get(key)
@@ -34,6 +38,8 @@ const botHitCounts = new Map<string, number>()
export function botRateLimit(cooldownMs: number) {
return async (c: Context, next: Next) => {
if (isDev) return next()
const botId = c.req.param('botId')
if (!botId) return next()
+42 -8
View File
@@ -4,6 +4,7 @@ import { createHash, randomBytes } from 'crypto'
import { db, schema } from '../db/index.js'
import { eq, sql } from 'drizzle-orm'
import { isAllowedWebhookUrl } from '../engine/orchestrator.js'
import { validateCustomization } from '../engine/customization.js'
import { testWebhook } from '../engine/webhook-test.js'
import { rateLimit } from '../middleware/rate-limit.js'
@@ -31,19 +32,27 @@ authRouter.post('/login', async (c) => {
bestStreak: schema.bots.bestStreak,
tier: schema.bots.tier,
isActive: schema.bots.isActive,
customization: schema.bots.customization,
}).from(schema.bots).where(eq(schema.bots.publicKey, pubkey)).limit(1)
if (rows.length === 0) {
return c.json({ exists: false, pubkey })
}
return c.json({ exists: true, bot: rows[0] })
const bot = rows[0]
return c.json({
exists: true,
bot: {
...bot,
customization: bot.customization ? JSON.parse(bot.customization) : null,
},
})
})
// Register a new bot with Nostr pubkey
authRouter.post('/register', rateLimit(3600_000, 5), async (c) => {
const body = await c.req.json()
const { pubkey, name, webhookUrl, archetype, profilePicUrl } = body
const { pubkey, name, webhookUrl, archetype, profilePicUrl, customization: rawCustomization } = body
if (!pubkey || typeof pubkey !== 'string' || pubkey.length !== 64) {
return c.json({ error: 'Invalid pubkey.' }, 400)
@@ -57,6 +66,12 @@ authRouter.post('/register', rateLimit(3600_000, 5), async (c) => {
return c.json({ error: 'Name must be alphanumeric, hyphens, or underscores.' }, 400)
}
// Validate customization
const custResult = validateCustomization(rawCustomization)
if (!custResult.valid) {
return c.json({ error: custResult.error }, 400)
}
const normalizedName = name.toLowerCase()
if (!webhookUrl || typeof webhookUrl !== 'string') {
@@ -106,37 +121,42 @@ authRouter.post('/register', rateLimit(3600_000, 5), async (c) => {
const id = nanoid(12)
const secret = randomBytes(32).toString('hex')
const effectiveArchetype = custResult.data.archetype || archetype || 'standard'
const custJson = Object.keys(custResult.data).length > 0 ? JSON.stringify(custResult.data) : null
await db.insert(schema.bots).values({
id,
name: normalizedName,
webhookUrl,
avatarSeed: normalizedName,
archetype: archetype || 'standard',
archetype: effectiveArchetype,
secretHash: createHash('sha256').update(secret).digest('hex'),
publicKey: pubkey,
profilePicUrl: profilePicUrl || null,
customization: custJson,
createdAt: new Date().toISOString(),
})
return c.json({
id,
name: normalizedName,
archetype: archetype || 'standard',
archetype: effectiveArchetype,
customization: custResult.data,
webhookLatencyMs: testResult.latencyMs,
message: 'Bot registered. Webhook verified.',
}, 201)
})
// Update bot webhook (requires pubkey match)
// Update bot webhook and/or customization (requires pubkey match)
authRouter.post('/update', async (c) => {
const body = await c.req.json()
const { pubkey, webhookUrl, profilePicUrl } = body
const { pubkey, webhookUrl, profilePicUrl, customization: rawCustomization } = body
if (!pubkey || typeof pubkey !== 'string') {
return c.json({ error: 'Invalid pubkey.' }, 400)
}
const rows = await db.select({ id: schema.bots.id })
const rows = await db.select({ id: schema.bots.id, customization: schema.bots.customization })
.from(schema.bots)
.where(eq(schema.bots.publicKey, pubkey))
.limit(1)
@@ -151,7 +171,6 @@ authRouter.post('/update', async (c) => {
if (!isAllowedWebhookUrl(webhookUrl)) {
return c.json({ error: 'webhookUrl must not point to private/internal addresses.' }, 400)
}
// Test new webhook before accepting
const testResult = await testWebhook(webhookUrl)
if (!testResult.reachable || !testResult.validResponse) {
return c.json({
@@ -166,6 +185,21 @@ authRouter.post('/update', async (c) => {
if (profilePicUrl) updates.profilePicUrl = profilePicUrl
if (rawCustomization !== undefined) {
const custResult = validateCustomization(rawCustomization)
if (!custResult.valid) {
return c.json({ error: custResult.error }, 400)
}
// Merge with existing customization
const existing = rows[0].customization ? JSON.parse(rows[0].customization) : {}
const merged = { ...existing, ...custResult.data }
updates.customization = JSON.stringify(merged)
// Update archetype if set in customization
if (custResult.data.archetype) {
updates.archetype = custResult.data.archetype
}
}
if (Object.keys(updates).length > 0) {
await db.update(schema.bots).set(updates).where(eq(schema.bots.id, rows[0].id))
}
+27 -3
View File
@@ -100,10 +100,14 @@ botsRouter.get('/', async (c) => {
tier: schema.bots.tier,
isActive: schema.bots.isActive,
archetype: schema.bots.archetype,
customization: schema.bots.customization,
createdAt: schema.bots.createdAt,
}).from(schema.bots).orderBy(schema.bots.eloRating)
return c.json(rows)
return c.json(rows.map(r => ({
...r,
customization: r.customization ? JSON.parse(r.customization) : null,
})))
})
// Get single bot profile
@@ -121,6 +125,7 @@ botsRouter.get('/:name', async (c) => {
tier: schema.bots.tier,
isActive: schema.bots.isActive,
archetype: schema.bots.archetype,
customization: schema.bots.customization,
createdAt: schema.bots.createdAt,
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
@@ -128,7 +133,11 @@ botsRouter.get('/:name', async (c) => {
return c.json({ error: 'Bot not found.' }, 404)
}
return c.json(rows[0])
const bot = rows[0]
return c.json({
...bot,
customization: bot.customization ? JSON.parse(bot.customization) : null,
})
})
// Get bot stats -- full account page data
@@ -147,6 +156,7 @@ botsRouter.get('/:name/stats', async (c) => {
tier: schema.bots.tier,
isActive: schema.bots.isActive,
archetype: schema.bots.archetype,
customization: schema.bots.customization,
createdAt: schema.bots.createdAt,
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
@@ -154,7 +164,11 @@ botsRouter.get('/:name/stats', async (c) => {
return c.json({ error: 'Bot not found.' }, 404)
}
const bot = botRows[0]
const rawBot = botRows[0]
const bot = {
...rawBot,
customization: rawBot.customization ? JSON.parse(rawBot.customization) : null,
}
const total = bot.wins + bot.losses
const winRate = total > 0 ? Math.round((bot.wins / total) * 100) : 0
@@ -273,6 +287,16 @@ botsRouter.post('/:name/health', async (c) => {
}
})
// ══════════════════════════════════════════════════════════
// Customization
// ══════════════════════════════════════════════════════════
import { getArchetypeList } from '../engine/customization.js'
botsRouter.get('/meta/archetypes', (c) => {
return c.json(getArchetypeList())
})
// ══════════════════════════════════════════════════════════
// Developer Tools
// ══════════════════════════════════════════════════════════
+7 -2
View File
@@ -70,6 +70,7 @@ fightsRouter.get('/:id', async (c) => {
name: schema.bots.name,
avatarSeed: schema.bots.avatarSeed,
archetype: schema.bots.archetype,
customization: schema.bots.customization,
profilePicUrl: schema.bots.profilePicUrl,
eloRating: schema.bots.eloRating,
wins: schema.bots.wins,
@@ -88,11 +89,15 @@ fightsRouter.get('/:id', async (c) => {
.orderBy(schema.rounds.roundNumber)
const arena = ARENAS.find(a => a.id === fight.arena)
const parseBot = (b: typeof botARows[0] | undefined) => {
if (!b) return null
return { ...b, customization: b.customization ? JSON.parse(b.customization) : null }
}
return c.json({
...fight,
botA: botARows[0] || null,
botB: botBRows[0] || null,
botA: parseBot(botARows[0]),
botB: parseBot(botBRows[0]),
arenaInfo: arena || null,
rounds: roundRows,
})