Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,8 @@ jobs:
node --check portal/static/js/booth-reconnect.js
node --check portal/static/js/mic-activity.js
node --check portal/static/js/whep-listener.js
node --check portal/static/js/embed-player.js
node --check portal/static/js/audio-scheduler.js
node --check portal/static/js/admin.js
node --check portal/static/js/attendance.js
node --check portal/static/js/booth-detail.js
Expand All @@ -308,6 +310,7 @@ jobs:
run: |
node tests/test_audio_scheduler.js
node tests/test_tts_parser.js
node tests/test_embed_player.js
node --test tests/test_demo_modal.js
node tests/test_listener_event.js
node tests/test_whep_listener.js
Expand Down
14 changes: 12 additions & 2 deletions portal/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,24 +162,28 @@ def create_listener_token(*, event_slug: str) -> str:
return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256")


def create_embed_token(*, event_slug: str) -> str:
def create_embed_token(*, event_slug: str, room_id: int | None = None) -> str:
"""Create a short-lived JWT for embed iframe access.

Identical claim shape to create_listener_token (kind='listener', event_slug)
so it passes both the embed route's claim checks and the /ws/captions
WebSocket auth's booth_id.startswith(event_slug + '-') check.
When ``room_id`` is provided, /embed, /ws/captions, and /ws/tts enforce
that the target channel belongs to that room.
Uses a shorter expiry (embed_token_expiry_seconds, default 30 min) because
the token is visible in the iframe src= attribute in the third party's HTML.
"""
now = datetime.now(timezone.utc)
payload = {
payload: dict[str, object] = {
"sub": str(uuid.uuid4()),
"kind": LISTENER_TOKEN_KIND,
"purpose": "embed",
"event_slug": event_slug,
"iat": now,
"exp": now + timedelta(seconds=settings.embed_token_expiry_seconds),
}
if room_id is not None:
payload["room_id"] = room_id
return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256")


Expand All @@ -193,6 +197,12 @@ class WSAuthError(Exception):
pass


class EmbedTokenExpiredError(WSAuthError):
"""Raised when a short-lived embed WebSocket token has expired."""

pass


def token_issued_at(payload: dict) -> datetime | None:
issued_at = payload.get("iat")
if isinstance(issued_at, bool) or not isinstance(issued_at, (int, float)):
Expand Down
99 changes: 72 additions & 27 deletions portal/routers/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import asyncio
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypedDict

import jwt
from fastapi import APIRouter, HTTPException, Query, Request, status
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import JSONResponse, Response

from portal.auth import (
Expand All @@ -30,6 +32,7 @@
)
from portal.globals import _JS_CACHE_BUST, asset_version_context
from portal.join_code_limit import JoinCodeThrottled, verify_join_code
from portal.models import Event, Room
from portal.overlay_channels import overlay_channels
from portal.utils import _ensure_mediamtx_path

Expand Down Expand Up @@ -250,7 +253,7 @@ async def subtitle_overlay(
return response


def _verify_embed_token(token: str, event_slug: str) -> None:
def _verify_embed_token(token: str, event_slug: str) -> dict[str, Any]:
"""Validate the embed token and its listener/embed claims for ``event_slug``.

Raises ``HTTPException(403)`` for a missing, expired, invalid, or mismatched token.
Expand All @@ -272,10 +275,20 @@ def _verify_embed_token(token: str, event_slug: str) -> None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token must be an embed token.")
if payload.get("event_slug") != event_slug:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this event.")
return payload


async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tuple[int, int]:
"""Resolve the target room id and its audio delay for an embed request."""
@dataclass(frozen=True)
class EmbedChannel:
booth_id: str
channel_id: str
audio_mode: str = "whep"
tts_booth_id: str = ""
tts_language_code: str = ""


async def _resolve_embed_room(session: AsyncSession, ev: Event, room_id: int | None) -> tuple[Room, int]:
"""Resolve the target room and its audio delay for an embed request."""
rooms = await list_rooms_for_event(session, ev.id, limit=None)
if room_id is None:
if not rooms:
Expand All @@ -285,39 +298,56 @@ async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tup
status_code=status.HTTP_400_BAD_REQUEST,
detail="This event has multiple rooms. Please use the /embed/{event_slug}/{room_id}/{language_code} URL instead.",
)
return rooms[0].id, rooms[0].audio_delay_ms
return rooms[0], rooms[0].audio_delay_ms

room = next((r for r in rooms if r.id == room_id), None)
if not room:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Room not found.")
return room.id, room.audio_delay_ms
return room, room.audio_delay_ms


async def _resolve_embed_channel(
session: Any, ev: Any, event_slug: str, room_id: int, language_code: str
) -> tuple[str, str]:
"""Resolve the booth id and mediamtx channel id for the requested language."""
session: AsyncSession, ev: Event, event_slug: str, room: Room, language_code: str
) -> EmbedChannel:
"""Resolve the booth id, mediamtx channel id, and audio mode for the requested language."""
from portal.booth_identity import make_booth_id, make_mediamtx_path

norm_lang = language_code.lower()
try:
booth_id = make_booth_id(ev.slug, room_id, language_code.lower())
channel_id = make_mediamtx_path(ev.slug, room_id, language_code.lower())
booth_id = make_booth_id(ev.slug, room.id, norm_lang)
channel_id = make_mediamtx_path(ev.slug, room.id, norm_lang)
except ValueError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invalid language code.")

if language_code.lower() != "floor":
db_booths = await list_booths_for_event(session, ev.id, limit=None)
booth = next(
(b for b in db_booths if b.language_code.lower() == language_code.lower() and b.room_id == room_id),
if norm_lang == "floor":
return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep")

db_booths = await list_booths_for_room(session, room.id)
booth = next((b for b in db_booths if b.language_code.lower() == norm_lang), None)
if booth is not None:
return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep")

if room.floor_translation_enabled:
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
lang = next(
(item for item in room.translation_languages if item.enabled and item.language_code.lower() == norm_lang),
None,
)
if booth is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No booth for language '{language_code}' in event '{event_slug}'.",
)

return booth_id, channel_id
if lang is not None:
if room.floor_tts_enabled and lang.tts_enabled:
floor_booth_id = make_booth_id(ev.slug, room.id, "floor")
return EmbedChannel(
booth_id=booth_id,
channel_id="",
audio_mode="tts",
tts_booth_id=floor_booth_id,
tts_language_code=norm_lang,
)
return EmbedChannel(booth_id=booth_id, channel_id="", audio_mode="none")

raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No booth for language '{language_code}' in event '{event_slug}'.",
)


def _sanitize_embed_theme(
Expand Down Expand Up @@ -369,13 +399,17 @@ def _build_embed_context(
postmessage_target_origin: str,
allowed_origins_list: list[str],
audio_delay_ms: int,
audio_mode: str = "whep",
tts_url: str = "",
) -> dict[str, Any]:
"""Assemble the Jinja2 context for the embed template."""
return {
"event_slug": event_slug,
"language_code": language_code,
"whep_url": whep_url,
"caption_url": caption_url,
"tts_url": tts_url,
"audio_mode": audio_mode,
"token": token,
"theme": safe_theme,
"primary_color": safe_primary,
Expand Down Expand Up @@ -406,20 +440,29 @@ async def _embed_listener_impl(
target_lang: str | None,
):
# Authentication
_verify_embed_token(token, event_slug)
token_payload = _verify_embed_token(token, event_slug)

# Resolve booth
async with get_session() as session:
ev = await get_event_by_slug(session, event_slug)
if not ev:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found.")

resolved_room_id, audio_delay_ms = await _resolve_embed_room(session, ev, room_id)
booth_id, channel_id = await _resolve_embed_channel(session, ev, event_slug, resolved_room_id, language_code)
room, audio_delay_ms = await _resolve_embed_room(session, ev, room_id)
token_room = token_payload.get("room_id")
if token_room is not None and str(token_room) != str(room.id):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this room.")
channel = await _resolve_embed_channel(session, ev, event_slug, room, language_code)

whep_url = f"{settings.mediamtx_whip_base}/{channel_id}/whep"
whep_url = f"{settings.mediamtx_whip_base}/{channel.channel_id}/whep" if channel.audio_mode == "whep" else ""
host = settings.public_base_url.replace("https://", "").replace("http://", "")
caption_url = f"wss://{host}/ws/captions/{booth_id}"
caption_url = f"wss://{host}/ws/captions/{channel.booth_id}"
tts_url = (
f"wss://{host}/ws/tts/{room.id}/{channel.tts_language_code}/{channel.tts_booth_id}"
if channel.audio_mode == "tts"
else ""
)
captions_effective = captions or channel.audio_mode == "none"

# Sanitize theming params
safe_theme, safe_font, safe_primary, safe_custom_css = _sanitize_embed_theme(
Expand All @@ -443,13 +486,15 @@ async def _embed_listener_impl(
safe_theme=safe_theme,
safe_primary=safe_primary,
safe_font=safe_font,
captions=captions,
captions=captions_effective,
safe_custom_css=safe_custom_css,
target_lang=target_lang,
headless=headless,
postmessage_target_origin=postmessage_target_origin,
allowed_origins_list=allowed_origins_list,
audio_delay_ms=audio_delay_ms,
audio_mode=channel.audio_mode,
tts_url=tts_url,
)

return templates.TemplateResponse(request=request, name="embed.html", context=context, headers=response_headers)
Expand Down
6 changes: 5 additions & 1 deletion portal/static/css/embed.css
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ body {
flex-shrink: 0;
transition: background 0.3s;
}
.status-dot.live { background: #22c55e; box-shadow: 0 0 6px #22c55e88; }
.status-dot.live,
.status-dot.captions { background: var(--vb-color-live); box-shadow: 0 0 6px color-mix(in srgb, var(--vb-color-live) 53%, transparent); }
.status-dot.error { background: #ef4444; }
.status-dot.connecting { background: var(--primary); animation: pulse 1.2s infinite; }

Expand All @@ -70,6 +71,9 @@ body {
}

/* ── Play button ─────────────────────────────────────────────────────── */
.play-btn[hidden] {
display: none;
}
.play-btn {
display: flex;
align-items: center;
Expand Down
5 changes: 3 additions & 2 deletions portal/static/js/audio-scheduler.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ function createAudioScheduler(audioCtx, opts) {
? opts.comfortNoiseLevelDb : -40;
var COMFORT_NOISE_FADE_SEC = typeof opts.comfortNoiseFadeSec === 'number'
? opts.comfortNoiseFadeSec : 0.5;
var destination = opts.destination || audioCtx.destination;

/** @type {number} audioCtx.currentTime when the last scheduled buffer ends */
var nextScheduledTime = 0;
Expand Down Expand Up @@ -95,7 +96,7 @@ function createAudioScheduler(audioCtx, opts) {
comfortNoiseGain.gain.linearRampToValueAtTime(
1, audioCtx.currentTime + COMFORT_NOISE_FADE_SEC
);
comfortNoiseGain.connect(audioCtx.destination);
comfortNoiseGain.connect(destination);

comfortNoiseSource = audioCtx.createBufferSource();
comfortNoiseSource.buffer = getComfortNoiseBuffer();
Expand Down Expand Up @@ -196,7 +197,7 @@ function createAudioScheduler(audioCtx, opts) {

var source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.connect(destination);
source.onended = function () {
scheduledSources.delete(source);
};
Expand Down
Loading