Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.
import { DataPacket_Kind, RoomServiceClient } from "livekit-server-sdk";
import { isLiveKitConfigured } from "@/lib/config";
import { ADMIN_TOPIC, BRIDGE_IDENTITY, type AdminCommand } from "@/lib/types";
/**
* Server-side helpers for the admin surface (/admin). Commands are password-gated here and then sent
* to the Pi control bridge over LiveKit via the server SDK — so the password and the LiveKit API
* secret never reach the browser. Reuses the same LIVEKIT_* credentials as the token route.
*/
/**
* The admin password. Falls back to "test" in dev only; in production `ADMIN_PASSWORD` must be set
* explicitly — a default password on a public deploy is a wide-open door, so admin auth is refused
* outright (returns null) rather than silently guessable.
*/
export function adminPassword(): string | null {
if (process.env.ADMIN_PASSWORD) return process.env.ADMIN_PASSWORD;
return process.env.NODE_ENV === "production" ? null : "test";
}
/** Admin routes need LiveKit creds (to reach the bridge). Password always has a default. */
export function isAdminConfigured(): boolean {
return isLiveKitConfigured();
}
/** Password check — via the `x-admin-password` header or a `?password=` query param. */
export function isAdminAuthorized(req: Request): boolean {
const provided =
req.headers.get("x-admin-password") || new URL(req.url).searchParams.get("password");
const expected = adminPassword();
return expected != null && provided != null && provided === expected;
}
/** LiveKit's HTTP API host, derived from the ws(s):// url the browser connects to. */
function livekitHost(): string {
return process.env.LIVEKIT_URL!.replace(/^ws/, "http");
}
function roomService(): RoomServiceClient {
return new RoomServiceClient(
livekitHost(),
process.env.LIVEKIT_API_KEY!,
process.env.LIVEKIT_API_SECRET!,
);
}
/**
* Deliver an admin command to the bridge on the "admin" topic (reliable). This is SERVER-injected
* data (via the LiveKit HTTP API with the API secret), so on the bridge it arrives with NO source
* participant. SECURITY: the bridge must only honor "admin" commands that are server-injected
* (participant absent) and IGNORE any "admin" data published by a normal participant — otherwise any
* connected browser could publish to the topic and bypass the password entirely.
*/
export async function sendAdminCommand(cmd: AdminCommand): Promise<void> {
await roomService().sendData(
process.env.LIVEKIT_ROOM!,
new TextEncoder().encode(JSON.stringify(cmd)),
DataPacket_Kind.RELIABLE,
{ destinationIdentities: [BRIDGE_IDENTITY], topic: ADMIN_TOPIC },
);
}