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

190 lines
6.9 KiB
JavaScript

/**
* Token handling for the Menivor cast receiver (Wave Q QM1.4, P-M16).
*
* Playback tokens last 10 minutes. The token sits in the stream path
* (`/ott/stream/<token>/...`) and in the AES-128 key URL (`?t=<token>`).
* The receiver asks the API for a fresh grant a minute before expiry and
* rewrites every manifest, segment and key request to carry the newest token,
* so a 30-minute title plays to the end on a TV.
*
* Plain ES module with no browser globals, so the same code runs on the
* Chromecast and under vitest.
*/
import { ALLOW_LOCALHOST, API_ORIGINS } from "./config.js";
import { markOf } from "./mark.js";
export const REFRESH_EARLY_S = 60;
export const RETRY_S = 15;
const STREAM = /(\/ott\/stream\/)([^/?#]+)(\/)/;
const KEY_PARAM = /([?&]t=)([^&#]+)/;
/** The token inside a manifest URL, or "" when there is none. */
export function tokenOf(url) {
const match = STREAM.exec(String(url || ""));
return match ? decodeURIComponent(match[2]) : "";
}
/** `url` with every playback token replaced by `token` (stream path and key query). */
export function swapToken(url, token) {
if (!token) return url;
const enc = encodeURIComponent(token);
return String(url).replace(STREAM, `$1${enc}$3`).replace(KEY_PARAM, `$1${enc}`);
}
/** Milliseconds until the grant should be refreshed: a minute before it expires, never negative. */
export function refreshInMs(expiresAtS, nowMs) {
return Math.max(0, (expiresAtS - REFRESH_EARLY_S) * 1000 - nowMs);
}
/** @typedef {{ origins: readonly string[], allowLocalhost: boolean }} Policy */
/** The receiver's API allowlist from config.js (build time). @type {Policy} */
export const DEFAULT_POLICY = Object.freeze({ origins: API_ORIGINS, allowLocalhost: ALLOW_LOCALHOST });
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
/** The exact origin of an allowlist entry, or "" when it is not a plain https origin. */
function allowedOrigin(entry) {
try {
const url = new URL(String(entry));
return url.protocol === "https:" && !url.username && !url.password ? url.origin : "";
} catch {
return "";
}
}
/**
* Why `apiBase` may not be used, or "" when it may. Only https origins on the
* allowlist (scheme, host and port compared exactly); http://localhost only
* when the dev flag is on. No credentials, query or fragment in the base.
* @param {string} apiBase
* @param {Policy} [policy]
*/
export function apiBaseProblem(apiBase, policy = DEFAULT_POLICY) {
if (!apiBase) return "The cast request has no API address.";
let url;
try {
url = new URL(apiBase);
} catch {
return "The cast request has an invalid API address.";
}
if (url.username || url.password || url.search || url.hash) return "The cast request has an invalid API address.";
const local = policy.allowLocalhost === true && url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname);
if (url.protocol !== "https:" && !local) return "This receiver only plays from a secure (https) API address.";
const allowed = new Set((policy.origins || []).map(allowedOrigin).filter(Boolean));
if (!local && !allowed.has(url.origin)) return `This receiver does not play from ${url.origin}.`;
return "";
}
/**
* What the sender put in `customData`, checked against the allowlist:
* `{data}` when the cast may load, `{error}` (a sentence for the TV screen) when not.
* @param {unknown} raw
* @param {Policy} [policy]
* @returns {{ data?: { apiBase: string, titleId: string, session: string, deviceId: string }, error?: string }}
*/
export function readCast(raw, policy = DEFAULT_POLICY) {
const source = raw && typeof raw === "object" ? raw : {};
const text = (v) => (typeof v === "string" ? v.trim() : "");
const data = {
apiBase: text(source.apiBase).replace(/\/+$/, ""),
titleId: text(source.titleId),
session: text(source.session),
deviceId: text(source.deviceId),
};
const problem = apiBaseProblem(data.apiBase, policy);
if (problem) return { error: problem };
if (!/^[A-Za-z0-9_-]{1,32}$/.test(data.titleId)) return { error: "The cast request has no valid title." };
return { data };
}
/**
* `readCast` data, or null when the cast must not load.
* @param {unknown} raw
* @param {Policy} [policy]
*/
export function readCustomData(raw, policy = DEFAULT_POLICY) {
return readCast(raw, policy).data || null;
}
/**
* Keeps the newest grant for one title. `fetchGrant()` resolves to the
* `/ott/play/<id>` envelope data: `{manifest_url, expires_at}`.
*/
export class TokenKeeper {
constructor(fetchGrant, { now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
this.fetchGrant = fetchGrant;
this.now = now;
this.setTimer = setTimer;
this.clearTimer = clearTimer;
this.token = "";
this.expiresAt = 0;
this.manifestUrl = "";
this.mark = "";
this.timer = null;
this.refreshes = 0;
this.stopped = false;
}
async start() {
await this.refresh();
return this.manifestUrl;
}
async refresh() {
if (this.stopped) return;
try {
// The current token rides along so the API keeps the same stream session (no second slot).
const grant = await this.fetchGrant(this.token);
this.manifestUrl = grant.manifest_url;
this.token = tokenOf(grant.manifest_url);
this.expiresAt = Number(grant.expires_at) || 0;
this.mark = markOf(grant);
this.refreshes += 1;
this.schedule(refreshInMs(this.expiresAt, this.now()));
} catch (err) {
if (!this.token) throw err;
this.schedule(RETRY_S * 1000);
}
}
schedule(ms) {
if (this.timer) this.clearTimer(this.timer);
if (!this.stopped) this.timer = this.setTimer(() => void this.refresh(), ms);
}
/** Rewrites one request URL to the newest token. */
rewrite(url) {
return swapToken(url, this.token);
}
stop() {
this.stopped = true;
if (this.timer) this.clearTimer(this.timer);
this.timer = null;
}
}
/** POST /ott/play/<title> as the viewer who cast, with the device id the phone uses. */
export function grantFetcher(data, fetchImpl, policy = DEFAULT_POLICY) {
return async (previousToken = "") => {
// Checked again here so no code path can fetch from an address off the allowlist.
const problem = apiBaseProblem(data.apiBase, policy);
if (problem) throw new Error(problem);
const headers = { "Content-Type": "application/json", Accept: "application/json" };
if (data.session) headers["X-OTT-Viewer"] = data.session;
const body = { viewer_id: data.deviceId };
if (previousToken) body.previous_token = previousToken;
const response = await fetchImpl(`${data.apiBase}/ott/play/${encodeURIComponent(data.titleId)}`, {
method: "POST", headers, body: JSON.stringify(body),
});
const reply = await response.json().catch(() => ({}));
if (!response.ok || !reply.data || !reply.data.manifest_url) {
throw new Error((reply && reply.message) || "playback refused");
}
return reply.data;
};
}