Null-DRM-Official/apps/streamd/internal/ui/static/js/views/admin.js
404errordeveloper 8fc7e4c0b8 streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
2026-10-10 18:05:51 +02:00

736 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Schedule overview, global settings, people and keys, and the audit log.
import {
el, pill, toast, confirmDialog, fmtDateTime, fmtRelative, copyText, clear, append, openModal, setText,
} from "../util.js";
import { state, isAdmin, canEdit, refresh } from "../store.js";
import { api } from "../api.js";
import { daysLabel } from "./dashboard.js";
import { openScheduleDialog } from "./stream.js";
// ---------- schedule overview ----------
export function scheduleView(root) {
const body = el("tbody");
const pick = el("select");
root.append(el("div.stack",
el("div.card",
el("div.card-head",
el("h2", { text: "All schedules" }),
el("span.spacer"),
canEdit() ? el("div.row",
pick,
el("button.sm", {
text: "+ Add schedule",
onclick: () => {
if (!pick.value) {
toast("Pick a stream first", true);
return;
}
openScheduleDialog(Number(pick.value), load);
},
}),
) : null,
),
el("p.hint", {
text: "A scheduled start enables the stream and brings it up; a scheduled stop takes it down. " +
"Credentials are refreshed a few minutes beforehand.",
}),
el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Stream" }), el("th", { text: "Action" }),
el("th", { text: "When" }), el("th", { text: "Next" }),
el("th", { text: "Last fired" }), el("th", { text: "" }),
)),
body,
)),
),
));
function fillStreams() {
const want = (state.streams || []).map((s) => `${s.id}:${s.name}`).join("|");
if (pick.dataset.opts === want) return;
pick.dataset.opts = want;
clear(pick);
append(pick, [
el("option", { value: "", text: "Choose a stream…" }),
...(state.streams || []).map((s) => el("option", { value: s.id, text: s.title || s.name })),
]);
}
async function load() {
fillStreams();
try {
const d = await api.allSchedules();
const list = d.schedules || [];
clear(body);
if (!list.length) {
body.append(el("tr", el("td.empty", { colspan: "6", text: "Nothing scheduled yet." })));
return;
}
for (const sc of list) {
body.append(el("tr",
el("td", el("a", { href: `#/stream/${sc.stream_id}`, text: sc.stream_name || `#${sc.stream_id}` })),
el("td", pill(sc.action)),
el("td",
el("div", { text: sc.kind === "weekly" ? `${daysLabel(sc.days_mask)} at ${sc.time_of_day}` : "once" }),
el("div.sub", { text: sc.kind === "weekly" ? sc.tz : fmtDateTime(sc.at_utc) }),
),
el("td",
el("div", { text: sc.enabled ? fmtRelative(sc.next_fire_at) : "disabled" }),
el("div.sub", { text: sc.enabled ? fmtDateTime(sc.next_fire_at) : "" }),
),
el("td", { text: sc.last_fired_at ? fmtDateTime(sc.last_fired_at) : "—" }),
el("td.actions", canEdit() ? el("div.row",
el("button.tiny.ghost", {
text: sc.enabled ? "Disable" : "Enable",
onclick: async () => {
try {
await api.patchSchedule(sc.id, { enabled: !sc.enabled });
load();
} catch (err) {
toast(err.message, true);
}
},
}),
el("button.tiny.danger", {
text: "Delete",
onclick: async () => {
if (!(await confirmDialog("Delete this schedule?", "", "Delete"))) return;
try {
await api.deleteSchedule(sc.id);
load();
} catch (err) {
toast(err.message, true);
}
},
}),
) : null),
));
}
} catch (err) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "6", text: err.message })));
}
}
load();
refresh("schedule");
return () => {};
}
// ---------- settings ----------
export function settingsView(root) {
const wrap = el("div.stack");
root.append(wrap);
async function load() {
clear(wrap);
if (!isAdmin()) {
wrap.append(el("div.card", el("p", { text: "Settings are administrator-only." })));
return;
}
let data;
try {
data = await api.settings();
} catch (err) {
wrap.append(el("div.card", el("p.msg.err", { text: err.message })));
return;
}
const vals = data.settings || {};
const field = (key, label, hint, attrs = {}) => {
const input = el("input", { value: vals[key] || "", placeholder: "default", ...attrs });
input.dataset.key = key;
return el("label", el("span.lbl", { text: label }), input, hint ? el("small.hint", { text: hint }) : null);
};
const form = el("form",
el("div.grid",
field("hls_time", "Segment seconds", "Shorter means lower latency and more requests.",
{ type: "number", min: "1", max: "30" }),
field("hls_list_size", "Playlist length", "How many segments stay in a live playlist.",
{ type: "number", min: "1", max: "500" }),
field("live_wait", "Downloader live wait", "Seconds the downloader waits before starting.",
{ type: "number", min: "0", max: "120" }),
field("ts_ready_bytes", "Buffer before packaging", "Bytes of muxed media to collect before probing.",
{ type: "number", min: "0" }),
field("idle_timeout_s", "Default idle timeout", "Applied to new streams when create omits idle_timeout_s.",
{ type: "number", min: "30", max: "86400" }),
field("default_on_demand", "Default on-demand", "true/false — applied when create omits on_demand."),
field("default_outputs", "Default outputs JSON", "JSON array of output specs for new streams that omit outputs."),
),
el("p.hint", {
text: "Blank means the built-in default. Packager knobs apply the next time a stream starts. " +
"On-demand / idle / outputs defaults apply when a new stream is created without those fields.",
}),
el("div.row.end", { style: { marginTop: "14px" } }, el("button", { type: "submit", text: "Save settings" })),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
const body = {};
for (const input of form.querySelectorAll("input[data-key]")) {
body[input.dataset.key] = input.value.trim();
}
try {
await api.saveSettings(body);
toast("Settings saved — applies at each stream's next start");
load();
} catch (err) {
toast(err.message, true);
}
});
const eff = data.effective || {};
wrap.append(
el("div.card", el("div.card-head", el("h2", { text: "Packaging defaults" })), form),
el("div.card",
el("div.card-head", el("h2", { text: "In effect now" })),
el("div.grid",
...Object.entries(eff).map(([k, v]) =>
el("div", el("div.k.muted", { text: k }), el("div.mono", { text: String(v || "built-in default") }))),
),
),
);
wrap.append(await egressCard());
}
load();
return () => {};
}
async function egressCard() {
const box = el("div.card",
el("div.card-head",
el("h2", { text: "Egress tunnels" }),
el("span.spacer"),
el("button.sm", { type: "button", text: "+ Add profile", onclick: () => openEgressDialog(reload) }),
),
el("p.hint", {
text: "Named WireGuard (Linux netns + local SOCKS) or SOCKS URL profiles. " +
"Assign a profile per stream so only that stream’s origin fetch exits via the tunnel. " +
"Full-tunnel WG stays inside a network namespace — SSH and the dashboard keep the host route.",
}),
);
const list = el("div");
box.append(list);
async function reload() {
clear(list);
let data;
try {
data = await api.egress();
} catch (err) {
list.append(el("p.msg.err", { text: err.message }));
return;
}
const profiles = data.profiles || [];
if (!profiles.length) {
list.append(el("p.hint", { text: "No profiles yet. Add london (or dublin, …) from a WireGuard client .conf." }));
return;
}
for (const p of profiles) {
const status = p.status || "stopped";
const meta = [
p.kind,
status,
p.listen_port ? `:${p.listen_port}` : null,
p.egress_ip || null,
p.has_conf ? "conf" : null,
p.enabled ? "autostart" : null,
].filter(Boolean).join(" · ");
const row = el("div.row", {
style: { alignItems: "center", gap: "8px", flexWrap: "wrap", padding: "8px 0", borderBottom: "1px solid var(--border)" },
},
el("div", { style: { flex: "1 1 160px" } },
el("div.mono", { text: p.name }),
el("small.muted", { text: meta }),
p.last_error ? el("div.msg.err", { text: p.last_error, style: { marginTop: "4px" } }) : null,
),
el("button.ghost.sm", {
type: "button", text: "Up",
onclick: async () => {
try { await api.egressUp(p.name); toast(`${p.name} up`); reload(); }
catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Down",
onclick: async () => {
try { await api.egressDown(p.name); toast(`${p.name} down`); reload(); }
catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Test IP",
onclick: async () => {
try {
const r = await api.egressTest(p.name);
toast(`${p.name} egress IP: ${r.egress_ip || r.ip || JSON.stringify(r)}`);
reload();
} catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Edit",
onclick: () => openEgressDialog(reload, p),
}),
el("button.ghost.sm.danger", {
type: "button", text: "Delete",
onclick: async () => {
if (!confirm(`Delete egress profile ${p.name}?`)) return;
try { await api.deleteEgress(p.name); toast("Deleted"); reload(); }
catch (err) { toast(err.message, true); }
},
}),
);
list.append(row);
}
}
await reload();
return box;
}
function openEgressDialog(onDone, existing) {
const isEdit = !!existing;
const name = el("input", {
required: true, placeholder: "london",
value: existing?.name || "",
disabled: isEdit,
});
const kind = el("select",
el("option", { value: "wireguard", text: "WireGuard (Linux netns)", selected: !existing || existing.kind === "wireguard" }),
el("option", { value: "socks", text: "SOCKS/HTTP URL only", selected: existing?.kind === "socks" }),
);
const enabled = el("input", { type: "checkbox", checked: existing ? !!existing.enabled : true });
const socksURL = el("input", {
placeholder: "socks5://127.0.0.1:1081",
value: existing?.socks_url || "",
});
const conf = el("textarea", {
rows: "12",
placeholder: "[Interface]\nPrivateKey = …\nAddress = …\n\n[Peer]\nPublicKey = …\nEndpoint = …\nAllowedIPs = 0.0.0.0/0, ::/0\n",
spellcheck: "false",
});
const msg = el("p.msg");
function syncKind() {
socksURL.closest("label").hidden = kind.value !== "socks";
conf.closest("label").hidden = kind.value !== "wireguard";
}
kind.addEventListener("change", syncKind);
const form = el("form",
el("div.grid",
el("label", el("span.lbl", { text: "Name (slug)" }), name),
el("label", el("span.lbl", { text: "Kind" }), kind),
el("label.inline-check", enabled, el("span", { text: "Auto-start with streamd serve" })),
el("label.span2", el("span.lbl", { text: "SOCKS/HTTP URL" }), socksURL),
el("label.span2", el("span.lbl", { text: "WireGuard client config" }), conf,
el("small.hint", { text: isEdit ? "Leave blank to keep the stored conf. Pasting replaces it." : "Paste a client .conf (e.g. vps-london.conf). Private keys stay on the server." })),
),
msg,
el("div.row.end", { style: { marginTop: "12px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: isEdit ? "Save" : "Create" }),
),
);
syncKind();
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
msg.textContent = "";
msg.classList.remove("err");
const slug = name.value.trim();
try {
if (isEdit) {
const body = { kind: kind.value, enabled: enabled.checked };
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
if (kind.value === "wireguard" && conf.value.trim()) body.conf = conf.value;
await api.saveEgress(existing.name, body);
} else {
const body = { name: slug, kind: kind.value, enabled: enabled.checked };
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
await api.createEgress(body);
if (kind.value === "wireguard" && conf.value.trim()) {
await api.saveEgress(slug, { conf: conf.value });
}
}
toast(isEdit ? "Saved" : "Created");
close();
onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(
el("h2", { text: isEdit ? `Edit egress · ${existing.name}` : "Add egress profile" }),
form,
);
}
// ---------- people and API keys ----------
export function peopleView(root) {
const usersBox = el("div");
const keysBox = el("div");
root.append(el("div.stack",
el("div.card",
el("div.card-head",
el("h2", { text: "People" }),
el("span.spacer"),
el("button.sm", { text: "+ Add person", onclick: () => openUserDialog(loadUsers) }),
),
el("p.hint", {
text: "Administrators manage people, keys and settings. Operators run and edit streams. " +
"Viewers can look but not touch, and never see credentials.",
}),
usersBox,
),
el("div.card",
el("div.card-head",
el("h2", { text: "API keys" }),
el("span.spacer"),
el("button.sm", { text: "+ New key", onclick: () => openKeyDialog(loadKeys) }),
),
el("p.hint", {
text: "Machine credentials, one per capture agent. The secret is shown once, " +
"on creation, and only its hash is stored.",
}),
keysBox,
),
));
if (!isAdmin()) {
clear(usersBox);
usersBox.append(el("p", { text: "Administrator-only." }));
return () => {};
}
async function loadUsers() {
try {
const d = await api.users();
const body = el("tbody");
for (const u of d.users || []) {
const self = state.me && state.me.user_id === u.id;
body.append(el("tr",
el("td",
el("div", { text: u.username }),
self ? el("div.sub", { text: "that is you" }) : null,
),
el("td", pill(u.role, "role")),
el("td", u.disabled ? pill("disabled") : pill("active", "ok")),
el("td", { text: u.last_login_at ? fmtDateTime(u.last_login_at) : "never" }),
el("td.actions", el("div.row",
el("select", {
onchange: async (e) => {
try {
await api.patchUser(u.id, { role: e.target.value });
toast("Role updated");
loadUsers();
} catch (err) {
toast(err.message, true);
loadUsers();
}
},
}, ...["viewer", "operator", "admin"].map((r) =>
el("option", { value: r, text: r, selected: u.role === r }))),
el("button.tiny.ghost", {
text: u.disabled ? "Enable" : "Disable",
onclick: async () => {
try {
await api.patchUser(u.id, { disabled: !u.disabled });
loadUsers();
} catch (err) {
toast(err.message, true);
}
},
}),
el("button.tiny.ghost", { text: "Password", onclick: () => openPasswordDialog(u, self) }),
el("button.tiny.danger", {
text: "Remove",
onclick: async () => {
if (!(await confirmDialog(`Remove ${u.username}?`,
"Their sessions end immediately.", "Remove"))) return;
try {
await api.deleteUser(u.id);
toast("Removed");
loadUsers();
} catch (err) {
toast(err.message, true);
}
},
}),
)),
));
}
usersBox.replaceChildren(el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Username" }), el("th", { text: "Role" }), el("th", { text: "Status" }),
el("th", { text: "Last signed in" }), el("th", { text: "" }),
)),
body,
)));
} catch (err) {
usersBox.replaceChildren(el("p.msg.err", { text: err.message }));
}
}
async function loadKeys() {
try {
const d = await api.apiKeys();
const body = el("tbody");
for (const k of d.api_keys || []) {
body.append(el("tr",
el("td", { text: k.name }),
el("td", pill(k.role, "role")),
el("td", k.revoked_at ? pill("revoked") : pill("active", "ok")),
el("td", { text: k.last_used_at ? fmtDateTime(k.last_used_at) : "never" }),
el("td.actions", k.revoked_at ? null : el("button.tiny.danger", {
text: "Revoke",
onclick: async () => {
if (!(await confirmDialog(`Revoke "${k.name}"?`,
"Any agent using it stops working immediately.", "Revoke"))) return;
try {
await api.revokeKey(k.id);
toast("Revoked");
loadKeys();
} catch (err) {
toast(err.message, true);
}
},
})),
));
}
if (!(d.api_keys || []).length) {
body.append(el("tr", el("td.empty", { colspan: "5", text: "No API keys yet." })));
}
keysBox.replaceChildren(el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "Name" }), el("th", { text: "Role" }), el("th", { text: "Status" }),
el("th", { text: "Last used" }), el("th", { text: "" }),
)),
body,
)));
} catch (err) {
keysBox.replaceChildren(el("p.msg.err", { text: err.message }));
}
}
loadUsers();
loadKeys();
return () => {};
}
function openUserDialog(onDone) {
const username = el("input", { required: true, autocomplete: "off" });
const password = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" });
const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r })));
const msg = el("p.msg");
const form = el("form",
el("h2", { text: "Add person" }),
el("div.stack", { style: { marginTop: "12px" } },
el("label", el("span.lbl", { text: "Username" }), username),
el("label", el("span.lbl", { text: "Password" }), password,
el("small.hint", { text: "At least 8 characters." })),
el("label", el("span.lbl", { text: "Role" }), role),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Add" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
await api.createUser({ username: username.value.trim(), password: password.value, role: role.value });
close();
toast("Added");
if (onDone) onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
username.focus();
}
function openPasswordDialog(user, self) {
const current = el("input", { type: "password", autocomplete: "current-password" });
const next = el("input", { type: "password", required: true, minlength: "8", autocomplete: "new-password" });
const msg = el("p.msg");
const form = el("form",
el("h2", { text: `Change password for ${user.username}` }),
el("p.hint", {
text: self
? "You will be signed out, because changing a password ends every session for the account."
: "Their sessions end immediately.",
}),
el("div.stack", { style: { marginTop: "12px" } },
self ? el("label", el("span.lbl", { text: "Current password" }), current) : null,
el("label", el("span.lbl", { text: "New password" }), next),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Change" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
await api.setPassword(user.id, { current_password: current.value, password: next.value });
close();
if (self) {
toast("Password changed — sign in again");
setTimeout(() => location.reload(), 900);
} else {
toast("Password changed");
}
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
}
function openKeyDialog(onDone) {
const name = el("input", { required: true, placeholder: "phone-agent-01" });
const role = el("select", ...["operator", "viewer", "admin"].map((r) => el("option", { value: r, text: r })));
const msg = el("p.msg");
const form = el("form",
el("h2", { text: "New API key" }),
el("p.hint", { text: "A capture agent needs the operator role." }),
el("div.stack", { style: { marginTop: "12px" } },
el("label", el("span.lbl", { text: "Name" }), name),
el("label", el("span.lbl", { text: "Role" }), role),
),
msg,
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: "Create" }),
),
);
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
try {
const k = await api.createKey({ name: name.value.trim(), role: role.value });
// Replace this dialog in place — do not close() first. Closing raced the
// next openModal and wiped the secret box empty.
showSecret(k);
if (onDone) onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(form);
name.focus();
}
function showSecret(key) {
const value = (key && (key.secret || key.token || key.key)) || "";
if (!value) {
openModal(
el("h2", { text: "Key created, but secret missing" }),
el("p.msg.err", {
text: "The server did not return the one-time secret. Check the streamd version, then revoke this key and create another.",
}),
el("div.row.end", { style: { marginTop: "14px" } },
el("button", { text: "Close", onclick: () => document.getElementById("modal").close() })),
);
return;
}
const secret = el("pre.logbox", { text: value, style: { maxHeight: "none" } });
const close = openModal(
el("h2", { text: `Key "${key.name || "agent"}" created` }),
el("p.hint", {
text: "Copy it now. Only a hash is stored, so this is the one and only time it is shown.",
}),
secret,
el("p.hint", { text: "In apps/agent/agent.yaml set: api_key: <the value above>" }),
el("div.row.end", { style: { marginTop: "14px" } },
el("button.ghost", { text: "Copy", onclick: () => copyText(value, "API key") }),
el("button", { text: "Done", onclick: () => close() }),
),
);
}
// ---------- audit log ----------
export function auditView(root) {
const body = el("tbody");
const filter = el("input", { type: "search", placeholder: "Filter by actor…" });
root.append(el("div.card",
el("div.card-head",
el("h2", { text: "Audit log" }),
el("span.spacer"),
filter,
el("button.ghost.sm", { text: "Reload", onclick: () => load() }),
),
el("p.hint", { text: "Every change, who made it, and from where. Login attempts included." }),
el("div.table-wrap", el("table",
el("thead", el("tr",
el("th", { text: "When" }), el("th", { text: "Actor" }), el("th", { text: "Action" }),
el("th", { text: "Status" }), el("th", { text: "From" }),
)),
body,
)),
));
let rows = [];
function paint() {
const q = filter.value.trim().toLowerCase();
const list = q ? rows.filter((e) => String(e.actor || "").toLowerCase().includes(q)) : rows;
clear(body);
if (!list.length) {
body.append(el("tr", el("td.empty", { colspan: "5", text: "Nothing recorded." })));
return;
}
for (const e of list) {
const bad = e.status >= 400;
body.append(el("tr",
el("td.mono", { text: fmtDateTime(e.at), title: e.at }),
el("td",
el("div", { text: e.actor || "anonymous" }),
el("div.sub", { text: e.actor_kind || "" }),
),
el("td",
el("div", { text: e.note || `${e.method} ${e.path}` }),
el("div.sub.mono", { text: `${e.method} ${e.path}` }),
),
el("td", pill(String(e.status), bad ? "down" : "ok")),
el("td.mono", { text: e.ip || "—" }),
));
}
}
async function load() {
if (!isAdmin()) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "5", text: "Administrator-only." })));
return;
}
try {
const d = await api.audit(300);
rows = d.audit || [];
paint();
} catch (err) {
clear(body);
body.append(el("tr", el("td.empty", { colspan: "5", text: err.message })));
}
}
filter.addEventListener("input", paint);
load();
return () => {};
}
export { setText };