Phase 7: Bot/extension system

Bot accounts (User rows with is_bot=True), scoped API tokens (read:messages,
write:messages, manage:rooms) authenticated via Authorization: Bearer on both
REST and the WS handshake, live bot WebSocket access on the same /ws/chat
endpoint humans use, message editing (WS "edit" envelope -> message_update
broadcast, fans out cross-instance for free via the existing broadcaster),
incoming webhooks (room-scoped, no auth beyond the URL token), and outgoing
webhooks/event subscriptions (HMAC-SHA256 signed, backgrounded delivery,
creation-time SSRF validation against private/loopback/link-local targets).

Token auth is additive, not a parallel system: a bearer-token-authenticated
bot goes through the exact same room-membership/role checks a session-
authenticated human does everywhere; only read:messages/write:messages are
separately scope-gated (the two message endpoints). manage:rooms scope
enforcement, full per-delivery SSRF re-validation, and bot API rate limiting
were explicitly scoped out (confirmed with the repo owner) as disproportionate
to this phase -- documented as known gaps in backend/README.md rather than
silently skipped.

Admin portal gains a Bots tab (create bots, issue/revoke scoped tokens,
cross-room webhook visibility); RoomInfoPanel gains room-scoped webhook/
subscription management, mirroring how invites already work there. The chat
UI also gets a minimal "edit your own message" affordance -- not asked for
by the issue, but the only practical way to exercise the edit pipeline by
hand instead of only via a scripted bot client.

Along the way: fixed a real bug caught while writing the incoming-webhook
test -- offline-push notification relied on the sender being "connected" to
exclude themselves, true for WS-originated messages but not for the new
webhook path, which has no WS connection for the attributed sender at all.
Now explicitly excluded. Also discovered the REST-only test fixture never
triggered ASGI lifespan, so app.state.broadcaster/presence didn't exist for
it; moved their construction out of the lifespan into create_app() itself
(Redis client construction is synchronous/lazy) so both the WS and
REST-only paths always have them.

New tests/test_bots.py, test_message_edit.py, test_webhooks.py (full suite
now 78/78, stable across repeated runs) plus a scripted end-to-end smoke
test (bot WS join/post/edit, incoming webhook, SSRF rejection, outgoing
delivery) and a full browser walkthrough of the new admin/room UI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-08-14 08:12:41 -06:00
1 parent 4aa8ef89c5
commit 0ab23c44a7
41 files changed
+2607 -137

No files matched your search

+175 -1
View File
@@ -9,12 +9,30 @@ import {
transferOwnership,
updateRoom,
} from '../api/rooms'
import {
createEventSubscription,
createIncomingWebhook,
listEventSubscriptions,
listIncomingWebhooks,
revokeEventSubscription,
revokeIncomingWebhook,
} from '../api/webhooks'
import { useAuth } from '../context/AuthContext'
import type { Invite, MyRoomItem, RoomMember, RoomRole } from '../types'
import type {
EventSubscription,
EventType,
Invite,
MyRoomItem,
RoomMember,
RoomRole,
WebhookIncoming,
} from '../types'
import { RoomAvatar } from './RoomAvatar'
import { UserAvatar } from './UserAvatar'
import './RoomInfoPanel.css'
const EVENT_TYPES: EventType[] = ['message.created', 'message.updated']
interface RoomInfoPanelProps {
room: MyRoomItem
members: RoomMember[]
@@ -46,6 +64,15 @@ export function RoomInfoPanel({
const [descDraft, setDescDraft] = useState(room.description ?? '')
const [roomError, setRoomError] = useState<string | null>(null)
const [integrationsOpen, setIntegrationsOpen] = useState(false)
const [incomingWebhooks, setIncomingWebhooks] = useState<WebhookIncoming[]>([])
const [webhookDescription, setWebhookDescription] = useState('')
const [eventSubscriptions, setEventSubscriptions] = useState<EventSubscription[]>([])
const [targetUrl, setTargetUrl] = useState('')
const [selectedEventTypes, setSelectedEventTypes] = useState<EventType[]>([])
const [newSigningSecret, setNewSigningSecret] = useState<string | null>(null)
const [integrationsError, setIntegrationsError] = useState<string | null>(null)
const canManage = myRole === 'admin' || myRole === 'owner'
useEffect(() => {
@@ -53,8 +80,12 @@ export function RoomInfoPanel({
setDescDraft(room.description ?? '')
if (canManage) {
listRoomInvites(room.id).then(setPendingInvites).catch(() => setPendingInvites([]))
listIncomingWebhooks(room.id).then(setIncomingWebhooks).catch(() => setIncomingWebhooks([]))
listEventSubscriptions(room.id).then(setEventSubscriptions).catch(() => setEventSubscriptions([]))
} else {
setPendingInvites([])
setIncomingWebhooks([])
setEventSubscriptions([])
}
}, [room.id, room.name, room.description, canManage])
@@ -77,6 +108,50 @@ export function RoomInfoPanel({
setPendingInvites(await listRoomInvites(room.id))
}
async function handleCreateWebhook(e: FormEvent) {
e.preventDefault()
setIntegrationsError(null)
try {
await createIncomingWebhook(room.id, webhookDescription.trim())
setWebhookDescription('')
setIncomingWebhooks(await listIncomingWebhooks(room.id))
} catch (err) {
setIntegrationsError(err instanceof ApiError ? err.message : String(err))
}
}
async function handleRevokeWebhook(webhookId: string) {
await revokeIncomingWebhook(room.id, webhookId)
setIncomingWebhooks(await listIncomingWebhooks(room.id))
}
function toggleEventType(eventType: EventType) {
setSelectedEventTypes((prev) =>
prev.includes(eventType) ? prev.filter((t) => t !== eventType) : [...prev, eventType],
)
}
async function handleCreateSubscription(e: FormEvent) {
e.preventDefault()
setIntegrationsError(null)
const url = targetUrl.trim()
if (!url || selectedEventTypes.length === 0) return
try {
const created = await createEventSubscription(room.id, selectedEventTypes, url)
setNewSigningSecret(created.signing_secret)
setTargetUrl('')
setSelectedEventTypes([])
setEventSubscriptions(await listEventSubscriptions(room.id))
} catch (err) {
setIntegrationsError(err instanceof ApiError ? err.message : String(err))
}
}
async function handleRevokeSubscription(subscriptionId: string) {
await revokeEventSubscription(room.id, subscriptionId)
setEventSubscriptions(await listEventSubscriptions(room.id))
}
async function handleRemove(userId: string) {
setBusyUserId(userId)
try {
@@ -252,6 +327,105 @@ export function RoomInfoPanel({
</div>
)}
{canManage && (
<div className="room-info-section">
<button
type="button"
className="room-info-settings-toggle"
onClick={() => setIntegrationsOpen((v) => !v)}
>
Integrations {integrationsOpen ? '−' : '+'}
</button>
{integrationsOpen && (
<div className="room-info-integrations">
{integrationsError && <p className="room-info-error">{integrationsError}</p>}
<div className="room-info-integration-group">
<div className="room-info-label">Incoming webhooks</div>
{incomingWebhooks.map((w) => (
<div key={w.id} className="room-info-webhook-row">
<div className="room-info-webhook-info">
<code>{`${window.location.origin}/api/webhooks/incoming/${w.token}`}</code>
{w.description && <span className="room-info-webhook-desc">{w.description}</span>}
</div>
<button
type="button"
className="room-info-danger-link"
onClick={() => handleRevokeWebhook(w.id)}
>
Revoke
</button>
</div>
))}
<form className="room-info-invite-form" onSubmit={handleCreateWebhook}>
<input
type="text"
placeholder="Description (optional)"
value={webhookDescription}
onChange={(e) => setWebhookDescription(e.target.value)}
/>
<button type="submit" className="btn-secondary">
Add
</button>
</form>
</div>
<div className="room-info-integration-group">
<div className="room-info-label">Outgoing event subscriptions</div>
{eventSubscriptions.map((s) => (
<div key={s.id} className="room-info-webhook-row">
<div className="room-info-webhook-info">
<code>{s.target_url}</code>
<span className="room-info-webhook-desc">{s.event_types.join(', ')}</span>
</div>
<button
type="button"
className="room-info-danger-link"
onClick={() => handleRevokeSubscription(s.id)}
>
Revoke
</button>
</div>
))}
<form className="room-info-subscription-form" onSubmit={handleCreateSubscription}>
<input
type="text"
placeholder="https://example.com/hook"
value={targetUrl}
onChange={(e) => setTargetUrl(e.target.value)}
/>
<div className="room-info-event-types">
{EVENT_TYPES.map((eventType) => (
<label key={eventType} className="room-info-event-type-checkbox">
<input
type="checkbox"
checked={selectedEventTypes.includes(eventType)}
onChange={() => toggleEventType(eventType)}
/>
{eventType}
</label>
))}
</div>
<button
type="submit"
className="btn-secondary"
disabled={!targetUrl.trim() || selectedEventTypes.length === 0}
>
Add
</button>
</form>
{newSigningSecret && (
<p className="room-info-signing-secret">
New signing secret (copy it now, it won't be shown again):{' '}
<code>{newSigningSecret}</code>
</p>
)}
</div>
</div>
)}
</div>
)}
{myRole === 'owner' && (
<div className="room-info-section">
<button