SPB Git

Repository Public

access.ts 5.8 KB 76 lines typescript

1import crypto from "node:crypto";2import { get, now, run } from "../db";3import { enabled } from "./config";4import { event } from "./events";56// RelayAccessControl — who may open a relay, and for which sources.7// A relay re-serves a stream from this server. That is only done for sources whose owner declared, in the administration,8// that relaying is permitted (own files, own servers, a provider whose terms allow it, an openly licensed stream), and9// never for a stream that needs forged request headers. Nothing here weakens what a source enforces: no DRM handling,10// no header or address spoofing, and the number of upstream connections never exceeds what the source allows.1112export interface Policy { allowed: boolean; basis: string; share: boolean; record: boolean; maxConnections: number | null; declaredAt: number | null }13export const NO_POLICY: Policy = { allowed: false, basis: "", share: true, record: false, maxConnections: null, declaredAt: null };14export function parsePolicy(raw: string | null | undefined): Policy {15  if (!raw) return NO_POLICY;16  try {17    const p = JSON.parse(raw) as Partial<Policy>;18    return { allowed: p.allowed === true, basis: String(p.basis ?? "").slice(0, 400), share: p.share !== false, record: p.record === true, maxConnections: Number(p.maxConnections) > 0 ? Math.min(50, Math.round(Number(p.maxConnections))) : null, declaredAt: Number(p.declaredAt) || null };19  } catch { return NO_POLICY; }20}2122export class RelayRefused extends Error { constructor(message: string, public status = 403) { super(message); } }2324export interface PolicyInput { allowed: boolean; basis?: string; share?: boolean; record?: boolean; maxConnections?: number | null; declaration?: boolean }25/** Records the owner's decision for one source. Authorising requires a stated basis and an explicit declaration. */26export function setPolicy(sourceId: number, input: PolicyInput): Policy {27  const src = get<{ id: number; name: string; kind: string; relay: string | null }>("SELECT id, name, kind, relay FROM sources WHERE id = ?", sourceId);28  if (!src) throw new RelayRefused("Source inconnue", 404);29  const cur = parsePolicy(src.relay);30  if (!input.allowed) {31    if (src.kind === "loop") throw new RelayRefused("Une chaîne maison n'existe que par le relais : supprimez-la plutôt", 400);32    run("UPDATE sources SET relay = ? WHERE id = ?", JSON.stringify({ ...cur, allowed: false }), sourceId);33    event("info", "access", `Relais retiré pour la source « ${src.name} »`);34    return { ...cur, allowed: false };35  }36  const basis = (input.basis ?? cur.basis).trim();37  if (basis.length < 10) throw new RelayRefused("Indiquez sur quoi repose l'autorisation de relayer cette source (au moins 10 caractères)", 400);38  if (!cur.allowed && input.declaration !== true) throw new RelayRefused("La déclaration d'autorisation est requise", 400);39  const next: Policy = { allowed: true, basis: basis.slice(0, 400), share: input.share ?? cur.share, record: input.record ?? cur.record,40    maxConnections: input.maxConnections === undefined ? cur.maxConnections : Number(input.maxConnections) > 0 ? Math.min(50, Math.round(Number(input.maxConnections))) : null, declaredAt: cur.allowed ? cur.declaredAt : now() };41  run("UPDATE sources SET relay = ? WHERE id = ?", JSON.stringify(next), sourceId);42  event("info", "access", `Relais autorisé pour la source « ${src.name} »${next.record ? " (enregistrement pour le différé autorisé)" : ""}`);43  return next;44}4546export interface StreamRow { id: number; channel_id: string; source_id: number; url: string; referrer: string | null; user_agent: string | null; kind: string; enabled: number; relay: string | null; source_name: string; channel_name: string }47export const streamRow = (streamId: number) => get<StreamRow>(48  `SELECT s.id, s.channel_id, s.source_id, s.url, s.referrer, s.user_agent, src.kind, src.enabled, src.relay, src.name source_name, c.name channel_name49   FROM streams s JOIN sources src ON src.id = s.source_id JOIN channels c ON c.id = s.channel_id WHERE s.id = ?`, streamId);5051export type Eligibility = { ok: true; policy: Policy } | { ok: false; reason: string };52/** Whether a stream may be relayed at all (independently of who asks and of the current load). */53export function eligibility(row: Pick<StreamRow, "url" | "referrer" | "user_agent" | "enabled" | "relay">): Eligibility {54  if (!enabled()) return { ok: false, reason: "Le moteur de relais est désactivé" };55  const policy = parsePolicy(row.relay);56  if (!policy.allowed) return { ok: false, reason: "Le relais n'est pas autorisé pour cette source" };57  if (!row.enabled) return { ok: false, reason: "Cette source est désactivée" };58  if (row.referrer || row.user_agent) return { ok: false, reason: "Ce flux exige des en-têtes particuliers : il n'est pas relayé" };59  if (!/^(https?|provider):\/\//i.test(row.url)) return { ok: false, reason: "Type d'adresse non relayable" };60  return { ok: true, policy };61}6263// --- playback capabilities ---------------------------------------------------------------------------------------------64// A relay session is addressed by a random 256-bit token placed in the path of its playback address; only its SHA-256 is stored.65export const newToken = () => crypto.randomBytes(32).toString("base64url");66export const tokenId = (token: string) => crypto.createHash("sha256").update(token).digest("hex");67export const TOKEN = /^[A-Za-z0-9_-]{43}$/;6869/** The sign-in (or personal playlist) a relay session was opened with must still be valid for the session to be served. */70export function authStillValid(auth: string): boolean {71  const [kind, id] = [auth.slice(0, 1), auth.slice(2)];72  if (kind === "s") return !!get("SELECT 1 FROM sessions WHERE token_hash = ? AND expires_at > ?", id, now());73  if (kind === "p") return !!get("SELECT 1 FROM playlists WHERE id = ?", Number(id));74  return false;75}76
Files main
Menu

Theme