videogen/apps/watch/tests/cast-receiver.test.ts
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

287 lines
14 KiB
TypeScript

import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { apiBaseProblem, DEFAULT_POLICY, readCast, readCustomData, refreshInMs, swapToken, tokenOf, TokenKeeper,
grantFetcher } from "../cast-receiver/token.js";
import { API_ORIGINS, ALLOW_LOCALHOST } from "../cast-receiver/config.js";
import { apiOrigins, renderConfig, uploads as castUploads } from "../scripts/cast-publish.mjs";
const API = "https://api.example/api/v1";
const POLICY = { origins: ["https://api.example"], allowLocalhost: false };
/** A fake clock and timer queue, so 30 minutes of casting run in a few milliseconds. */
function fakeTime() {
let now = 1_800_000_000_000;
let seq = 0;
const timers = new Map<number, { at: number; fn: () => void }>();
return {
now: () => now,
setTimer: (fn: () => void, ms: number) => {
seq += 1;
timers.set(seq, { at: now + ms, fn });
return seq;
},
clearTimer: (id: number) => void timers.delete(id),
async advanceTo(target: number) {
for (;;) {
const due = [...timers.entries()].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
if (!due) break;
timers.delete(due[0]);
now = due[1].at;
due[1].fn();
await new Promise((r) => setTimeout(r, 0));
}
now = target;
},
};
}
describe("cast receiver tokens", () => {
it("swaps the token in the stream path and in the key URL", () => {
const seg = `${API}/ott/stream/old.tok/v_720/12.m4s`;
expect(tokenOf(seg)).toBe("old.tok");
expect(swapToken(seg, "new.tok")).toBe(`${API}/ott/stream/new.tok/v_720/12.m4s`);
expect(swapToken(`${API}/ott/keys/t1?t=old.tok&kv=2`, "new.tok")).toBe(`${API}/ott/keys/t1?t=new.tok&kv=2`);
expect(swapToken("https://r2.example/seg.m4s", "new")).toBe("https://r2.example/seg.m4s");
expect(refreshInMs(1000, 900_000)).toBe(40_000);
expect(refreshInMs(1000, 999_000)).toBe(0);
});
it("refuses a cast without an https API or a title", () => {
expect(readCustomData({ apiBase: "http://x", titleId: "t1" }, POLICY)).toBeNull();
expect(readCustomData({ apiBase: API, titleId: "../x" }, POLICY)).toBeNull();
expect(readCustomData({ apiBase: `${API}/`, titleId: "t1", session: "vs", deviceId: "d" }, POLICY))
.toEqual({ apiBase: API, titleId: "t1", session: "vs", deviceId: "d" });
});
it("casts a 30-minute title to the end on 10-minute tokens", async () => {
const time = fakeTime();
let issued = 0;
const expiry = new Map<string, number>();
const fetchGrant = async () => {
issued += 1;
const token = `tok${issued}`;
const expiresAt = Math.floor(time.now() / 1000) + 600;
expiry.set(token, expiresAt);
return { manifest_url: `${API}/ott/stream/${token}/master.m3u8`, expires_at: expiresAt };
};
const keeper = new TokenKeeper(fetchGrant, time as never);
const manifest = await keeper.start();
const start = time.now();
let refused = 0;
let served = 0;
// The player keeps the first manifest's relative URLs: every segment starts with tok1.
for (let t = 0; t <= 30 * 60; t += 6) {
await time.advanceTo(start + t * 1000);
const url = keeper.rewrite(manifest.replace("master.m3u8", `v_720/${t / 6}.m4s`));
const exp = expiry.get(tokenOf(url)) ?? 0;
if (exp * 1000 > time.now()) served += 1;
else refused += 1;
}
keeper.stop();
expect(refused).toBe(0);
expect(served).toBe(301);
expect(issued).toBeGreaterThanOrEqual(4);
});
it("keeps the last token and retries when one refresh fails", async () => {
const time = fakeTime();
let calls = 0;
const keeper = new TokenKeeper(async () => {
calls += 1;
if (calls === 2) throw new Error("offline");
return { manifest_url: `${API}/ott/stream/t${calls}/master.m3u8`, expires_at: Math.floor(time.now() / 1000) + 600 };
}, time as never);
await keeper.start();
await time.advanceTo(time.now() + 541_000);
expect(keeper.token).toBe("t1");
await time.advanceTo(time.now() + 15_000);
expect(keeper.token).toBe("t3");
keeper.stop();
});
it("asks the API as the viewer who cast", async () => {
const seen: { url: string; init: RequestInit }[] = [];
const fetcher = grantFetcher({ apiBase: API, titleId: "t1", session: "vs-1", deviceId: "dev-1" },
async (url: string, init: RequestInit) => {
seen.push({ url, init });
return { ok: true, json: async () => ({ data: { manifest_url: `${API}/ott/stream/a/master.m3u8`, expires_at: 1 } }) };
}, POLICY);
await fetcher();
expect(seen[0].url).toBe(`${API}/ott/play/t1`);
expect((seen[0].init.headers as Record<string, string>)["X-OTT-Viewer"]).toBe("vs-1");
expect(JSON.parse(String(seen[0].init.body))).toEqual({ viewer_id: "dev-1" });
await fetcher("tok-old");
expect(JSON.parse(String(seen[1].init.body))).toEqual({ viewer_id: "dev-1", previous_token: "tok-old" });
});
it("a refresh carries the current token so the stream keeps its session", async () => {
const time = fakeTime();
const passed: string[] = [];
let n = 0;
const keeper = new TokenKeeper(async (previous?: string) => {
passed.push(previous ?? "");
n += 1;
return { manifest_url: `${API}/ott/stream/k${n}/master.m3u8`, expires_at: Math.floor(time.now() / 1000) + 600 };
}, time as never);
await keeper.start();
await time.advanceTo(time.now() + 541_000);
keeper.stop();
expect(passed).toEqual(["", "k1"]);
});
it("the receiver page loads the CAF framework and our module only, with the Apache notice", () => {
const root = join(__dirname, "../cast-receiver");
const html = readFileSync(join(root, "index.html"), "utf8");
expect(html).toContain("caf_receiver/v3/cast_receiver_framework.js");
expect(html).toContain('src="receiver.js" type="module"');
const receiver = readFileSync(join(root, "receiver.js"), "utf8");
for (const handler of ["manifestRequestHandler", "segmentRequestHandler", "licenseRequestHandler"]) {
expect(receiver).toContain(handler);
}
expect(readFileSync(join(root, "NOTICE"), "utf8")).toMatch(/Apache License, Version 2\.0/);
});
});
describe("cast receiver API allowlist (QM verify gap e)", () => {
const PROD = "https://api.menivor.com/api/v1";
const cast = (apiBase: unknown) => ({ apiBase, titleId: "t1", session: "vs", deviceId: "d" });
it("ships the production API origin as the default, without the dev flag", () => {
expect(API_ORIGINS).toEqual(["https://api.menivor.com"]);
expect(ALLOW_LOCALHOST).toBe(false);
expect(DEFAULT_POLICY.origins).toEqual(API_ORIGINS);
});
it("accepts an allowed origin with the API path", () => {
expect(readCast(cast(PROD))).toEqual({ data: { apiBase: PROD, titleId: "t1", session: "vs", deviceId: "d" } });
expect(readCast(cast("https://api.menivor.com:443/api/v1")).data).toBeTruthy();
});
it("refuses an origin that is not on the list", () => {
expect(readCast(cast("https://evil.example/api/v1")).error).toMatch(/does not play from https:\/\/evil\.example/);
expect(readCustomData(cast("https://evil.example/api/v1"))).toBeNull();
expect(apiBaseProblem("https://api.menivor.com:8443/api/v1")).not.toBe("");
expect(apiBaseProblem("https://menivor.com/api/v1")).not.toBe("");
});
it("refuses look-alike hosts and credentials tricks", () => {
for (const base of ["https://api.menivor.com.evil.com/api/v1", "https://evilapi.menivor.com/api/v1",
"https://api.menivor.com@evil.com/api/v1", "https://user@api.menivor.com/api/v1", "https://api.menivor.co/api/v1",
"https://api.menivor.com/api/v1?x=1"]) {
expect(readCast(cast(base)).error, base).toBeTruthy();
}
});
it("refuses an http downgrade, and allows http://localhost only with the dev flag", () => {
expect(readCast(cast("http://api.menivor.com/api/v1")).error).toMatch(/https/);
expect(readCast(cast("http://localhost:8000/api/v1")).error).toMatch(/https/);
const dev = { origins: API_ORIGINS, allowLocalhost: true };
expect(readCast(cast("http://localhost:8000/api/v1"), dev).data?.apiBase).toBe("http://localhost:8000/api/v1");
expect(readCast(cast("http://127.0.0.1:8000/api/v1"), dev).data).toBeTruthy();
expect(readCast(cast("http://api.menivor.com/api/v1"), dev).error).toMatch(/https/);
expect(readCast(cast("http://localhost.evil.com/api/v1"), dev).error).toBeTruthy();
});
it("refuses a missing or malformed base", () => {
expect(readCast(cast(undefined)).error).toMatch(/no API address/);
expect(readCast(cast("")).error).toMatch(/no API address/);
expect(readCast(cast(42)).error).toMatch(/no API address/);
expect(readCast(null).error).toMatch(/no API address/);
expect(readCast(cast("not a url")).error).toMatch(/invalid API address/);
expect(readCast(cast("javascript:alert(1)")).error).toBeTruthy();
});
it("keeps the viewer code of a paid grant for the TV overlay, none for a free one", async () => {
const paid = new TokenKeeper(async () => ({ manifest_url: `${API}/ott/stream/a/master.m3u8`, expires_at: 1,
protected: true, viewer_mark: "AB12CD34" }), { setTimer: () => 0, clearTimer: () => undefined } as never);
await paid.start();
paid.stop();
expect(paid.mark).toBe("AB12CD34");
const free = new TokenKeeper(async () => ({ manifest_url: `${API}/ott/stream/a/master.m3u8`, expires_at: 1,
protected: false }), { setTimer: () => 0, clearTimer: () => undefined } as never);
await free.start();
free.stop();
expect(free.mark).toBe("");
});
it("never fetches from a refused base, even if handed one directly", async () => {
let calls = 0;
const fetcher = grantFetcher({ apiBase: "https://api.menivor.com.evil.com/api/v1", titleId: "t1", session: "", deviceId: "d" },
async () => {
calls += 1;
return { ok: true, json: async () => ({}) };
});
await expect(fetcher()).rejects.toThrow(/does not play from/);
expect(calls).toBe(0);
});
it("the receiver shows a visible error and returns before any fetch on a refused cast", () => {
const root = join(__dirname, "../cast-receiver");
const receiver = readFileSync(join(root, "receiver.js"), "utf8");
const refused = receiver.indexOf("if (!loadRequestData || !loadRequestData.media || !parsed.data)");
expect(refused).toBeGreaterThan(0);
const block = receiver.slice(refused, receiver.indexOf("}", refused));
expect(block).toContain("showStatus(parsed.error");
expect(block).toContain("return loadError");
expect(refused).toBeLessThan(receiver.indexOf("new TokenKeeper"));
expect(readFileSync(join(root, "index.html"), "utf8")).toMatch(/<p id="status" role="alert" hidden><\/p>/);
});
it("publish builds config.js from CAST_API_ORIGINS and rejects anything but bare https origins", () => {
expect(apiOrigins({})).toEqual(["https://api.menivor.com"]);
expect(apiOrigins({ CAST_API_ORIGINS: "https://api.menivor.com, https://staging-api.menivor.com/" }))
.toEqual(["https://api.menivor.com", "https://staging-api.menivor.com"]);
for (const bad of ["http://api.menivor.com", "https://api.menivor.com/api/v1", "api.menivor.com", "https://u@x.com"]) {
expect(() => apiOrigins({ CAST_API_ORIGINS: bad }), bad).toThrow(/CAST_API_ORIGINS/);
}
const generated = renderConfig({ CAST_API_ORIGINS: "https://staging-api.menivor.com", CAST_ALLOW_LOCALHOST: "1" });
expect(generated).toContain('export const API_ORIGINS = ["https://staging-api.menivor.com"];');
expect(generated).toContain("export const ALLOW_LOCALHOST = true;");
expect(renderConfig({})).toContain("export const ALLOW_LOCALHOST = false;");
const cmd = castUploads(["config.js"], "b", "cast", "/tmp/gen/config.js");
expect(cmd[0][3]).toBe("b/cast/config.js");
expect(cmd[0][5]).toBe("/tmp/gen/config.js");
});
});
describe("cast button plan", async () => {
const { castPlan, DEFAULT_RECEIVER_ID } = await import("../src/cast/plan");
it("offers any length with our receiver, short titles only with the default one", () => {
expect(castPlan({ live: true, receiverId: "ABCD1234", durationS: 1800 })).toEqual({ show: true, customReceiver: true });
expect(castPlan({ live: true, receiverId: DEFAULT_RECEIVER_ID, durationS: 1800 }).show).toBe(false);
expect(castPlan({ live: true, receiverId: "", durationS: 300 })).toEqual({ show: true, customReceiver: false });
expect(castPlan({ live: false, receiverId: "ABCD1234", durationS: 60 }).show).toBe(false);
});
});
describe("store build scripts", async () => {
const { releaseGaps } = await import("../scripts/release-check.mjs");
const { uploads } = await import("../scripts/cast-publish.mjs");
const pkg = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf8"));
const eas = JSON.parse(readFileSync(join(__dirname, "../eas.json"), "utf8"));
it("builds locally after the licence check, phone and TV, and submits to internal testing", () => {
for (const name of ["build:ios", "build:android", "build:tvos", "build:androidtv"]) {
expect(pkg.scripts[name]).toMatch(/^npm run licence:check && .*eas build --local/);
}
expect(pkg.scripts["build:tvos"]).toContain("EXPO_TV=1");
expect(eas.build.tv.env.EXPO_TV).toBe("1");
expect(eas.submit.production.android.track).toBe("internal");
});
it("names the owner inputs a store build still needs", () => {
const gaps: string[] = releaseGaps(eas, {} as never, () => false);
expect(gaps.join("\n")).toMatch(/App Store Connect app id/);
expect(gaps.join("\n")).toMatch(/EXPO_TOKEN/);
expect(releaseGaps({ submit: { production: { ios: { ascAppId: "123" } } } }, { EXPO_TOKEN: "x" } as never, () => true)).toEqual([]);
});
it("publishes only the receiver page and scripts", () => {
const commands: string[][] = uploads(["index.html", "receiver.js", "token.js", "config.js", "mark.js", "README.md", "NOTICE"],
"b", "cast");
expect(commands.map((c) => c[3])).toEqual(["b/cast/config.js", "b/cast/index.html", "b/cast/mark.js",
"b/cast/receiver.js", "b/cast/token.js"]);
});
});