SPB Git

Repository Public

engine.test.ts 9.8 KB 132 lines typescript

1import http from "node:http";2import type { AddressInfo } from "node:net";3import { afterAll, beforeAll, describe, expect, it } from "vitest";4import { all, get, run } from "@/server/db";5import { open, redact, seal } from "@/server/secrets";6import * as E from "@/server/engine";7import { presentable } from "@/server/connectors/nasa";8import { ensureBuiltinSources } from "@/server/sync";910describe("credentials at rest", () => {11  it("round-trips, differs every time, and refuses tampering", () => {12    const a = seal("s3cret-pass"), b = seal("s3cret-pass");13    expect(a).not.toBe(b); expect(a).not.toContain("s3cret"); expect(open(a)).toBe("s3cret-pass");14    expect(open(a.slice(0, -3) + "AAA")).toBeNull(); expect(open(null)).toBeNull(); expect(open("garbage")).toBeNull();15  });16  it("redacts credentials from messages", () => {17    expect(redact("GET http://p.example/player_api.php?username=bob&password=hunter2 failed", "hunter2", "bob")).not.toMatch(/hunter2|bob/);18    expect(redact("https://jf/Videos/1/stream?api_key=abcdef&x=1")).toBe("https://jf/Videos/1/stream?api_key=•••&x=1");19  });20});2122describe("NASA titles", () => {23  it("keeps real titles and drops raw file names", () => {24    expect(presentable("Apollo 11: One Small Step")).toBe(true);25    expect(presentable("iss065m261881109_Expedition_65_JAXA_PAO_Event_210707")).toBe(false);26    expect(presentable("KSC-20190311-MH-CSH01")).toBe(false);27  });28});2930// A stand-in for a provider portal: the adapter is exercised against the documented player API, not against a real31// subscription (none is configured). It only proves the adapter, the pipeline and the handling of credentials.32describe("Xtream-compatible provider (local stand-in portal)", () => {33  let server: http.Server, base: string; const seen: string[] = [];34  beforeAll(async () => {35    process.env.SPTV_ALLOW_PRIVATE_HOSTS = "1";36    ensureBuiltinSources();37    server = http.createServer((req, res) => {38      const u = new URL(req.url!, "http://x"); seen.push(u.pathname);39      const ok = u.searchParams.get("username") === "abonne" && u.searchParams.get("password") === "m0t-de-passe";40      const send = (o: unknown) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(o)); };41      if (u.pathname !== "/player_api.php") { res.writeHead(404); return res.end(); }42      if (!ok) return send({ user_info: { auth: 0 } });43      switch (u.searchParams.get("action")) {44        case null: return send({ user_info: { auth: 1, status: "Active", exp_date: "1893456000", max_connections: "2" } });45        case "get_live_categories": return send([{ category_id: "1", category_name: "Actualités" }]);46        case "get_live_streams": return send([{ stream_id: 101, name: "Chaîne Fournisseur 1", stream_icon: "https://example.org/1.png", epg_channel_id: "ch1.example", category_id: "1" }, { stream_id: 102, name: "Chaîne Fournisseur 2", category_id: "1" }]);47        case "get_vod_categories": return send([{ category_id: "9", category_name: "Documentaires" }]);48        case "get_vod_streams": return send([{ stream_id: 501, name: "Film du fournisseur (2020)", container_extension: "mp4", category_id: "9" }, { stream_id: 502, name: "Film MKV", container_extension: "mkv", category_id: "9" }]);49        case "get_series_categories": return send([]);50        case "get_series": return send([{ series_id: 7, name: "Série du fournisseur", plot: "Résumé." }]);51        case "get_series_info": return send({ episodes: { "1": [{ id: "9001", episode_num: 1, title: "Épisode un", container_extension: "mp4", info: { duration_secs: 1200 } }, { id: "9002", episode_num: 2, title: "Épisode deux", container_extension: "mp4" }] } });52      }53      res.writeHead(400); res.end();54    });55    await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));56    base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;57  });58  afterAll(() => { process.env.SPTV_ALLOW_PRIVATE_HOSTS = "0"; server.closeAllConnections(); server.close(); });59  const fields = () => ({ name: "Fournisseur test", server: base, username: "abonne", password: "m0t-de-passe" });6061  it("tests a configuration without storing it", async () => {62    expect(await E.test("xtream", fields())).toMatchObject({ ok: true, details: { statut: "Active", connexions: 2 } });63    const bad = await E.test("xtream", { ...fields(), password: "faux" });64    expect(bad.ok).toBe(false); expect(JSON.stringify(bad)).not.toContain("faux");65    expect(get("SELECT 1 FROM sources WHERE kind = 'xtream'")).toBeUndefined();66  });67  let uid = "";68  it("stores credentials encrypted; nothing readable in the database or the instance list", () => {69    uid = E.create("xtream", fields());70    const row = get<{ config: string; secret: string; url: string }>("SELECT config, secret, url FROM sources WHERE kind = 'xtream'")!;71    expect(JSON.stringify(row)).not.toContain("m0t-de-passe"); expect(open(row.secret)).toBe("m0t-de-passe");72    expect(JSON.stringify(E.instances())).not.toContain("m0t-de-passe");73    expect(() => E.create("xtream", fields())).toThrow(/existe déjà/);74    // the same subscription also registered its film catalogue and its guide75    expect(get("SELECT 1 FROM vod_sources WHERE kind = 'xtream'")).toBeTruthy(); expect(get("SELECT 1 FROM epg_sources WHERE url LIKE 'provider://%'")).toBeTruthy();76  });77  it("imports live channels as opaque references and resolves them only on demand", async () => {78    const src = get<E.LiveSource>("SELECT id, name, url, country, kind, config, secret, content FROM sources WHERE kind = 'xtream'")!;79    const loaded = await E.loadLive(src, () => "");80    expect(loaded.entries.map((e) => e.name)).toEqual(["Chaîne Fournisseur 1", "Chaîne Fournisseur 2"]);81    expect(loaded.entries[0]).toMatchObject({ url: `provider://live/${src.id}/101.m3u8`, group: ["Actualités"], logo: "https://example.org/1.png" });82    expect(JSON.stringify(loaded)).not.toContain("m0t-de-passe");83    expect(await E.resolveProvider(loaded.entries[0].url)).toBe(`${base}/live/abonne/m0t-de-passe/101.m3u8`);84    await expect(E.resolveProvider("provider://live/99999/1.m3u8")).rejects.toThrow();85    await expect(E.resolveProvider("https://example.org/x")).rejects.toThrow();86  });87  it("imports the provider's films and series; a container browsers cannot read gets no play address", async () => {88    const v = get<{ id: number; name: string; config: string; secret: string }>("SELECT id, name, config, secret FROM vod_sources WHERE kind = 'xtream'")!;89    expect(await E.importXtreamVod(v)).toEqual({ movies: 2, series: 1, episodes: 2 });90    const media = all<{ url: string; playback: string }>("SELECT m.url, m.playback FROM media m JOIN titles t ON t.id = m.title_id WHERE t.origin = ? ORDER BY m.id", `xtream:${v.id}`);91    expect(media.map((m) => m.playback)).toEqual(["direct", "unsupported", "direct", "direct"]);92    expect(media.every((m) => m.url.startsWith(`provider://xvod/${v.id}/`))).toBe(true);93    expect(get<{ rights_status: string }>("SELECT rights_status FROM titles WHERE origin = ?", `xtream:${v.id}`)!.rights_status).toBe("provider");94    expect(await E.resolveProvider(media[2].url)).toBe(`${base}/series/abonne/m0t-de-passe/9001.mp4`);95  });96  it("a disabled provider no longer resolves; removing it removes what it brought", async () => {97    E.setEnabled(uid, false);98    await expect(E.resolveProvider(`provider://live/${uid.split(":")[1]}/101.m3u8`)).rejects.toThrow(/désactivé/);99    E.remove(uid);100    expect(get("SELECT 1 FROM sources WHERE kind = 'xtream'")).toBeUndefined(); expect(get("SELECT 1 FROM vod_sources WHERE kind = 'xtream'")).toBeUndefined();101    expect(get("SELECT 1 FROM titles WHERE origin LIKE 'xtream:%'")).toBeUndefined(); expect(get("SELECT 1 FROM epg_sources WHERE url LIKE 'provider://%'")).toBeUndefined();102  });103});104105describe("adding sources without code", () => {106  it("imports an uploaded playlist, a single stream, a guide; validates everything", () => {107    const m3u = "#EXTM3U\n#EXTINF:-1 tvg-id=\"A.ca\" group-title=\"News\",Chaîne A\nhttps://example.org/a.m3u8\n";108    const file = E.create("m3u-file", { name: "Fichier perso", content: m3u, country: "ca" });109    expect(get<{ kind: string; country: string; content: string }>("SELECT kind, country, content FROM sources WHERE id = ?", Number(file.split(":")[1]))).toMatchObject({ kind: "file", country: "CA", content: m3u });110    expect(() => E.create("m3u-file", { name: "Vide", content: "pas une playlist" })).toThrow();111    const st = E.create("stream", { name: "Mon flux", url: "https://example.org/live/master.m3u8", country: "CA" });112    expect(st.startsWith("live:")).toBe(true);113    expect(() => E.create("stream", { name: "Interne", url: "http://192.168.2.1/x.m3u8" })).toThrow(/privée|interne/i);114    expect(() => E.create("m3u-url", { name: "Fichier local", url: "file:///etc/passwd" })).toThrow();115    expect(() => E.create("m3u-url", { name: "", url: "https://example.org/a.m3u" })).toThrow(/Champ requis/);116    expect(() => E.create("wikidata", { name: "x" })).toThrow(/inconnu/);117    expect(E.create("xmltv", { name: "Guide", url: "https://example.org/g.xml.gz" }).startsWith("guide:")).toBe(true);118    E.setPriority(file, 5); expect(get<{ priority: number }>("SELECT priority FROM sources WHERE id = ?", Number(file.split(":")[1]))!.priority).toBe(5);119    expect(() => E.setPriority("vod:1", 5)).toThrow();120    const builtin = E.instances().find((i) => i.builtin && i.family === "live")!;121    expect(() => E.remove(builtin.uid)).toThrow(/désactive/);122    E.remove(file); E.remove(st);123    void run;124  });125  it("lists every family with the same shape and real metrics", () => {126    const list = E.instances();127    expect(new Set(list.map((i) => i.family))).toEqual(new Set(["live", "guide"]));128    expect(list.every((i) => typeof i.uid === "string" && Array.isArray(i.metrics))).toBe(true);129    expect(E.TYPES.filter((t) => !t.builtin).map((t) => t.type)).toEqual(["m3u-url", "m3u-file", "stream", "loop", "xtream", "xmltv", "jellyfin", "folder"]);130  });131});132
Files main
Menu

Theme