Add URL previews for chat messages (#43)

Slack/Discord-style link unfurling: the first http(s) URL in a message's
content gets a small preview card (title/description/image/site name)
fetched from the page's Open Graph tags.

Backend:
- Message.preview_url (extracted at create/edit time, cheap regex, no
  I/O) points at a link_previews cache row keyed by URL -- the same URL
  posted in different messages/rooms fetches once, and a failed fetch is
  cached too so a dead URL isn't retried on every reference.
- The actual fetch runs in a background asyncio.create_task from
  broadcast_new_message/broadcast_message_update, on its own DB session,
  so a slow third-party site never delays message delivery. A separate
  "link_preview" WS envelope carries the result once it resolves.
- SSRF protection reuses app/services/ssrf.py's validate_target_url
  (renamed from UnsafeWebhookUrlError to UnsafeUrlError now that it's
  shared with webhooks), but re-validates before every hop of a redirect
  chain rather than once up front -- redirects are followed manually so
  each intermediate URL is checked before it's ever connected to.
- Parsed with stdlib html.parser -- no new dependency.

Frontend: a LinkPreviewCard rendered under message content when present,
patched into state live via the new WS envelope and included in message
history for reloads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-17 17:50:55 -06:00
co-authored by Claude Sonnet 5
parent 752da74c5a
commit 760d2cf5dd
18 changed files with 835 additions and 21 deletions
+8 -1
View File
@@ -8,6 +8,7 @@ from sqlalchemy.orm import selectinload
from app.models import Message, MessageMention, MessageReaction
from app.schemas.message import ReactionSummary
from app.services.link_preview_service import extract_first_url
from app.services.mention_service import extract_mentioned_user_ids
@@ -28,7 +29,12 @@ async def create_message(
file_id: uuid.UUID | None = None,
) -> Message:
message = Message(
room_id=room_id, user_id=user_id, content=content, image_id=image_id, file_id=file_id
room_id=room_id,
user_id=user_id,
content=content,
image_id=image_id,
file_id=file_id,
preview_url=extract_first_url(content),
)
db.add(message)
# message.id is available immediately (a Python-side uuid4 default, not
@@ -52,6 +58,7 @@ async def edit_message(
raise NotMessageAuthorError()
message.content = content
message.preview_url = extract_first_url(content)
message.edited_at = datetime.now(timezone.utc)
await db.commit()
await db.refresh(message)