/* Kronic room playback bridge: LiveKit is the ONLY transport between peers. * Parent and embedded Chat share the same origin through /borg-chat/app. * No URLs, passwords, or media bytes are sent to other participants. */ (() => { 'use strict'; const PREFIX = 'KRONIC_ROOM_SYNC'; const TOPIC = 'kronic-room-playback-v1'; const VALID_KINDS = new Set(['library', 'youtube', 'twitch', 'music', 'iptv']); const VALID_ACTIONS = new Set(['open', 'play', 'pause', 'seek']); let sequence = 0; const parentIsSameOrigin = () => window.parent !== window && (() => { try { return window.parent.location.origin === location.origin; } catch { return false; } })(); function valid(message) { if (!message || message.v !== 1 || !VALID_KINDS.has(message.kind) || !VALID_ACTIONS.has(message.action)) return false; if (message.kind === 'library' || message.kind === 'music') { if (!Number.isSafeInteger(Number(message.id)) || Number(message.id) <= 0) return false; } else if (typeof message.id !== 'string' || message.id.length < 1 || message.id.length > 100 || !/^[\w-]+$/.test(message.id)) return false; if (message.title !== undefined && (typeof message.title !== 'string' || message.title.length > 240)) return false; if (message.position !== undefined && (!Number.isFinite(message.position) || message.position < 0 || message.position > 864000)) return false; return true; } function toParent(payload) { if (parentIsSameOrigin()) window.parent.postMessage({type: PREFIX + '_INCOMING', payload}, location.origin); } // Do not use the legacy "media" URL player: these messages target Media's native players. window.Kronick = window.Kronick || {}; Kronick.handleNativeRoomPlayback = function (payload, participant) { if (!participant || !valid(payload)) return; toParent(payload); }; window.addEventListener('message', (event) => { if (!parentIsSameOrigin() || event.origin !== location.origin || event.source !== window.parent) return; const message = event.data; if (message?.type !== PREFIX + '_OUTGOING' || !valid(message.payload)) return; const room = Kronick.state?.room; if (!room?.localParticipant || room.state !== 'connected') { window.parent.postMessage({type: PREFIX + '_STATUS', connected: false}, location.origin); return; } const payload = {...message.payload, v: 1, seq: ++sequence}; room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(payload)), { reliable: true, topic: TOPIC, }).catch(error => console.warn('[Kronic room sync] LiveKit publish failed:', error)); }); Kronick.roomPlaybackTopic = TOPIC; })();