SPB Git

Repository Public

sources.ts 3.5 KB 57 lines typescript

1import dns from "node:dns/promises";2import fs from "node:fs";3import net from "node:net";4import { all, get } from "../db";5import { assertPublicUrl, isBlockedIp, UrlRejected } from "../ssrf";6import { parsePolicy, RelayRefused, type Policy, type StreamRow } from "./access";78// SourceManager — the relay side of the IPTV sources: which ones may be relayed, and what the ingest process must read.9// The real address of a stream is only ever produced here, on the server, for the ingest process.1011export interface SourceView { id: number; name: string; kind: string; enabled: boolean; builtin: boolean; streams: number; channels: number; policy: Policy }12export function listSources(): SourceView[] {13  const counts = new Map(all<{ source_id: number; streams: number; channels: number }>("SELECT source_id, COUNT(*) streams, COUNT(DISTINCT channel_id) channels FROM streams GROUP BY source_id").map((r) => [r.source_id, r]));14  return all<{ id: number; name: string; kind: string; enabled: number; builtin: number; relay: string | null }>("SELECT id, name, kind, enabled, builtin, relay FROM sources ORDER BY (relay IS NULL), priority, id")15    .map((s) => ({ id: s.id, name: s.name, kind: s.kind, enabled: !!s.enabled, builtin: !!s.builtin, streams: counts.get(s.id)?.streams ?? 0, channels: counts.get(s.id)?.channels ?? 0, policy: parsePolicy(s.relay) }));16}1718export type Input = { type: "url"; url: string } | { type: "files"; files: string[] };1920/** Destination control: only public http(s) hosts, checked on the name and on every address it resolves to. */21export async function guardUrl(raw: string): Promise<string> {22  let u: URL;23  try { u = assertPublicUrl(raw); } catch (e) { throw new RelayRefused(e instanceof UrlRejected ? e.message : "Adresse invalide", 400); }24  const host = u.hostname.replace(/^\[|\]$/g, "");25  const addrs = net.isIP(host) ? [host] : (await dns.lookup(host, { all: true }).catch(() => [])).map((a) => a.address);26  if (!addrs.length) throw new RelayRefused("Hôte de la source introuvable", 502);27  if (addrs.some(isBlockedIp)) throw new RelayRefused("Destination réseau refusée (adresse privée ou réservée)", 400);28  return u.toString();29}3031export const LOOP_REF = /^provider:\/\/loop\/(\d+)\//;32/** Files of a home channel, in play order. Only media of the personal library, that still exist. */33export function loopFiles(sourceId: number): string[] {34  const src = get<{ config: string | null }>("SELECT config FROM sources WHERE id = ? AND kind = 'loop'", sourceId);35  const ids = ((JSON.parse(src?.config ?? "{}") as { mediaIds?: number[] }).mediaIds ?? []).filter((n) => Number.isInteger(n));36  const files: string[] = [];37  for (const id of ids) {38    const m = get<{ path: string | null }>("SELECT m.path FROM media m JOIN titles t ON t.id = m.title_id WHERE m.id = ? AND m.path IS NOT NULL AND t.library_dir IS NOT NULL", id);39    if (m?.path && fs.existsSync(m.path)) files.push(m.path);40  }41  return files;42}4344export async function resolveInput(row: Pick<StreamRow, "url" | "source_id">): Promise<Input> {45  const loop = LOOP_REF.exec(row.url);46  if (loop) {47    const files = loopFiles(Number(loop[1]));48    if (!files.length) throw new RelayRefused("Les fichiers de cette chaîne maison sont introuvables", 404);49    return { type: "files", files };50  }51  if (row.url.startsWith("provider://")) {52    const { resolveProvider } = await import("../engine");53    return { type: "url", url: await guardUrl(await resolveProvider(row.url)) };54  }55  return { type: "url", url: await guardUrl(row.url) };56}57
Files main
Menu

Theme