import { Hono, type Context } from 'hono' import { streamSSE } from 'hono/streaming' import { z } from 'zod' import { BUILTIN_LOOKALIKES } from '../../shared/lookalikes.ts' import { DOC_PERMISSION, SINGLETON_PERMISSION } from '../../shared/permissions.ts' import { ActivityRefSchema, DOC_KINDS, LookalikeSchema, PRESET_KINDS, SINGLETONS, type DocKind, type SingletonKey, } from '../../shared/schemas.ts' import { env } from '../env.ts' import { getProfile, xrpcGet } from '../atproto/identity.ts' import { runNuke } from '../bot/commands.ts' import { resolveLookalikes } from '../bot/engine/config.ts' import { compileLookalikes, graphemeLength } from '../bot/engine/text.ts' import { NotConnectedError } from '../atproto/streamer.ts' import { bus, type ChannelEvent } from '../bot/platform.ts' import { Exec } from '../bot/runtime.ts' import { searchGames } from '../streamplace.ts' import { ValidationError } from '../db/store.ts' import { NSID } from '../records/collections.ts' import { accessFor, can, readSession, resolveChannel, type Access, type AppEnv, type Deps, type SessionUser } from './context.ts' class HttpError extends Error { status: number constructor(status: number, message: string) { super(message) this.status = status } } const isDocKind = (k: string): k is DocKind => k in DOC_KINDS const isSingleton = (k: string): k is SingletonKey => k in SINGLETONS export function apiRoutes(deps: Deps) { const { store, manager } = deps const app = new Hono() app.onError((err, c) => { if (err instanceof HttpError) return c.json({ error: err.message }, err.status as 400) if (err instanceof ValidationError) return c.json({ error: 'Some fields are invalid.', issues: err.issues }, 400) if (err instanceof z.ZodError) return c.json({ error: 'Some fields are invalid.', issues: err.issues }, 400) console.error('[api]', err) return c.json({ error: err instanceof Error ? err.message : 'Something went wrong.' }, 500) }) app.use('*', async (c, next) => { c.set('user', await readSession(c, deps)) await next() }) const requireUser = (c: Context): SessionUser => { const user = c.get('user') if (!user) throw new HttpError(401, 'Please sign in.') return user } /** Resolve :cid and check the signed-in user's access, optionally requiring a permission. */ const access = async (c: Context, permission?: string): Promise => { const user = requireUser(c) const channel = resolveChannel(deps, c.req.param('cid') ?? '') if (!channel) throw new HttpError(404, 'Channel not found.') const a = await accessFor(deps, user, channel) if (!a) throw new HttpError(403, 'You don’t have access to this channel.') if (permission && !can(a, permission)) throw new HttpError(403, 'Your role doesn’t allow this.') return a } const actorOf = (c: Context) => { const u = c.get('user')! return { did: u.did, handle: u.handle } } const runtime = (a: Access) => { const rt = manager.runtimeFor(a.channel.id) if (!rt) throw new HttpError(404, 'Channel not found.') return rt } // --- session & channels ---------------------------------------------------------- app.get('/me', async (c) => { const user = c.get('user') if (!user) return c.json({ user: null, channels: [] }) const owned = store.listOwnedChannels(user.did) const shared = [] for (const ch of store.listAllChannels()) { if (ch.owner_did === user.did) continue const a = await accessFor(deps, user, ch).catch(() => null) if (a) shared.push(ch) } const view = (ch: (typeof owned)[number]) => ({ id: ch.id, kind: ch.kind, handle: ch.handle, displayName: ch.display_name, avatar: ch.avatar, slug: ch.slug, owner: ch.owner_did === user.did }) return c.json({ user, channels: [...owned, ...shared].map(view) }) }) app.get('/c/:cid', async (c) => { const a = await access(c) const rt = runtime(a) const connection = a.channel.kind === 'channel' ? await deps.streamer.status(a.channel.id) : { connected: true, missingScopes: [] } return c.json({ channel: { id: a.channel.id, kind: a.channel.kind, handle: a.channel.handle, displayName: a.channel.display_name, avatar: a.channel.avatar, slug: a.channel.slug, description: a.channel.description, private: !!a.channel.private, botJoined: !!a.channel.bot_joined, botMuted: !!a.channel.bot_muted, }, owner: a.owner, permissions: [...a.permissions], live: rt.liveSnapshot(), bot: { handle: deps.bot.handle, did: deps.bot.did, ready: deps.bot.ready, ...manager.status(a.channel.id) }, connection, records: deps.records.status(a.channel.owner_did), publicUrl: env.publicUrl, }) }) app.patch('/c/:cid/bot', async (c) => { const a = await access(c, 'stream') const body = z.object({ joined: z.boolean().optional(), muted: z.boolean().optional() }).parse(await c.req.json()) if (body.joined !== undefined) { store.updateChannel(a.channel.id, { bot_joined: body.joined ? 1 : 0 }) store.audit(a.channel.id, actorOf(c), 'bot', body.joined ? 'Joined the bot to the channel' : 'Removed the bot from the channel') } if (body.muted !== undefined) { store.updateChannel(a.channel.id, { bot_muted: body.muted ? 1 : 0 }) store.audit(a.channel.id, actorOf(c), 'bot', body.muted ? 'Muted the bot' : 'Unmuted the bot') } return c.json({ ok: true }) }) // --- live events ---------------------------------------------------------------------- app.get('/c/:cid/events', async (c) => { const a = await access(c) return streamSSE(c, async (stream) => { const queue: ChannelEvent[] = [] let wake: (() => void) | null = null const onEvent = (channelId: string, ev: ChannelEvent) => { if (channelId !== a.channel.id) return if (ev.type === 'audit' && !can(a, 'audit')) return queue.push(ev) wake?.() } bus.on('event', onEvent) stream.onAbort(() => { bus.off('event', onEvent) wake?.() }) await stream.writeSSE({ event: 'ready', data: '{}' }) while (!stream.aborted) { if (!queue.length) { await Promise.race([new Promise((r) => (wake = r)), new Promise((r) => setTimeout(r, 25_000))]) wake = null } if (stream.aborted) break if (!queue.length) { await stream.writeSSE({ event: 'ping', data: '{}' }) continue } const ev = queue.shift()! await stream.writeSSE({ event: ev.type, data: JSON.stringify(ev) }) } bus.off('event', onEvent) }) }) app.get('/c/:cid/chat', async (c) => { const a = await access(c) const rows = store.db.all<{ uri: string; author_did: string; author_handle: string; author_name: string; text: string; badges: string; color: string | null; created_at: string; hidden: number }>( 'SELECT * FROM chat_messages WHERE channel_id = ? ORDER BY created_at DESC LIMIT 150', a.channel.id, ) return c.json( rows.reverse().map((r) => ({ uri: r.uri, did: r.author_did, handle: r.author_handle, displayName: r.author_name, text: r.text, badges: JSON.parse(r.badges ?? '[]'), color: r.color, createdAt: r.created_at, isBot: r.author_did === deps.bot.did, hidden: !!r.hidden, })), ) }) /** Chat from the dashboard as the signed-in person, through their own OAuth session. */ app.post('/c/:cid/chat', async (c) => { const a = await access(c) if (a.channel.kind !== 'channel') throw new HttpError(400, 'Presets don’t have a chat.') const { text } = z.object({ text: z.string().trim().min(1).max(3000) }).parse(await c.req.json()) if (graphemeLength(text) > 300) throw new HttpError(400, 'Chat messages can be at most 300 characters.') const user = requireUser(c) const reconnect = () => c.json({ error: 'Sign in again to chat from the dashboard. Superbot needs permission to post chat messages from your account.', reconnect: true }, 403) if (!(await deps.streamer.canChat(user.did))) return reconnect() try { await deps.streamer.chat(user.did, a.channel.id, text) } catch (err) { if (err instanceof NotConnectedError || (err as { status?: number }).status === 401 || (err as { status?: number }).status === 403) return reconnect() throw err } return c.json({ ok: true }) }) // --- documents ------------------------------------------------------------------------ app.get('/c/:cid/docs/:kind', async (c) => { const kind = c.req.param('kind') if (!isDocKind(kind)) throw new HttpError(404, 'Unknown type.') const a = await access(c) return c.json(store.listDocs(a.channel.id, kind)) }) app.get('/c/:cid/docs/:kind/:id', async (c) => { const kind = c.req.param('kind') if (!isDocKind(kind)) throw new HttpError(404, 'Unknown type.') const a = await access(c) const doc = store.getDoc(a.channel.id, kind, c.req.param('id')) if (!doc) throw new HttpError(404, 'Not found.') return c.json(doc) }) const docLabel = (kind: DocKind, data: Record) => { switch (kind) { case 'command': return `command !${data.name}` case 'keyword': return `keyword “${data.name}”` case 'variable': return `variable ${data.name}` case 'timer': return `timer “${data.name}”` case 'blocked_term': return `blocked term “${(data.phrase as { text: string }).text}”` case 'filter': return `spam filter “${data.name}”` case 'role': return `role “${data.name}”` case 'quote': return `quote #${data.number}` } } const checkUnique = (channelId: string, kind: DocKind, data: Record, exceptId?: string) => { if (kind === 'command') { const triggers = new Set([data.name as string, ...((data.aliases as string[]) ?? [])]) const clash = store.listDocs(channelId, 'command').find((c) => c.id !== exceptId && [c.data.name, ...c.data.aliases].some((t) => triggers.has(t))) if (clash) throw new HttpError(409, `!${clash.data.name} already uses that name or alias.`) } if (kind === 'variable') { if (store.listDocs(channelId, 'variable').some((v) => v.id !== exceptId && v.data.name === data.name)) throw new HttpError(409, 'A variable with that name already exists.') } } app.post('/c/:cid/docs/:kind', async (c) => { const kind = c.req.param('kind') if (!isDocKind(kind)) throw new HttpError(404, 'Unknown type.') const a = await access(c, DOC_PERMISSION[kind]) if (kind === 'role') { const body = await c.req.json() if (body.platform) throw new HttpError(400, 'Platform roles are built in.') } let body = (await c.req.json()) as Record if (kind === 'quote' && body.number === undefined) { body = { ...body, number: Math.max(0, ...store.listDocs(a.channel.id, 'quote').map((q) => q.data.number)) + 1, addedBy: c.get('user')!.handle } } const value = store.validate(kind, body) as Record checkUnique(a.channel.id, kind, value) const doc = store.createDoc(a.channel.id, kind, value) store.audit(a.channel.id, actorOf(c), kind, `Created ${docLabel(kind, value)}`) return c.json(doc, 201) }) app.put('/c/:cid/docs/:kind/:id', async (c) => { const kind = c.req.param('kind') if (!isDocKind(kind)) throw new HttpError(404, 'Unknown type.') const a = await access(c, DOC_PERMISSION[kind]) const existing = store.getDoc(a.channel.id, kind, c.req.param('id')) if (!existing) throw new HttpError(404, 'Not found.') const value = store.validate(kind, await c.req.json()) as Record if (kind === 'role') { // Platform roles keep their identity; the broadcaster is always an administrator. const prev = existing.data as { platform: string | null } value.platform = prev.platform if (prev.platform === 'broadcaster') value.administrator = true if (prev.platform) value.members = [] } checkUnique(a.channel.id, kind, value, existing.id) const doc = store.updateDoc(a.channel.id, kind, existing.id, value) store.audit(a.channel.id, actorOf(c), kind, `Updated ${docLabel(kind, value)}`) return c.json(doc) }) app.delete('/c/:cid/docs/:kind/:id', async (c) => { const kind = c.req.param('kind') if (!isDocKind(kind)) throw new HttpError(404, 'Unknown type.') const a = await access(c, DOC_PERMISSION[kind]) const existing = store.getDoc(a.channel.id, kind, c.req.param('id')) if (!existing) throw new HttpError(404, 'Not found.') if (kind === 'role' && (existing.data as { platform: string | null }).platform) throw new HttpError(400, 'Platform roles can’t be deleted.') store.deleteDoc(a.channel.id, kind, existing.id) store.audit(a.channel.id, actorOf(c), kind, `Deleted ${docLabel(kind, existing.data as Record)}`) return c.json({ ok: true }) }) // --- settings singletons ---------------------------------------------------------------- app.get('/c/:cid/settings/:key', async (c) => { const key = c.req.param('key') if (!isSingleton(key)) throw new HttpError(404, 'Unknown setting.') const a = await access(c) return c.json(store.getSingleton(a.channel.id, key)) }) app.put('/c/:cid/settings/:key', async (c) => { const key = c.req.param('key') if (!isSingleton(key)) throw new HttpError(404, 'Unknown setting.') const a = await access(c, SINGLETON_PERMISSION[key]) let body = await c.req.json() if (key === 'presets') { const slugs = z.array(z.string()).parse(body) for (const slug of slugs) { const p = store.getPresetBySlug(slug) if (!p || (p.private && p.owner_did !== c.get('user')!.did && p.owner_did !== a.channel.owner_did)) throw new HttpError(404, `Preset “${slug}” doesn’t exist or is private.`) if (p.id === a.channel.id) throw new HttpError(400, 'A preset can’t install itself.') } body = [...new Set(slugs)] } if (key === 'giveaway') { const prev = store.getSingleton(a.channel.id, 'giveaway') const next = SINGLETONS.giveaway.parse(body) if (next.running && !prev.running) next.startedAt = new Date().toISOString() body = next } const value = store.setSingleton(a.channel.id, key, body) store.audit(a.channel.id, actorOf(c), 'settings', `Updated ${key.replace(/[._]/g, ' ')} settings`) return c.json(value) }) // --- audit, stream, tester ------------------------------------------------------------------ app.get('/c/:cid/audit', async (c) => { const a = await access(c, 'audit') const before = Number(c.req.query('before')) || undefined return c.json(store.listAudit(a.channel.id, { before, limit: 50, category: c.req.query('category') || undefined })) }) app.put('/c/:cid/stream', async (c) => { const a = await access(c, 'stream') const body = z.object({ title: z.string().max(140).optional(), activity: ActivityRefSchema.nullable().optional() }).parse(await c.req.json()) const rt = runtime(a) try { await rt.setStream(body) } catch (err) { throw new HttpError(409, err instanceof Error ? err.message : 'Couldn’t update the stream.') } if (body.title !== undefined) store.audit(a.channel.id, actorOf(c), 'stream', `Changed title to “${body.title}”`) if (body.activity !== undefined) store.audit(a.channel.id, actorOf(c), 'stream', `Changed activity to ${body.activity?.name ?? 'nothing'}`) return c.json(rt.liveSnapshot()) }) app.post('/c/:cid/test', async (c) => { const a = await access(c) const body = z.object({ text: z.string().min(1).max(3000), handle: z.string().min(1).max(253), roles: z.array(z.string()).default([]) }).parse(await c.req.json()) const steps = await runtime(a).simulate(body) return c.json({ steps }) }) app.get('/games', async (c) => { requireUser(c) const q = c.req.query('q')?.trim() if (!q) return c.json([]) return c.json(await searchGames(q).catch(() => [])) }) app.get('/actors', async (c) => { requireUser(c) const q = c.req.query('q')?.trim() if (!q) return c.json([]) const res = await xrpcGet<{ actors: { did: string; handle: string; displayName?: string; avatar?: string }[] }>(env.appviewUrl, 'app.bsky.actor.searchActorsTypeahead', { q, limit: 8 }).catch(() => ({ actors: [] })) return c.json(res.actors.map((x) => ({ did: x.did, handle: x.handle, displayName: x.displayName ?? '', avatar: x.avatar ?? '' }))) }) // --- moderation ------------------------------------------------------------------------------- app.get('/c/:cid/nukes', async (c) => { const a = await access(c, 'nukes') const rows = store.db.all<{ id: number; actor_handle: string; query: string; lookback: number; action: string; duration: number; affected: string; created_at: string }>( 'SELECT * FROM nukes WHERE channel_id = ? ORDER BY id DESC LIMIT 100', a.channel.id, ) return c.json(rows.map((r) => ({ ...r, affected: JSON.parse(r.affected) }))) }) app.post('/c/:cid/nukes', async (c) => { const a = await access(c, 'nukes') const body = z .object({ pattern: z.string().min(1).max(500), regex: z.boolean().default(false), lookback: z.number().int().min(5).max(3600).default(60), action: z.enum(['delete', 'timeout', 'ban']).default('delete'), duration: z.number().int().min(0).max(14 * 86400).default(600), preview: z.boolean().default(false), }) .parse(await c.req.json()) const exec = new Exec(body.preview) const result = await runNuke(runtime(a), body, actorOf(c), exec) return c.json({ ...result, steps: exec.steps }) }) app.get('/c/:cid/punishments', async (c) => { const a = await access(c, 'nukes') return c.json(store.db.all('SELECT * FROM punishments WHERE channel_id = ? AND lifted_at IS NULL ORDER BY id DESC LIMIT 200', a.channel.id)) }) app.post('/c/:cid/moderate', async (c) => { const a = await access(c, 'nukes') const body = z .object({ action: z.enum(['hide', 'timeout', 'ban', 'unban']), user: z.string().optional(), uri: z.string().optional(), seconds: z.number().int().min(1).max(14 * 86400).default(600), reason: z.string().max(300).default('') }) .parse(await c.req.json()) const rt = runtime(a) if (body.action === 'hide') { if (!body.uri) throw new HttpError(400, 'Missing message.') await rt.hideMessage(body.uri) store.audit(a.channel.id, actorOf(c), 'moderation', 'Hid a chat message') return c.json({ ok: true }) } const p = body.user ? await getProfile(body.user.replace(/^@/, '')) : null if (!p) throw new HttpError(404, 'User not found.') try { if (body.action === 'timeout') await rt.timeout(p, body.seconds, body.reason, 'dashboard') else if (body.action === 'ban') await rt.ban(p, body.reason, 'dashboard') else await rt.unban(p.did) } catch (err) { throw new HttpError(409, err instanceof Error ? err.message : String(err)) } const verb = body.action === 'timeout' ? `Timed out @${p.handle} for ${body.seconds}s` : body.action === 'ban' ? `Banned @${p.handle}` : `Unbanned @${p.handle}` store.audit(a.channel.id, actorOf(c), 'moderation', verb, { reason: body.reason }) return c.json({ ok: true }) }) // --- counters, loyalty ---------------------------------------------------------------------------- app.get('/c/:cid/counters', async (c) => { const a = await access(c) return c.json(store.listCounters(a.channel.id).filter((x) => x.name.startsWith('count:')).map((x) => ({ name: x.name.slice(6), value: x.value }))) }) app.put('/c/:cid/counters/:name', async (c) => { const a = await access(c, 'commands') const { value } = z.object({ value: z.number().int().min(0) }).parse(await c.req.json()) const name = c.req.param('name').toLowerCase() if (!/^[a-z0-9_-]+$/.test(name)) throw new HttpError(400, 'Counter names can only use letters, numbers, dashes and underscores.') store.counterSet(a.channel.id, `count:${name}`, value) store.audit(a.channel.id, actorOf(c), 'commands', `Set counter ${name} to ${value}`) return c.json({ name, value }) }) app.delete('/c/:cid/counters/:name', async (c) => { const a = await access(c, 'commands') store.db.run('DELETE FROM counters WHERE channel_id = ? AND name = ?', a.channel.id, `count:${c.req.param('name').toLowerCase()}`) return c.json({ ok: true }) }) // --- API key (Stream Deck and other tools) --------------------------------------------------------- /** The key runs commands as the broadcaster, so only the channel owner manages it. */ const ownerAccess = async (c: Context) => { const a = await access(c) if (!a.owner || a.channel.kind !== 'channel') throw new HttpError(403, 'Only the streamer can manage the API key.') return a } app.get('/c/:cid/api-key', async (c) => { const a = await ownerAccess(c) return c.json({ key: store.getApiKey(a.channel.id) }) }) app.post('/c/:cid/api-key', async (c) => { const a = await ownerAccess(c) const replaced = !!store.getApiKey(a.channel.id) const created = store.createApiKey(a.channel.id) store.audit(a.channel.id, actorOf(c), 'settings', replaced ? 'Replaced the API key' : 'Created an API key') return c.json({ secret: created.key, key: store.getApiKey(a.channel.id) }, 201) }) app.delete('/c/:cid/api-key', async (c) => { const a = await ownerAccess(c) if (store.deleteApiKey(a.channel.id)) store.audit(a.channel.id, actorOf(c), 'settings', 'Revoked the API key') return c.json({ ok: true }) }) app.get('/c/:cid/loyalty', async (c) => { const a = await access(c, 'loyalty') const q = c.req.query('q')?.trim().toLowerCase() ?? '' const page = Math.max(0, Number(c.req.query('page')) || 0) const rows = store.db.all( 'SELECT did, handle, display_name, time_online, time_offline, messages, first_seen, last_seen FROM chatters WHERE channel_id = ? AND (? = \'\' OR lower(handle) LIKE ? OR lower(display_name) LIKE ?) ORDER BY time_online + time_offline DESC, messages DESC LIMIT 50 OFFSET ?', a.channel.id, q, `%${q}%`, `%${q}%`, page * 50, ) const total = store.db.get<{ n: number }>('SELECT count(*) AS n FROM chatters WHERE channel_id = ?', a.channel.id)?.n ?? 0 return c.json({ rows, total }) }) app.post('/c/:cid/loyalty/reset', async (c) => { const a = await access(c, 'loyalty') const { did } = z.object({ did: z.string().optional() }).parse(await c.req.json().catch(() => ({}))) if (did) store.db.run('UPDATE chatters SET time_online = 0, time_offline = 0 WHERE channel_id = ? AND did = ?', a.channel.id, did) else store.db.run('UPDATE chatters SET time_online = 0, time_offline = 0 WHERE channel_id = ?', a.channel.id) store.audit(a.channel.id, actorOf(c), 'loyalty', did ? 'Reset a viewer’s watchtime' : 'Reset all watchtime') return c.json({ ok: true }) }) // --- giveaways --------------------------------------------------------------------------------------- app.get('/c/:cid/giveaway', async (c) => { const a = await access(c, 'giveaways') const rt = runtime(a) return c.json({ settings: store.getSingleton(a.channel.id, 'giveaway'), entries: rt.modules.giveaway.entries() }) }) app.post('/c/:cid/giveaway/:action', async (c) => { const a = await access(c, 'giveaways') const rt = runtime(a) const action = c.req.param('action') if (action === 'reset') { rt.modules.giveaway.reset() store.audit(a.channel.id, actorOf(c), 'giveaway', 'Reset giveaway entries') return c.json({ ok: true }) } if (action === 'draw') { const result = await rt.modules.giveaway.draw() if (!result) throw new HttpError(409, 'There are no entries yet.') return c.json(result) } if (action === 'remove') { const { did } = z.object({ did: z.string() }).parse(await c.req.json()) rt.modules.giveaway.remove(did) return c.json({ ok: true }) } throw new HttpError(404, 'Unknown action.') }) // --- media request ----------------------------------------------------------------------------------- app.get('/c/:cid/media', async (c) => { const a = await access(c, 'media') const m = runtime(a).modules.media return c.json({ settings: store.getSingleton(a.channel.id, 'media'), current: m.current() ?? null, queue: m.queue(), pending: m.queue('pending'), history: m.history() }) }) app.post('/c/:cid/media/:action', async (c) => { const a = await access(c, 'media') const m = runtime(a).modules.media const action = c.req.param('action') const body = (await c.req.json().catch(() => ({}))) as Record switch (action) { case 'next': return c.json({ current: (await m.next(body.skipped ? 'skipped' : 'played')) ?? null }) case 'request': { const url = z.string().min(1).parse(body.url) const message = await m.request(url, actorOf(c), { bypassLimits: true }) return c.json({ message }) } case 'approve': m.setStatus(Number(body.id), 'queued') return c.json({ ok: true }) case 'remove': m.setStatus(Number(body.id), 'removed') return c.json({ ok: true }) case 'top': m.moveToTop(Number(body.id)) return c.json({ ok: true }) case 'clear': m.clear() store.audit(a.channel.id, actorOf(c), 'media', 'Cleared the media queue') return c.json({ ok: true }) case 'volume': m.setVolume(Number(body.volume)) return c.json({ ok: true }) } throw new HttpError(404, 'Unknown action.') }) // --- lookalikes ----------------------------------------------------------------------------------------- const lookalikeView = (l: NonNullable>, userDid: string) => ({ id: l.id, owner: l.owner_did === userDid, ...l.data, publication: l.data.public ? deps.records.publication({ repo: l.owner_did, collection: NSID.lookalike, rkey: l.slug }) : 'none', }) app.get('/lookalikes', async (c) => { const user = requireUser(c) const parsed = store.listLookalikes().map((l) => lookalikeView(l, user.did)) return c.json({ builtin: BUILTIN_LOOKALIKES.map((l) => ({ ...l, owner: false, builtin: true })), mine: parsed.filter((l) => l.owner), public: parsed.filter((l) => !l.owner && l.public), }) }) app.post('/lookalikes', async (c) => { const user = requireUser(c) const value = LookalikeSchema.parse(await c.req.json()) if (store.getLookalikeBySlug(value.slug)) throw new HttpError(409, 'That ID is taken.') return c.json(lookalikeView(store.putLookalike(user.did, value), user.did), 201) }) app.put('/lookalikes/:id', async (c) => { const user = requireUser(c) const row = store.getLookalike(c.req.param('id')) if (!row || row.owner_did !== user.did) throw new HttpError(404, 'Not found.') const value = LookalikeSchema.parse(await c.req.json()) value.slug = row.slug return c.json(lookalikeView(store.putLookalike(user.did, value), user.did)) }) app.delete('/lookalikes/:id', async (c) => { const user = requireUser(c) if (!store.deleteLookalike(c.req.param('id'), user.did)) throw new HttpError(404, 'Not found.') return c.json({ ok: true }) }) app.post('/c/:cid/lookalikes/test', async (c) => { const a = await access(c) const { text } = z.object({ text: z.string().max(3000) }).parse(await c.req.json()) const normalize = compileLookalikes(resolveLookalikes(store, store.getSingleton(a.channel.id, 'lookalikes'))) return c.json({ output: normalize(text) }) }) // --- presets ---------------------------------------------------------------------------------------------- const presetView = (p: NonNullable>, userDid?: string) => ({ id: p.id, slug: p.slug, name: p.display_name, description: p.description, private: !!p.private, owner: p.owner_did === userDid, ownerHandle: p.handle, publication: p.private || !p.slug ? 'none' : deps.records.publication({ repo: p.owner_did, collection: NSID.preset, rkey: p.slug }), needsSignIn: p.owner_did === userDid && deps.records.status(p.owner_did).needsSignIn, counts: Object.fromEntries(PRESET_KINDS.map((k) => [k, store.listDocs(p.id, k).length])), }) app.get('/presets', async (c) => { const user = requireUser(c) const mine = store.listOwnedChannels(user.did).filter((p) => p.kind === 'preset') return c.json({ mine: mine.map((p) => presetView(p, user.did)), public: store.listPublicPresets().filter((p) => p.owner_did !== user.did).map((p) => presetView(p, user.did)) }) }) app.get('/presets/:slug', async (c) => { const user = requireUser(c) const p = store.getPresetBySlug(c.req.param('slug')) if (!p || (p.private && p.owner_did !== user.did)) throw new HttpError(404, 'Preset not found.') return c.json(presetView(p, user.did)) }) app.post('/presets', async (c) => { const user = requireUser(c) const body = z .object({ slug: z.string().min(2).max(40).regex(/^[a-z0-9_-]+$/), name: z.string().min(1).max(60), description: z.string().max(300).default('') }) .parse(await c.req.json()) if (store.getPresetBySlug(body.slug)) throw new HttpError(409, 'That preset ID is taken.') const p = store.createPreset({ did: user.did, handle: user.handle }, body.slug, body.name, body.description) return c.json(presetView(p, user.did), 201) }) app.patch('/presets/:slug', async (c) => { const user = requireUser(c) const p = store.getPresetBySlug(c.req.param('slug')) if (!p || p.owner_did !== user.did) throw new HttpError(404, 'Preset not found.') const body = z.object({ name: z.string().min(1).max(60).optional(), description: z.string().max(300).optional(), private: z.boolean().optional() }).parse(await c.req.json()) store.updateChannel(p.id, { ...(body.name !== undefined ? { display_name: body.name } : {}), ...(body.description !== undefined ? { description: body.description } : {}), ...(body.private !== undefined ? { private: body.private ? 1 : 0 } : {}), }) return c.json(presetView(store.getChannel(p.id)!, user.did)) }) app.delete('/presets/:slug', async (c) => { const user = requireUser(c) const p = store.getPresetBySlug(c.req.param('slug')) if (!p || p.owner_did !== user.did) throw new HttpError(404, 'Preset not found.') store.deleteChannel(p.id) return c.json({ ok: true }) }) // --- import / export -------------------------------------------------------------------------------------- app.get('/c/:cid/export', async (c) => { const a = await access(c, 'settings') const docs = Object.fromEntries( (['command', 'keyword', 'variable', 'timer', 'blocked_term', 'filter', 'quote', 'role'] as DocKind[]).map((k) => [ k, store.listDocs(a.channel.id, k).filter((d) => k !== 'role' || !(d.data as { platform: string | null }).platform).map((d) => d.data), ]), ) const settings = Object.fromEntries((Object.keys(SINGLETONS) as SingletonKey[]).filter((k) => k !== 'giveaway').map((k) => [k, store.getSingleton(a.channel.id, k)])) c.header('content-disposition', `attachment; filename="superbot-${a.channel.handle}.json"`) return c.json({ format: 'superbot-export', version: 1, exportedAt: new Date().toISOString(), docs, settings }) }) app.post('/c/:cid/import', async (c) => { const a = await access(c, 'settings') const body = z .object({ format: z.literal('superbot-export'), docs: z.record(z.string(), z.array(z.unknown())).default({}), settings: z.record(z.string(), z.unknown()).default({}), replace: z.boolean().default(false), }) .parse(await c.req.json()) const counts: Record = {} const errors: string[] = [] store.db.tx(() => { for (const [kind, items] of Object.entries(body.docs)) { if (!isDocKind(kind)) continue if (body.replace) for (const d of store.listDocs(a.channel.id, kind)) if (kind !== 'role' || !(d.data as { platform: string | null }).platform) store.deleteDoc(a.channel.id, kind, d.id) for (const item of items) { try { store.createDoc(a.channel.id, kind, item) counts[kind] = (counts[kind] ?? 0) + 1 } catch { errors.push(`Skipped an invalid ${kind.replace('_', ' ')}`) } } } for (const [key, value] of Object.entries(body.settings)) { if (!isSingleton(key) || key === 'giveaway') continue try { store.setSingleton(a.channel.id, key, value) } catch { errors.push(`Skipped invalid ${key} settings`) } } }) store.audit(a.channel.id, actorOf(c), 'settings', `Imported configuration (${Object.entries(counts).map(([k, n]) => `${n} ${k.replace('_', ' ')}s`).join(', ') || 'settings only'})`) return c.json({ counts, errors }) }) return app }