SPB Git

Repository Public

relay.test.ts 12.3 KB 142 lines typescript

1import { beforeAll, describe, expect, it } from "vitest";2import { get, now, run, setSetting } from "@/server/db";3import * as A from "@/server/relay/access";4import * as C from "@/server/relay/config";5import { event, recentEvents } from "@/server/relay/events";6import { usage } from "@/server/relay/health";7import * as R from "@/server/relay/relays";8import * as S from "@/server/relay/sessions";9import { guardUrl, resolveInput } from "@/server/relay/sources";10import { choose, explainProbe, ffmpegArgs } from "@/server/relay/transcode";11import { createSession } from "@/server/auth";1213let sourceId = 0, streamId = 0, auth = "";14beforeAll(() => {15  sourceId = Number(run("INSERT INTO sources(kind, name, url, created_at) VALUES('stream', 'Source de test relais', 'https://relay-test.example/live.m3u8', ?)", now()).lastInsertRowid);16  run("INSERT INTO channels(id, name, first_seen, updated_at) VALUES('x-relay-test', 'Chaîne relais', ?, ?)", now(), now());17  streamId = Number(run("INSERT INTO streams(channel_id, source_id, url, first_seen, last_seen) VALUES('x-relay-test', ?, 'https://relay-test.example/live.m3u8', ?, ?)", sourceId, now(), now()).lastInsertRowid);18  const s = createSession({ ip: "198.51.100.7", userAgent: "vitest", method: "password" });19  auth = `s:${A.tokenId(s.token).length ? get<{ token_hash: string }>("SELECT token_hash FROM sessions ORDER BY created_at DESC LIMIT 1")!.token_hash : ""}`;20});2122describe("RelayAccessControl", () => {23  it("refuses every source until its owner declares that relaying is permitted", () => {24    const row = A.streamRow(streamId)!;25    expect(A.eligibility(row)).toEqual({ ok: false, reason: "Le relais n'est pas autorisé pour cette source" });26    expect(() => A.setPolicy(sourceId, { allowed: true, basis: "court" })).toThrow(/au moins 10/);27    expect(() => A.setPolicy(sourceId, { allowed: true, basis: "Flux de test dont je suis l'auteur" })).toThrow(/déclaration/);28    const p = A.setPolicy(sourceId, { allowed: true, basis: "Flux de test dont je suis l'auteur", declaration: true, record: true, maxConnections: 2 });29    expect(p).toMatchObject({ allowed: true, share: true, record: true, maxConnections: 2 }); expect(p.declaredAt).toBeGreaterThan(0);30    expect(A.eligibility(A.streamRow(streamId)!).ok).toBe(true);31  });32  it("never relays a stream that needs forged headers, a disabled source, or anything when the engine is off", () => {33    const row = A.streamRow(streamId)!;34    expect(A.eligibility({ ...row, referrer: "https://site.example/" })).toMatchObject({ ok: false, reason: expect.stringMatching(/en-têtes/) });35    expect(A.eligibility({ ...row, user_agent: "Mozilla/5.0 Forged" }).ok).toBe(false);36    expect(A.eligibility({ ...row, enabled: 0 }).ok).toBe(false);37    expect(A.eligibility({ ...row, url: "rtmp://host/app" }).ok).toBe(false);38    setSetting("relay_enabled", "0"); expect(A.eligibility(row)).toMatchObject({ ok: false, reason: expect.stringMatching(/désactivé/) }); setSetting("relay_enabled", "1");39  });40  it("issues unguessable session tokens and stores only their hash", () => {41    const t = A.newToken(); expect(t).toMatch(A.TOKEN); expect(A.newToken()).not.toBe(t); expect(A.tokenId(t)).toMatch(/^[0-9a-f]{64}$/); expect(A.tokenId(t)).not.toContain(t);42    expect(A.TOKEN.test("../../etc/passwd")).toBe(false);43  });44  it("ties a relay session to a sign-in that still exists", () => {45    expect(A.authStillValid(auth)).toBe(true); expect(A.authStillValid("s:" + "0".repeat(64))).toBe(false); expect(A.authStillValid("p:99999")).toBe(false); expect(A.authStillValid("x:1")).toBe(false);46  });47});4849describe("SourceManager — destination control", () => {50  it("rejects private, loopback and non-http destinations before FFmpeg is ever started", async () => {51    for (const u of ["http://127.0.0.1:8672/r1/index.m3u8", "http://192.168.2.93:8096/x.m3u8", "http://[::1]/a.m3u8", "file:///etc/passwd", "rtsp://198.51.100.1/a", "http://user:pw@example.org/a.m3u8", "http://169.254.169.254/latest"])52      await expect(guardUrl(u), u).rejects.toBeInstanceOf(A.RelayRefused);53  });54  it("a home channel without files is refused", async () => {55    await expect(resolveInput({ url: "provider://loop/987654/1", source_id: 987654 })).rejects.toThrow(/introuvables/);56  });57});5859describe("TranscodeManager", () => {60  const url = { type: "url" as const, url: "https://example.org/live.m3u8" };61  it("copies H.264 8-bit untouched and picks the best picture up to 1080p with the audio of the same programme", () => {62    const p = choose({ programs: [{ program_id: 1, streams: [{ index: 0 }, { index: 1 }] }, { program_id: 2, streams: [{ index: 2 }, { index: 3 }] }, { program_id: 3, streams: [{ index: 4 }, { index: 5 }] }],63      streams: [{ index: 0, codec_type: "video", codec_name: "h264", height: 480, pix_fmt: "yuv420p" }, { index: 1, codec_type: "audio", codec_name: "aac" }, { index: 2, codec_type: "video", codec_name: "h264", height: 1080, pix_fmt: "yuv420p" }, { index: 3, codec_type: "audio", codec_name: "aac" },64        { index: 4, codec_type: "video", codec_name: "h264", height: 2160, pix_fmt: "yuv420p" }, { index: 5, codec_type: "audio", codec_name: "aac" }] }, url);65    expect(p).toMatchObject({ mode: "copy", realtime: false, video: { index: 2, copy: true, height: 1080 }, audio: { index: 3 } });66    const a = ffmpegArgs("r1", url, p, "rtsp://ingest:secret@127.0.0.1:8675/r1", { videoKbps: 4500 });67    expect(a.join(" ")).toContain("-map 0:2 -map 0:3"); expect(a.join(" ")).toContain("-c:v copy"); expect(a).not.toContain("-re");68    expect(a[a.indexOf("-protocol_whitelist") + 1]).toBe("http,https,tcp,tls,crypto"); expect(a.slice(-4)).toEqual(["rtsp", "-rtsp_transport", "tcp", "rtsp://ingest:secret@127.0.0.1:8675/r1"]);69  });70  it("re-encodes what browsers cannot play (HEVC, 10-bit, MPEG-2) and caps the bitrate", () => {71    for (const v of [{ codec_name: "hevc", pix_fmt: "yuv420p" }, { codec_name: "h264", pix_fmt: "yuv420p10le" }, { codec_name: "mpeg2video", pix_fmt: "yuv420p" }]) {72      const p = choose({ streams: [{ index: 0, codec_type: "video", height: 720, ...v }, { index: 1, codec_type: "audio", codec_name: "ac3" }] }, url);73      expect(p.mode, v.codec_name).toBe("transcode");74      const a = ffmpegArgs("r1", url, p, "rtsp://x", { videoKbps: 2000 }).join(" ");75      expect(a).toMatch(/-c:v (h264_videotoolbox|libx264)/); expect(a).toContain("-b:v 2000k"); expect(a).toContain("-c:a aac");76    }77  });78  it("reads files at their natural speed, in a loop, and makes several files uniform", () => {79    const one = { type: "files" as const, files: ["/media/a.mp4"] };80    const p1 = choose({ streams: [{ index: 0, codec_type: "video", codec_name: "h264", height: 360, pix_fmt: "yuv420p" }, { index: 1, codec_type: "audio", codec_name: "aac" }], format: { duration: "596.4" } }, one);81    expect(p1).toMatchObject({ mode: "copy", realtime: true, uniform: false });82    expect(ffmpegArgs("r1", one, p1, "rtsp://x", { videoKbps: 4500 }).slice(4, 9)).toEqual(["-re", "-stream_loop", "-1", "-i", "/media/a.mp4"]);83    const p3 = choose({ streams: [{ index: 0, codec_type: "video", codec_name: "h264", height: 1080, pix_fmt: "yuv420p" }, { index: 1, codec_type: "audio", codec_name: "aac" }] }, { type: "files", files: ["/a.mp4", "/b.mp4"] });84    expect(p3).toMatchObject({ mode: "transcode", uniform: true });85  });86  it("ignores cover art, accepts audio-only streams, refuses empty ones, and names protected streams as such", () => {87    expect(choose({ streams: [{ index: 0, codec_type: "video", codec_name: "mjpeg", disposition: { attached_pic: 1 } }, { index: 1, codec_type: "audio", codec_name: "mp3" }] }, url).mode).toBe("audio");88    expect(() => choose({ streams: [] }, url)).toThrow(/Aucune piste/);89    expect(explainProbe("SAMPLE-AES encryption is not supported")).toMatch(/DRM/); expect(explainProbe("Server returned 403 Forbidden")).toMatch(/rien n'est contourné/);90    expect(explainProbe("https://secret.example/tok=abc: Connection timed out")).not.toContain("secret.example");91  });92});9394describe("RelayManager and StreamSessionManager", () => {95  it("shares one relay per stream, or one per sign-in when the source does not allow sharing", () => {96    const pol = A.parsePolicy(JSON.stringify({ allowed: true, basis: "x", share: true, record: false }));97    expect(R.relayId(35, pol, "s:a")).toBe("rz"); expect(R.relayId(35, pol, "s:b")).toBe("rz"); expect(R.relayId(35, { ...pol, record: true }, "s:a")).toBe("tz");98    const solo = { ...pol, share: false }; expect(R.relayId(35, solo, "s:a")).not.toBe(R.relayId(35, solo, "s:b")); expect(R.relayId(35, solo, "s:a")).toMatch(C.RELAY_ID);99    expect(C.RELAY_ID.test("r1/../x")).toBe(false); expect(C.RELAY_ID.test("all_others")).toBe(false);100  });101  it("opens sessions up to the limit, counts their traffic, and closes them on silence or sign-out", () => {102    const row = A.streamRow(streamId)!;103    run("INSERT INTO relays(id, stream_id, channel_id, source_id, plan, mode, state, created_at) VALUES('rtest', ?, 'x-relay-test', ?, '{}', 'copy', 'idle', ?)", streamId, sourceId, now());104    const relay = R.getRelay("rtest")!;105    setSetting("relay_max_sessions", "2");106    const a = S.open(relay, row, auth, { ip: "198.51.100.7", userAgent: "ua" }), b = S.open(relay, row, auth, { ip: "198.51.100.7", userAgent: "ua" });107    expect(() => S.open(relay, row, auth, { ip: "198.51.100.7", userAgent: "ua" })).toThrow(/Nombre maximal de lecteurs/);108    expect(S.lookup(a.token)?.relay_id).toBe("rtest"); expect(S.lookup(A.newToken())).toBeNull();109    S.touch(a.id, 0); S.touch(a.id, 5000); S.touch(a.id, 7000); S.flush();110    expect(get<{ bytes_out: number; requests: number }>("SELECT bytes_out, requests FROM relay_sessions WHERE id = ?", a.id)).toEqual({ bytes_out: 12000, requests: 1 });111    expect(S.close(a.id, "fermé par le lecteur")).toBe(true); expect(S.close(a.id, "encore")).toBe(false); expect(S.lookup(a.token)).toBeNull();112    run("UPDATE relay_sessions SET last_seen_at = ? WHERE id = ?", now() - S.idleMs() - 1000, b.id);113    expect(S.expire()).toBe(1); expect(get<{ end_reason: string }>("SELECT end_reason FROM relay_sessions WHERE id = ?", b.id)!.end_reason).toBe("inactivité");114    setSetting("relay_max_sessions", "12");115  });116  it("stopping a relay closes its sessions", () => {117    const s = S.open(R.getRelay("rtest")!, A.streamRow(streamId)!, auth, { ip: "x", userAgent: null });118    expect(R.stop("rtest", "arrêt manuel")).toBe(true); expect(S.lookup(s.token)).toBeNull(); expect(R.getRelay("rtest")!.state).toBe("stopped"); expect(R.stop("rnope", "x")).toBe(false);119  });120});121122describe("engine configuration, journal and measurements", () => {123  it("binds every MediaMTX listener to the loopback interface and disables what is not used", () => {124    const y = C.renderConfig("/app");125    for (const k of ["apiAddress", "playbackAddress", "rtspAddress", "hlsAddress"]) expect(y, k).toMatch(new RegExp(`^${k}: 127\\.0\\.0\\.1:\\d+$`, "m"));126    for (const k of ["rtmp", "webrtc", "srt", "moq", "metrics", "pprof"]) expect(y).toMatch(new RegExp(`^${k}: no$`, "m"));127    expect(y).toContain('ips: ["127.0.0.1", "::1"]'); expect(y).not.toMatch(/ips: \[\]/); expect(y).toContain("rtspTransports: [tcp]"); expect(y).not.toContain("all_others");128    expect(y).toContain("hlsSegmentCount: 9"); expect(y).toContain("hlsMuxerCloseAfter: 30s"); expect(y).toContain("recordDeleteAfter: 120m");129    setSetting("relay_buffer_sec", "30"); setSetting("relay_idle_sec", "90");130    const z = C.renderConfig("/app"); expect(z).toContain("hlsSegmentCount: 18"); expect(z).toContain("hlsMuxerCloseAfter: 90s");131    setSetting("relay_buffer_sec", "12"); setSetting("relay_idle_sec", "30");132  });133  it("never writes an address or a credential in the journal", () => {134    event("warn", "ingest", "Flux interrompu : https://provider.example/live/bob/hunter2/12.m3u8 a répondu 502, rtsp://ingest:pass@127.0.0.1:8675/r1 fermé");135    const m = recentEvents(1)[0].message; expect(m).not.toMatch(/hunter2|provider\.example|ingest:pass/); expect(m).toContain("(adresse masquée)");136  });137  it("adds up a process and everything it started", () => {138    const procs = [{ pid: 10, ppid: 1, cpu: 1.5, rssMb: 60, args: "node ingest.ts" }, { pid: 11, ppid: 10, cpu: 8, rssMb: 120, args: "/opt/homebrew/bin/ffmpeg -i x" }, { pid: 12, ppid: 1, cpu: 50, rssMb: 900, args: "other" }];139    expect(usage(procs, 10)).toEqual({ cpu: 9.5, rssMb: 180, ffmpeg: 11 }); expect(usage(procs, 99)).toEqual({ cpu: 0, rssMb: 0, ffmpeg: null });140  });141});142
Files main
Menu

Theme