Private
Public Access
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:
@@ -1,5 +1,11 @@
|
||||
import { apiFetch } from './client'
|
||||
import type { AdminRoom, AdminUser, AuditLogEntry } from '../types'
|
||||
import type {
|
||||
AdminRoom,
|
||||
AdminUser,
|
||||
AuditLogEntry,
|
||||
EventSubscriptionAdmin,
|
||||
WebhookIncomingAdmin,
|
||||
} from '../types'
|
||||
|
||||
export function listAdminUsers(): Promise<AdminUser[]> {
|
||||
return apiFetch<AdminUser[]>('/api/admin/users')
|
||||
@@ -50,3 +56,11 @@ export function transferOwnershipAdmin(roomId: string, newOwnerId: string): Prom
|
||||
export function listAuditLog(limit = 50, offset = 0): Promise<AuditLogEntry[]> {
|
||||
return apiFetch<AuditLogEntry[]>(`/api/admin/audit-log?limit=${limit}&offset=${offset}`)
|
||||
}
|
||||
|
||||
export function listAllIncomingWebhooks(): Promise<WebhookIncomingAdmin[]> {
|
||||
return apiFetch<WebhookIncomingAdmin[]>('/api/admin/webhooks/incoming')
|
||||
}
|
||||
|
||||
export function listAllEventSubscriptions(): Promise<EventSubscriptionAdmin[]> {
|
||||
return apiFetch<EventSubscriptionAdmin[]>('/api/admin/event-subscriptions')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { apiFetch } from './client'
|
||||
import type { ApiScope, ApiToken, ApiTokenCreated, Bot } from '../types'
|
||||
|
||||
export function createBot(username: string): Promise<Bot> {
|
||||
return apiFetch<Bot>('/api/admin/bots', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username }),
|
||||
})
|
||||
}
|
||||
|
||||
export function listBots(): Promise<Bot[]> {
|
||||
return apiFetch<Bot[]>('/api/admin/bots')
|
||||
}
|
||||
|
||||
export function createApiToken(botId: string, scopes: ApiScope[]): Promise<ApiTokenCreated> {
|
||||
return apiFetch<ApiTokenCreated>(`/api/admin/bots/${botId}/tokens`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ scopes }),
|
||||
})
|
||||
}
|
||||
|
||||
export function listApiTokens(botId: string): Promise<ApiToken[]> {
|
||||
return apiFetch<ApiToken[]>(`/api/admin/bots/${botId}/tokens`)
|
||||
}
|
||||
|
||||
export function revokeApiToken(tokenId: string): Promise<void> {
|
||||
return apiFetch<void>(`/api/admin/bots/tokens/${tokenId}`, { method: 'DELETE' })
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { apiFetch } from './client'
|
||||
import type {
|
||||
EventSubscription,
|
||||
EventSubscriptionCreated,
|
||||
EventType,
|
||||
WebhookIncoming,
|
||||
} from '../types'
|
||||
|
||||
export function createIncomingWebhook(
|
||||
roomId: string,
|
||||
description?: string,
|
||||
): Promise<WebhookIncoming> {
|
||||
return apiFetch<WebhookIncoming>(`/api/rooms/${roomId}/webhooks/incoming`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ description: description || null }),
|
||||
})
|
||||
}
|
||||
|
||||
export function listIncomingWebhooks(roomId: string): Promise<WebhookIncoming[]> {
|
||||
return apiFetch<WebhookIncoming[]>(`/api/rooms/${roomId}/webhooks/incoming`)
|
||||
}
|
||||
|
||||
export function revokeIncomingWebhook(roomId: string, webhookId: string): Promise<void> {
|
||||
return apiFetch<void>(`/api/rooms/${roomId}/webhooks/incoming/${webhookId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export function createEventSubscription(
|
||||
roomId: string,
|
||||
eventTypes: EventType[],
|
||||
targetUrl: string,
|
||||
): Promise<EventSubscriptionCreated> {
|
||||
return apiFetch<EventSubscriptionCreated>(`/api/rooms/${roomId}/event-subscriptions`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ event_types: eventTypes, target_url: targetUrl }),
|
||||
})
|
||||
}
|
||||
|
||||
export function listEventSubscriptions(roomId: string): Promise<EventSubscription[]> {
|
||||
return apiFetch<EventSubscription[]>(`/api/rooms/${roomId}/event-subscriptions`)
|
||||
}
|
||||
|
||||
export function revokeEventSubscription(roomId: string, subscriptionId: string): Promise<void> {
|
||||
return apiFetch<void>(`/api/rooms/${roomId}/event-subscriptions/${subscriptionId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
@@ -43,6 +43,17 @@ export function ChatPane({ room, members, isMobile, onBack, onToggleInfo, infoOp
|
||||
const onMessage = useCallback((envelope: ServerEnvelope) => {
|
||||
if (envelope.type === 'message') {
|
||||
setLive((prev) => [...prev, envelope])
|
||||
} else if (envelope.type === 'message_update') {
|
||||
setHistory((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === envelope.id ? { ...m, content: envelope.content, edited_at: envelope.edited_at } : m,
|
||||
),
|
||||
)
|
||||
setLive((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === envelope.id ? { ...m, content: envelope.content, edited_at: envelope.edited_at } : m,
|
||||
),
|
||||
)
|
||||
} else if (envelope.type === 'error') {
|
||||
setWsError(envelope.detail)
|
||||
}
|
||||
@@ -50,7 +61,7 @@ export function ChatPane({ room, members, isMobile, onBack, onToggleInfo, infoOp
|
||||
|
||||
const onUnauthenticated = useCallback(() => navigate('/login'), [navigate])
|
||||
|
||||
const { connected, send } = useChatSocket({ roomId: room.id, onMessage, onUnauthenticated })
|
||||
const { connected, send, sendEdit } = useChatSocket({ roomId: room.id, onMessage, onUnauthenticated })
|
||||
|
||||
return (
|
||||
<section className="chat-pane">
|
||||
@@ -88,7 +99,7 @@ export function ChatPane({ room, members, isMobile, onBack, onToggleInfo, infoOp
|
||||
</p>
|
||||
)}
|
||||
|
||||
<MessageList messages={[...history, ...live]} members={members} />
|
||||
<MessageList messages={[...history, ...live]} members={members} onEdit={sendEdit} />
|
||||
<Composer roomName={room.name} disabled={!connected} onSend={send} />
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
position: relative;
|
||||
background: var(--ds-surface-2);
|
||||
color: var(--ds-text);
|
||||
padding: 8px 12px;
|
||||
@@ -56,9 +57,45 @@
|
||||
background: var(--ds-accent-2);
|
||||
}
|
||||
|
||||
.message-edit-link {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: -18px;
|
||||
right: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--ds-muted);
|
||||
font-size: 0.68rem;
|
||||
cursor: pointer;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
|
||||
.message-edit-link:hover {
|
||||
color: var(--ds-text);
|
||||
}
|
||||
|
||||
.message-bubble:hover .message-edit-link {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.message-edit-input {
|
||||
background: var(--ds-surface-2);
|
||||
border: 1px solid var(--ds-accent);
|
||||
border-radius: 10px;
|
||||
padding: 8px 12px;
|
||||
font-size: 0.88rem;
|
||||
color: var(--ds-text);
|
||||
font-family: var(--sans);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 0.68rem;
|
||||
color: var(--ds-muted);
|
||||
margin-top: 3px;
|
||||
font-family: var(--mono);
|
||||
}
|
||||
|
||||
.message-edited {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { senderColorIndex } from '../lib/messageGrouping'
|
||||
import type { ChatMessageEnvelope, Message, RoomMember } from '../types'
|
||||
@@ -8,16 +8,30 @@ import './MessageList.css'
|
||||
interface MessageListProps {
|
||||
messages: (Message | ChatMessageEnvelope)[]
|
||||
members: RoomMember[]
|
||||
onEdit: (messageId: string, content: string) => void
|
||||
}
|
||||
|
||||
export function MessageList({ messages, members }: MessageListProps) {
|
||||
export function MessageList({ messages, members, onEdit }: MessageListProps) {
|
||||
const { user } = useAuth()
|
||||
const bottomRef = useRef<HTMLDivElement>(null)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [draft, setDraft] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ block: 'end' })
|
||||
}, [messages.length])
|
||||
|
||||
function startEdit(msg: Message | ChatMessageEnvelope) {
|
||||
setEditingId(msg.id)
|
||||
setDraft(msg.content)
|
||||
}
|
||||
|
||||
function commitEdit(messageId: string) {
|
||||
const trimmed = draft.trim()
|
||||
if (trimmed) onEdit(messageId, trimmed)
|
||||
setEditingId(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="message-list">
|
||||
{messages.map((msg, i) => {
|
||||
@@ -25,6 +39,7 @@ export function MessageList({ messages, members }: MessageListProps) {
|
||||
const prev = messages[i - 1]
|
||||
const showAvatar = !mine && (!prev || prev.user_id !== msg.user_id)
|
||||
const showName = showAvatar
|
||||
const editing = editingId === msg.id
|
||||
|
||||
return (
|
||||
<div key={msg.id} className={`message-row${mine ? ' message-row-mine' : ''}`}>
|
||||
@@ -37,9 +52,36 @@ export function MessageList({ messages, members }: MessageListProps) {
|
||||
)}
|
||||
<div className="message-bubble-wrap">
|
||||
{showName && <div className="message-author">{msg.username}</div>}
|
||||
<div className={`message-bubble${mine ? ' message-bubble-mine' : ''}`}>{msg.content}</div>
|
||||
{editing ? (
|
||||
<input
|
||||
autoFocus
|
||||
className="message-edit-input"
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') commitEdit(msg.id)
|
||||
if (e.key === 'Escape') setEditingId(null)
|
||||
}}
|
||||
onBlur={() => commitEdit(msg.id)}
|
||||
/>
|
||||
) : (
|
||||
<div className={`message-bubble${mine ? ' message-bubble-mine' : ''}`}>
|
||||
{msg.content}
|
||||
{mine && (
|
||||
<button
|
||||
type="button"
|
||||
className="message-edit-link"
|
||||
onClick={() => startEdit(msg)}
|
||||
aria-label="Edit message"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="message-time">
|
||||
{new Date(msg.created_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}
|
||||
{msg.edited_at && <span className="message-edited"> (edited)</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -206,6 +206,90 @@
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.room-info-integrations {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-4);
|
||||
margin-top: var(--sp-2);
|
||||
}
|
||||
|
||||
.room-info-integration-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.room-info-webhook-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-2);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.room-info-webhook-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.room-info-webhook-info code {
|
||||
background: var(--ds-surface-2);
|
||||
padding: 3px 6px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.72rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.room-info-webhook-desc {
|
||||
color: var(--ds-muted);
|
||||
font-size: 0.74rem;
|
||||
}
|
||||
|
||||
.room-info-subscription-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.room-info-subscription-form input {
|
||||
background: var(--ds-surface-2);
|
||||
border: 1px solid var(--ds-border);
|
||||
border-radius: var(--radius);
|
||||
padding: 7px 10px;
|
||||
color: var(--ds-text);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.room-info-event-types {
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.room-info-event-type-checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 0.74rem;
|
||||
font-family: var(--mono);
|
||||
color: var(--ds-muted);
|
||||
}
|
||||
|
||||
.room-info-signing-secret {
|
||||
font-size: 0.76rem;
|
||||
color: var(--ds-accent);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.room-info-signing-secret code {
|
||||
background: var(--ds-surface-2);
|
||||
padding: 3px 6px;
|
||||
border-radius: 6px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.room-info-danger-link {
|
||||
background: transparent;
|
||||
border: none;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -141,3 +141,90 @@
|
||||
.admin-load-more {
|
||||
margin-top: var(--sp-4);
|
||||
}
|
||||
|
||||
.admin-create-form {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-4);
|
||||
}
|
||||
|
||||
.admin-create-form input {
|
||||
flex: 1;
|
||||
max-width: 280px;
|
||||
background: var(--ds-surface-2);
|
||||
border: 1px solid var(--ds-border);
|
||||
border-radius: var(--radius);
|
||||
padding: 7px 10px;
|
||||
color: var(--ds-text);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.admin-bot-detail {
|
||||
background: var(--ds-void-2);
|
||||
}
|
||||
|
||||
.admin-token-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-bottom: var(--sp-3);
|
||||
}
|
||||
|
||||
.admin-token-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.admin-token-scopes {
|
||||
font-family: var(--mono);
|
||||
color: var(--ds-text);
|
||||
}
|
||||
|
||||
.admin-token-meta {
|
||||
color: var(--ds-muted);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.admin-token-revoke {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--ds-danger);
|
||||
font-size: 0.76rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin-issue-token {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.admin-scope-checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 0.78rem;
|
||||
font-family: var(--mono);
|
||||
color: var(--ds-muted);
|
||||
}
|
||||
|
||||
.admin-new-token {
|
||||
margin-top: var(--sp-3);
|
||||
font-size: 0.8rem;
|
||||
color: var(--ds-accent);
|
||||
}
|
||||
|
||||
.admin-new-token code {
|
||||
background: var(--ds-surface-2);
|
||||
padding: 3px 8px;
|
||||
border-radius: 6px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.admin-subheading {
|
||||
font-size: 0.95rem;
|
||||
margin: var(--sp-6) 0 var(--sp-3);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Fragment, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
archiveRoom,
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
demoteUser,
|
||||
listAdminRooms,
|
||||
listAdminUsers,
|
||||
listAllEventSubscriptions,
|
||||
listAllIncomingWebhooks,
|
||||
listAuditLog,
|
||||
promoteUser,
|
||||
reactivateUser,
|
||||
@@ -14,14 +16,25 @@ import {
|
||||
unarchiveRoom,
|
||||
} from '../api/admin'
|
||||
import { ApiError } from '../api/client'
|
||||
import { createApiToken, createBot, listApiTokens, listBots, revokeApiToken } from '../api/bots'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import type { AdminRoom, AdminUser, AuditLogEntry } from '../types'
|
||||
import type {
|
||||
AdminRoom,
|
||||
AdminUser,
|
||||
ApiScope,
|
||||
ApiToken,
|
||||
AuditLogEntry,
|
||||
Bot,
|
||||
EventSubscriptionAdmin,
|
||||
WebhookIncomingAdmin,
|
||||
} from '../types'
|
||||
import { TopBar } from '../components/TopBar'
|
||||
import './AdminPage.css'
|
||||
|
||||
type Tab = 'users' | 'rooms' | 'audit' | 'settings'
|
||||
type Tab = 'users' | 'rooms' | 'bots' | 'audit' | 'settings'
|
||||
|
||||
const AUDIT_PAGE_SIZE = 50
|
||||
const ALL_SCOPES: ApiScope[] = ['read:messages', 'write:messages', 'manage:rooms']
|
||||
|
||||
export function AdminPage() {
|
||||
const { user: currentUser } = useAuth()
|
||||
@@ -33,6 +46,15 @@ export function AdminPage() {
|
||||
const [busyId, setBusyId] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const [bots, setBots] = useState<Bot[]>([])
|
||||
const [newBotUsername, setNewBotUsername] = useState('')
|
||||
const [expandedBotId, setExpandedBotId] = useState<string | null>(null)
|
||||
const [tokensByBot, setTokensByBot] = useState<Record<string, ApiToken[]>>({})
|
||||
const [newTokenScopes, setNewTokenScopes] = useState<ApiScope[]>([])
|
||||
const [justCreatedToken, setJustCreatedToken] = useState<string | null>(null)
|
||||
const [incomingWebhooks, setIncomingWebhooks] = useState<WebhookIncomingAdmin[]>([])
|
||||
const [eventSubscriptions, setEventSubscriptions] = useState<EventSubscriptionAdmin[]>([])
|
||||
|
||||
function reportError(err: unknown) {
|
||||
setError(err instanceof ApiError ? err.message : String(err))
|
||||
}
|
||||
@@ -54,12 +76,25 @@ export function AdminPage() {
|
||||
.catch(reportError)
|
||||
}
|
||||
|
||||
function loadBots() {
|
||||
listBots().then(setBots).catch(reportError)
|
||||
}
|
||||
|
||||
function loadWebhooksAdmin() {
|
||||
listAllIncomingWebhooks().then(setIncomingWebhooks).catch(reportError)
|
||||
listAllEventSubscriptions().then(setEventSubscriptions).catch(reportError)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (tab === 'users') loadUsers()
|
||||
if (tab === 'rooms') {
|
||||
loadRooms()
|
||||
if (users.length === 0) loadUsers() // needed to resolve usernames for ownership transfer
|
||||
}
|
||||
if (tab === 'bots') {
|
||||
loadBots()
|
||||
loadWebhooksAdmin()
|
||||
}
|
||||
if (tab === 'audit') loadAuditLog()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tab])
|
||||
@@ -119,6 +154,59 @@ export function AdminPage() {
|
||||
})
|
||||
}
|
||||
|
||||
async function handleCreateBot() {
|
||||
const username = newBotUsername.trim()
|
||||
if (!username) return
|
||||
setError(null)
|
||||
try {
|
||||
await createBot(username)
|
||||
setNewBotUsername('')
|
||||
loadBots()
|
||||
} catch (err) {
|
||||
reportError(err)
|
||||
}
|
||||
}
|
||||
|
||||
function toggleExpandBot(botId: string) {
|
||||
if (expandedBotId === botId) {
|
||||
setExpandedBotId(null)
|
||||
return
|
||||
}
|
||||
setExpandedBotId(botId)
|
||||
setNewTokenScopes([])
|
||||
setJustCreatedToken(null)
|
||||
if (!tokensByBot[botId]) {
|
||||
listApiTokens(botId)
|
||||
.then((tokens) => setTokensByBot((prev) => ({ ...prev, [botId]: tokens })))
|
||||
.catch(reportError)
|
||||
}
|
||||
}
|
||||
|
||||
function toggleScope(scope: ApiScope) {
|
||||
setNewTokenScopes((prev) =>
|
||||
prev.includes(scope) ? prev.filter((s) => s !== scope) : [...prev, scope],
|
||||
)
|
||||
}
|
||||
|
||||
async function handleIssueToken(botId: string) {
|
||||
if (newTokenScopes.length === 0) return
|
||||
await withBusy(botId, async () => {
|
||||
const created = await createApiToken(botId, newTokenScopes)
|
||||
setJustCreatedToken(created.token)
|
||||
setNewTokenScopes([])
|
||||
const tokens = await listApiTokens(botId)
|
||||
setTokensByBot((prev) => ({ ...prev, [botId]: tokens }))
|
||||
})
|
||||
}
|
||||
|
||||
async function handleRevokeToken(botId: string, tokenId: string) {
|
||||
await withBusy(tokenId, async () => {
|
||||
await revokeApiToken(tokenId)
|
||||
const tokens = await listApiTokens(botId)
|
||||
setTokensByBot((prev) => ({ ...prev, [botId]: tokens }))
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<TopBar />
|
||||
@@ -131,7 +219,7 @@ export function AdminPage() {
|
||||
</div>
|
||||
|
||||
<div className="admin-tabs" role="tablist">
|
||||
{(['users', 'rooms', 'audit', 'settings'] as const).map((t) => (
|
||||
{(['users', 'rooms', 'bots', 'audit', 'settings'] as const).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
@@ -142,6 +230,7 @@ export function AdminPage() {
|
||||
>
|
||||
{t === 'users' && 'Users'}
|
||||
{t === 'rooms' && 'Rooms'}
|
||||
{t === 'bots' && 'Bots'}
|
||||
{t === 'audit' && 'Audit log'}
|
||||
{t === 'settings' && 'Settings'}
|
||||
</button>
|
||||
@@ -237,6 +326,147 @@ export function AdminPage() {
|
||||
</table>
|
||||
)}
|
||||
|
||||
{tab === 'bots' && (
|
||||
<>
|
||||
<div className="admin-create-form">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Bot username"
|
||||
value={newBotUsername}
|
||||
onChange={(e) => setNewBotUsername(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="btn-secondary" onClick={handleCreateBot}>
|
||||
Create bot
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Status</th>
|
||||
<th>Created</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{bots.map((b) => (
|
||||
<Fragment key={b.id}>
|
||||
<tr>
|
||||
<td>{b.username}</td>
|
||||
<td>
|
||||
<span className={`status-badge ${b.is_active ? 'active' : 'inactive'}`}>
|
||||
{b.is_active ? 'Active' : 'Deactivated'}
|
||||
</span>
|
||||
</td>
|
||||
<td>{new Date(b.created_at).toLocaleDateString()}</td>
|
||||
<td className="admin-actions">
|
||||
<button type="button" onClick={() => toggleExpandBot(b.id)}>
|
||||
{expandedBotId === b.id ? 'Hide tokens' : 'Manage tokens'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{expandedBotId === b.id && (
|
||||
<tr>
|
||||
<td colSpan={4} className="admin-bot-detail">
|
||||
<div className="admin-token-list">
|
||||
{(tokensByBot[b.id] ?? []).map((t) => (
|
||||
<div key={t.id} className="admin-token-row">
|
||||
<span className="admin-token-scopes">{t.scopes.join(', ')}</span>
|
||||
<span className="admin-token-meta">
|
||||
{t.last_used_at
|
||||
? `last used ${new Date(t.last_used_at).toLocaleDateString()}`
|
||||
: 'never used'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-token-revoke"
|
||||
disabled={busyId === t.id}
|
||||
onClick={() => handleRevokeToken(b.id, t.id)}
|
||||
>
|
||||
Revoke
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{(tokensByBot[b.id] ?? []).length === 0 && (
|
||||
<p className="admin-placeholder">No tokens yet.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="admin-issue-token">
|
||||
{ALL_SCOPES.map((scope) => (
|
||||
<label key={scope} className="admin-scope-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={newTokenScopes.includes(scope)}
|
||||
onChange={() => toggleScope(scope)}
|
||||
/>
|
||||
{scope}
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary"
|
||||
disabled={newTokenScopes.length === 0 || busyId === b.id}
|
||||
onClick={() => handleIssueToken(b.id)}
|
||||
>
|
||||
Issue token
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{justCreatedToken && (
|
||||
<p className="admin-new-token">
|
||||
New token (copy it now, it won't be shown again):{' '}
|
||||
<code>{justCreatedToken}</code>
|
||||
</p>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h2 className="admin-subheading">Registered webhooks</h2>
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Room</th>
|
||||
<th>Type</th>
|
||||
<th>Details</th>
|
||||
<th>Created by</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{incomingWebhooks.map((w) => (
|
||||
<tr key={w.id}>
|
||||
<td>#{w.room_name}</td>
|
||||
<td>Incoming</td>
|
||||
<td>{w.description || '—'}</td>
|
||||
<td>{w.created_by_username}</td>
|
||||
</tr>
|
||||
))}
|
||||
{eventSubscriptions.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.room_name ? `#${s.room_name}` : 'Global'}</td>
|
||||
<td>Outgoing ({s.event_types.join(', ')})</td>
|
||||
<td>{s.target_url}</td>
|
||||
<td>{s.created_by_username}</td>
|
||||
</tr>
|
||||
))}
|
||||
{incomingWebhooks.length === 0 && eventSubscriptions.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="admin-placeholder">
|
||||
No webhooks registered yet.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'audit' && (
|
||||
<>
|
||||
<table className="admin-table">
|
||||
|
||||
+70
-1
@@ -58,6 +58,7 @@ export interface Message {
|
||||
username: string
|
||||
content: string
|
||||
created_at: string
|
||||
edited_at: string | null
|
||||
}
|
||||
|
||||
export interface ChatMessageEnvelope {
|
||||
@@ -68,6 +69,15 @@ export interface ChatMessageEnvelope {
|
||||
username: string
|
||||
content: string
|
||||
created_at: string
|
||||
edited_at: string | null
|
||||
}
|
||||
|
||||
export interface ChatMessageUpdateEnvelope {
|
||||
type: 'message_update'
|
||||
id: string
|
||||
room_id: string
|
||||
content: string
|
||||
edited_at: string | null
|
||||
}
|
||||
|
||||
export interface ChatJoinedEnvelope {
|
||||
@@ -80,7 +90,11 @@ export interface ChatErrorEnvelope {
|
||||
detail: string
|
||||
}
|
||||
|
||||
export type ServerEnvelope = ChatMessageEnvelope | ChatJoinedEnvelope | ChatErrorEnvelope
|
||||
export type ServerEnvelope =
|
||||
| ChatMessageEnvelope
|
||||
| ChatMessageUpdateEnvelope
|
||||
| ChatJoinedEnvelope
|
||||
| ChatErrorEnvelope
|
||||
|
||||
export interface AdminUser {
|
||||
id: string
|
||||
@@ -113,3 +127,58 @@ export interface AuditLogEntry {
|
||||
metadata: Record<string, unknown> | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export type ApiScope = 'read:messages' | 'write:messages' | 'manage:rooms'
|
||||
|
||||
export interface Bot {
|
||||
id: string
|
||||
username: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ApiToken {
|
||||
id: string
|
||||
owner_id: string
|
||||
scopes: ApiScope[]
|
||||
last_used_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ApiTokenCreated extends ApiToken {
|
||||
token: string
|
||||
}
|
||||
|
||||
export interface WebhookIncoming {
|
||||
id: string
|
||||
room_id: string
|
||||
token: string
|
||||
created_by: string
|
||||
description: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface WebhookIncomingAdmin extends WebhookIncoming {
|
||||
room_name: string
|
||||
created_by_username: string
|
||||
}
|
||||
|
||||
export type EventType = 'message.created' | 'message.updated'
|
||||
|
||||
export interface EventSubscription {
|
||||
id: string
|
||||
room_id: string | null
|
||||
event_types: EventType[]
|
||||
target_url: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface EventSubscriptionCreated extends EventSubscription {
|
||||
signing_secret: string
|
||||
}
|
||||
|
||||
export interface EventSubscriptionAdmin extends EventSubscription {
|
||||
room_name: string | null
|
||||
created_by_username: string
|
||||
}
|
||||
|
||||
@@ -48,5 +48,11 @@ export function useChatSocket({ roomId, onMessage, onUnauthenticated }: UseChatS
|
||||
ws.send(JSON.stringify({ type: 'message', room_id: roomId, content }))
|
||||
}, [roomId])
|
||||
|
||||
return { connected, send }
|
||||
const sendEdit = useCallback((messageId: string, content: string) => {
|
||||
const ws = socketRef.current
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||
ws.send(JSON.stringify({ type: 'edit', room_id: roomId, message_id: messageId, content }))
|
||||
}, [roomId])
|
||||
|
||||
return { connected, send, sendEdit }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user